text stringlengths 14 6.51M |
|---|
program binarytree;
TYPE
TreeNodePtr = ^TreeNode;
VisitProcPtr = Procedure(node: TreeNodePtr);
TreeNode = RECORD
parent : TreeNodePtr;
left: TreeNodePtr;
right: TreeNodePtr;
ID: integer;
visit: VisitProcPtr;
END;
PROCEDURE Visit(node: TreeNodePtr);
BEGIN
writeln(node^.ID);
END;
(* Add Element to the binary search tree. Assumes that no *)
(* element with the same key exists in the tree. *)
PROCEDURE InsertElement(VAR Tree : TreeNodePtr; element: integer);
VAR
NewNode : TreeNodePtr; (* pointer to new node *)
ParentPtr : TreeNodePtr; (* points to new node's parent *)
CurrentNodePtr : TreeNodePtr;
BEGIN (* InsertElement *)
(* Create a new node. *)
New (NewNode);
NewNode^.left := NIL;
NewNode^.right := NIL;
NewNode^.ID := Element;
NewNode^.visit := @Visit;
(* IF this is first node in tree, set Tree to NewNode; *)
(* otherwise, link new node to Node(ParentPtr). *)
IF Tree = NIL THEN
Tree := NewNode (* first node in the tree *)
ELSE (* Add to the existing tree. *)
(* Set up to search. *)
CurrentNodePtr := Tree;
ParentPtr := NIL;
(* Search until no more nodes to search or until found. *)
WHILE (CurrentNodePtr <> NIL) DO
IF CurrentNodePtr^.ID = element THEN
//Found := True
ELSE
BEGIN
ParentPtr := CurrentNodePtr;
IF CurrentNodePtr^.ID > element THEN
CurrentNodePtr := CurrentNodePtr^.left
ELSE
CurrentNodePtr := CurrentNodePtr^.right
END;
IF ParentPtr^.ID > element THEN
ParentPtr^.left := NewNode
ELSE
ParentPtr^.right := NewNode
END; (* InsertElement *)
PROCEDURE DepthFirstTraversal(root: TreeNodePtr);
BEGIN
IF root <> NIL THEN
BEGIN
// Visit the root.
root^.visit(root);
//Traverse the left subtree.
DepthFirstTraversal(root^.left);
//Traverse the right subtree.
DepthFirstTraversal(root^.right);
END
END;
VAR
tree: TreeNodePtr;
BEGIN
writeln('Creating Tree');
tree := NIL;
InsertElement(tree, 5);
InsertElement(tree, 2);
InsertElement(tree, 6);
InsertElement(tree, 7);
InsertElement(tree, 1);
DepthFirstTraversal(tree);
END. |
unit stretchf;
interface
uses Windows, SysUtils, Vcl.Graphics;
type
TRGBColor = record
B: Byte;
G: Byte;
R: Byte;
end;
TRGBColorArray = array[0..400000] of TRGBColor;
PRGBColorArray = ^TRGBColorArray;
TIntArray = array[0..400000] of Integer;
PIntArray = ^TIntArray;
TInt4Array = array[0..3] of Integer;
TInt4AA = array[0..400000] of TInt4Array;
PInt4AA = ^TInt4AA;
TProgressProc = procedure(Progress: Integer);
procedure Stretch(const Src: TBitmap; Width, Height: Integer; const PProc: TProgressProc);
implementation
procedure ProgressProcCaller(Progress: Integer; PProc: TProgressProc);
begin
if Assigned(PProc) then PProc(Progress);
end;
procedure HLI3(const Src, Dst: TBitmap; const PProc: TProgressProc);
var
SP, DP: PRGBColorArray;
SXA: PIntArray;
LR: PInt4AA;
X, Y, SX, V: Integer;
Z: Extended;
begin
ProgressProcCaller(0, PProc);
try
GetMem(SXA, SizeOf(Integer) * Dst.Width);
except
on EHeapException do Exit;
end;
try
GetMem(LR, SizeOf(TInt4Array) * Dst.Width);
except
on EHeapException do
begin
FreeMem(SXA);
Exit;
end;
end;
try
for X := 0 to Dst.Width - 1 do
begin
Z := X * (Src.Width - 1) / (Dst.Width - 1);
SXA[X] := Trunc(Z);
Z := Frac(Z) + 1;
LR[X][0] := Trunc($10000 * (Z - 1) * (Z - 2) * (Z - 3) * (1 / -6) + 0.5);
LR[X][1] := Trunc($10000 * (Z - 0) * (Z - 2) * (Z - 3) * (1 / 2) + 0.5);
LR[X][2] := Trunc($10000 * (Z - 0) * (Z - 1) * (Z - 3) * (1 / -2) + 0.5);
LR[X][3] := Trunc($10000 * (Z - 0) * (Z - 1) * (Z - 2) * (1 / 6) + 0.5);
end;
for Y := 0 to Dst.Height - 1 do
begin
SP := Src.ScanLine[Y];
DP := Dst.ScanLine[Y];
X := 0;
SX := SXA[X];
while SX < 1 do
begin
Z := Frac(X * (Src.Width - 1) / (Dst.Width - 1));
DP[X].B := Trunc(SP[SX].B * (1 - Z) + SP[SX + 1].B * Z + 0.5);
DP[X].G := Trunc(SP[SX].G * (1 - Z) + SP[SX + 1].G * Z + 0.5);
DP[X].R := Trunc(SP[SX].R * (1 - Z) + SP[SX + 1].R * Z + 0.5);
Inc(X);
SX := SXA[X];
end;
while SX < Src.Width - 2 do
begin
V := $8000 + SP[SX - 1].B * LR[X][0] + SP[SX ].B * LR[X][1] +
SP[SX + 1].B * LR[X][2] + SP[SX + 2].B * LR[X][3];
if V < 0 then V := 0
else if V > $FF * $10000 then V := $FF * $10000;
DP[X].B := V shr 16;
V := $8000 + SP[SX - 1].G * LR[X][0] + SP[SX ].G * LR[X][1] +
SP[SX + 1].G * LR[X][2] + SP[SX + 2].G * LR[X][3];
if V < 0 then V := 0
else if V > $FF * $10000 then V := $FF * $10000;
DP[X].G := V shr 16;
V := $8000 + SP[SX - 1].R * LR[X][0] + SP[SX ].R * LR[X][1] +
SP[SX + 1].R * LR[X][2] + SP[SX + 2].R * LR[X][3];
if V < 0 then V := 0
else if V > $FF * $10000 then V := $FF * $10000;
DP[X].R := V shr 16;
Inc(X);
SX := SXA[X];
end;
while SX < Src.Width - 1 do
begin
Z := Frac(X * (Src.Width - 1) / (Dst.Width - 1));
DP[X].B := Trunc(SP[SX].B * (1 - Z) + SP[SX + 1].B * Z + 0.5);
DP[X].G := Trunc(SP[SX].G * (1 - Z) + SP[SX + 1].G * Z + 0.5);
DP[X].R := Trunc(SP[SX].R * (1 - Z) + SP[SX + 1].R * Z + 0.5);
Inc(X);
SX := SXA[X];
end;
DP[X] := SP[SX];
ProgressProcCaller((100 * Y) div ((Dst.Height - 1) * 2), PProc);
end;
finally
FreeMem(LR);
FreeMem(SXA);
end;
end;
procedure VLI3(const Src, Dst: TBitmap; const PProc: TProgressProc);
var
DP: PRGBColorArray;
SP: array[0..3] of PRGBColorArray;
LR: PInt4AA;
X, Y, SY, V: Integer;
Z: Extended;
begin
ProgressProcCaller(50, PProc);
try
GetMem(LR, SizeOf(TInt4Array) * Dst.Height);
except
on EOutOfMemory do Exit;
end;
try
for Y := 0 to Dst.Height - 1 do
begin
Z := Frac(Y * (Src.Height - 1) / (Dst.Height - 1)) + 1;
LR[Y][0] := Trunc($10000 * (Z - 1) * (Z - 2) * (Z - 3) * (1 / -6) + 0.5);
LR[Y][1] := Trunc($10000 * (Z - 0) * (Z - 2) * (Z - 3) * (1 / 2) + 0.5);
LR[Y][2] := Trunc($10000 * (Z - 0) * (Z - 1) * (Z - 3) * (1 / -2) + 0.5);
LR[Y][3] := Trunc($10000 * (Z - 0) * (Z - 1) * (Z - 2) * (1 / 6) + 0.5);
end;
for Y := 0 to Dst.Height - 1 do
begin
Z := Y * (Src.Height - 1) / (Dst.Height - 1);
SY := Trunc(Z);
DP := Dst.ScanLine[Y];
if SY = Src.Height - 1 then
begin
SP[0] := Src.ScanLine[SY];
for X := 0 to Dst.Width - 1 do
begin
DP[X] := SP[0][X];
end;
end
else if (SY = 0) or (SY = Src.Height - 2) then
begin
SP[0] := Src.ScanLine[SY];
SP[1] := Src.ScanLine[SY + 1];
Z := Frac(Z);
for X := 0 to Dst.Width - 1 do
begin
DP[X].B := Trunc(SP[0][X].B * (1 - Z) + SP[1][X].B * Z + 0.5);
DP[X].G := Trunc(SP[0][X].G * (1 - Z) + SP[1][X].G * Z + 0.5);
DP[X].R := Trunc(SP[0][X].R * (1 - Z) + SP[1][X].R * Z + 0.5);
end;
end
else
begin
SP[0] := Src.ScanLine[SY - 1];
SP[1] := Src.ScanLine[SY ];
SP[2] := Src.ScanLine[SY + 1];
SP[3] := Src.ScanLine[SY + 2];
for X := 0 to Dst.Width - 1 do
begin
V := $8000 + SP[0][X].B * LR[Y][0] + SP[1][X].B * LR[Y][1] +
SP[2][X].B * LR[Y][2] + SP[3][X].B * LR[Y][3];
if V < 0 then V := 0
else if V > $FF * $10000 then V := $FF * $10000;
DP[X].B := V shr 16;
V := $8000 + SP[0][X].G * LR[Y][0] + SP[1][X].G * LR[Y][1] +
SP[2][X].G * LR[Y][2] + SP[3][X].G * LR[Y][3];
if V < 0 then V := 0
else if V > $FF * $10000 then V := $FF * $10000;
DP[X].G := V shr 16;
V := $8000 + SP[0][X].R * LR[Y][0] + SP[1][X].R * LR[Y][1] +
SP[2][X].R * LR[Y][2] + SP[3][X].R * LR[Y][3];
if V < 0 then V := 0
else if V > $FF * $10000 then V := $FF * $10000;
DP[X].R := V shr 16;
end;
end;
ProgressProcCaller(50 + (100 * Y) div ((Dst.Height - 1) * 2), PProc);
end;
finally
FreeMem(LR);
end;
end;
procedure HAO(const Src, Dst: TBitmap; const PProc: TProgressProc);
var
X, Y: Integer;
I, DX, HDX, SX, XD: Integer;
SXA, XDA: PIntArray;
SP, DP: PRGBColorArray;
B, G, R: Integer;
Z: Extended;
begin
ProgressProcCaller(0, PProc);
try
GetMem(SXA, SizeOf(Integer) * (Src.Width + 1));
except
on EOutOfMemory do Exit;
end;
try
GetMem(XDA, SizeOf(Integer) * (Src.Width + 1));
except
on EOutOfMemory do
begin
FreeMem(SXA);
Exit;
end;
end;
try
for X := 0 to Dst.Width do
begin
Z := X * Src.Width / Dst.Width;
SXA[X] := Trunc(Z);
XDA[X] := Trunc(Frac(Z) * $10000);
end;
DX := Trunc(Src.Width * $10000 / Dst.Width + 0.5);
HDX := (DX + 1) div 2;
for Y := 0 to Dst.Height - 1 do
begin
SP := Src.ScanLine[Y];
DP := Dst.ScanLine[Y];
SX := 0;
XD := $10000;
for X := 0 to Dst.Width - 1 do
begin
B := 0;
G := 0;
R := 0;
if XD <> 0 then
begin
Inc(B, SP[SX].B * XD);
Inc(G, SP[SX].G * XD);
Inc(R, SP[SX].R * XD);
end;
I := SX;
SX := SXA[X + 1];
for I := I + 1 to SX - 1 do
begin
Inc(B, SP[I].B shl 16);
Inc(G, SP[I].G shl 16);
Inc(R, SP[I].R shl 16);
end;
XD := XDA[X + 1];
if XD <> 0 then
begin
Inc(B, SP[SX].B * XD);
Inc(G, SP[SX].G * XD);
Inc(R, SP[SX].R * XD);
end;
XD := $10000 - XD;
DP[X].B := (B + HDX) div DX;
DP[X].G := (G + HDX) div DX;
DP[X].R := (R + HDX) div DX;
end;
ProgressProcCaller((100 * Y) div ((Dst.Height - 1) * 2), PProc);
end;
finally
FreeMem(XDA);
FreeMem(SXA);
end;
end;
procedure VAO(const Src, Dst: TBitmap; const PProc: TProgressProc);
var
X, Y: Integer;
DP, SP: PRGBColorArray;
Z: Extended;
I, DY, HDY, YD, SY: Integer;
B, G, R: PIntArray;
begin
ProgressProcCaller(50, PProc);
try
GetMem(B, SizeOf(Integer) * Src.Width);
except
on EOutOfMemory do Exit;
end;
try
GetMem(G, SizeOf(Integer) * Src.Width);
except
on EOutOfMemory do
begin
FreeMem(B);
Exit;
end;
end;
try
GetMem(R, SizeOf(Integer) * Src.Width);
except
on EOutOfMemory do
begin
FreeMem(G);
FreeMem(B);
Exit;
end;
end;
try
YD := $10000;
SY := 0;
SP := Src.ScanLine[SY];
DY := Trunc(Src.Height * $10000 / Dst.Height + 0.5);
HDY := (DY + 1) div 2;
for Y := 0 to Dst.Height - 1 do
begin
for X := 0 to Dst.Width - 1 do
begin
B[X] := 0;
G[X] := 0;
R[X] := 0;
end;
if YD <> 0 then
begin
for X := 0 to Dst.Width - 1 do
begin
Inc(B[X], SP[X].B * YD);
Inc(G[X], SP[X].G * YD);
Inc(R[X], SP[X].R * YD);
end;
end;
I := SY;
Z := (Y + 1) * Src.Height / Dst.Height;
SY := Trunc(Z);
for I := I + 1 to SY - 1 do
begin
SP := Src.ScanLine[I];
for X := 0 to Dst.Width - 1 do
begin
Inc(B[X], SP[X].B shl 16);
Inc(G[X], SP[X].G shl 16);
Inc(R[X], SP[X].R shl 16);
end;
end;
YD := Trunc(Frac(Z) * $10000);
if Y <> Dst.Height - 1 then
begin
SP := Src.ScanLine[SY];
if YD <> 0 then
begin
for X := 0 to Dst.Width - 1 do
begin
Inc(B[X], SP[X].B * YD);
Inc(G[X], SP[X].G * YD);
Inc(R[X], SP[X].R * YD);
end;
end;
end;
DP := Dst.ScanLine[Y];
for X := 0 to Dst.Width - 1 do
begin
DP[X].B := (B[X] + HDY) div DY;
DP[X].G := (G[X] + HDY) div DY;
DP[X].R := (R[X] + HDY) div DY;
end;
YD := $10000 - YD;
ProgressProcCaller(50 + (100 * Y) div ((Dst.Height - 1) * 2), PProc);
end;
finally
FreeMem(R);
FreeMem(G);
FreeMem(B);
end;
end;
procedure Stretch(const Src: TBitmap; Width, Height: Integer; const PProc: TProgressProc);
var
Dst: TBitmap;
begin
if (Src = nil) or Src.Empty then Exit;
if Src.PixelFormat <> pf24bit then
begin
Src.PixelFormat := pf24bit;
Src.ReleasePalette;
end;
Dst := TBitmap.Create;
try
if Src.Width <> Width then
begin
Dst.Assign(Src);
Dst.Width := Width;
if Width > Src.Width then HLI3(Src, Dst, PProc)
else HAO(Src, Dst, PProc);
Src.Assign(Dst);
end;
if Src.Height <> Height then
begin
Dst.Assign(Src);
Dst.Height := Height;
if Height > Src.Height then VLI3(Src, Dst, PProc)
else VAO(Src, Dst, PProc);
Src.Assign(Dst);
end;
finally
Dst.Free;
end;
end;
end.
|
unit FAskForLabel;
(*====================================================================
Dialog for disk name, under which the disk will be put into the database.
======================================================================*)
interface
uses
SysUtils,
{$ifdef mswindows}
Windows,
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls,
UTypes;
type
TFormAskForLabel = class(TForm)
EditDiskName: TEdit;
ButtonOK: TButton;
ButtonCancel: TButton;
Label1: TLabel;
ButtonUseGenerated: TButton;
LabelGenerated: TLabel;
procedure ButtonOKClick(Sender: TObject);
procedure ButtonCancelClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ButtonUseGeneratedClick(Sender: TObject);
private
{ Private declarations }
public
GeneratedName: ShortString;
GeneratedNameUsed: boolean;
procedure DefaultHandler(var Message); override;
end;
var
FormAskForLabel: TFormAskForLabel;
implementation
uses ULang, FSettings;
{$R *.dfm}
//-----------------------------------------------------------------------------
procedure TFormAskForLabel.ButtonOKClick(Sender: TObject);
begin
ModalResult := mrOK;
end;
//-----------------------------------------------------------------------------
procedure TFormAskForLabel.ButtonCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
//-----------------------------------------------------------------------------
procedure TFormAskForLabel.FormShow(Sender: TObject);
begin
ActiveControl := EditDiskName;
EditDiskName.SelectAll;
GeneratedNameUsed := false;
if GeneratedName <> ''
then
begin
ButtonUseGenerated.Visible := true;
LabelGenerated.Visible := true;
LabelGenerated.Caption := lsGenerated + GeneratedName;
end
else
begin
ButtonUseGenerated.Visible := false;
LabelGenerated.Visible := false;
end;
end;
//-----------------------------------------------------------------------------
procedure TFormAskForLabel.ButtonUseGeneratedClick(Sender: TObject);
begin
EditDiskName.Text := GeneratedName;
GeneratedNameUsed := true;
end;
//-----------------------------------------------------------------------------
// Disables CD AutoRun feature - Windows send the message QueryCancelAutoPlay
// to the top window, so we must have this handler in all forms.
procedure TFormAskForLabel.DefaultHandler(var Message);
begin
with TMessage(Message) do
if (Msg = g_CommonOptions.dwQueryCancelAutoPlay) and
g_CommonOptions.bDisableCdAutorun
then
Result := 1
else
inherited DefaultHandler(Message)
end;
//-----------------------------------------------------------------------------
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2011 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of Delphi, C++Builder or RAD Studio (Embarcadero Products).
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit CustomizedDSRESTCreatorsUnit;
interface
uses
System.SysUtils, System.Classes, DSRESTExpertsCreators,
DSServerWebBrokerExpertsCreators, ExpertsTemplates, ExpertsProject,
ExpertsModules, DSServerExpertsCreators, DSServerMethodsExpertsCreators;
type
TCustomizedDSRESTCreatorsModule = class(TDSRESTExpertsCreatorsModule)
private
FComments: string;
FAddFiles: TArray<string>;
function FormatComments(const AText: string): string;
procedure SetComments(const Value: string);
protected
function GetServerMethodsCreatorModuleClass: TDSServerMethodsCreatorModuleClass; override;
procedure UpdateProperties; override;
procedure AddFiles(const APersonality: string); override;
{ Private declarations }
public
{ Public declarations }
property Comments: string read FComments write SetComments;
property FilesToAdd: TArray<string> read FAddFiles write FAddFiles;
end;
var
CustomizedDSRESTCreatorsModule: TCustomizedDSRESTCreatorsModule;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
{$R *.dfm}
uses CustomizedServerMethodsCreatorUnit, CustomizedFeatures, DSServerScriptGen,
Windows, ToolsAPI;
procedure TCustomizedDSRESTCreatorsModule.SetComments(const Value: string);
begin
FComments := Value;
UpdateProperties;
end;
procedure TCustomizedDSRESTCreatorsModule.AddFiles(const APersonality: string);
var
S: string;
LProject: IOTAProject;
LPath: string;
LDestination: string;
begin
inherited;
LProject := GetActiveProject;
LPath := ExtractFilePath(LProject.FileName);
LPath := LPath + 'addedfiles\';
// Add files without opening in the project
// Assumes files are not units
for S in FAddFiles do
begin
LDestination := LPath + ExtractFileName(S);
ForceDirectories(LPath);
if CopyFile(PChar(S), PChar(LDestination), True) then
begin
// Add as if not a unit
LProject.AddFile(LDestination,
False); // Not a unit
end;
end;
end;
function TCustomizedDSRESTCreatorsModule.FormatComments(const AText: string): string;
var
LResult: TStrings;
LLines: TStrings;
S: string;
begin
LLines := TStringList.Create;
try
LLines.Text := AText;
LResult := TStringList.Create;
try
for S in LLines do
LResult.Add('//' + S);
Result := LResult.Text;
finally
LResult.Free;
end;
finally
LLines.Free;
end;
end;
function TCustomizedDSRESTCreatorsModule.GetServerMethodsCreatorModuleClass: TDSServerMethodsCreatorModuleClass;
begin
Result := TCustomizedServerMethodsCreator;
end;
procedure TCustomizedDSRESTCreatorsModule.UpdateProperties;
var
LNow: TDateTime;
begin
inherited;
// Customization: Set properties used in templates
SetBoolTemplateProperty(sCustomFeatureCommentModule, IsFeatureEnabled(cCustomFeatureCommentModule));
SetBoolTemplateProperty(sCustomFeatureTimeStamp, IsFeatureEnabled(cCustomFeatureTimeStampModule));
SetBoolTemplateProperty(sCustomSampleMethods, IsFeatureEnabled(cCustomFeatureSampleMethods));
CommonTemplateProperties.Properties.Values[sCommentModuleText] := FormatComments(FComments);
LNow := Now;
CommonTemplateProperties.Properties.Values[sTimeStampText] :=
FormatDateTime(FormatSettings.ShortDateFormat, LNow) + ' ' + FormatDateTime(FormatSettings.LongTimeFormat, LNow);
end;
end.
|
{ *
* Copyright (C) 2014-2015 ozok <ozok26@gmail.com>
*
* This file is part of InstagramSaver.
*
* InstagramSaver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* InstagramSaver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with InstagramSaver. If not, see <http://www.gnu.org/licenses/>.
*
* }
unit UnitSettings;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, sSkinProvider, Vcl.StdCtrls, sButton,
sCheckBox, IniFiles, sComboBox, sEdit, sSpinEdit;
type
TSettingsForm = class(TForm)
sSkinProvider1: TsSkinProvider;
CheckUpdateBtn: TsCheckBox;
OpenOutBtn: TsCheckBox;
sButton1: TsButton;
DontDoubleDownloadBtn: TsCheckBox;
DownloadVideoBtn: TsCheckBox;
SkinList: TsComboBox;
ThreadList: TsComboBox;
DontCheckBtn: TsCheckBox;
WaitEdit: TsSpinEdit;
procedure sButton1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure SkinListChange(Sender: TObject);
private
{ Private declarations }
procedure LoadSettings;
procedure SaveSettings;
public
{ Public declarations }
end;
var
SettingsForm: TSettingsForm;
implementation
{$R *.dfm}
uses UnitMain;
procedure TSettingsForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
SaveSettings;
MainForm.Enabled := True;
MainForm.BringToFront;
end;
procedure TSettingsForm.FormCreate(Sender: TObject);
begin
WaitEdit.MinValue := 0;
WaitEdit.MaxValue := MaxInt;
LoadSettings;
end;
procedure TSettingsForm.LoadSettings;
var
LSetFile: TIniFile;
begin
LSetFile := TIniFile.Create(MainForm.FAppDataFolder + 'settings.ini');
try
with LSetFile do
begin
CheckUpdateBtn.Checked := ReadBool('general', 'update', True);
OpenOutBtn.Checked := ReadBool('general', 'openout', True);
DontDoubleDownloadBtn.Checked := ReadBool('general', 'nodouble', True);
DownloadVideoBtn.Checked := ReadBool('general', 'video', False);
SkinList.ItemIndex := ReadInteger('general', 'skin', 0);
if CPUCount > 16 then
begin
ThreadList.ItemIndex := ReadInteger('general', 'thread', 15);
end
else
begin
ThreadList.ItemIndex := ReadInteger('general', 'thread', CPUCount-1);
end;
DontCheckBtn.Checked := ReadBool('general', 'check', False);
WaitEdit.Text := ReadString('general', 'wait', '0');
end;
finally
LSetFile.Free;
end;
end;
procedure TSettingsForm.SaveSettings;
var
LSetFile: TIniFile;
begin
LSetFile := TIniFile.Create(MainForm.FAppDataFolder + 'settings.ini');
try
with LSetFile do
begin
WriteBool('general', 'update', CheckUpdateBtn.Checked);
WriteBool('general', 'openout', OpenOutBtn.Checked);
WriteBool('general', 'nodouble', DontDoubleDownloadBtn.Checked);
WriteBool('general', 'video', DownloadVideoBtn.Checked);
WriteInteger('general', 'skin', SkinList.ItemIndex);
WriteInteger('general', 'thread', ThreadList.ItemIndex);
WriteBool('general', 'check', DontCheckBtn.Checked);
WriteString('general', 'wait', WaitEdit.Text);
end;
finally
LSetFile.Free;
SkinListChange(Self);
end;
end;
procedure TSettingsForm.sButton1Click(Sender: TObject);
begin
Close;
end;
procedure TSettingsForm.SkinListChange(Sender: TObject);
begin
case SkinList.ItemIndex of
0:
begin
MainForm.sSkinManager1.Active := True;
MainForm.sSkinManager1.SkinName := 'DarkMetro (internal)';
end;
1:
begin
MainForm.sSkinManager1.Active := True;
MainForm.sSkinManager1.SkinName := 'AlterMetro (internal)';
end;
2:
begin
MainForm.sSkinManager1.Active := False;
end;
end;
end;
end.
|
unit dt_address_FORM_ADD;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Mask, Variants,
cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit,
cxLookAndFeelPainters, cxButtons, GlobalSPR, ExtCtrls;
type
TFdt_address_form_add = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
LabelZip: TLabel;
CountryEdit: TcxButtonEdit;
RegionEdit: TcxButtonEdit;
PlaceEdit: TcxButtonEdit;
DistrictEdit: TcxButtonEdit;
TypeStreetEdit: TcxButtonEdit;
StreetEdit: TcxTextEdit;
KorpusEdit: TcxTextEdit;
HouseEdit: TcxTextEdit;
FlatEdit: TcxTextEdit;
ZipEdit: TcxTextEdit;
OKButton: TcxButton;
CancelButton: TcxButton;
Bevel1: TBevel;
procedure CancelButtonClick(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure FullNameEditKeyPress(Sender: TObject; var Key: Char);
procedure CountryEditButtonClick(Sender: TObject;
AbsoluteIndex: Integer);
procedure PlaceEditButtonClick(Sender: TObject;
AbsoluteIndex: Integer);
procedure DistrictEditButtonClick(Sender: TObject;
AbsoluteIndex: Integer);
procedure TypeStreetEditButtonClick(Sender: TObject;
AbsoluteIndex: Integer);
procedure FormCreate(Sender: TObject);
procedure RegionEditButtonClick(Sender: TObject;
AbsoluteIndex: Integer);
procedure ZipEditKeyPress(Sender: TObject; var Key: Char);
public
id_country : integer;
id_place : integer;
id_district : integer;
id_type_street : integer;
id_region : integer;
id_type_region : integer;
id_type_place : integer;
end;
implementation
uses BaseTypes, dt_address_FORM;
{$R *.DFM}
procedure TFdt_address_form_add.CancelButtonClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TFdt_address_form_add.OKButtonClick(Sender: TObject);
begin
if not isInteger(ZipEdit.Text) then begin
agShowMessage('Необходимо ввести индекс');
exit;
end;
ModalResult := mrOK;
end;
procedure TFdt_address_form_add.FullNameEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
Key := #0;
OKButton.SetFocus;
end;
end;
procedure TFdt_address_form_add.CountryEditButtonClick(Sender: TObject;
AbsoluteIndex: Integer);
var
id:variant;
begin
id:=GlobalSPR.GetCountries(self.Owner, TFdt_address(self.Owner).WorkDatabase.Handle,fsnormal, TFdt_address(self.Owner).ActualDate);
if VarArrayDimCount(id)>0
then begin
if id[0]<>NULL
then begin
id_country := id[0];
CountryEdit.Text := id[1];
end;
end;
end;
procedure TFdt_address_form_add.PlaceEditButtonClick(Sender: TObject;
AbsoluteIndex: Integer);
var
id:variant;
begin
id:=GlobalSPR.GetPlaces(self.Owner, TFdt_address(self.Owner).WorkDatabase.Handle,fsnormal, TFdt_address(self.Owner).ActualDate);
if VarArrayDimCount(id)>0
then begin
if id[0]<>NULL
then begin
id_place := id[0];
PlaceEdit.Text:=id[1];
id_type_place:=id[2];
end;
end;
end;
procedure TFdt_address_form_add.DistrictEditButtonClick(Sender: TObject;
AbsoluteIndex: Integer);
var
id:variant;
begin
id:=GlobalSPR.GetDistincts(self.Owner, TFdt_address(self.Owner).WorkDatabase.Handle,fsnormal, TFdt_address(self.Owner).ActualDate);
if VarArrayDimCount(id)>0
then begin
if id[0]<>NULL
then begin
id_district := id[0];
DistrictEdit.Text:=id[1];
end;
end;
end;
procedure TFdt_address_form_add.TypeStreetEditButtonClick(Sender: TObject;
AbsoluteIndex: Integer);
var
id:variant;
begin
id:=GlobalSPR.GetIniTypeStreet(self.Owner, TFdt_address(self.Owner).WorkDatabase.Handle,fsnormal, TFdt_address(self.Owner).ActualDate);
if VarArrayDimCount(id)>0
then begin
if id[0]<>NULL
then begin
id_type_street := id[0];
TypeStreetEdit.Text:=id[1];
end;
end;
end;
procedure TFdt_address_form_add.FormCreate(Sender: TObject);
begin
id_country := -1;
id_place := -1;
id_district := -1;
id_type_street := -1;
end;
procedure TFdt_address_form_add.RegionEditButtonClick(Sender: TObject;
AbsoluteIndex: Integer);
var
id:variant;
begin
id:=GlobalSPR.GetRegions(self.Owner, TFdt_address(self.Owner).WorkDatabase.Handle,fsnormal, TFdt_address(self.Owner).ActualDate);
if VarArrayDimCount(id)>0
then begin
if id[0]<>NULL
then begin
id_region := id[0];
RegionEdit.Text:=id[1];
id_type_region:=id[2]
end;
end;
end;
procedure TFdt_address_form_add.ZipEditKeyPress(Sender: TObject;
var Key: Char);
begin
CheckInteger(Key);
end;
end.
|
unit uNewBeginningBalance;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, StrUtils,
uNewUnit, uTSBaseClass, uConstanta, uNewPOS, uNewShift;
type
TBeginningBalance = class(TSBaseClass)
private
FDATE_CREATE: TDateTime;
FDATE_MODIFY: TDateTime;
FDescription: String;
FID: string;
FKasirID: string;
// FKasirUnitID: Integer;
FModal: Double;
FNewUnit: TUnit;
FNewUnitID: string;
// FOPC_UNIT: TUnit;
// FOPC_UNITID: Integer;
// FOPM_UNIT: TUnit;
// FOPM_UNITID: Integer;
FOP_CREATE: string;
FOP_MODIFY: string;
FPOS: TPOS;
FPOSID: string;
FShift: TNewShift;
FShiftDate: TDateTime;
FShiftID: string;
FStatus: string;
function FLoadFromDB( aSQL : String ): Boolean;
function GetNewUnit: TUnit;
// function GetOPC_UNIT: TUnit;
// function GetOPM_UNIT: TUnit;
function GetPOS: TPOS;
function GetShift: TNewShift;
procedure SetNewUnit(Value: TUnit);
// procedure SetOPC_UNIT(Value: TUnit);
// procedure SetOPM_UNIT(Value: TUnit);
procedure SetPOS(Value: TPOS);
procedure SetShift(Value: TNewShift);
public
constructor Create(AOwner : TComponent); override;
constructor CreateWithUser(AOwner: TComponent; AUserID: string);
destructor Destroy; override;
procedure ClearProperties;
function CustomSQLTask: Tstrings;
function CustomSQLTaskPrior: Tstrings;
function CustomTableName: string;
function GenerateInterbaseMetaData: TStrings;
function GenerateSQL(ARepeatCount: Integer = 1): TStrings;
function GetFieldNameFor_DATE_CREATE: string; dynamic;
function GetFieldNameFor_DATE_MODIFY: string; dynamic;
function GetFieldNameFor_Description: string; dynamic;
function GetFieldNameFor_ID: string; dynamic;
function GetFieldNameFor_KasirID: string; dynamic;
// function GetFieldNameFor_KasirUnitID: string; dynamic;
function GetFieldNameFor_Modal: string; dynamic;
function GetFieldNameFor_NewUnit: string; dynamic;
// function GetFieldNameFor_OPC_UNIT: string; dynamic;
// function GetFieldNameFor_OPM_UNIT: string; dynamic;
function GetFieldNameFor_OP_CREATE: string; dynamic;
function GetFieldNameFor_OP_MODIFY: string; dynamic;
function GetFieldNameFor_POS: string; dynamic;
// function GetFieldNameFor_POSUnit: string; dynamic;
function GetFieldNameFor_Shift: string; dynamic;
function GetFieldNameFor_ShiftDate: string; dynamic;
// function GetFieldNameFor_ShiftUnit: string; dynamic;
function GetFieldNameFor_Status: string; dynamic;
function GetFieldPrefix: string; dynamic;
function GetGeneratorName: string; dynamic;
function GetHeaderFlag: Integer;
function GetPlannedID: string;
function IsKasirIniSudahDisettingBBnya: Boolean;
function IsKasirIniSudahDiShiftLain: Boolean;
function IsPOSIniSudahDisettingBBnya: Boolean;
function LoadByID(AID, AUnitID: string): Boolean;
function RemoveFromDB: Boolean;
function SaveToDB: Boolean;
procedure UpdateData(ANewUnitID, ADescription, AID, AKasirID: string; AModal:
Double; APOS_ID, AShift_ID: string; AShiftDate: TDateTime; AStatus: string);
procedure UpdateStatus(AStatus: String);
function UpdateStatusAndSaveToDB(AStatus: String): Boolean;
property DATE_CREATE: TDateTime read FDATE_CREATE write FDATE_CREATE;
property DATE_MODIFY: TDateTime read FDATE_MODIFY write FDATE_MODIFY;
property Description: String read FDescription write FDescription;
property ID: string read FID write FID;
property KasirID: string read FKasirID write FKasirID;
// property KasirUnitID: Integer read FKasirUnitID write FKasirUnitID;
property Modal: Double read FModal write FModal;
property NewUnit: TUnit read GetNewUnit write SetNewUnit;
// property OPC_UNIT: TUnit read GetOPC_UNIT write SetOPC_UNIT;
// property OPM_UNIT: TUnit read GetOPM_UNIT write SetOPM_UNIT;
property OP_CREATE: string read FOP_CREATE write FOP_CREATE;
property OP_MODIFY: string read FOP_MODIFY write FOP_MODIFY;
property POS: TPOS read GetPOS write SetPOS;
property Shift: TNewShift read GetShift write SetShift;
property ShiftDate: TDateTime read FShiftDate write FShiftDate;
property Status: string read FStatus write FStatus;
end;
implementation
uses udmMain, uAppUtils;
{
****************************** TBeginningBalance *******************************
}
constructor TBeginningBalance.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
end;
constructor TBeginningBalance.CreateWithUser(AOwner: TComponent; AUserID:
string);
begin
Create(AOwner);
OP_MODIFY := AUserID;
// FOPM_UNITID := AUnitID;
end;
destructor TBeginningBalance.Destroy;
begin
ClearProperties;
inherited Destroy;
end;
procedure TBeginningBalance.ClearProperties;
begin
Status := '';
Description := '';
OP_MODIFY := '';
OP_CREATE := '';
Modal := 0;
// KasirUnitID := 0;
KasirID := '';
ID := '';
FreeAndNil(FNewUnit);
// FreeAndNil(FOPC_UNIT);
// FreeAndNil(FOPM_UNIT);
FreeAndNil(FPOS);
FreeAndNil(FShift);
end;
function TBeginningBalance.CustomSQLTask: Tstrings;
begin
result := nil;
end;
function TBeginningBalance.CustomSQLTaskPrior: Tstrings;
begin
result := nil;
end;
function TBeginningBalance.CustomTableName: string;
begin
result := 'BEGINNING_BALANCE';
end;
function TBeginningBalance.FLoadFromDB( aSQL : String ): Boolean;
begin
Result := False;
State := csNone;
ClearProperties;
with cOpenQuery(aSQL) do
begin
try
if not EOF then
begin
FDATE_CREATE := FieldByName(GetFieldNameFor_DATE_CREATE).AsDateTime;
FDATE_MODIFY := FieldByName(GetFieldNameFor_DATE_MODIFY).AsDateTime;
FDescription := FieldByName(GetFieldNameFor_Description).AsString;
FID := FieldByName(GetFieldNameFor_ID).AsString;
FKasirID := FieldByName(GetFieldNameFor_KasirID).AsString;
// FKasirUnitID := FieldByName(GetFieldNameFor_KasirUnitID).AsInteger;
FModal := FieldByName(GetFieldNameFor_Modal).AsFloat;
FNewUnitID := FieldByName(GetFieldNameFor_NewUnit).AsString;
// FOPC_UNITID := FieldByName(GetFieldNameFor_OPC_UNIT).AsInteger;
// FOPM_UNITID := FieldByName(GetFieldNameFor_OPM_UNIT).AsInteger;
FOP_CREATE := FieldByName(GetFieldNameFor_OP_CREATE).AsString;
FOP_MODIFY := FieldByName(GetFieldNameFor_OP_MODIFY).AsString;
FPOSID := FieldByName(GetFieldNameFor_POS).AsString;
FShiftID := FieldByName(GetFieldNameFor_Shift).AsString;
FShiftDate := FieldByName(GetFieldNameFor_ShiftDate).AsDateTime;
FStatus := FieldByName(GetFieldNameFor_Status).AsString;
Self.State := csLoaded;
Result := True;
end;
finally
Free;
end;
End;
end;
function TBeginningBalance.GenerateInterbaseMetaData: TStrings;
begin
Result := TStringList.Create;
Result.Append( '' );
Result.Append( 'Create Table ''+ CustomTableName +'' ( ' );
Result.Append( 'TRMSBaseClass_ID Integer not null, ' );
Result.Append( 'DATE_CREATE Date Not Null , ' );
Result.Append( 'DATE_MODIFY Date Not Null , ' );
Result.Append( 'Description Date Not Null , ' );
Result.Append( 'ID Integer Not Null Unique, ' );
Result.Append( 'KasirID Integer Not Null , ' );
Result.Append( 'KasirUnitID Integer Not Null , ' );
Result.Append( 'Modal double precision Not Null , ' );
Result.Append( 'NewUnit_ID Integer Not Null, ' );
Result.Append( 'OPC_UNIT_ID Integer Not Null, ' );
Result.Append( 'OPM_UNIT_ID Integer Not Null, ' );
Result.Append( 'OP_CREATE Integer Not Null , ' );
Result.Append( 'OP_MODIFY Integer Not Null , ' );
Result.Append( 'POS_ID Integer Not Null, ' );
Result.Append( 'Shift_ID Integer Not Null, ' );
Result.Append( 'ShiftDate Date Not Null , ' );
Result.Append( 'Status Varchar(30) Not Null , ' );
Result.Append( 'Stamp TimeStamp ' );
Result.Append( ' ); ' );
end;
function TBeginningBalance.GenerateSQL(ARepeatCount: Integer = 1): TStrings;
var
sSQL: string;
//i: Integer;
ssSQL: TStrings;
begin
// DecimalSeparator := '.';
Result := TStringList.Create;
if State = csNone then
begin
raise Exception.create('Tidak bisa generate dalam Mode csNone')
end;
ssSQL := CustomSQLTaskPrior;
if ssSQL <> nil then
begin
Result.AddStrings(ssSQL);
end;
ssSQL := nil;
DATE_MODIFY := cGetServerDateTime;
// FOPM_UNITID := FNewUnitID;
// If FID <= 0 then
If FID = '' then
begin
//Generate Insert SQL
OP_CREATE := OP_MODIFY;
DATE_CREATE := DATE_MODIFY;
// FOPC_UNITID := FOPM_UNITID;
// FID := cGetNextID(GetFieldNameFor_ID, CustomTableName);
FID := cGetNextIDGUIDToString;
sSQL := 'insert into ' + CustomTableName + ' ('
+ GetFieldNameFor_DATE_CREATE + ', '
+ GetFieldNameFor_DATE_MODIFY + ', '
+ GetFieldNameFor_Description + ', '
+ GetFieldNameFor_ID + ', '
+ GetFieldNameFor_KasirID + ', '
// + GetFieldNameFor_KasirUnitID + ', '
+ GetFieldNameFor_Modal + ', '
+ GetFieldNameFor_NewUnit + ', '
// + GetFieldNameFor_OPC_UNIT + ', '
// + GetFieldNameFor_OPM_UNIT + ', '
+ GetFieldNameFor_OP_CREATE + ', '
+ GetFieldNameFor_OP_MODIFY + ', '
+ GetFieldNameFor_POS + ', '
// + GetFieldNameFor_POSUnit + ', '
+ GetFieldNameFor_Shift + ', '
// + GetFieldNameFor_ShiftUnit + ', '
+ GetFieldNameFor_ShiftDate + ', '
+ GetFieldNameFor_Status +') values ('
+ TAppUtils.QuotDT(FDATE_CREATE) + ', '
+ TAppUtils.QuotDT(FDATE_MODIFY) + ', '
+ QuotedStr(FDescription) + ', '
+ QuotedStr(FID) + ', '
+ QuotedStr(FKasirID) + ', '
// + IntToStr(FKasirUnitID) + ', '
+ FormatFloat('0.00', FModal) + ', '
+ QuotedStr(FNewUnitID) + ', '
// + InttoStr(FOPC_UNITID) + ', '
// + InttoStr(FOPM_UNITID) + ', '
+ QuotedStr(FOP_CREATE) + ', '
+ QuotedStr(FOP_MODIFY) + ', '
+ QuotedStr(FPOSID) + ', '
// + QuotedStr(FNewUnitID) + ', '
+ QuotedStr(FShiftID) + ', '
// + QuotedStr(FNewUnitID) + ', '
+ TAppUtils.QuotDT(FShiftDate) + ', '
+ QuotedStr(FStatus) + ');'
end
else
begin
//generate Update SQL
sSQL := 'update ' + CustomTableName + ' set '
+ GetFieldNameFor_DATE_MODIFY + ' = ' + TAppUtils.QuotDT(FDATE_MODIFY)
+ ', ' + GetFieldNameFor_Description + ' = ' + QuotedStr(FDescription)
+ ', ' + GetFieldNameFor_KasirID + ' = ' + QuotedStr(FKasirID)
// + ', ' + GetFieldNameFor_KasirUnitID + ' = ' + IntToStr(FKasirUnitID)
+ ', ' + GetFieldNameFor_Modal + ' = ' + FormatFloat('0.00', FModal)
+ ', ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(FNewUnitID)
// + ', ' + GetFieldNameFor_OPM_UNIT + ' = ' + IntToStr(FOPM_UNITID)
+ ', ' + GetFieldNameFor_OP_MODIFY + ' = ' + QuotedStr(FOP_MODIFY)
+ ', ' + GetFieldNameFor_POS + ' = ' + QuotedStr(FPOSID)
+ ', ' + GetFieldNameFor_Shift + ' = ' + QuotedStr(FShiftID)
+ ', ' + GetFieldNameFor_ShiftDate + ' = ' + TAppUtils.QuotDT(FShiftDate)
+ ', ' + GetFieldNameFor_Status + ' = ' + QuotedStr(FStatus)
+ ' where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(FID)
+ ' and ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(FNewUnitID) + ';';
end;
Result.Append(sSQL);
//generating Collections SQL
ssSQL := CustomSQLTask;
if ssSQL <> nil then
begin
Result.AddStrings(ssSQL);
end;
FreeAndNil(ssSQL)
end;
function TBeginningBalance.GetFieldNameFor_DATE_CREATE: string;
begin
Result := 'DATE_CREATE';
end;
function TBeginningBalance.GetFieldNameFor_DATE_MODIFY: string;
begin
Result := 'DATE_MODIFY';
end;
function TBeginningBalance.GetFieldNameFor_Description: string;
begin
Result := GetFieldPrefix + 'Description';
end;
function TBeginningBalance.GetFieldNameFor_ID: string;
begin
// Result := GetFieldPrefix + 'ID';
Result := 'BEGINNING_BALANCE_ID';
end;
function TBeginningBalance.GetFieldNameFor_KasirID: string;
begin
// Result := GetFieldPrefix + 'USR_ID';
Result := 'AUT$USER_ID';
end;
//function TBeginningBalance.GetFieldNameFor_KasirUnitID: string;
//begin
// Result := GetFieldPrefix + 'USR_UNT_ID';
//end;
function TBeginningBalance.GetFieldNameFor_Modal: string;
begin
Result := GetFieldPrefix + 'Modal';
end;
function TBeginningBalance.GetFieldNameFor_NewUnit: string;
begin
// Result := GetFieldPrefix + 'UNT_ID';
Result := 'AUT$UNIT_ID';
end;
//function TBeginningBalance.GetFieldNameFor_OPC_UNIT: string;
//begin
// Result := 'OPC_UNIT';
//end;
//function TBeginningBalance.GetFieldNameFor_OPM_UNIT: string;
//begin
// Result := 'OPM_UNIT';
//end;
function TBeginningBalance.GetFieldNameFor_OP_CREATE: string;
begin
Result := 'OP_CREATE';
end;
function TBeginningBalance.GetFieldNameFor_OP_MODIFY: string;
begin
Result := 'OP_MODIFY';
end;
function TBeginningBalance.GetFieldNameFor_POS: string;
begin
// Result := GetFieldPrefix + 'SETUPPOS_ID';
Result := 'SETUPPOS_ID';
end;
//function TBeginningBalance.GetFieldNameFor_POSUnit: string;
//begin
// Result := GetFieldPrefix + 'SETUPPOS_UNT_ID';
//end;
function TBeginningBalance.GetFieldNameFor_Shift: string;
begin
// Result := GetFieldPrefix + 'Shift_ID';
Result := 'SHIFT_ID';
end;
function TBeginningBalance.GetFieldNameFor_ShiftDate: string;
begin
Result := GetFieldPrefix + 'Shift_Date';
end;
//function TBeginningBalance.GetFieldNameFor_ShiftUnit: string;
//begin
// Result := GetFieldPrefix + 'Shift_UNT_ID';
//end;
function TBeginningBalance.GetFieldNameFor_Status: string;
begin
Result := GetFieldPrefix + 'Status';
end;
function TBeginningBalance.GetFieldPrefix: string;
begin
Result := 'BALANCE_';
end;
function TBeginningBalance.GetGeneratorName: string;
begin
Result := 'GEN_' + CustomTableName + '_ID';
end;
function TBeginningBalance.GetHeaderFlag: Integer;
begin
result := 4705;
end;
function TBeginningBalance.GetNewUnit: TUnit;
begin
//Result := nil;
if FNewUnit = nil then
begin
FNewUnit := TUnit.Create(Self);
FNewUnit.LoadByID(FNewUnitID);
end;
Result := FNewUnit;
end;
//function TBeginningBalance.GetOPC_UNIT: TUnit;
//begin
// //Result := nil;
// if FOPC_UNIT = nil then
// begin
// FOPC_UNIT := TUnit.Create(Self);
// FOPC_UNIT.LoadByID(FOPC_UNITID);
// end;
// Result := FOPC_UNIT;
//end;
//function TBeginningBalance.GetOPM_UNIT: TUnit;
//begin
// //Result := nil;
// if FOPM_UNIT = nil then
// begin
// FOPM_UNIT := TUnit.Create(Self);
// FOPM_UNIT.LoadByID(FOPM_UNITID);
// end;
// Result := FOPM_UNIT;
//end;
function TBeginningBalance.GetPlannedID: string;
begin
// result := -1;
Result := '';
if State = csNone then
begin
Raise exception.create('Tidak bisa GetPlannedID di Mode csNone');
exit;
end
else if state = csCreated then
begin
// Result := cGetNextID(GetFieldNameFor_ID, CustomTableName);
Result := cGetNextIDGUIDToString;
end
else if State = csLoaded then
begin
Result := FID;
end;
end;
function TBeginningBalance.GetPOS: TPOS;
begin
//Result := nil;
if FPOS = nil then
begin
FPOS := TPOS.Create(Self);
FPOS.LoadByID(FPOSID,FNewUnitID);
end;
Result := FPOS;
end;
function TBeginningBalance.GetShift: TNewShift;
begin
//Result := nil;
if FShift = nil then
begin
FShift := TNewShift.Create(Self);
FShift.LoadByID(FShiftID);
end;
Result := FShift;
end;
function TBeginningBalance.IsKasirIniSudahDisettingBBnya: Boolean;
var
sSQL: string;
begin
Result := False;
sSQL := 'select count(1)'
+ ' from ' + CustomTableName
// + ' where balance_unt_id = ' + IntToStr(FNewUnitID)
+ ' where ' + GetFieldNameFor_KasirID + ' = ' + QuotedStr(FKasirID)
+ ' and ' + GetFieldNameFor_Shift + ' = '+ QuotedStr(FShiftID)
+ ' AND BALANCE_SHIFT_DATE = ' + TAppUtils.Quotd(ShiftDate);
with cOpenQuery(sSQL) do
begin
try
if Fields[0].AsInteger > 0 then
Result := True;
finally
Free;
end;
end;
end;
function TBeginningBalance.IsKasirIniSudahDiShiftLain: Boolean;
var
sSQL: string;
begin
Result := False;
sSQL := 'select count(1)'
+ ' from ' + CustomTableName
// + ' where balance_unt_id = ' + IntToStr(FNewUnitID)
+ ' where ' + GetFieldNameFor_KasirID + ' = ' + QuotedStr(FKasirID)
+ ' AND BALANCE_SHIFT_DATE = ' + TAppUtils.Quotd(ShiftDate);
with cOpenQuery(sSQL) do
begin
try
if Fields[0].AsInteger > 0 then
Result := True;
finally
Free;
end;
end;
end;
function TBeginningBalance.IsPOSIniSudahDisettingBBnya: Boolean;
var
sSQL: string;
begin
Result := False;
sSQL := 'select count(1)'
+ ' from ' + CustomTableName
// + ' where balance_unt_id = ' + IntToStr(FNewUnitID)
+ ' where ' + GetFieldNameFor_POS + ' = ' + QuotedStr(FPOSID)
+ ' and ' + GetFieldNameFor_Shift + ' = '+ QuotedStr(FShiftID)
+ ' AND BALANCE_SHIFT_DATE = ' + TAppUtils.Quotd(ShiftDate);
with cOpenQuery(sSQL) do
begin
try
if Fields[0].AsInteger > 0 then
Result := True;
finally
Free;
end;
end;
end;
function TBeginningBalance.LoadByID(AID, AUnitID: string): Boolean;
var
sSQL: string;
begin
sSQL := 'select * from ' + CustomTableName
+ ' where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(AID)
+ ' and ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(AUnitID);
Result := FloadFromDB(sSQL);
end;
function TBeginningBalance.RemoveFromDB: Boolean;
var
sSQL: string;
begin
Result := False;
sSQL := 'delete from ' + CustomTableName
+ ' where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(FID)
+ ' and ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(FNewUnitID);
if cExecSQL(sSQL, dbtPOS, false) then
Result := True; //SimpanBlob(sSQL, GetHeaderFlag);
end;
function TBeginningBalance.SaveToDB: Boolean;
var
ssSQL: TStrings;
begin
Result := False;
try
ssSQL := GenerateSQL();
try
if cExecSQL(ssSQL) then
// if SimpanBlob(ssSQL,GetHeaderFlag) then
Result := True;
except
end;
finally
FreeAndNil(ssSQL);
end;
end;
procedure TBeginningBalance.SetNewUnit(Value: TUnit);
begin
FNewUnitID := Value.ID;
end;
//procedure TBeginningBalance.SetOPC_UNIT(Value: TUnit);
//begin
// FOPC_UNITID := Value.ID;
//end;
//procedure TBeginningBalance.SetOPM_UNIT(Value: TUnit);
//begin
// FOPM_UNITID := Value.ID;
//end;
procedure TBeginningBalance.SetPOS(Value: TPOS);
begin
FPOSID := Value.ID;
end;
procedure TBeginningBalance.SetShift(Value: TNewShift);
begin
FShiftID := Value.ID;
end;
procedure TBeginningBalance.UpdateData(ANewUnitID, ADescription, AID, AKasirID:
string; AModal: Double; APOS_ID, AShift_ID: string; AShiftDate: TDateTime;
AStatus: string);
begin
FNewUnitID := ANewUnitID;
FDescription := ADescription;
FID := AID;
FKasirID := AKasirID;
// FKasirUnitID := AKasirUnitID;
FModal := AModal;
FPOSID := APOS_ID;
FShiftID := AShift_ID;
FShiftDate := AShiftDate;
FStatus := Trim(AStatus);
State := csCreated;
end;
procedure TBeginningBalance.UpdateStatus(AStatus: String);
begin
Status := AStatus;
end;
function TBeginningBalance.UpdateStatusAndSaveToDB(AStatus: String): Boolean;
begin
//Result := False;
UpdateStatus(AStatus);
Result := SaveToDB;
end;
end.
|
unit gr_AcctCard_MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, ExtCtrls, cxMaskEdit, cxDropDownEdit,
cxCalendar, cxTextEdit, cxButtonEdit, cxContainer, cxEdit, cxLabel,
cxControls, cxGroupBox, StdCtrls, cxButtons,
PackageLoad, DB, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, IBase,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, GlobalSpr,
cxSpinEdit, FIBQuery, pFIBQuery, pFIBStoredProc, gr_uCommonConsts, zTypes,
ActnList, zProc, gr_uMessage, gr_AcctCard_DM, cxCheckBox, gr_uCommonLoader,
cxGraphics, dxStatusBar, Registry, cxDBEdit;
type
TFTnAccessControl = class(TForm)
YesBtn: TcxButton;
CancelBtn: TcxButton;
BoxMan: TcxGroupBox;
EditMan: TcxButtonEdit;
LabelMan: TcxLabel;
BoxPriv: TcxGroupBox;
LabelTypeViplata: TcxLabel;
Actions: TActionList;
Action1: TAction;
LabelAcctCard: TcxLabel;
MaskEditCard: TcxMaskEdit;
ClearBtn: TcxButton;
BpxShifr: TcxGroupBox;
LabelShifr: TcxLabel;
MaskEditShifr: TcxMaskEdit;
CheckBoxShifrIsEdit: TcxCheckBox;
Action2: TAction;
dxStatusBar1: TdxStatusBar;
Action3: TAction;
LookupCBoxTypePayment: TcxLookupComboBox;
procedure CancelBtnClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure MaskEditCardKeyPress(Sender: TObject; var Key: Char);
procedure Action1Execute(Sender: TObject);
procedure ClearBtnClick(Sender: TObject);
procedure MaskEditShifrKeyPress(Sender: TObject; var Key: Char);
procedure CheckBoxShifrIsEditPropertiesChange(Sender: TObject);
procedure Action2Execute(Sender: TObject);
procedure RestoreFromBuffer(Sender:TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Action3Execute(Sender: TObject);
procedure LookupCBoxTypePaymentPropertiesChange(Sender: TObject);
private
Pcfs:TZControlFormStyle;
PId_man:Integer;
PId_Viplata:Integer;
PResault:Variant;
PLanguageIndex:Byte;
DM:TDM_Ctrl;
public
constructor Create(AParameter:TgrCtrlSimpleParam);reintroduce;
property Resault:Variant read PResault;
end;
implementation
uses VarConv;
{$R *.dfm}
constructor TFTnAccessControl.Create(AParameter:TgrCtrlSimpleParam);
begin
inherited Create(AParameter.Owner);
PLanguageIndex:=LanguageIndex;
PId_man:= AParameter.Id;
//******************************************************************************
Caption := LabelAcctCard_Caption[PLanguageIndex];
YesBtn.Caption := YesBtn_Caption[PLanguageIndex];
CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex];
ClearBtn.Caption := ClearBtn_Caption[PLanguageIndex];
LabelMan.Caption := LabelStudent_Caption[PLanguageIndex];
LabelTypeViplata.Caption := LabelTypePayment_Caption[PLanguageIndex];
LabelAcctCard.Caption := LabelAcctCard_Caption[PLanguageIndex];
CheckBoxShifrIsEdit.Properties.Caption := UpdateBtn_Caption[PLanguageIndex];
LabelShifr.Caption := LabelShifr_Caption[PLanguageIndex];
//******************************************************************************
DM:=TDM_Ctrl.Create(self);
with Dm do
begin
DataBase.Handle := AParameter.DB_Handle;
DSet.SQLs.SelectSQL.Text := 'SELECT * FROM GR_ACCTCARD_S_BY_ID_MAN('+IntToStr(PID_man)+')';
DSet.Open;
DSetTypePayment.SelectSQL.Text := 'SELECT * FROM Z_SP_TYPE_PAYMENT_SELECT';
DSetTypePayment.Open;
LookupCBoxTypePayment.Properties.DataController.DataSource := DM.DSourceTypePayment;
EditMan.Text := VarToStrDef(DSet['FIO'],'');
if VarIsNULL(DSet['ID_PAYMENT']) then
begin
PId_Viplata:=-99;
MaskEditCard.Text := '';
end
else
begin
PId_Viplata:=DSet['ID_PAYMENT'];
MaskEditCard.Text := VarToStrDef(DSet['ACCT_CARD'],'');
LookupCBoxTypePayment.EditValue := DSet['ID_PAYMENT'];
end;
MaskEditShifr.Text:=VarToStrDef(DSet['SHIFR'],'');
end;
//******************************************************************************
end;
procedure TFTnAccessControl.CancelBtnClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TFTnAccessControl.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if DM.DefaultTransaction.Active then DM.DefaultTransaction.Commit;
end;
procedure TFTnAccessControl.FormDestroy(Sender: TObject);
begin
if DM<>nil then DM.Destroy;
end;
procedure TFTnAccessControl.MaskEditCardKeyPress(Sender: TObject;
var Key: Char);
begin
if not((Key in ['0'..'9']) and (Length(MaskEditCard.Text)<16)) then Key:=#0;
end;
procedure TFTnAccessControl.Action1Execute(Sender: TObject);
begin
with DM do
try
StoredProc.Database := DataBase;
StoredProc.Transaction := WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName := 'GR_ACCTCARD_IUD';
StoredProc.Prepare;
StoredProc.ParamByName('ID_MAN').AsInteger := PId_man;
if PId_Viplata=-99 then
StoredProc.ParamByName('ID_PAYMENT').AsVariant := NULL
else
StoredProc.ParamByName('ID_PAYMENT').AsInteger := PId_Viplata;
if MaskEditCard.Text='' then
StoredProc.ParamByName('ACCT_CARD').AsVariant := NULL
else StoredProc.ParamByName('ACCT_CARD').AsString := MaskEditCard.Text;
if MaskEditShifr.Text='' then
StoredProc.ParamByName('SHIFR').AsVariant:=NULL
else StoredProc.ParamByName('SHIFR').AsInteger:=StrToInt(MaskEditShifr.Text);
StoredProc.ExecProc;
StoredProc.Transaction.Commit;
ModalResult:=mrYes;
except
on e:exception do
begin
grShowMessage(ECaption[PLanguageIndex],E.Message,mtError,[mbOK]);
StoredProc.Transaction.Rollback;
end;
end
end;
procedure TFTnAccessControl.ClearBtnClick(Sender: TObject);
begin
PId_Viplata := -99;
MaskEditCard.Text := '';
end;
procedure TFTnAccessControl.MaskEditShifrKeyPress(Sender: TObject;
var Key: Char);
begin
if not((Key in ['0'..'9']) and (Length(MaskEditShifr.Text)<16)) then Key:=#0;
end;
procedure TFTnAccessControl.CheckBoxShifrIsEditPropertiesChange(
Sender: TObject);
begin
if TcxCheckBox(Sender).Checked=true then MaskEditShifr.Enabled:=true
else MaskEditShifr.Enabled:=false;
end;
procedure TFTnAccessControl.Action2Execute(Sender: TObject);
var reg: TRegistry;
Key:string;
begin
CancelBtn.SetFocus;
Key := '\Software\Grant\TnAccessControl';
reg:=TRegistry.Create;
try
reg.RootKey:=HKEY_CURRENT_USER;
reg.OpenKey(Key,True);
reg.WriteString('IsBuffer','1');
reg.WriteString('MaskEditCard',MaskEditCard.EditValue);
if(MaskEditShifr.Enabled=true) then begin
reg.WriteString('MaskEditShifr',MaskEditShifr.EditValue);
reg.WriteString('MaskEditShifrEnabled','True');
end;
//buttonEdit
reg.WriteString('EditViplata',LookupCBoxTypePayment.EditValue);
reg.WriteInteger('PId_Viplata',PId_Viplata);
finally
reg.Free;
end;
end;
procedure TFTnAccessControl.RestoreFromBuffer(Sender:TObject);
var reg:TRegistry;
Kod:integer;
Key:string;
begin
Key := '\Software\Grant\TnAccessControl';
reg := TRegistry.Create;
reg.RootKey:=HKEY_CURRENT_USER;
if not reg.OpenKey(Key,False) then
begin
reg.free;
Exit;
end;
if reg.ReadString('IsBuffer')<>'1' then
begin
reg.Free;
exit;
end;
MaskEditCard.EditValue:=reg.ReadString('MaskEditCard');
if(reg.ReadString('MaskEditShifrEnabled')='True') then begin
MaskEditShifr.Enabled:=True;
MaskEditShifr.EditValue:=reg.ReadString('MaskEditShifr');
CheckBoxShifrIsEdit.Checked:=True;
end;
//buttonEdit
LookupCBoxTypePayment.EditValue:= reg.ReadString('EditViplata');
PId_Viplata:=reg.ReadInteger('PId_Viplata');
Reg.Free;
end;
procedure TFTnAccessControl.FormShow(Sender: TObject);
begin
if Pcfs=zcfsInsert then RestoreFromBuffer(self);
LookupCBoxTypePayment.SetFocus;
end;
procedure TFTnAccessControl.FormCreate(Sender: TObject);
begin
dxStatusBar1.Panels[0].Text := 'F9 - '+ToBuffer_Caption[PLanguageIndex];
dxStatusBar1.Panels[1].Text := 'F10 - '+YesBtn.Caption;
dxStatusBar1.Panels[2].Text := 'Esc - '+CancelBtn.Caption;
end;
procedure TFTnAccessControl.Action3Execute(Sender: TObject);
begin
if CancelBtn.focused=true then close();
if YesBtn.Focused then Action1.Execute;
if MaskEditShifr.IsFocused and MaskEditShifr.Enabled and MaskEditShifr.Visible then YesBtn.setFocus;
if CheckBoxShifrIsEdit.IsFocused then
if MaskEditShifr.enabled=true and MaskEditShifr.visible then
MaskEditShifr.SetFocus
else YesBtn.setFocus;
if MaskEditCard.IsFocused and CheckBoxShifrIsEdit.visible and CheckBoxShifrIsEdit.Enabled then CheckBoxShifrIsEdit.setFocus;
if LookupCBoxTypePayment.IsFocused and MaskEditCard.visible and MaskEditCard.Enabled
then CheckBoxShifrIsEdit.setFocus
else if LookupCBoxTypePayment.IsFocused=true then CheckBoxShifrIsEdit.SetFocus;
end;
procedure TFTnAccessControl.LookupCBoxTypePaymentPropertiesChange(
Sender: TObject);
begin
if(LookupCBoxTypePayment.EditValue<> null)then
PId_Viplata:=LookupCBoxTypePayment.EditValue;
end;
end.
|
{==============================================================================|
| Project : Ararat Synapse | 007.006.001 |
|==============================================================================|
| Content: Serial port support |
|==============================================================================|
| Copyright (c)2001-2017, Lukas Gebauer |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are met: |
| |
| Redistributions of source code must retain the above copyright notice, this |
| list of conditions and the following disclaimer. |
| |
| Redistributions in binary form must reproduce the above copyright notice, |
| this list of conditions and the following disclaimer in the documentation |
| and/or other materials provided with the distribution. |
| |
| Neither the name of Lukas Gebauer nor the names of its contributors may |
| be used to endorse or promote products derived from this software without |
| specific prior written permission. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
| ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
| OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
| DAMAGE. |
|==============================================================================|
| The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).|
| Portions created by Lukas Gebauer are Copyright (c)2001-2017. |
| All Rights Reserved. |
|==============================================================================|
| Contributor(s): |
| (c)2002, Hans-Georg Joepgen (cpom Comport Ownership Manager and bugfixes) |
|==============================================================================|
| History: see HISTORY.HTM from distribution package |
| (Found at URL: http://www.ararat.cz/synapse/) |
|==============================================================================}
{: @abstract(Serial port communication library)
This unit contains a class that implements serial port communication
for Windows, Linux, Unix or MacOSx. This class provides numerous methods with
same name and functionality as methods of the Ararat Synapse TCP/IP library.
The following is a small example how establish a connection by modem (in this
case with my USB modem):
@longcode(#
ser:=TBlockSerial.Create;
try
ser.Connect('COM3');
ser.config(460800,8,'N',0,false,true);
ser.ATCommand('AT');
if (ser.LastError <> 0) or (not ser.ATResult) then
Exit;
ser.ATConnect('ATDT+420971200111');
if (ser.LastError <> 0) or (not ser.ATResult) then
Exit;
// you are now connected to a modem at +420971200111
// you can transmit or receive data now
finally
ser.free;
end;
#)
}
//old Delphi does not have MSWINDOWS define.
{$IFDEF WIN32}
{$IFNDEF MSWINDOWS}
{$DEFINE MSWINDOWS}
{$ENDIF}
{$ENDIF}
//Kylix does not known UNIX define
{$IFDEF LINUX}
{$IFNDEF UNIX}
{$DEFINE UNIX}
{$ENDIF}
{$ENDIF}
{$IFDEF FPC}
{$MODE DELPHI}
{$IFDEF MSWINDOWS}
{$ASMMODE intel}
{$ENDIF}
{define working mode w/o LIBC for fpc}
{$DEFINE NO_LIBC}
{$ENDIF}
{$Q-}
{$H+}
{$M+}
unit synaser;
interface
uses
{$IFNDEF MSWINDOWS}
{$IFNDEF NO_LIBC}
Libc,
KernelIoctl,
{$ELSE}
termio, baseunix, unix,
{$ENDIF}
{$IFNDEF FPC}
Types,
{$ENDIF}
{$ELSE}
Windows, registry,
{$IFDEF FPC}
winver,
{$ENDIF}
{$ENDIF}
synafpc,
Classes, SysUtils, synautil;
const
CR = #$0d;
LF = #$0a;
CRLF = CR + LF;
cSerialChunk = 8192;
LockfileDirectory = '/var/lock'; {HGJ}
PortIsClosed = -1; {HGJ}
ErrAlreadyOwned = 9991; {HGJ}
ErrAlreadyInUse = 9992; {HGJ}
ErrWrongParameter = 9993; {HGJ}
ErrPortNotOpen = 9994; {HGJ}
ErrNoDeviceAnswer = 9995; {HGJ}
ErrMaxBuffer = 9996;
ErrTimeout = 9997;
ErrNotRead = 9998;
ErrFrame = 9999;
ErrOverrun = 10000;
ErrRxOver = 10001;
ErrRxParity = 10002;
ErrTxFull = 10003;
dcb_Binary = $00000001;
dcb_ParityCheck = $00000002;
dcb_OutxCtsFlow = $00000004;
dcb_OutxDsrFlow = $00000008;
dcb_DtrControlMask = $00000030;
dcb_DtrControlDisable = $00000000;
dcb_DtrControlEnable = $00000010;
dcb_DtrControlHandshake = $00000020;
dcb_DsrSensivity = $00000040;
dcb_TXContinueOnXoff = $00000080;
dcb_OutX = $00000100;
dcb_InX = $00000200;
dcb_ErrorChar = $00000400;
dcb_NullStrip = $00000800;
dcb_RtsControlMask = $00003000;
dcb_RtsControlDisable = $00000000;
dcb_RtsControlEnable = $00001000;
dcb_RtsControlHandshake = $00002000;
dcb_RtsControlToggle = $00003000;
dcb_AbortOnError = $00004000;
dcb_Reserveds = $FFFF8000;
{:stopbit value for 1 stopbit}
SB1 = 0;
{:stopbit value for 1.5 stopbit}
SB1andHalf = 1;
{:stopbit value for 2 stopbits}
SB2 = 2;
{$IFNDEF MSWINDOWS}
const
INVALID_HANDLE_VALUE = THandle(-1);
CS7fix = $0000020;
type
TDCB = record
DCBlength: DWORD;
BaudRate: DWORD;
Flags: Longint;
wReserved: Word;
XonLim: Word;
XoffLim: Word;
ByteSize: Byte;
Parity: Byte;
StopBits: Byte;
XonChar: CHAR;
XoffChar: CHAR;
ErrorChar: CHAR;
EofChar: CHAR;
EvtChar: CHAR;
wReserved1: Word;
end;
PDCB = ^TDCB;
const
{$IFDEF UNIX}
{$IFDEF BSD}
MaxRates = 18; //MAC
{$ELSE}
MaxRates = 30; //UNIX
{$ENDIF}
{$ELSE}
MaxRates = 19; //WIN
{$ENDIF}
Rates: array[0..MaxRates, 0..1] of cardinal =
(
(0, B0),
(50, B50),
(75, B75),
(110, B110),
(134, B134),
(150, B150),
(200, B200),
(300, B300),
(600, B600),
(1200, B1200),
(1800, B1800),
(2400, B2400),
(4800, B4800),
(9600, B9600),
(19200, B19200),
(38400, B38400),
(57600, B57600),
(115200, B115200),
(230400, B230400)
{$IFNDEF BSD}
,(460800, B460800)
{$IFDEF UNIX}
,(500000, B500000),
(576000, B576000),
(921600, B921600),
(1000000, B1000000),
(1152000, B1152000),
(1500000, B1500000),
(2000000, B2000000),
(2500000, B2500000),
(3000000, B3000000),
(3500000, B3500000),
(4000000, B4000000)
{$ENDIF}
{$ENDIF}
);
{$ENDIF}
{$IFDEF BSD}
const // From fcntl.h
O_SYNC = $0080; { synchronous writes }
{$ENDIF}
const
sOK = 0;
sErr = integer(-1);
type
{:Possible status event types for @link(THookSerialStatus)}
THookSerialReason = (
HR_SerialClose,
HR_Connect,
HR_CanRead,
HR_CanWrite,
HR_ReadCount,
HR_WriteCount,
HR_Wait
);
{:procedural prototype for status event hooking}
THookSerialStatus = procedure(Sender: TObject; Reason: THookSerialReason;
const Value: string) of object;
{:@abstract(Exception type for SynaSer errors)}
ESynaSerError = class(Exception)
public
ErrorCode: integer;
ErrorMessage: string;
end;
{:@abstract(Main class implementing all communication routines)}
TBlockSerial = class(TObject)
protected
FOnStatus: THookSerialStatus;
Fhandle: THandle;
FTag: integer;
FDevice: string;
FLastError: integer;
FLastErrorDesc: string;
FBuffer: AnsiString;
FRaiseExcept: boolean;
FRecvBuffer: integer;
FSendBuffer: integer;
FModemWord: integer;
FRTSToggle: Boolean;
FDeadlockTimeout: integer;
FInstanceActive: boolean; {HGJ}
FTestDSR: Boolean;
FTestCTS: Boolean;
FLastCR: Boolean;
FLastLF: Boolean;
FMaxLineLength: Integer;
FLinuxLock: Boolean;
FMaxSendBandwidth: Integer;
FNextSend: LongWord;
FMaxRecvBandwidth: Integer;
FNextRecv: LongWord;
FConvertLineEnd: Boolean;
FATResult: Boolean;
FAtTimeout: integer;
FInterPacketTimeout: Boolean;
FComNr: integer;
{$IFDEF MSWINDOWS}
FPortAddr: Word;
function CanEvent(Event: dword; Timeout: integer): boolean;
procedure DecodeCommError(Error: DWord); virtual;
{$IFDEF WIN32}
function GetPortAddr: Word; virtual;
function ReadTxEmpty(PortAddr: Word): Boolean; virtual;
{$ENDIF}
{$ENDIF}
procedure SetSizeRecvBuffer(size: integer); virtual;
function GetDSR: Boolean; virtual;
procedure SetDTRF(Value: Boolean); virtual;
function GetCTS: Boolean; virtual;
procedure SetRTSF(Value: Boolean); virtual;
function GetCarrier: Boolean; virtual;
function GetRing: Boolean; virtual;
procedure DoStatus(Reason: THookSerialReason; const Value: string); virtual;
procedure GetComNr(Value: string); virtual;
function PreTestFailing: boolean; virtual;{HGJ}
function TestCtrlLine: Boolean; virtual;
{$IFDEF UNIX}
procedure DcbToTermios(const dcb: TDCB; var term: termios); virtual;
procedure TermiosToDcb(const term: termios; var dcb: TDCB); virtual;
function ReadLockfile: integer; virtual;
function LockfileName: String; virtual;
procedure CreateLockfile(PidNr: integer); virtual;
{$ENDIF}
procedure LimitBandwidth(Length: Integer; MaxB: integer; var Next: LongWord); virtual;
procedure SetBandwidth(Value: Integer); virtual;
public
{: data Control Block with communication parameters. Usable only when you
need to call API directly.}
DCB: Tdcb;
{$IFDEF UNIX}
TermiosStruc: termios;
{$ENDIF}
{:Object constructor.}
constructor Create;
{:Object destructor.}
destructor Destroy; override;
{:Returns a string containing the version number of the library.}
class function GetVersion: string; virtual;
{:Destroy handle in use. It close connection to serial port.}
procedure CloseSocket; virtual;
{:Reconfigure communication parameters on the fly. You must be connected to
port before!
@param(baud Define connection speed. Baud rate can be from 50 to 4000000
bits per second. (it depends on your hardware!))
@param(bits Number of bits in communication.)
@param(parity Define communication parity (N - None, O - Odd, E - Even, M - Mark or S - Space).)
@param(stop Define number of stopbits. Use constants @link(SB1),
@link(SB1andHalf) and @link(SB2).)
@param(softflow Enable XON/XOFF handshake.)
@param(hardflow Enable CTS/RTS handshake.)}
procedure Config(baud, bits: integer; parity: char; stop: integer;
softflow, hardflow: boolean); virtual;
{:Connects to the port indicated by comport. Comport can be used in Windows
style (COM2), or in Linux style (/dev/ttyS1). When you use windows style
in Linux, then it will be converted to Linux name. And vice versa! However
you can specify any device name! (other device names then standart is not
converted!)
After successfull connection the DTR signal is set (if you not set hardware
handshake, then the RTS signal is set, too!)
Connection parameters is predefined by your system configuration. If you
need use another parameters, then you can use Config method after.
Notes:
- Remember, the commonly used serial Laplink cable does not support
hardware handshake.
- Before setting any handshake you must be sure that it is supported by
your hardware.
- Some serial devices are slow. In some cases you must wait up to a few
seconds after connection for the device to respond.
- when you connect to a modem device, then is best to test it by an empty
AT command. (call ATCommand('AT'))}
procedure Connect(comport: string); virtual;
{:Set communication parameters from the DCB structure (the DCB structure is
simulated under Linux).}
procedure SetCommState; virtual;
{:Read communication parameters into the DCB structure (DCB structure is
simulated under Linux).}
procedure GetCommState; virtual;
{:Sends Length bytes of data from Buffer through the connected port.}
function SendBuffer(buffer: pointer; length: integer): integer; virtual;
{:One data BYTE is sent.}
procedure SendByte(data: byte); virtual;
{:Send the string in the data parameter. No terminator is appended by this
method. If you need to send a string with CR/LF terminator, you must append
the CR/LF characters to the data string!
Since no terminator is appended, you can use this function for sending
binary data too.}
procedure SendString(data: AnsiString); virtual;
{:send four bytes as integer.}
procedure SendInteger(Data: integer); virtual;
{:send data as one block. Each block begins with integer value with Length
of block.}
procedure SendBlock(const Data: AnsiString); virtual;
{:send content of stream from current position}
procedure SendStreamRaw(const Stream: TStream); virtual;
{:send content of stream as block. see @link(SendBlock)}
procedure SendStream(const Stream: TStream); virtual;
{:send content of stream as block, but this is compatioble with Indy library.
(it have swapped lenght of block). See @link(SendStream)}
procedure SendStreamIndy(const Stream: TStream); virtual;
{:Waits until the allocated buffer is filled by received data. Returns number
of data bytes received, which equals to the Length value under normal
operation. If it is not equal, the communication channel is possibly broken.
This method not using any internal buffering, like all others receiving
methods. You cannot freely combine this method with all others receiving
methods!}
function RecvBuffer(buffer: pointer; length: integer): integer; virtual;
{:Method waits until data is received. If no data is received within
the Timeout (in milliseconds) period, @link(LastError) is set to
@link(ErrTimeout). This method is used to read any amount of data
(e. g. 1MB), and may be freely combined with all receviving methods what
have Timeout parameter, like the @link(RecvString), @link(RecvByte) or
@link(RecvTerminated) methods.}
function RecvBufferEx(buffer: pointer; length: integer; timeout: integer): integer; virtual;
{:It is like recvBufferEx, but data is readed to dynamicly allocated binary
string.}
function RecvBufferStr(Length: Integer; Timeout: Integer): AnsiString; virtual;
{:Read all available data and return it in the function result string. This
function may be combined with @link(RecvString), @link(RecvByte) or related
methods.}
function RecvPacket(Timeout: Integer): AnsiString; virtual;
{:Waits until one data byte is received which is returned as the function
result. If no data is received within the Timeout (in milliseconds) period,
@link(LastError) is set to @link(ErrTimeout).}
function RecvByte(timeout: integer): byte; virtual;
{:This method waits until a terminated data string is received. This string
is terminated by the Terminator string. The resulting string is returned
without this termination string! If no data is received within the Timeout
(in milliseconds) period, @link(LastError) is set to @link(ErrTimeout).}
function RecvTerminated(Timeout: Integer; const Terminator: AnsiString): AnsiString; virtual;
{:This method waits until a terminated data string is received. The string
is terminated by a CR/LF sequence. The resulting string is returned without
the terminator (CR/LF)! If no data is received within the Timeout (in
milliseconds) period, @link(LastError) is set to @link(ErrTimeout).
If @link(ConvertLineEnd) is used, then the CR/LF sequence may not be exactly
CR/LF. See the description of @link(ConvertLineEnd).
This method serves for line protocol implementation and uses its own
buffers to maximize performance. Therefore do NOT use this method with the
@link(RecvBuffer) method to receive data as it may cause data loss.}
function Recvstring(timeout: integer): AnsiString; virtual;
{:Waits until four data bytes are received which is returned as the function
integer result. If no data is received within the Timeout (in milliseconds) period,
@link(LastError) is set to @link(ErrTimeout).}
function RecvInteger(Timeout: Integer): Integer; virtual;
{:Waits until one data block is received. See @link(sendblock). If no data
is received within the Timeout (in milliseconds) period, @link(LastError)
is set to @link(ErrTimeout).}
function RecvBlock(Timeout: Integer): AnsiString; virtual;
{:Receive all data to stream, until some error occured. (for example timeout)}
procedure RecvStreamRaw(const Stream: TStream; Timeout: Integer); virtual;
{:receive requested count of bytes to stream}
procedure RecvStreamSize(const Stream: TStream; Timeout: Integer; Size: Integer); virtual;
{:receive block of data to stream. (Data can be sended by @link(sendstream)}
procedure RecvStream(const Stream: TStream; Timeout: Integer); virtual;
{:receive block of data to stream. (Data can be sended by @link(sendstreamIndy)}
procedure RecvStreamIndy(const Stream: TStream; Timeout: Integer); virtual;
{:Returns the number of received bytes waiting for reading. 0 is returned
when there is no data waiting.}
function WaitingData: integer; virtual;
{:Same as @link(WaitingData), but in respect to data in the internal
@link(LineBuffer).}
function WaitingDataEx: integer; virtual;
{:Returns the number of bytes waiting to be sent in the output buffer.
0 is returned when the output buffer is empty.}
function SendingData: integer; virtual;
{:Enable or disable RTS driven communication (half-duplex). It can be used
to communicate with RS485 converters, or other special equipment. If you
enable this feature, the system automatically controls the RTS signal.
Notes:
- On Windows NT (or higher) ir RTS signal driven by system driver.
- On Win9x family is used special code for waiting until last byte is
sended from your UART.
- On Linux you must have kernel 2.1 or higher!}
procedure EnableRTSToggle(value: boolean); virtual;
{:Waits until all data to is sent and buffers are emptied.
Warning: On Windows systems is this method returns when all buffers are
flushed to the serial port controller, before the last byte is sent!}
procedure Flush; virtual;
{:Unconditionally empty all buffers. It is good when you need to interrupt
communication and for cleanups.}
procedure Purge; virtual;
{:Returns @True, if you can from read any data from the port. Status is
tested for a period of time given by the Timeout parameter (in milliseconds).
If the value of the Timeout parameter is 0, the status is tested only once
and the function returns immediately. If the value of the Timeout parameter
is set to -1, the function returns only after it detects data on the port
(this may cause the process to hang).}
function CanRead(Timeout: integer): boolean; virtual;
{:Returns @True, if you can write any data to the port (this function is not
sending the contents of the buffer). Status is tested for a period of time
given by the Timeout parameter (in milliseconds). If the value of
the Timeout parameter is 0, the status is tested only once and the function
returns immediately. If the value of the Timeout parameter is set to -1,
the function returns only after it detects that it can write data to
the port (this may cause the process to hang).}
function CanWrite(Timeout: integer): boolean; virtual;
{:Same as @link(CanRead), but the test is against data in the internal
@link(LineBuffer) too.}
function CanReadEx(Timeout: integer): boolean; virtual;
{:Returns the status word of the modem. Decoding the status word could yield
the status of carrier detect signaland other signals. This method is used
internally by the modem status reading properties. You usually do not need
to call this method directly.}
function ModemStatus: integer; virtual;
{:Send a break signal to the communication device for Duration milliseconds.}
procedure SetBreak(Duration: integer); virtual;
{:This function is designed to send AT commands to the modem. The AT command
is sent in the Value parameter and the response is returned in the function
return value (may contain multiple lines!).
If the AT command is processed successfully (modem returns OK), then the
@link(ATResult) property is set to True.
This function is designed only for AT commands that return OK or ERROR
response! To call connection commands the @link(ATConnect) method.
Remember, when you connect to a modem device, it is in AT command mode.
Now you can send AT commands to the modem. If you need to transfer data to
the modem on the other side of the line, you must first switch to data mode
using the @link(ATConnect) method.}
function ATCommand(value: AnsiString): AnsiString; virtual;
{:This function is used to send connect type AT commands to the modem. It is
for commands to switch to connected state. (ATD, ATA, ATO,...)
It sends the AT command in the Value parameter and returns the modem's
response (may be multiple lines - usually with connection parameters info).
If the AT command is processed successfully (the modem returns CONNECT),
then the ATResult property is set to @True.
This function is designed only for AT commands which respond by CONNECT,
BUSY, NO DIALTONE NO CARRIER or ERROR. For other AT commands use the
@link(ATCommand) method.
The connect timeout is 90*@link(ATTimeout). If this command is successful
(@link(ATresult) is @true), then the modem is in data state. When you now
send or receive some data, it is not to or from your modem, but from the
modem on other side of the line. Now you can transfer your data.
If the connection attempt failed (@link(ATResult) is @False), then the
modem is still in AT command mode.}
function ATConnect(value: AnsiString): AnsiString; virtual;
{:If you "manually" call API functions, forward their return code in
the SerialResult parameter to this function, which evaluates it and sets
@link(LastError) and @link(LastErrorDesc).}
function SerialCheck(SerialResult: integer): integer; virtual;
{:If @link(Lasterror) is not 0 and exceptions are enabled, then this procedure
raises an exception. This method is used internally. You may need it only
in special cases.}
procedure ExceptCheck; virtual;
{:Set Synaser to error state with ErrNumber code. Usually used by internal
routines.}
procedure SetSynaError(ErrNumber: integer); virtual;
{:Raise Synaser error with ErrNumber code. Usually used by internal routines.}
procedure RaiseSynaError(ErrNumber: integer); virtual;
{$IFDEF UNIX}
function cpomComportAccessible: boolean; virtual;{HGJ}
procedure cpomReleaseComport; virtual; {HGJ}
{$ENDIF}
{:True device name of currently used port}
property Device: string read FDevice;
{:Error code of last operation. Value is defined by the host operating
system, but value 0 is always OK.}
property LastError: integer read FLastError;
{:Human readable description of LastError code.}
property LastErrorDesc: string read FLastErrorDesc;
{:Indicates if the last @link(ATCommand) or @link(ATConnect) method was successful}
property ATResult: Boolean read FATResult;
{:Read the value of the RTS signal.}
property RTS: Boolean write SetRTSF;
{:Indicates the presence of the CTS signal}
property CTS: boolean read GetCTS;
{:Use this property to set the value of the DTR signal.}
property DTR: Boolean write SetDTRF;
{:Exposes the status of the DSR signal.}
property DSR: boolean read GetDSR;
{:Indicates the presence of the Carrier signal}
property Carrier: boolean read GetCarrier;
{:Reflects the status of the Ring signal.}
property Ring: boolean read GetRing;
{:indicates if this instance of SynaSer is active. (Connected to some port)}
property InstanceActive: boolean read FInstanceActive; {HGJ}
{:Defines maximum bandwidth for all sending operations in bytes per second.
If this value is set to 0 (default), bandwidth limitation is not used.}
property MaxSendBandwidth: Integer read FMaxSendBandwidth Write FMaxSendBandwidth;
{:Defines maximum bandwidth for all receiving operations in bytes per second.
If this value is set to 0 (default), bandwidth limitation is not used.}
property MaxRecvBandwidth: Integer read FMaxRecvBandwidth Write FMaxRecvBandwidth;
{:Defines maximum bandwidth for all sending and receiving operations
in bytes per second. If this value is set to 0 (default), bandwidth
limitation is not used.}
property MaxBandwidth: Integer Write SetBandwidth;
{:Size of the Windows internal receive buffer. Default value is usually
4096 bytes. Note: Valid only in Windows versions!}
property SizeRecvBuffer: integer read FRecvBuffer write SetSizeRecvBuffer;
published
{:Returns the descriptive text associated with ErrorCode. You need this
method only in special cases. Description of LastError is now accessible
through the LastErrorDesc property.}
class function GetErrorDesc(ErrorCode: integer): string;
{:Freely usable property}
property Tag: integer read FTag write FTag;
{:Contains the handle of the open communication port.
You may need this value to directly call communication functions outside
SynaSer.}
property Handle: THandle read Fhandle write FHandle;
{:Internally used read buffer.}
property LineBuffer: AnsiString read FBuffer write FBuffer;
{:If @true, communication errors raise exceptions. If @false (default), only
the @link(LastError) value is set.}
property RaiseExcept: boolean read FRaiseExcept write FRaiseExcept;
{:This event is triggered when the communication status changes. It can be
used to monitor communication status.}
property OnStatus: THookSerialStatus read FOnStatus write FOnStatus;
{:If you set this property to @true, then the value of the DSR signal
is tested before every data transfer. It can be used to detect the presence
of a communications device.}
property TestDSR: boolean read FTestDSR write FTestDSR;
{:If you set this property to @true, then the value of the CTS signal
is tested before every data transfer. It can be used to detect the presence
of a communications device. Warning: This property cannot be used if you
need hardware handshake!}
property TestCTS: boolean read FTestCTS write FTestCTS;
{:Use this property you to limit the maximum size of LineBuffer
(as a protection against unlimited memory allocation for LineBuffer).
Default value is 0 - no limit.}
property MaxLineLength: Integer read FMaxLineLength Write FMaxLineLength;
{:This timeout value is used as deadlock protection when trying to send data
to (or receive data from) a device that stopped communicating during data
transmission (e.g. by physically disconnecting the device).
The timeout value is in milliseconds. The default value is 30,000 (30 seconds).}
property DeadlockTimeout: Integer read FDeadlockTimeout Write FDeadlockTimeout;
{:If set to @true (default value), port locking is enabled (under Linux only).
WARNING: To use this feature, the application must run by a user with full
permission to the /var/lock directory!}
property LinuxLock: Boolean read FLinuxLock write FLinuxLock;
{:Indicates if non-standard line terminators should be converted to a CR/LF pair
(standard DOS line terminator). If @TRUE, line terminators CR, single LF
or LF/CR are converted to CR/LF. Defaults to @FALSE.
This property has effect only on the behavior of the RecvString method.}
property ConvertLineEnd: Boolean read FConvertLineEnd Write FConvertLineEnd;
{:Timeout for AT modem based operations}
property AtTimeout: integer read FAtTimeout Write FAtTimeout;
{:If @true (default), then all timeouts is timeout between two characters.
If @False, then timeout is overall for whoole reading operation.}
property InterPacketTimeout: Boolean read FInterPacketTimeout Write FInterPacketTimeout;
end;
{:Returns list of existing computer serial ports. Working properly only in Windows!}
function GetSerialPortNames: string;
implementation
constructor TBlockSerial.Create;
begin
inherited create;
FRaiseExcept := false;
FHandle := INVALID_HANDLE_VALUE;
FDevice := '';
FComNr:= PortIsClosed; {HGJ}
FInstanceActive:= false; {HGJ}
Fbuffer := '';
FRTSToggle := False;
FMaxLineLength := 0;
FTestDSR := False;
FTestCTS := False;
FDeadlockTimeout := 30000;
FLinuxLock := True;
FMaxSendBandwidth := 0;
FNextSend := 0;
FMaxRecvBandwidth := 0;
FNextRecv := 0;
FConvertLineEnd := False;
SetSynaError(sOK);
FRecvBuffer := 4096;
FLastCR := False;
FLastLF := False;
FAtTimeout := 1000;
FInterPacketTimeout := True;
end;
destructor TBlockSerial.Destroy;
begin
CloseSocket;
inherited destroy;
end;
class function TBlockSerial.GetVersion: string;
begin
Result := 'SynaSer 7.6.0';
end;
procedure TBlockSerial.CloseSocket;
begin
if Fhandle <> INVALID_HANDLE_VALUE then
begin
Purge;
RTS := False;
DTR := False;
FileClose(FHandle);
end;
if InstanceActive then
begin
{$IFDEF UNIX}
if FLinuxLock then
cpomReleaseComport;
{$ENDIF}
FInstanceActive:= false
end;
Fhandle := INVALID_HANDLE_VALUE;
FComNr:= PortIsClosed;
SetSynaError(sOK);
DoStatus(HR_SerialClose, FDevice);
end;
{$IFDEF WIN32}
function TBlockSerial.GetPortAddr: Word;
begin
Result := 0;
if Win32Platform <> VER_PLATFORM_WIN32_NT then
begin
EscapeCommFunction(FHandle, 10);
asm
MOV @Result, DX;
end;
end;
end;
function TBlockSerial.ReadTxEmpty(PortAddr: Word): Boolean;
begin
Result := True;
if Win32Platform <> VER_PLATFORM_WIN32_NT then
begin
asm
MOV DX, PortAddr;
ADD DX, 5;
IN AL, DX;
AND AL, $40;
JZ @K;
MOV AL,1;
@K: MOV @Result, AL;
end;
end;
end;
{$ENDIF}
procedure TBlockSerial.GetComNr(Value: string);
begin
FComNr := PortIsClosed;
if pos('COM', uppercase(Value)) = 1 then
FComNr := StrToIntdef(copy(Value, 4, Length(Value) - 3), PortIsClosed + 1) - 1;
if pos('/DEV/TTYS', uppercase(Value)) = 1 then
FComNr := StrToIntdef(copy(Value, 10, Length(Value) - 9), PortIsClosed - 1);
end;
procedure TBlockSerial.SetBandwidth(Value: Integer);
begin
MaxSendBandwidth := Value;
MaxRecvBandwidth := Value;
end;
procedure TBlockSerial.LimitBandwidth(Length: Integer; MaxB: integer; var Next: LongWord);
var
x: LongWord;
y: LongWord;
begin
if MaxB > 0 then
begin
y := GetTick;
if Next > y then
begin
x := Next - y;
if x > 0 then
begin
DoStatus(HR_Wait, IntToStr(x));
sleep(x);
end;
end;
Next := GetTick + Trunc((Length / MaxB) * 1000);
end;
end;
procedure TBlockSerial.Config(baud, bits: integer; parity: char; stop: integer;
softflow, hardflow: boolean);
begin
FillChar(dcb, SizeOf(dcb), 0);
GetCommState;
dcb.DCBlength := SizeOf(dcb);
dcb.BaudRate := baud;
dcb.ByteSize := bits;
case parity of
'N', 'n': dcb.parity := 0;
'O', 'o': dcb.parity := 1;
'E', 'e': dcb.parity := 2;
'M', 'm': dcb.parity := 3;
'S', 's': dcb.parity := 4;
end;
dcb.StopBits := stop;
dcb.XonChar := #17;
dcb.XoffChar := #19;
dcb.XonLim := FRecvBuffer div 4;
dcb.XoffLim := FRecvBuffer div 4;
dcb.Flags := dcb_Binary;
if softflow then
dcb.Flags := dcb.Flags or dcb_OutX or dcb_InX;
if hardflow then
dcb.Flags := dcb.Flags or dcb_OutxCtsFlow or dcb_RtsControlHandshake
else
dcb.Flags := dcb.Flags or dcb_RtsControlEnable;
dcb.Flags := dcb.Flags or dcb_DtrControlEnable;
if dcb.Parity > 0 then
dcb.Flags := dcb.Flags or dcb_ParityCheck;
SetCommState;
end;
procedure TBlockSerial.Connect(comport: string);
{$IFDEF MSWINDOWS}
var
CommTimeouts: TCommTimeouts;
{$ENDIF}
begin
// Is this TBlockSerial Instance already busy?
if InstanceActive then {HGJ}
begin {HGJ}
RaiseSynaError(ErrAlreadyInUse);
Exit; {HGJ}
end; {HGJ}
FBuffer := '';
FDevice := comport;
GetComNr(comport);
{$IFDEF MSWINDOWS}
SetLastError (sOK);
{$ELSE}
{$IFNDEF FPC}
SetLastError (sOK);
{$ELSE}
fpSetErrno(sOK);
{$ENDIF}
{$ENDIF}
{$IFNDEF MSWINDOWS}
if FComNr <> PortIsClosed then
FDevice := '/dev/ttyS' + IntToStr(FComNr);
// Comport already owned by another process? {HGJ}
if FLinuxLock then
if not cpomComportAccessible then
begin
RaiseSynaError(ErrAlreadyOwned);
Exit;
end;
{$IFNDEF FPC}
FHandle := THandle(Libc.open(pchar(FDevice), O_RDWR or O_SYNC));
{$ELSE}
FHandle := THandle(fpOpen(FDevice, O_RDWR or O_SYNC));
{$ENDIF}
if FHandle = INVALID_HANDLE_VALUE then //because THandle is not integer on all platforms!
SerialCheck(-1)
else
SerialCheck(0);
{$IFDEF UNIX}
if FLastError <> sOK then
if FLinuxLock then
cpomReleaseComport;
{$ENDIF}
ExceptCheck;
if FLastError <> sOK then
Exit;
{$ELSE}
if FComNr <> PortIsClosed then
FDevice := '\\.\COM' + IntToStr(FComNr + 1);
FHandle := THandle(CreateFile(PChar(FDevice), GENERIC_READ or GENERIC_WRITE,
0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_OVERLAPPED, 0));
if FHandle = INVALID_HANDLE_VALUE then //because THandle is not integer on all platforms!
SerialCheck(-1)
else
SerialCheck(0);
ExceptCheck;
if FLastError <> sOK then
Exit;
SetCommMask(FHandle, 0);
SetupComm(Fhandle, FRecvBuffer, 0);
CommTimeOuts.ReadIntervalTimeout := MAXWORD;
CommTimeOuts.ReadTotalTimeoutMultiplier := 0;
CommTimeOuts.ReadTotalTimeoutConstant := 0;
CommTimeOuts.WriteTotalTimeoutMultiplier := 0;
CommTimeOuts.WriteTotalTimeoutConstant := 0;
SetCommTimeOuts(FHandle, CommTimeOuts);
{$IFDEF WIN32}
FPortAddr := GetPortAddr;
{$ENDIF}
{$ENDIF}
SetSynaError(sOK);
if not TestCtrlLine then {HGJ}
begin
SetSynaError(ErrNoDeviceAnswer);
FileClose(FHandle); {HGJ}
{$IFDEF UNIX}
if FLinuxLock then
cpomReleaseComport; {HGJ}
{$ENDIF} {HGJ}
Fhandle := INVALID_HANDLE_VALUE; {HGJ}
FComNr:= PortIsClosed; {HGJ}
end
else
begin
FInstanceActive:= True;
RTS := True;
DTR := True;
Purge;
end;
ExceptCheck;
DoStatus(HR_Connect, FDevice);
end;
function TBlockSerial.SendBuffer(buffer: pointer; length: integer): integer;
{$IFDEF MSWINDOWS}
var
Overlapped: TOverlapped;
x, y, Err: DWord;
{$ENDIF}
begin
Result := 0;
if PreTestFailing then {HGJ}
Exit; {HGJ}
LimitBandwidth(Length, FMaxSendBandwidth, FNextsend);
if FRTSToggle then
begin
Flush;
RTS := True;
end;
{$IFNDEF MSWINDOWS}
result := FileWrite(Fhandle, Buffer^, Length);
serialcheck(result);
{$ELSE}
FillChar(Overlapped, Sizeof(Overlapped), 0);
SetSynaError(sOK);
y := 0;
if not WriteFile(FHandle, Buffer^, Length, DWord(Result), @Overlapped) then
y := GetLastError;
if y = ERROR_IO_PENDING then
begin
x := WaitForSingleObject(FHandle, FDeadlockTimeout);
if x = WAIT_TIMEOUT then
begin
PurgeComm(FHandle, PURGE_TXABORT);
SetSynaError(ErrTimeout);
end;
GetOverlappedResult(FHandle, Overlapped, Dword(Result), False);
end
else
SetSynaError(y);
err := 0;
ClearCommError(FHandle, err, nil);
if err <> 0 then
DecodeCommError(err);
{$ENDIF}
if FRTSToggle then
begin
Flush;
CanWrite(255);
RTS := False;
end;
ExceptCheck;
DoStatus(HR_WriteCount, IntToStr(Result));
end;
procedure TBlockSerial.SendByte(data: byte);
begin
SendBuffer(@Data, 1);
end;
procedure TBlockSerial.SendString(data: AnsiString);
begin
SendBuffer(Pointer(Data), Length(Data));
end;
procedure TBlockSerial.SendInteger(Data: integer);
begin
SendBuffer(@data, SizeOf(Data));
end;
procedure TBlockSerial.SendBlock(const Data: AnsiString);
begin
SendInteger(Length(data));
SendString(Data);
end;
procedure TBlockSerial.SendStreamRaw(const Stream: TStream);
var
si: integer;
x, y, yr: integer;
s: AnsiString;
begin
si := Stream.Size - Stream.Position;
x := 0;
while x < si do
begin
y := si - x;
if y > cSerialChunk then
y := cSerialChunk;
Setlength(s, y);
yr := Stream.read(PAnsiChar(s)^, y);
if yr > 0 then
begin
SetLength(s, yr);
SendString(s);
Inc(x, yr);
end
else
break;
end;
end;
procedure TBlockSerial.SendStreamIndy(const Stream: TStream);
var
si: integer;
begin
si := Stream.Size - Stream.Position;
si := Swapbytes(si);
SendInteger(si);
SendStreamRaw(Stream);
end;
procedure TBlockSerial.SendStream(const Stream: TStream);
var
si: integer;
begin
si := Stream.Size - Stream.Position;
SendInteger(si);
SendStreamRaw(Stream);
end;
function TBlockSerial.RecvBuffer(buffer: pointer; length: integer): integer;
{$IFNDEF MSWINDOWS}
begin
Result := 0;
if PreTestFailing then {HGJ}
Exit; {HGJ}
LimitBandwidth(Length, FMaxRecvBandwidth, FNextRecv);
result := FileRead(FHandle, Buffer^, length);
serialcheck(result);
{$ELSE}
var
Overlapped: TOverlapped;
x, y, Err: DWord;
begin
Result := 0;
if PreTestFailing then {HGJ}
Exit; {HGJ}
LimitBandwidth(Length, FMaxRecvBandwidth, FNextRecv);
FillChar(Overlapped, Sizeof(Overlapped), 0);
SetSynaError(sOK);
y := 0;
if not ReadFile(FHandle, Buffer^, length, Dword(Result), @Overlapped) then
y := GetLastError;
if y = ERROR_IO_PENDING then
begin
x := WaitForSingleObject(FHandle, FDeadlockTimeout);
if x = WAIT_TIMEOUT then
begin
PurgeComm(FHandle, PURGE_RXABORT);
SetSynaError(ErrTimeout);
end;
GetOverlappedResult(FHandle, Overlapped, Dword(Result), False);
end
else
SetSynaError(y);
err := 0;
ClearCommError(FHandle, err, nil);
if err <> 0 then
DecodeCommError(err);
{$ENDIF}
ExceptCheck;
DoStatus(HR_ReadCount, IntToStr(Result));
end;
function TBlockSerial.RecvBufferEx(buffer: pointer; length: integer; timeout: integer): integer;
var
s: AnsiString;
rl, l: integer;
ti: LongWord;
begin
Result := 0;
if PreTestFailing then {HGJ}
Exit; {HGJ}
SetSynaError(sOK);
rl := 0;
repeat
ti := GetTick;
s := RecvPacket(Timeout);
l := System.Length(s);
if (rl + l) > Length then
l := Length - rl;
Move(Pointer(s)^, IncPoint(Buffer, rl)^, l);
rl := rl + l;
if FLastError <> sOK then
Break;
if rl >= Length then
Break;
if not FInterPacketTimeout then
begin
Timeout := Timeout - integer(TickDelta(ti, GetTick));
if Timeout <= 0 then
begin
SetSynaError(ErrTimeout);
Break;
end;
end;
until False;
delete(s, 1, l);
FBuffer := s;
Result := rl;
end;
function TBlockSerial.RecvBufferStr(Length: Integer; Timeout: Integer): AnsiString;
var
x: integer;
begin
Result := '';
if PreTestFailing then {HGJ}
Exit; {HGJ}
SetSynaError(sOK);
if Length > 0 then
begin
Setlength(Result, Length);
x := RecvBufferEx(PAnsiChar(Result), Length , Timeout);
if FLastError = sOK then
SetLength(Result, x)
else
Result := '';
end;
end;
function TBlockSerial.RecvPacket(Timeout: Integer): AnsiString;
var
x: integer;
begin
Result := '';
if PreTestFailing then {HGJ}
Exit; {HGJ}
SetSynaError(sOK);
if FBuffer <> '' then
begin
Result := FBuffer;
FBuffer := '';
end
else
begin
//not drain CPU on large downloads...
Sleep(0);
x := WaitingData;
if x > 0 then
begin
SetLength(Result, x);
x := RecvBuffer(Pointer(Result), x);
if x >= 0 then
SetLength(Result, x);
end
else
begin
if CanRead(Timeout) then
begin
x := WaitingData;
if x = 0 then
SetSynaError(ErrTimeout);
if x > 0 then
begin
SetLength(Result, x);
x := RecvBuffer(Pointer(Result), x);
if x >= 0 then
SetLength(Result, x);
end;
end
else
SetSynaError(ErrTimeout);
end;
end;
ExceptCheck;
end;
function TBlockSerial.RecvByte(timeout: integer): byte;
begin
Result := 0;
if PreTestFailing then {HGJ}
Exit; {HGJ}
SetSynaError(sOK);
if FBuffer = '' then
FBuffer := RecvPacket(Timeout);
if (FLastError = sOK) and (FBuffer <> '') then
begin
Result := Ord(FBuffer[1]);
System.Delete(FBuffer, 1, 1);
end;
ExceptCheck;
end;
function TBlockSerial.RecvTerminated(Timeout: Integer; const Terminator: AnsiString): AnsiString;
var
x: Integer;
s: AnsiString;
l: Integer;
CorCRLF: Boolean;
t: ansistring;
tl: integer;
ti: LongWord;
begin
Result := '';
if PreTestFailing then {HGJ}
Exit; {HGJ}
SetSynaError(sOK);
l := system.Length(Terminator);
if l = 0 then
Exit;
tl := l;
CorCRLF := FConvertLineEnd and (Terminator = CRLF);
s := '';
x := 0;
repeat
ti := GetTick;
//get rest of FBuffer or incomming new data...
s := s + RecvPacket(Timeout);
if FLastError <> sOK then
Break;
x := 0;
if Length(s) > 0 then
if CorCRLF then
begin
if FLastCR and (s[1] = LF) then
Delete(s, 1, 1);
if FLastLF and (s[1] = CR) then
Delete(s, 1, 1);
FLastCR := False;
FLastLF := False;
t := '';
x := PosCRLF(s, t);
tl := system.Length(t);
if t = CR then
FLastCR := True;
if t = LF then
FLastLF := True;
end
else
begin
x := pos(Terminator, s);
tl := l;
end;
if (FMaxLineLength <> 0) and (system.Length(s) > FMaxLineLength) then
begin
SetSynaError(ErrMaxBuffer);
Break;
end;
if x > 0 then
Break;
if not FInterPacketTimeout then
begin
Timeout := Timeout - integer(TickDelta(ti, GetTick));
if Timeout <= 0 then
begin
SetSynaError(ErrTimeout);
Break;
end;
end;
until False;
if x > 0 then
begin
Result := Copy(s, 1, x - 1);
System.Delete(s, 1, x + tl - 1);
end;
FBuffer := s;
ExceptCheck;
end;
function TBlockSerial.RecvString(Timeout: Integer): AnsiString;
var
s: AnsiString;
begin
Result := '';
s := RecvTerminated(Timeout, #13 + #10);
if FLastError = sOK then
Result := s;
end;
function TBlockSerial.RecvInteger(Timeout: Integer): Integer;
var
s: AnsiString;
begin
Result := 0;
s := RecvBufferStr(4, Timeout);
if FLastError = 0 then
Result := (ord(s[1]) + ord(s[2]) * 256) + (ord(s[3]) + ord(s[4]) * 256) * 65536;
end;
function TBlockSerial.RecvBlock(Timeout: Integer): AnsiString;
var
x: integer;
begin
Result := '';
x := RecvInteger(Timeout);
if FLastError = 0 then
Result := RecvBufferStr(x, Timeout);
end;
procedure TBlockSerial.RecvStreamRaw(const Stream: TStream; Timeout: Integer);
var
s: AnsiString;
begin
repeat
s := RecvPacket(Timeout);
if FLastError = 0 then
WriteStrToStream(Stream, s);
until FLastError <> 0;
end;
procedure TBlockSerial.RecvStreamSize(const Stream: TStream; Timeout: Integer; Size: Integer);
var
s: AnsiString;
n: integer;
begin
for n := 1 to (Size div cSerialChunk) do
begin
s := RecvBufferStr(cSerialChunk, Timeout);
if FLastError <> 0 then
Exit;
Stream.Write(PAnsichar(s)^, cSerialChunk);
end;
n := Size mod cSerialChunk;
if n > 0 then
begin
s := RecvBufferStr(n, Timeout);
if FLastError <> 0 then
Exit;
Stream.Write(PAnsichar(s)^, n);
end;
end;
procedure TBlockSerial.RecvStreamIndy(const Stream: TStream; Timeout: Integer);
var
x: integer;
begin
x := RecvInteger(Timeout);
x := SwapBytes(x);
if FLastError = 0 then
RecvStreamSize(Stream, Timeout, x);
end;
procedure TBlockSerial.RecvStream(const Stream: TStream; Timeout: Integer);
var
x: integer;
begin
x := RecvInteger(Timeout);
if FLastError = 0 then
RecvStreamSize(Stream, Timeout, x);
end;
{$IFNDEF MSWINDOWS}
function TBlockSerial.WaitingData: integer;
begin
{$IFNDEF FPC}
serialcheck(ioctl(FHandle, FIONREAD, @result));
{$ELSE}
serialcheck(fpIoctl(FHandle, FIONREAD, @result));
{$ENDIF}
if FLastError <> 0 then
Result := 0;
ExceptCheck;
end;
{$ELSE}
function TBlockSerial.WaitingData: integer;
var
stat: TComStat;
err: DWORD;
begin
err := 0;
if ClearCommError(FHandle, err, @stat) then
begin
SetSynaError(sOK);
Result := stat.cbInQue;
end
else
begin
SerialCheck(sErr);
Result := 0;
end;
ExceptCheck;
end;
{$ENDIF}
function TBlockSerial.WaitingDataEx: integer;
begin
if FBuffer <> '' then
Result := Length(FBuffer)
else
Result := Waitingdata;
end;
{$IFNDEF MSWINDOWS}
function TBlockSerial.SendingData: integer;
begin
SetSynaError(sOK);
Result := 0;
end;
{$ELSE}
function TBlockSerial.SendingData: integer;
var
stat: TComStat;
err: DWORD;
begin
SetSynaError(sOK);
err := 0;
if not ClearCommError(FHandle, err, @stat) then
serialcheck(sErr);
ExceptCheck;
result := stat.cbOutQue;
end;
{$ENDIF}
{$IFNDEF MSWINDOWS}
procedure TBlockSerial.DcbToTermios(const dcb: TDCB; var term: termios);
var
n: integer;
x: cardinal;
begin
//others
cfmakeraw(term);
term.c_cflag := term.c_cflag or CREAD;
term.c_cflag := term.c_cflag or CLOCAL;
term.c_cflag := term.c_cflag or HUPCL;
//hardware handshake
if (dcb.flags and dcb_RtsControlHandshake) > 0 then
term.c_cflag := term.c_cflag or CRTSCTS
else
term.c_cflag := term.c_cflag and (not CRTSCTS);
//software handshake
if (dcb.flags and dcb_OutX) > 0 then
term.c_iflag := term.c_iflag or IXON or IXOFF or IXANY
else
term.c_iflag := term.c_iflag and (not (IXON or IXOFF or IXANY));
//size of byte
term.c_cflag := term.c_cflag and (not CSIZE);
case dcb.bytesize of
5:
term.c_cflag := term.c_cflag or CS5;
6:
term.c_cflag := term.c_cflag or CS6;
7:
{$IFDEF FPC}
term.c_cflag := term.c_cflag or CS7;
{$ELSE}
term.c_cflag := term.c_cflag or CS7fix;
{$ENDIF}
8:
term.c_cflag := term.c_cflag or CS8;
end;
//parity
if (dcb.flags and dcb_ParityCheck) > 0 then
term.c_cflag := term.c_cflag or PARENB
else
term.c_cflag := term.c_cflag and (not PARENB);
case dcb.parity of
1: //'O'
term.c_cflag := term.c_cflag or PARODD;
2: //'E'
term.c_cflag := term.c_cflag and (not PARODD);
end;
//stop bits
if dcb.stopbits > 0 then
term.c_cflag := term.c_cflag or CSTOPB
else
term.c_cflag := term.c_cflag and (not CSTOPB);
//set baudrate;
x := 0;
for n := 0 to Maxrates do
if rates[n, 0] = dcb.BaudRate then
begin
x := rates[n, 1];
break;
end;
cfsetospeed(term, x);
cfsetispeed(term, x);
end;
procedure TBlockSerial.TermiosToDcb(const term: termios; var dcb: TDCB);
var
n: integer;
x: cardinal;
begin
//set baudrate;
dcb.baudrate := 0;
{$IFDEF FPC}
//why FPC not have cfgetospeed???
x := term.c_oflag and $0F;
{$ELSE}
x := cfgetospeed(term);
{$ENDIF}
for n := 0 to Maxrates do
if rates[n, 1] = x then
begin
dcb.baudrate := rates[n, 0];
break;
end;
//hardware handshake
if (term.c_cflag and CRTSCTS) > 0 then
dcb.flags := dcb.flags or dcb_RtsControlHandshake or dcb_OutxCtsFlow
else
dcb.flags := dcb.flags and (not (dcb_RtsControlHandshake or dcb_OutxCtsFlow));
//software handshake
if (term.c_cflag and IXOFF) > 0 then
dcb.flags := dcb.flags or dcb_OutX or dcb_InX
else
dcb.flags := dcb.flags and (not (dcb_OutX or dcb_InX));
//size of byte
case term.c_cflag and CSIZE of
CS5:
dcb.bytesize := 5;
CS6:
dcb.bytesize := 6;
CS7fix:
dcb.bytesize := 7;
CS8:
dcb.bytesize := 8;
end;
//parity
if (term.c_cflag and PARENB) > 0 then
dcb.flags := dcb.flags or dcb_ParityCheck
else
dcb.flags := dcb.flags and (not dcb_ParityCheck);
dcb.parity := 0;
if (term.c_cflag and PARODD) > 0 then
dcb.parity := 1
else
dcb.parity := 2;
//stop bits
if (term.c_cflag and CSTOPB) > 0 then
dcb.stopbits := 2
else
dcb.stopbits := 0;
end;
{$ENDIF}
{$IFNDEF MSWINDOWS}
procedure TBlockSerial.SetCommState;
begin
DcbToTermios(dcb, termiosstruc);
SerialCheck(tcsetattr(FHandle, TCSANOW, termiosstruc));
ExceptCheck;
end;
{$ELSE}
procedure TBlockSerial.SetCommState;
begin
SetSynaError(sOK);
if not windows.SetCommState(Fhandle, dcb) then
SerialCheck(sErr);
ExceptCheck;
end;
{$ENDIF}
{$IFNDEF MSWINDOWS}
procedure TBlockSerial.GetCommState;
begin
SerialCheck(tcgetattr(FHandle, termiosstruc));
ExceptCheck;
TermiostoDCB(termiosstruc, dcb);
end;
{$ELSE}
procedure TBlockSerial.GetCommState;
begin
SetSynaError(sOK);
if not windows.GetCommState(Fhandle, dcb) then
SerialCheck(sErr);
ExceptCheck;
end;
{$ENDIF}
procedure TBlockSerial.SetSizeRecvBuffer(size: integer);
begin
{$IFDEF MSWINDOWS}
SetupComm(Fhandle, size, 0);
GetCommState;
dcb.XonLim := size div 4;
dcb.XoffLim := size div 4;
SetCommState;
{$ENDIF}
FRecvBuffer := size;
end;
function TBlockSerial.GetDSR: Boolean;
begin
ModemStatus;
{$IFNDEF MSWINDOWS}
Result := (FModemWord and TIOCM_DSR) > 0;
{$ELSE}
Result := (FModemWord and MS_DSR_ON) > 0;
{$ENDIF}
end;
procedure TBlockSerial.SetDTRF(Value: Boolean);
begin
{$IFNDEF MSWINDOWS}
ModemStatus;
if Value then
FModemWord := FModemWord or TIOCM_DTR
else
FModemWord := FModemWord and not TIOCM_DTR;
{$IFNDEF FPC}
ioctl(FHandle, TIOCMSET, @FModemWord);
{$ELSE}
fpioctl(FHandle, TIOCMSET, @FModemWord);
{$ENDIF}
{$ELSE}
if Value then
EscapeCommFunction(FHandle, SETDTR)
else
EscapeCommFunction(FHandle, CLRDTR);
{$ENDIF}
end;
function TBlockSerial.GetCTS: Boolean;
begin
ModemStatus;
{$IFNDEF MSWINDOWS}
Result := (FModemWord and TIOCM_CTS) > 0;
{$ELSE}
Result := (FModemWord and MS_CTS_ON) > 0;
{$ENDIF}
end;
procedure TBlockSerial.SetRTSF(Value: Boolean);
begin
{$IFNDEF MSWINDOWS}
ModemStatus;
if Value then
FModemWord := FModemWord or TIOCM_RTS
else
FModemWord := FModemWord and not TIOCM_RTS;
{$IFNDEF FPC}
ioctl(FHandle, TIOCMSET, @FModemWord);
{$ELSE}
fpioctl(FHandle, TIOCMSET, @FModemWord);
{$ENDIF}
{$ELSE}
if Value then
EscapeCommFunction(FHandle, SETRTS)
else
EscapeCommFunction(FHandle, CLRRTS);
{$ENDIF}
end;
function TBlockSerial.GetCarrier: Boolean;
begin
ModemStatus;
{$IFNDEF MSWINDOWS}
Result := (FModemWord and TIOCM_CAR) > 0;
{$ELSE}
Result := (FModemWord and MS_RLSD_ON) > 0;
{$ENDIF}
end;
function TBlockSerial.GetRing: Boolean;
begin
ModemStatus;
{$IFNDEF MSWINDOWS}
Result := (FModemWord and TIOCM_RNG) > 0;
{$ELSE}
Result := (FModemWord and MS_RING_ON) > 0;
{$ENDIF}
end;
{$IFDEF MSWINDOWS}
function TBlockSerial.CanEvent(Event: dword; Timeout: integer): boolean;
var
ex: DWord;
y: Integer;
Overlapped: TOverlapped;
begin
FillChar(Overlapped, Sizeof(Overlapped), 0);
Overlapped.hEvent := CreateEvent(nil, True, False, nil);
try
SetCommMask(FHandle, Event);
SetSynaError(sOK);
if (Event = EV_RXCHAR) and (Waitingdata > 0) then
Result := True
else
begin
y := 0;
ex := 0;
if not WaitCommEvent(FHandle, ex, @Overlapped) then
y := GetLastError;
if y = ERROR_IO_PENDING then
begin
//timedout
WaitForSingleObject(Overlapped.hEvent, Timeout);
SetCommMask(FHandle, 0);
GetOverlappedResult(FHandle, Overlapped, DWord(y), True);
end;
Result := (ex and Event) = Event;
end;
finally
SetCommMask(FHandle, 0);
CloseHandle(Overlapped.hEvent);
end;
end;
{$ENDIF}
{$IFNDEF MSWINDOWS}
function TBlockSerial.CanRead(Timeout: integer): boolean;
var
FDSet: TFDSet;
TimeVal: PTimeVal;
TimeV: TTimeVal;
x: Integer;
begin
TimeV.tv_usec := (Timeout mod 1000) * 1000;
TimeV.tv_sec := Timeout div 1000;
TimeVal := @TimeV;
if Timeout = -1 then
TimeVal := nil;
{$IFNDEF FPC}
FD_ZERO(FDSet);
FD_SET(FHandle, FDSet);
x := Select(FHandle + 1, @FDSet, nil, nil, TimeVal);
{$ELSE}
fpFD_ZERO(FDSet);
fpFD_SET(FHandle, FDSet);
x := fpSelect(FHandle + 1, @FDSet, nil, nil, TimeVal);
{$ENDIF}
SerialCheck(x);
if FLastError <> sOK then
x := 0;
Result := x > 0;
ExceptCheck;
if Result then
DoStatus(HR_CanRead, '');
end;
{$ELSE}
function TBlockSerial.CanRead(Timeout: integer): boolean;
begin
Result := WaitingData > 0;
if not Result then
Result := CanEvent(EV_RXCHAR, Timeout) or (WaitingData > 0);
//check WaitingData again due some broken virtual ports
if Result then
DoStatus(HR_CanRead, '');
end;
{$ENDIF}
{$IFNDEF MSWINDOWS}
function TBlockSerial.CanWrite(Timeout: integer): boolean;
var
FDSet: TFDSet;
TimeVal: PTimeVal;
TimeV: TTimeVal;
x: Integer;
begin
TimeV.tv_usec := (Timeout mod 1000) * 1000;
TimeV.tv_sec := Timeout div 1000;
TimeVal := @TimeV;
if Timeout = -1 then
TimeVal := nil;
{$IFNDEF FPC}
FD_ZERO(FDSet);
FD_SET(FHandle, FDSet);
x := Select(FHandle + 1, nil, @FDSet, nil, TimeVal);
{$ELSE}
fpFD_ZERO(FDSet);
fpFD_SET(FHandle, FDSet);
x := fpSelect(FHandle + 1, nil, @FDSet, nil, TimeVal);
{$ENDIF}
SerialCheck(x);
if FLastError <> sOK then
x := 0;
Result := x > 0;
ExceptCheck;
if Result then
DoStatus(HR_CanWrite, '');
end;
{$ELSE}
function TBlockSerial.CanWrite(Timeout: integer): boolean;
var
t: LongWord;
begin
Result := SendingData = 0;
if not Result then
Result := CanEvent(EV_TXEMPTY, Timeout);
{$IFDEF WIN32}
if Result and (Win32Platform <> VER_PLATFORM_WIN32_NT) then
begin
t := GetTick;
while not ReadTxEmpty(FPortAddr) do
begin
if TickDelta(t, GetTick) > 255 then
Break;
Sleep(0);
end;
end;
{$ENDIF}
if Result then
DoStatus(HR_CanWrite, '');
end;
{$ENDIF}
function TBlockSerial.CanReadEx(Timeout: integer): boolean;
begin
if Fbuffer <> '' then
Result := True
else
Result := CanRead(Timeout);
end;
procedure TBlockSerial.EnableRTSToggle(Value: boolean);
begin
SetSynaError(sOK);
{$IFNDEF MSWINDOWS}
FRTSToggle := Value;
if Value then
RTS:=False;
{$ELSE}
if Win32Platform = VER_PLATFORM_WIN32_NT then
begin
GetCommState;
if value then
dcb.Flags := dcb.Flags or dcb_RtsControlToggle
else
dcb.flags := dcb.flags and (not dcb_RtsControlToggle);
SetCommState;
end
else
begin
FRTSToggle := Value;
if Value then
RTS:=False;
end;
{$ENDIF}
end;
procedure TBlockSerial.Flush;
begin
{$IFNDEF MSWINDOWS}
SerialCheck(tcdrain(FHandle));
{$ELSE}
SetSynaError(sOK);
if not Flushfilebuffers(FHandle) then
SerialCheck(sErr);
{$ENDIF}
ExceptCheck;
end;
{$IFNDEF MSWINDOWS}
procedure TBlockSerial.Purge;
begin
{$IFNDEF FPC}
SerialCheck(ioctl(FHandle, TCFLSH, TCIOFLUSH));
{$ELSE}
{$IFDEF DARWIN}
SerialCheck(fpioctl(FHandle, TCIOflush, Pointer(PtrInt(TCIOFLUSH))));
{$ELSE}
SerialCheck(fpioctl(FHandle, {$IFDEF FreeBSD}TCIOFLUSH{$ELSE}TCFLSH{$ENDIF}, Pointer(PtrInt(TCIOFLUSH))));
{$ENDIF}
{$ENDIF}
FBuffer := '';
ExceptCheck;
end;
{$ELSE}
procedure TBlockSerial.Purge;
var
x: integer;
begin
SetSynaError(sOK);
x := PURGE_TXABORT or PURGE_TXCLEAR or PURGE_RXABORT or PURGE_RXCLEAR;
if not PurgeComm(FHandle, x) then
SerialCheck(sErr);
FBuffer := '';
ExceptCheck;
end;
{$ENDIF}
function TBlockSerial.ModemStatus: integer;
begin
Result := 0;
{$IFNDEF MSWINDOWS}
{$IFNDEF FPC}
SerialCheck(ioctl(FHandle, TIOCMGET, @Result));
{$ELSE}
SerialCheck(fpioctl(FHandle, TIOCMGET, @Result));
{$ENDIF}
{$ELSE}
SetSynaError(sOK);
if not GetCommModemStatus(FHandle, dword(Result)) then
SerialCheck(sErr);
{$ENDIF}
ExceptCheck;
FModemWord := Result;
end;
procedure TBlockSerial.SetBreak(Duration: integer);
begin
{$IFNDEF MSWINDOWS}
SerialCheck(tcsendbreak(FHandle, Duration));
{$ELSE}
SetCommBreak(FHandle);
Sleep(Duration);
SetSynaError(sOK);
if not ClearCommBreak(FHandle) then
SerialCheck(sErr);
{$ENDIF}
end;
{$IFDEF MSWINDOWS}
procedure TBlockSerial.DecodeCommError(Error: DWord);
begin
if (Error and DWord(CE_FRAME)) > 1 then
FLastError := ErrFrame;
if (Error and DWord(CE_OVERRUN)) > 1 then
FLastError := ErrOverrun;
if (Error and DWord(CE_RXOVER)) > 1 then
FLastError := ErrRxOver;
if (Error and DWord(CE_RXPARITY)) > 1 then
FLastError := ErrRxParity;
if (Error and DWord(CE_TXFULL)) > 1 then
FLastError := ErrTxFull;
end;
{$ENDIF}
//HGJ
function TBlockSerial.PreTestFailing: Boolean;
begin
if not FInstanceActive then
begin
RaiseSynaError(ErrPortNotOpen);
result:= true;
Exit;
end;
Result := not TestCtrlLine;
if result then
RaiseSynaError(ErrNoDeviceAnswer)
end;
function TBlockSerial.TestCtrlLine: Boolean;
begin
result := ((not FTestDSR) or DSR) and ((not FTestCTS) or CTS);
end;
function TBlockSerial.ATCommand(value: AnsiString): AnsiString;
var
s: AnsiString;
ConvSave: Boolean;
begin
result := '';
FAtResult := False;
ConvSave := FConvertLineEnd;
try
FConvertLineEnd := True;
SendString(value + #$0D);
repeat
s := RecvString(FAtTimeout);
if s <> Value then
result := result + s + CRLF;
if s = 'OK' then
begin
FAtResult := True;
break;
end;
if s = 'ERROR' then
break;
until FLastError <> sOK;
finally
FConvertLineEnd := Convsave;
end;
end;
function TBlockSerial.ATConnect(value: AnsiString): AnsiString;
var
s: AnsiString;
ConvSave: Boolean;
begin
result := '';
FAtResult := False;
ConvSave := FConvertLineEnd;
try
FConvertLineEnd := True;
SendString(value + #$0D);
repeat
s := RecvString(90 * FAtTimeout);
if s <> Value then
result := result + s + CRLF;
if s = 'NO CARRIER' then
break;
if s = 'ERROR' then
break;
if s = 'BUSY' then
break;
if s = 'NO DIALTONE' then
break;
if Pos('CONNECT', s) = 1 then
begin
FAtResult := True;
break;
end;
until FLastError <> sOK;
finally
FConvertLineEnd := Convsave;
end;
end;
function TBlockSerial.SerialCheck(SerialResult: integer): integer;
begin
if SerialResult = integer(INVALID_HANDLE_VALUE) then
{$IFDEF MSWINDOWS}
result := GetLastError
{$ELSE}
{$IFNDEF FPC}
result := GetLastError
{$ELSE}
result := fpGetErrno
{$ENDIF}
{$ENDIF}
else
result := sOK;
FLastError := result;
FLastErrorDesc := GetErrorDesc(FLastError);
end;
procedure TBlockSerial.ExceptCheck;
var
e: ESynaSerError;
s: string;
begin
if FRaiseExcept and (FLastError <> sOK) then
begin
s := GetErrorDesc(FLastError);
e := ESynaSerError.CreateFmt('Communication error %d: %s', [FLastError, s]);
e.ErrorCode := FLastError;
e.ErrorMessage := s;
raise e;
end;
end;
procedure TBlockSerial.SetSynaError(ErrNumber: integer);
begin
FLastError := ErrNumber;
FLastErrorDesc := GetErrorDesc(FLastError);
end;
procedure TBlockSerial.RaiseSynaError(ErrNumber: integer);
begin
SetSynaError(ErrNumber);
ExceptCheck;
end;
procedure TBlockSerial.DoStatus(Reason: THookSerialReason; const Value: string);
begin
if assigned(OnStatus) then
OnStatus(Self, Reason, Value);
end;
{======================================================================}
class function TBlockSerial.GetErrorDesc(ErrorCode: integer): string;
begin
Result:= '';
case ErrorCode of
sOK: Result := 'OK';
ErrAlreadyOwned: Result := 'Port owned by other process';{HGJ}
ErrAlreadyInUse: Result := 'Instance already in use'; {HGJ}
ErrWrongParameter: Result := 'Wrong parameter at call'; {HGJ}
ErrPortNotOpen: Result := 'Instance not yet connected'; {HGJ}
ErrNoDeviceAnswer: Result := 'No device answer detected'; {HGJ}
ErrMaxBuffer: Result := 'Maximal buffer length exceeded';
ErrTimeout: Result := 'Timeout during operation';
ErrNotRead: Result := 'Reading of data failed';
ErrFrame: Result := 'Receive framing error';
ErrOverrun: Result := 'Receive Overrun Error';
ErrRxOver: Result := 'Receive Queue overflow';
ErrRxParity: Result := 'Receive Parity Error';
ErrTxFull: Result := 'Tranceive Queue is full';
end;
if Result = '' then
begin
Result := SysErrorMessage(ErrorCode);
end;
end;
{---------- cpom Comport Ownership Manager Routines -------------
by Hans-Georg Joepgen of Stuttgart, Germany.
Copyright (c) 2002, by Hans-Georg Joepgen
Stefan Krauss of Stuttgart, Germany, contributed literature and Internet
research results, invaluable advice and excellent answers to the Comport
Ownership Manager.
}
{$IFDEF UNIX}
function TBlockSerial.LockfileName: String;
var
s: string;
begin
s := SeparateRight(FDevice, '/dev/');
result := LockfileDirectory + '/LCK..' + s;
end;
procedure TBlockSerial.CreateLockfile(PidNr: integer);
var
f: TextFile;
s: string;
begin
// Create content for file
s := IntToStr(PidNr);
while length(s) < 10 do
s := ' ' + s;
// Create file
try
AssignFile(f, LockfileName);
try
Rewrite(f);
writeln(f, s);
finally
CloseFile(f);
end;
// Allow all users to enjoy the benefits of cpom
s := 'chmod a+rw ' + LockfileName;
{$IFNDEF FPC}
FileSetReadOnly( LockfileName, False ) ;
// Libc.system(pchar(s));
{$ELSE}
fpSystem(s);
{$ENDIF}
except
// not raise exception, if you not have write permission for lock.
on Exception do
;
end;
end;
function TBlockSerial.ReadLockfile: integer;
{Returns PID from Lockfile. Lockfile must exist.}
var
f: TextFile;
s: string;
begin
AssignFile(f, LockfileName);
Reset(f);
try
readln(f, s);
finally
CloseFile(f);
end;
Result := StrToIntDef(s, -1)
end;
function TBlockSerial.cpomComportAccessible: boolean;
var
MyPid: integer;
Filename: string;
begin
Filename := LockfileName;
{$IFNDEF FPC}
MyPid := Libc.getpid;
{$ELSE}
MyPid := fpGetPid;
{$ENDIF}
// Make sure, the Lock Files Directory exists. We need it.
if not DirectoryExists(LockfileDirectory) then
CreateDir(LockfileDirectory);
// Check the Lockfile
if not FileExists (Filename) then
begin // comport is not locked. Lock it for us.
CreateLockfile(MyPid);
result := true;
exit; // done.
end;
// Is port owned by orphan? Then it's time for error recovery.
//FPC forgot to add getsid.. :-(
{$IFNDEF FPC}
if Libc.getsid(ReadLockfile) = -1 then
begin // Lockfile was left from former desaster
DeleteFile(Filename); // error recovery
CreateLockfile(MyPid);
result := true;
exit;
end;
{$ENDIF}
result := false // Sorry, port is owned by living PID and locked
end;
procedure TBlockSerial.cpomReleaseComport;
begin
DeleteFile(LockfileName);
end;
{$ENDIF}
{----------------------------------------------------------------}
{$IFDEF MSWINDOWS}
function GetSerialPortNames: string;
var
reg: TRegistry;
l, v: TStringList;
n: integer;
begin
l := TStringList.Create;
v := TStringList.Create;
reg := TRegistry.Create;
try
{$IFNDEF VER100}
{$IFNDEF VER120}
reg.Access := KEY_READ;
{$ENDIF}
{$ENDIF}
reg.RootKey := HKEY_LOCAL_MACHINE;
reg.OpenKey('\HARDWARE\DEVICEMAP\SERIALCOMM', false);
reg.GetValueNames(l);
for n := 0 to l.Count - 1 do
v.Add(PChar(reg.ReadString(l[n])));
Result := v.CommaText;
finally
reg.Free;
l.Free;
v.Free;
end;
end;
{$ENDIF}
{$IFNDEF MSWINDOWS}
function GetSerialPortNames: string;
var
sr : TSearchRec;
begin
Result := '';
if FindFirst('/dev/ttyS*', $FFFFFFFF, sr) = 0 then
repeat
if (sr.Attr and $FFFFFFFF) = Sr.Attr then
begin
if Result <> '' then
Result := Result + ',';
Result := Result + '/dev/' + sr.Name;
end;
until FindNext(sr) <> 0;
FindClose(sr);
if FindFirst('/dev/ttyUSB*', $FFFFFFFF, sr) = 0 then begin
repeat
if (sr.Attr and $FFFFFFFF) = Sr.Attr then begin
if Result <> '' then Result := Result + ',';
Result := Result + '/dev/' + sr.Name;
end;
until FindNext(sr) <> 0;
end;
FindClose(sr);
if FindFirst('/dev/ttyAM*', $FFFFFFFF, sr) = 0 then begin
repeat
if (sr.Attr and $FFFFFFFF) = Sr.Attr then begin
if Result <> '' then Result := Result + ',';
Result := Result + '/dev/' + sr.Name;
end;
until FindNext(sr) <> 0;
end;
FindClose(sr);
end;
{$ENDIF}
end.
|
PROGRAM READER (INPUT, OUTPUT);
VAR SYMBOL:CHAR;
BEGIN
WRITE('"');
REPEAT
READ(SYMBOL); WRITE(SYMBOL)
UNTIL (SYMBOL='.') OR (SYMBOL='?') OR (SYMBOL='!');
WRITE('"');
END.
|
unit MetNum;
interface
uses
Math,readf0nd;
const
{Скорость вращения Земли (рад/с)}
EARTH_ROT_SPEED = 2*PI/86400;
{Радиус земли в км}
EARTH_RAD = 6371;
{Стандартная эпоха (юлианские дни)}
STANDRD_ERA = 2451545.0;
{Маленькое число, для точности численных методов}
EPS = 10E-12;
{Кол-во километров в 1 а.е.}
AU_KM = 1.49597870691E+8;
{Константа для перевода градусов в радианы и обратно}
RAD = PI/180.0;
{Наклон эклиптики к экватору (радианы)}
ECL_EQ = 84381.412/3600*rad;
MU = 2.9591220828559110225E-4;
{Количество градусов в одном часе}
DEG_IN_HOUR = 15;
type
{fЭлементы орбиты метеороида: a,e,i,Om,w,v}
ElementsOfOrbit = record
a,e,i,Om,w,v: extended;
end;
{Декартовы координаты и скорости метеороида: X,Y,Z,Vx,Vy,Vz}
DecartCoords = record
X,Y,Z,Vx,Vy,Vz: extended;
end;
{Комбинированный тип данных для даты и времени}
DateTime = record
day,month,year,hour,minute: integer;
second: extended;
end;
{Экваториальные координаты (прямое восхождение, склонение)}
EquatorCoords = record
alpha,delta: extended;
end;
{Горизонтальные координаты (азимут, высота над горизонтом)}
HorizontalCoords = record
Az,h: extended;
end;
{Эклиптические координаты (долгота и широта)}
EclipticCoords = record
lamda,betta: extended;
end;
{Географические координаты (долгота и широта)}
GeogrCoords = record
long,lat: extended;
end;
{========================================================
Блок процедур и функций для инициализации и ввода.
Для автоматизации этой процедуры было придумано специальные
расширения .emet и .cmet, файлы которого являются специфицированным
текстом, то есть, данные идущие в определенном порядке для
облегчения процедуры ввода.
.emet хранит в себе элементы орбиты метеора в первой строке
в следующем порядке: a,e,i,Om,w,v.
.cmet хранит в себе координаты и скорости в первой строке в
следующем порядке: X,Y,Z,Vx,Vy,Vz.
Во второй строке обоих файлов хранится дата наблюдения в
формате dd mm yy hh mm ss.
В третей строке обоих файлов хранятся экваториальные координаты
наблюдаемого метеора в следующем порядке: alpha delta.
В зависимости от того, какой информацией о метеоре обладает
пользователь, будет выбираться функция для ввода.
Обе функции (для вариантов с координатами или элементами орбиты)
перегружены трижды. Соответственно, из файла может быть считана
лишь первая строка, первые две или все три.
=========================================================}
{+Ввод декартовых координат метеора, времени наблюдения и экваториальных координат
Test: +}
procedure inputCMet(filename: String; var met: DecartCoords; time: DateTime;
var eqCords: EquatorCoords); overload;
{+Ввод декартовых координат метеора и времени наблюдения
Test: +}
procedure inputCMet(filename: String; var met: DecartCoords; var time: DateTime); overload;
{+Ввод декартовых координат метеора
Test: +}
procedure inputCMet(filename: String; var met: DecartCoords); overload;
{+Ввод элементов орбиты метеора, времени наблюдения и экваториальных координат
Test: +}
procedure inputEMet(filename: String; var met: ElementsOfOrbit; var time: DateTime;
var eqCords: EquatorCoords); overload;
{+Ввод элементов орбиты метеора и времени его наблюдения
Test: +}
procedure inputEMet(filename: String; var met: ElementsOfOrbit; var time: DateTime); overload;
{+Ввод только элементов орбиты метеора
Test: +}
procedure inputEMet(filename: String; var met: ElementsOfOrbit); overload;
{+Инициализация даты и времени для дальнейшего использования в
программе
Test: +}
function initDateTime(day,month,year,hour,minute: integer; second: extended): DateTime;
{+Инициализация элементов орбиты метеора
Test: +}
function initElems(a,e,i,Om,w,v: extended): ElementsOfOrbit;
{+Инициализация декартовых координат метеора
Test: +}
function initDecartCoords(X,Y,Z,Vx,Vy,Vz: extended): DecartCoords;
{+Инициализация экваториальных координат
Test: +}
function initEquatorCoords(alpha,delta: extended): EquatorCoords;
{+Инициализация эклиптических координат
Test: +}
function initEclipticCoords(lamda,betta: extended): EclipticCoords;
{+Инициализация горизонтальных координат
Test: +}
function initHorizontalCoords(Az,h: extended): HorizontalCoords;
{+Инициализация георграфических координат
Test: +}
function initGeogrCoords(long,lat: extended): GeogrCoords;
{Вывод времени в файл
Test: +}
procedure printDateTime(t: DateTime; var fileName: text); overload;
{Вывод времени на экран
Test: +}
procedure printDateTime(t: DateTime); overload;
{+Вывод коордианат в файл
Test: +}
procedure printCoords(coords: DecartCoords; var fileName: text); overload;
{+Вывод координат на экран
Test: +}
procedure printCoords(coords: DecartCoords); overload;
{+Вывод скоростей в файл
Test: +}
procedure printVel(coords: DecartCoords; var fileName: text); overload;
{+Вывод скоростей на экран
Test: +}
procedure printVel(coords: DecartCoords); overload;
{+Вывод коордианат и скоростей в файл
Test: +}
procedure printCoordsVel(coords: DecartCoords; var fileName: text); overload;
{+Вывод координат и скоростей на экран
Test: +}
procedure printCoordsVel(coords: DecartCoords); overload;
{+Выводит в файл элементы орбиты
Test: +}
procedure printElements(elem: ElementsOfOrbit; var fileName: text); overload;
{+Выводит на экран элементы орбиты
Test: +}
procedure printElements(elem: ElementsOfOrbit); overload;
{+Вывод в файл небесных координат (конкретно, экваториальных)
Test: +}
procedure printCelCoords(coords: EquatorCoords; var fileName: text); overload;
{+Вывод в файл небесных координат (конкретно, горизонтальных)
Test: +}
procedure printCelCoords(coords: HorizontalCoords; var fileName: text); overload;
{+Вывод в файл небесных координат (конкретно, эклиптических)
Test: +}
procedure printCelCoords(coords: EclipticCoords; var fileName: text); overload;
{+Вывод в файл географических координат
Test: +}
procedure printCelCoords(coords: GeogrCoords; var filename: text); overload;
{+Вывод на экран небесных координат (конкретно, экваториальных)
Test: +}
procedure printCelCoords(coords: EquatorCoords); overload;
{+Вывод на экран небесных координат (конкретно, горизонтальных)
Test: +}
procedure printCelCoords(coords: HorizontalCoords); overload;
{+Вывод на экран небесных координат (конкретно, эклиптических)
Test: +}
procedure printCelCoords(coords: EclipticCoords); overload;
{+Вывод на экран географических координат
Test: +}
procedure printCelCoords(coords: GeogrCoords); overload;
{================================================================
Конец блока процедур инициализацции и ввода
=================================================================}
{=================================================================
Блок астрономических процедур и функций, связанных с переходами от одной СК
к другой, переходами от элементов орбиты к декартовым координатам и обратно,
процедурами, связанными с временем.
==================================================================}
{+Функция перехода от элементов орбиты к декартовым координатам
Test: +}
function fromOrbitToDecart(elems: ElementsOfOrbit): DecartCoords;
{+Функция перехода от декартовых координат к элементам орбиты
Test: +}
function fromDecartToOrbit(coord: DecartCoords): ElementsOfOrbit;
{+Перевод григорианской даты к юлианской
Test: +}
function JDate(dt: DateTime): extended;
{+Гринвичское звездное время на полночь введенной даты
Test: +}
function siderealTime(year,month,day: integer): extended;
{+Решает уравнение Кеплера методом Ньютона
Test: +}
function keplerSolution(e,M: extended): extended;
{+Возвращает уравнение Кеплера
Test: +}
function keplerEq(x,e,M: extended): extended;
{+Возвращает производную уравнения Кеплера
Test: +}
function keplerDifEq(x,e: extended): extended;
{+Получаем среднюю аномалию
Test: +}
function getM(t,t0,M0,a: extended): extended;
{+Получаем среднее движение
Test: +}
function getN(a: extended): extended;
{+Перевод юлианской даты к григорианской
Test: +}
function grDate(JD: extended): DateTime;
{+Звездное время на даную дату на данной долготе
Test: +}
function sidTimeOnLong(date: DateTime; long: extended): extended;
{+Переход от экваториальных координат к эклиптическим (случай сферы)
Test: +}
function fromEqToEcl(eq: EquatorCoords): EclipticCoords;
{+Переход от эклиптических координат к экваториальным (случай сферы)
Test: +}
function fromEclToEq(ecl: EclipticCoords): EquatorCoords;
{+Переход от горизонтальных координат к экваториальным (случай сферы)
Test: +}
function fromHorToEq(hor: HorizontalCoords; fi,sidTime: extended): EquatorCoords;
{+Переход от экваториальных координат к горизонтальным (случай сферы)
Test: +}
function fromEqToHor(eq: EquatorCoords; fi,sidTime: extended): HorizontalCoords;
{+Переход от экваториальных координат к эклиптичекским (декартов случай)
Test: +}
function fromEqToEclDecart(eq: DecartCoords): DecartCoords;
{+Переход от эклиптических координат к экваториальным (декартов случай)
Test: +}
function fromEclToEqDecart(ecl: DecartCoords): DecartCoords;
{+Возвращает радиант метеора
Test: +}
function getRadiant(met: DecartCoords): EquatorCoords;
{Рассчет элементов орбиты по методу, предложеному Дубяго}
function numElemsWithDubyago(eq: EquatorCoords; Vel: extended; Earth: DecartCoords): ElementsOfOrbit;
{=====================================================================
Конец блока астрономических процедур и функций
======================================================================}
{=====================================================================
Блок математических процедур и функций. Вращение систем координат,
модули векторов, перевод одних единиц в другие.
======================================================================}
{+Поворот системы координат вокруг оси Х на угол angle (в радианах)
Test: +}
function rotateSCX(angle: extended; dc: DecartCoords): DecartCoords;
{+Поворот системы координат вокруг оси Y на угол angle (в радианах)
Test: +}
function rotateSCY(angle: extended; dc: DecartCoords): DecartCoords;
{+Поворот системы координат вокруг оси Z на угол angle (в радианах)
Test: +}
function rotateSCZ(angle: extended; dc: DecartCoords): DecartCoords;
{+Переход от декартовых координат к сферическим
Test: +}
procedure fromDecartToSphere(A: DecartCoords; var fi,lam: extended);
{+Переход от сферы к декартовым координатам
Test: +}
function fromSphereToDecart(fi,lam,r: extended): DecartCoords;
{+Сумма двух векторов (и координат, и скоростей)
Test: +}
function sumOfVectors(A,B: DecartCoords): DecartCoords;
{+Разность двух векторов (и координат, и скоростей)
Test: +}
function differenceOfVectors(A,B: DecartCoords): DecartCoords;
{+Модуль вектора положения (части, отвечающей за координаты)
Test: +}
function moduleOfCoords(A: DecartCoords): extended;
{+Модуль вектора скорости (части, отвечающей за скорость)
Test: +}
function moduleOfVelocity(A: DecartCoords): extended;
{+Переход к представлению времени в виде десятичной дроби (в часах)
Test: +}
function timeToDotTime(t: DateTime): extended;
{+Переход к дискретному представлению времени (часы, минуты, секунды) от
вида двесятичной дроби (поля отвечающие за дату равны НУЛЮ)
Test: +}
function dotTimeToTime(t: extended): DateTime;
{+Перевод градусов в радианы
Test: +}
function toRadians(x: extended): extended; overload;
{+Перевод угловых величин элементов орбиты из градусов в радианы
Test: +}
function toRadians(elems: ElementsOfOrbit): ElementsOfOrbit; overload;
{+Перевод экваториальных координат из градусов в радианы
Test: +}
function toRadians(eq: EquatorCoords): EquatorCoords; overload;
{+Перевод эклиптических координат из градусов в радианы
Test: +}
function toRadians(ecl: EclipticCoords): EclipticCoords; overload;
{+Перевод горизонтальных координат из градусов в радианы
Test: +}
function toRadians(hor: HorizontalCoords): HorizontalCoords; overload;
{+Перевод географических координат из градусов в радианы
Test: +}
function toRadians(gCoords: GeogrCoords): GeogrCoords; overload;
{+Перевод радиан в градусы
Test: +}
function toDegree(x: extended): extended; overload;
{+Перевод угловых величин элементов орбиты из радиан в градусы
Test: +}
function toDegree(elems: ElementsOfOrbit): ElementsOfOrbit; overload;
{+Перевод экваториальных координат из радиан в градусы
Test: +}
function toDegree(eq: EquatorCoords): EquatorCoords; overload;
{+Перевод эклиптических координат из радиан в градусы
Test: +}
function toDegree(ecl: EclipticCoords): EclipticCoords; overload;
{+Перевод горизонтальных координат из радиан в градусы
Test: +}
function toDegree(hor: HorizontalCoords): HorizontalCoords; overload;
{+Перевод географических координат из радиан в градусы
Test: +}
function toDegree(gCoords: GeogrCoords): GeogrCoords; overload;
{+Перевод километров в астрономические единицы
Test: +}
function toAu(x: extended): extended;
{+Перевод декартовых координат из километров в астрономические единицы
ВНИМАНИЕ! Скорости переводятся из км/сек в Au/сут.
Test: +}
function coordsToAu(coords: DecartCoords): DecartCoords;
{+Перевод астрономических единиц в километры
Test: +}
function toKm(x: extended): extended;
{+Перевод декартовых координат из астрономических единиц в километры
ВНИМАНИЕ! Скорости переводятся из Au/сут. в км/сек.
Test: +}
function coordsToKm(coords: DecartCoords): DecartCoords;
{+Перевод градусов в часы
Test: +}
function toHour(x: extended): extended;
{+Перевод часов в градусы
Test: +}
function toDegFromHour(x: extended): extended;
{Перевод угла к интервалу [0,2*PI]
Test: +}
function toTwoPiInterval(angle: extended): extended;
{=====================================================================
Конец блока математических процедур и функций
======================================================================}
{=====================================================================
Блок процедур и функций, работающих со внешними данными.
Здесь работа с фондами больших планет. По надобности и использованию
сторонних библиотек будет дополняться.
======================================================================}
{Получаем координаты Земли из 406 фонда больших планет
Test: +}
function getEarthCoords(JD: extended): DecartCoords;
{=====================================================================
Конец блока процедур и функций, работающих со внешними данными
======================================================================}
implementation
{=============================================================================}
procedure inputCMet(filename: String; var met: DecartCoords; time: DateTime;
var eqCords: EquatorCoords); overload;
var infile: text;
begin
try
Assign(infile,filename);
Reset(infile);
except
Writeln('Файл не найден. Проверьте правильность пути.');
Readln;
Halt;
end;
try
Readln(infile,met.X,met.Y,met.Z,met.Vx,met.Vy,met.Vz);
except
Writeln('Невозможно считать координаты. Проверьте конфигурацию файла.');
Readln;
Halt;
end;
try
Readln(infile,time.day,time.month,time.year,time.hour,time.minute,time.second);
except
Writeln('Невозможно считать дату. Проверьте конфигурацию файла.');
Readln;
Halt;
end;
try
Readln(infile,eqCords.alpha,eqCords.delta);
except
Writeln('Невозможно считать экваториальные координаты. Проверьте конфигурацию файла.');
Readln;
Halt;
end;
Close(infile);
end;
procedure inputCMet(filename: String; var met: DecartCoords; var time: DateTime); overload;
var infile: text;
begin
try
Assign(infile,filename);
Reset(infile);
except
Writeln('Файл не найден. Проверьте правильность пути.');
Readln;
Halt;
end;
try
Readln(infile,met.X,met.Y,met.Z,met.Vx,met.Vy,met.Vz);
except
Writeln('Невозможно считать координаты. Проверьте конфигурацию файла.');
Readln;
Halt;
end;
try
Readln(infile,time.day,time.month,time.year,time.hour,time.minute,time.second);
except
Writeln('Невозможно считать дату. Проверьте конфигурацию файла.');
Readln;
Halt;
end;
Close(infile);
end;
procedure inputCMet(filename: String; var met: DecartCoords); overload;
var infile: text;
begin
try
Assign(infile,filename);
Reset(infile);
except
Writeln('Файл не найден. Проверьте правильность пути.');
Readln;
Halt;
end;
try
Readln(infile,met.X,met.Y,met.Z,met.Vx,met.Vy,met.Vz);
except
Writeln('Невозможно считать координаты. Проверьте конфигурацию файла.');
Readln;
Halt;
end;
Close(infile);
end;
procedure inputEMet(filename: String; var met: ElementsOfOrbit; var time: DateTime;
var eqCords: EquatorCoords); overload;
var infile: text;
begin
try
Assign(infile,filename);
Reset(infile);
except
Writeln('Файл не найден. Проверьте правильность пути.');
Readln;
Halt;
end;
try
Readln(infile,met.a,met.e,met.i,met.Om,met.w,met.v);
except
Writeln('Невозможно считать координаты. Проверьте конфигурацию файла.');
Readln;
Halt;
end;
try
Readln(infile,time.day,time.month,time.year,time.hour,time.minute,time.second);
except
Writeln('Невозможно считать дату. Проверьте конфигурацию файла.');
Readln;
Halt;
end;
try
Readln(infile,eqCords.alpha,eqCords.delta);
except
Writeln('Невозможно считать экваториальные координаты. Проверьте конфигурацию файла.');
Readln;
Halt;
end;
Close(infile);
end;
procedure inputEMet(filename: String; var met: ElementsOfOrbit; var time: DateTime); overload;
var infile: text;
begin
try
Assign(infile,filename);
Reset(infile);
except
Writeln('Файл не найден. Проверьте правильность пути.');
Readln;
Halt;
end;
try
Readln(infile,met.a,met.e,met.i,met.Om,met.w,met.v);
except
Writeln('Невозможно считать координаты. Проверьте конфигурацию файла.');
Readln;
Halt;
end;
try
Readln(infile,time.day,time.month,time.year,time.hour,time.minute,time.second);
except
Writeln('Невозможно считать дату. Проверьте конфигурацию файла.');
Readln;
Halt;
end;
Close(infile);
end;
procedure inputEMet(filename: String; var met: ElementsOfOrbit); overload;
var infile: text;
begin
try
Assign(infile,filename);
Reset(infile);
except
Writeln('Файл не найден. Проверьте правильность пути.');
Readln;
Halt;
end;
try
Readln(infile,met.a,met.e,met.i,met.Om,met.w,met.v);
except
Writeln('Невозможно считать координаты. Проверьте конфигурацию файла.');
Readln;
Halt;
end;
Close(infile);
end;
function initDateTime(day,month,year,hour,minute: integer; second: extended): DateTime;
var t: DateTime;
begin
t.day := day;
t.month := month;
t.year := year;
t.hour := hour;
t.minute := minute;
t.second := second;
result := t;
end;
function initElems(a,e,i,Om,w,v: extended): ElementsOfOrbit;
var el: ElementsOfOrbit;
begin
el.a := a;
el.e := e;
el.i := i;
el.Om := Om;
el.w := w;
el.v := v;
result := el;
end;
function initDecartCoords(X,Y,Z,Vx,Vy,Vz: extended): DecartCoords;
var coord: DecartCoords;
begin
coord.X := X;
coord.Y := Y;
coord.Z := Z;
coord.Vx := Vx;
coord.Vy := Vy;
coord.Vz := Vz;
result := coord;
end;
function initEquatorCoords(alpha,delta: extended): EquatorCoords;
var coor: EquatorCoords;
begin
coor.alpha := alpha;
coor.delta := delta;
result := coor;
end;
function initEclipticCoords(lamda,betta: extended): EclipticCoords;
var coor: EclipticCoords;
begin
coor.lamda := lamda;
coor.betta := betta;
result := coor;
end;
function initHorizontalCoords(Az,h: extended): HorizontalCoords;
var coor: HorizontalCoords;
begin
coor.Az := Az;
coor.h := h;
result := coor;
end;
function initGeogrCoords(long,lat: extended): GeogrCoords;
var coor: GeogrCoords;
begin
coor.long := long;
coor.lat := lat;
result := coor;
end;
procedure printDateTime(t: DateTime; var fileName: text); overload;
begin
with t do begin
Writeln(fileName, day,'.',month,'.',year,', ',hour,':',minute,':',second:5:3);
end;
end;
procedure printDateTime(t: DateTime); overload;
begin
with t do begin
Writeln(day,'.',month,'.',year,' ',hour,':',minute,':',second:5:3);
end;
end;
procedure printCoords(coords: DecartCoords; var fileName: text); overload;
begin
Writeln(fileName,coords.X,' ',coords.Y,' ',coords.Z);
end;
procedure printCoords(coords: DecartCoords); overload;
begin
Writeln(coords.X,' ',coords.Y,' ',coords.Z);
end;
procedure printVel(coords: DecartCoords; var fileName: text); overload;
begin
Writeln(fileName,coords.Vx,' ',coords.Vy,' ',coords.Vz);
end;
procedure printVel(coords: DecartCoords); overload;
begin
Writeln(coords.Vx,' ',coords.Vy,' ',coords.Vz);
end;
procedure printCoordsVel(coords: DecartCoords; var fileName: text); overload;
begin
Writeln(fileName, coords.X,' ',coords.Y,' ',coords.Z,' ',coords.Vx,' ',
coords.Vy,' ',coords.Vz);
end;
procedure printCoordsVel(coords: DecartCoords); overload;
begin
Writeln(coords.X,' ',coords.Y,' ',coords.Z,' ',coords.Vx,' ',coords.Vy,
' ',coords.Vz);
end;
procedure printElements(elem: ElementsOfOrbit; var fileName: text); overload;
begin
with elem do begin
Writeln(fileName,a,' ',e,' ',i,' ',Om,' ',w,' ',v);
end;
end;
procedure printElements(elem: ElementsOfOrbit); overload;
begin
with elem do begin
Writeln(a,' ',e,' ',i,' ',Om,' ',w,' ',v);
end;
end;
procedure printCelCoords(coords: EquatorCoords; var fileName: text); overload;
begin
Writeln(fileName,coords.alpha,' ',coords.delta);
end;
procedure printCelCoords(coords: HorizontalCoords; var fileName: text); overload;
begin
Writeln(fileName,coords.Az,' ',coords.h);
end;
procedure printCelCoords(coords: EclipticCoords; var fileName: text); overload;
begin
Writeln(fileName,coords.lamda,' ',coords.betta);
end;
procedure printCelCoords(coords: GeogrCoords; var filename: text); overload;
begin
Writeln(fileName,coords.long,' ',coords.lat);
end;
procedure printCelCoords(coords: EquatorCoords); overload;
begin
Writeln(coords.alpha,' ',coords.delta);
end;
procedure printCelCoords(coords: HorizontalCoords); overload;
begin
Writeln(coords.Az,' ',coords.h);
end;
procedure printCelCoords(coords: EclipticCoords); overload;
begin
Writeln(coords.lamda,' ',coords.betta);
end;
procedure printCelCoords(coords: GeogrCoords); overload;
begin
Writeln(coords.long,' ',coords.lat);
end;
{=============================================================================}
function fromOrbitToDecart(elems: ElementsOfOrbit): DecartCoords;
var
ra,u,p:extended;
Vr,Vn:extended;
si_i,co_i,si_u,co_u,si_Om,co_Om:extended;
one_pl,d_b_ra,sq_mu_div_p:extended;
coords: DecartCoords;
begin
{Вспомогательные вычисления для ускорения работы}
with elems do begin
p := a*(1 - sqr(e));
one_pl := (1 + e*cos(v));
ra := p/one_pl;
u := v + w;
co_u := cos(u);
si_u := sin(u);
si_Om := sin(Om);
co_Om := cos(Om);
si_i := sin(i);
co_i := cos(i);
d_b_ra := 1/ra;
sq_mu_div_p:= sqrt(mu/p);
{Вычисление гелиоцентрических координат}
coords.X := ra*(co_u*co_Om - si_u*si_Om*co_i);
coords.Y := ra*(co_u*si_Om + si_u*co_Om*co_i);
coords.Z := ra*si_u*si_i;
Vr := sq_mu_div_p*e*sin(v);
Vn := sq_mu_div_p*one_pl;
coords.Vx := coords.X*d_b_ra*Vr + (-si_u*co_Om - co_u*si_Om*co_i)*Vn;
coords.Vy := coords.Y*d_b_ra*Vr + (-si_u*si_Om + co_u*co_Om*co_i)*Vn;
coords.Vz := coords.Z*d_b_ra*Vr + co_u*si_i*Vn;
end;
result := coords;
end;{fromOrbitToDecart}
function fromDecartToOrbit(coord: DecartCoords): ElementsOfOrbit;
var
RV,mup,smup,p,u,R,Vel:extended;
si_i,co_i,si_Om,co_om,si_v,co_v,si_u,co_u:extended;
d_b_mup,d_b_smup,d_b_re,d_b_r,d_b_smup_a_si_i:extended;
elems: ElementsOfOrbit;
begin
{Блок вспомогательных для расчетов переменных. !d_b_ - divide by!}
RV := coord.X*coord.Vx + coord.Y*coord.Vy + coord.Z*coord.Vz;
R := sqrt(sqr(coord.X) + sqr(coord.Y) + sqr(coord.Z));
Vel := moduleOfVelocity(coord);
elems.a := 1/((2/R)-(sqr(Vel)/mu));
mup := sqr(R)*sqr(Vel) - sqr(RV);
elems.e := sqrt(1 - (mup)/(mu*elems.a));
p := elems.a*(1 - sqr(elems.e));
smup := sqrt(mu);
d_b_mup := 1/mup;
d_b_smup := 1/sqrt(mup);
d_b_re := 1/(R*elems.e);
d_b_r := 1/R;
{Синусы и косинусы для расчета углов}
co_i := (coord.X*coord.Vy-coord.Y*coord.Vx)/sqrt(mup);
si_i := sqrt((sqr(coord.Y*coord.Vz - coord.Z*coord.Vy) +
sqr(coord.X*coord.Vz - coord.Z*coord.Vx))/mup);
d_b_smup_a_si_i := d_b_smup/si_i; {Вспомогашка}
si_Om := (coord.Y*coord.Vz - coord.Z*coord.Vy)*d_b_smup_a_si_i;
co_Om := (coord.X*coord.Vz - coord.Z*coord.Vx)*d_b_smup_a_si_i;
si_v := (sqrt(p)*RV)*d_b_re/smup;
co_v := (p - R)*d_b_re;
si_u := coord.Z*d_b_r/si_i;
co_u := (coord.X*co_Om + coord.Y*si_Om)*d_b_r;
{Сами углы}
elems.i := Arctan2(si_i,co_i);
elems.Om := Arctan2(coord.Y*coord.Vz - coord.Z*coord.Vy,coord.X*coord.Vz - coord.Z*coord.Vx);
elems.v := Arctan2(si_v,co_v);
u := Arctan2(si_u,co_u);
elems.w := u - elems.v;
if elems.Om < 0 then elems.Om := elems.Om + 2*Pi;
if elems.v < 0 then elems.v := elems.v + 2*Pi;
result := elems;
end; {fromDecartToORbit}
function JDate(dt: DateTime): extended;
var JDN,a,y,m,y1,m1,d1: integer;
begin
with dt do begin
y1 := trunc(year);
m1 := trunc(month);
d1 := trunc(day);
a := (14 - m1) div 12;
y := y1 + 4800 - a;
m := m1 + 12*a -3;
JDN := d1 + ((153*m + 2) div 5) + 365*y + (y div 4)- (y div 100) + (y div 400) - 32045;
JDate := JDN + (hour - 12)/24 + minute/1440 + second/86400;
end;
end;
function siderealTime(year,month,day: integer): extended;
var teta,Tu,T,JD,sidTime: extended;
begin
JD := JDate(initDateTime(day,month,year,0,0,0));
Tu := JD - STANDRD_ERA;
T := Tu/36525;
teta := 360*(0.7790572732640 + 1.00273781191135448*Tu);
sidTime := teta + (0.014506 + 4612.15739966*T + 1.39667721*sqr(T) +
0.00009344*sqr(T)*T + 0.00001882*sqr(sqr(T)))/3600;
while sidTime > 360 do
sidTime := sidTime - 360;
result := sidTime/15;
end;
function keplerSolution(e,M: extended): extended;
var x1,x2: extended;
begin
x2 := M;
x1 := 0;
while (abs(x2-x1) > EPS) do
begin
x1 := x2;
x2 := x1 - keplerEq(x1,e,M)/keplerDifEq(x1,e);
end; {while}
result := x2;
end;
function keplerEq(x,e,M: extended): extended;
begin
result := x - M - e*sin(x);
end;
function keplerDifEq(x,e: extended): extended;
begin
result := 1 - e*cos(x);
end;
function getM(t,t0,M0,a: extended): extended;
begin
result := M0 + getN(a)*(t - t0);
end;
function getN(a: extended): extended;
begin
result := sqrt(MU/(a*a*a));
end;
function grDate(JD: extended): DateTime;
var a,b,c,d,e,m,JDN: integer;
day1,month1,year1: integer;
day,month,year,hour,minute,second: extended;
t: DateTime;
begin
JDN := trunc(JD);
a := JDN + 32044;
b := (4*a + 3) div 146097;
c := a - (146097*b) div 4;
d := (4*c + 3) div 1461;
e := c - (1461*d) div 4;
m := (5*e + 2) div 153;
day := e - ((153*m + 2) div 5) + 1;
month := m + 3 - 12*(m div 10);
year := 100*b + d - 4800 + m div 10;
hour := (JD - trunc(JD))*24 + 12;
minute := (hour - trunc(hour))*60;
second := (minute - trunc(minute))*60;
hour := trunc(hour);
minute := trunc(minute);
if second >= 60 then begin
second := second - 60;
minute := minute + 1;
end;
if minute >= 60 then begin
minute := minute - 60;
hour := hour + 1;
end;
if hour >= 24 then begin
hour := hour - 24;
day := day + 1;
end;
t.day := trunc(day);
t.month := trunc(month);
t.year := trunc(year);
t.hour := trunc(hour);
t.minute := trunc(minute);
t.second := second;
result := t;
end; //GrDate end
function sidTimeOnLong(date: DateTime; long: extended): extended;
var sidTime,ST,s0: extended;
begin
with date do begin
sidTime := siderealTime(year,month,day);
s0 := sidTime - long/DEG_IN_HOUR/24*(3/60+56.5554/3600);
ST := s0 + 1.002738*(hour + minute/60 + second/3600 + long/DEG_IN_HOUR);
Result := ST;
end;
end; //sidTimeOnLong end
function fromEqToEcl(eq: EquatorCoords): EclipticCoords;
var ecl: EclipticCoords;
begin
with eq do begin
ecl.betta := arcsin(sin(delta)*cos(ECL_EQ) - cos(delta)*sin(ECL_EQ)*sin(alpha));
ecl.lamda := arctan2(sin(delta)*sin(ECL_EQ) + cos(delta)*cos(ECL_EQ)*sin(alpha),
cos(delta)*cos(alpha));
end;
result := ecl;
end;
function fromEclToEq(ecl: EclipticCoords): EquatorCoords;
var eq: EquatorCoords;
begin
with ecl do begin
eq.delta := arcsin(sin(ECL_EQ)*sin(lamda)*cos(betta) + cos(ECL_EQ)*sin(betta));
eq.alpha := arctan2(cos(ECL_EQ)*sin(lamda)*cos(betta) - sin(ECL_EQ)*sin(betta),
cos(lamda)*cos(betta));
end;
result := eq;
end;
function fromHorToEq(hor: HorizontalCoords; fi,sidTime: extended): EquatorCoords;
var z,t: extended;
eq: EquatorCoords;
begin
with hor do begin
z := Pi/2 - h;
eq.delta := arcsin(sin(fi)*cos(z) - cos(fi)*sin(z)*cos(Az));
t := arctan2(sin(z)*sin(Az),cos(fi)*cos(z) + sin(fi)*sin(z)*cos(Az));
eq.alpha := sidTime - t;
end;
result := eq;
end;
function fromEqToHor(eq: EquatorCoords; fi,sidTime: extended): HorizontalCoords;
var t: extended;
hor: HorizontalCoords;
begin
with eq do begin
t := sidTime - alpha;
hor.Az := arctan2(cos(delta)*sin(t),sin(fi)*cos(delta)*cos(t) - cos(fi)*sin(delta));
hor.h := Pi/2 - arccos(sin(fi)*sin(delta) + cos(fi)*cos(delta)*cos(t));
end;
result := hor;
end;
function fromEqToEclDecart(eq: DecartCoords): DecartCoords;
begin
result := rotateSCX(-ECL_EQ,eq);
end;
function fromEclToEqDecart(ecl: DecartCoords): DecartCoords;
begin
result := rotateSCX(ECL_EQ,ecl);
end;
function getRadiant(met: DecartCoords): EquatorCoords;
var radiant: EquatorCoords;
begin
radiant.alpha := arctan2(-met.Vy,-met.Vx);
radiant.delta := arcsin(-met.Vz/moduleOfVelocity(met));
result := radiant;
end;
function numElemsWithDubyago(eq: EquatorCoords; Vel: extended; Earth: DecartCoords): ElementsOfOrbit;
var lambda_g,betta_g,lambda_a,Eg,gamma,Vh,Eh: extended;
lambda_h,betta_h,R_Earth,p_Meth,lambda_sun: extended;
V_Earth: extended;
meteor: ElementsOfOrbit;
begin
V_Earth := moduleOfVelocity(Earth);
R_Earth := moduleOfCoords(Earth);
with eq do begin
lambda_g := arctan2(sin(ECL_EQ)*sin(delta) + cos(ECL_EQ)*cos(delta)*sin(alpha),
cos(delta)*cos(alpha));
betta_g := arcsin(cos(ECL_EQ)*sin(delta) - sin(ECL_EQ)*cos(delta)*sin(alpha));
lambda_a := arctan2(Earth.Vy,Earth.Vx);
Eg := arccos(cos(betta_g)*cos(lambda_g - lambda_a));
gamma := arctan2(tan(betta_g),sin(lambda_g - lambda_a));
Vh := sqrt(sqr(Vel) + sqr(V_Earth) - 2*V_Earth*Vel*cos(Eg));
Eh := Vel*sin(Eg)/Vh;
lambda_h := lambda_a + arctan2(cos(gamma)*sin(Eh),cos(Eh));
betta_h := arctan2(sin(Eh)*sin(gamma)*cos(lambda_h - lambda_a),cos(Eh));
{ 1) a }
meteor.a := power(2/R_Earth - sqr(Vh)/MU,-1);
{ 2) i }
lambda_sun := arctan2(Earth.Y,Earth.X);
meteor.i := arctan2(abs(tan(betta_h)),sin(lambda_sun - lambda_h));
meteor.i := toTwoPiInterval(meteor.i);
{ 3) e }
p_Meth := sqr(R_Earth*Vh)*(1 - sqr(cos(betta_h)*cos(lambda_h - lambda_sun)))/MU;
meteor.e := sqrt(1 - p_Meth/meteor.a);
{ 4) Om }
if sin(betta_h) > 0 then
meteor.Om := lambda_sun
else meteor.Om := Pi + lambda_sun;
meteor.Om := toTwoPiInterval(meteor.Om);
{ 5) v }
meteor.v := arctan2(p_Meth*cos(meteor.i)*cotan(lambda_h - lambda_sun),p_Meth - R_Earth);
meteor.v := toTwoPiInterval(meteor.v);
{ 6) w }
if betta_h > 0 then
meteor.w := Pi - meteor.v
else meteor.w := 2*Pi - meteor.v;
meteor.w := toTwoPiInterval(meteor.w);
end;
result := meteor;
end;
{===========================================================================}
function rotateSCX(angle: extended; dc: DecartCoords): DecartCoords;
var dec: DecartCoords;
begin
with dc do begin
dec.X := X;
dec.Y := Y*cos(angle) - Z*sin(angle);
dec.Z := Y*sin(angle) + Z*cos(angle);
dec.Vx := Vx;
dec.Vy := Vy*cos(angle) - Vz*sin(angle);
dec.Vz := Vy*sin(angle) + Vz*cos(angle);
end;
result := dec;
end;
function rotateSCY(angle: extended; dc: DecartCoords): DecartCoords;
var dec: DecartCoords;
begin
with dc do begin
dec.X := X*cos(angle) + Z*sin(angle);
dec.Y := Y;
dec.Z := -X*sin(angle) + Z*cos(angle);
dec.Vx := Vx*cos(angle) + Vz*sin(angle);
dec.Vy := Vy;
dec.Vz := -Vx*sin(angle) + Vz*cos(angle);
end;
result := dec;
end;
function rotateSCZ(angle: extended; dc: DecartCoords): DecartCoords;
var dec: DecartCoords;
begin
with dc do begin
dec.X := X*cos(angle) - Y*sin(angle);
dec.Y := X*sin(angle) + Y*cos(angle);
dec.Z := Z;
dec.Vx := Vx*cos(angle) - Vy*sin(angle);
dec.Vy := Vx*sin(angle) + Vy*cos(angle);
dec.Vz := Vz;
end;
result := dec;
end;
procedure fromDecartToSphere(A: DecartCoords; var fi,lam: extended);
begin
lam := arctan2(A.Y,A.X);
fi := arcsin(A.Z/moduleOfCoords(A));
end;
function fromSphereToDecart(fi,lam,r: extended): DecartCoords;
var dc: DecartCoords;
begin
dc.X := r*cos(fi)*cos(lam);
dc.Y := r*cos(fi)*sin(lam);
dc.Z := r*sin(fi);
dc.Vx := 0;
dc.Vy := 0;
dc.Vz := 0;
result := dc;
end;
function sumOfVectors(A,B: DecartCoords): DecartCoords;
var res: DecartCoords;
begin
res.X := A.X + B.X;
res.Y := A.Y + B.Y;
res.Z := A.Z + B.Z;
res.Vx := A.Vx + B.Vx;
res.Vy := A.Vy + B.Vy;
res.Vz := A.Vz + B.Vz;
result := res;
end;
function differenceOfVectors(A,B: DecartCoords): DecartCoords;
var res: DecartCoords;
begin
res.X := A.X - B.X;
res.Y := A.Y - B.Y;
res.Z := A.Z - B.Z;
res.Vx := A.Vx - B.Vx;
res.Vy := A.Vy - B.Vy;
res.Vz := A.Vz - B.Vz;
result := res;
end;
function moduleOfCoords(A: DecartCoords): extended;
begin
result := sqrt(sqr(A.X) + sqr(A.Y) + sqr(A.Z));
end;
function moduleOfVelocity(A: DecartCoords): extended;
begin
result := sqrt(sqr(A.Vx) + sqr(A.Vy) + sqr(A.Vz));
end;
function timeToDotTime(t: DateTime): extended;
begin
result := t.hour + t.minute/60 + t.second/3600;
end;
function dotTimeToTime(t: extended): DateTime;
var time: DateTime;
hour,minute,second: extended;
begin
hour := trunc(t);
minute := (t - hour)*60;
second := (minute - trunc(minute))*60;
minute := trunc(minute);
result := initDateTime(0,0,0,trunc(hour),trunc(minute),second);
end;
function toRadians(x: extended): extended;
begin
result := x*RAD;
end;
function toRadians(elems: ElementsOfOrbit): ElementsOfOrbit; overload;
begin
with elems do begin
i := toRadians(i);
Om := toRadians(Om);
w := toRadians(w);
v := toRadians(v);
end;
result := elems;
end;
function toRadians(eq: EquatorCoords): EquatorCoords; overload;
begin
with eq do begin
alpha := toRadians(alpha);
delta := toRadians(delta);
end;
result := eq;
end;
function toRadians(ecl: EclipticCoords): EclipticCoords; overload;
begin
with ecl do begin
lamda := toRadians(lamda);
betta := toRadians(betta);
end;
result := ecl;
end;
function toRadians(hor: HorizontalCoords): HorizontalCoords; overload;
begin
with hor do begin
Az := toRadians(Az);
h := toRadians(h);
end;
result := hor;
end;
function toRadians(gCoords: GeogrCoords): GeogrCoords; overload;
begin
with gCoords do begin
long := toRadians(long);
lat := toRadians(lat);
end;
result := gCoords;
end;
function toDegree(x: extended): extended;
begin
result := x/RAD;
end;
function toDegree(elems: ElementsOfOrbit): ElementsOfOrbit; overload;
begin
with elems do begin
i := toDegree(i);
Om := toDegree(Om);
w := toDegree(w);
v := toDegree(v);
end;
result := elems;
end;
function toDegree(eq: EquatorCoords): EquatorCoords; overload;
begin
with eq do begin
alpha := toDegree(alpha);
delta := toDegree(delta);
end;
result := eq;
end;
function toDegree(ecl: EclipticCoords): EclipticCoords; overload;
begin
with ecl do begin
lamda := toDegree(lamda);
betta := toDegree(betta);
end;
result := ecl;
end;
function toDegree(hor: HorizontalCoords): HorizontalCoords; overload;
begin
with hor do begin
Az := toDegree(Az);
h := toDegree(h);
end;
result := hor;
end;
function toDegree(gCoords: GeogrCoords): GeogrCoords; overload;
begin
with gCoords do begin
long := toDegree(long);
lat := toDegree(lat);
end;
result := gCoords;
end;
function toAu(x: extended): extended;
begin
result := x/AU_KM;
end;
function coordsToAu(coords: DecartCoords): DecartCoords;
begin
with coords do begin
X := toAu(X);
Y := toAu(Y);
Z := toAu(Z);
Vx := toAu(Vx)*86400;
Vy := toAu(Vy)*86400;
Vz := toAu(Vz)*86400;
end;
result := coords;
end;
function toKm(x: extended): extended;
begin
result := x*AU_KM;
end;
function coordsToKm(coords: DecartCoords): DecartCoords;
begin
with coords do begin
X := toKm(X);
Y := toKm(Y);
Z := toKm(Z);
Vx := toKm(Vx)/86400;
Vy := toKm(Vy)/86400;
Vz := toKm(Vz)/86400;
end;
result := coords;
end;
function toHour(x: extended): extended;
begin
result := x/DEG_IN_HOUR;
end;
function toDegFromHour(x: extended): extended;
begin
result := x*DEG_IN_HOUR;
end;
function toTwoPiInterval(angle: extended): extended;
begin
if angle < 0 then begin
while angle < 0 do angle := angle + 2*PI;
end
else if angle > 2*PI then begin
while angle > 2*PI do angle := angle - 2*PI;
end;
result := angle;
end;
{==================================================================}
function getEarthCoords(JD: extended): DecartCoords;
var X: masc;
begin
read406(false,JD,X);
result := initDecartCoords(X[13],X[14],X[15],X[16],X[17],X[18]);
end;
end.
|
unit Form.SendMail;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Objekt.SendMail;
type
Tfrm_Sendmail = class(TForm)
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
edt_MeineWebEMail: TEdit;
edt_MeinWebPasswort: TEdit;
GroupBox2: TGroupBox;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
edt_Betreff: TEdit;
mem_Nachricht: TMemo;
edt_EMail: TEdit;
btn_Senden: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDeactivate(Sender: TObject);
procedure btn_SendenClick(Sender: TObject);
private
fSendMail: TSendMail;
public
end;
var
frm_Sendmail: Tfrm_Sendmail;
implementation
{$R *.dfm}
procedure Tfrm_Sendmail.btn_SendenClick(Sender: TObject);
begin
fSendMail.MeineEMail := edt_MeineWebEMail.Text;
fSendMail.MeinPasswort := edt_MeinWebPasswort.Text;
fSendMail.Betreff := edt_Betreff.Text;
fSendMail.Nachricht := mem_Nachricht.Text;
fSendMail.EMailAdresse := edt_EMail.Text;
//fSendMail.SendenUeberWebDe;
fSendMail.SendenUeberExchange;
ShowMessage('E-Mail wurde versendet');
end;
procedure Tfrm_Sendmail.FormCreate(Sender: TObject);
begin
fSendMail := TSendMail.Create;
edt_MeineWebEMail.Text := 'bachmann@new-frontiers.de';
edt_EMail.Text := 'bachmann@new-frontiers.de';
end;
procedure Tfrm_Sendmail.FormDeactivate(Sender: TObject);
begin
FreeAndNil(fSendMail);
end;
end.
|
unit SampleAdapter1;
interface
uses Data.Bind.ObjectScope, System.Classes, Generics.Collections, System.SysUtils;
type
TContact = class
private
FFirstName: string;
FLastName: string;
FAddress1: string;
FAddress2: string;
FState: string;
FZip: string;
FID: uint32;
procedure SetID(const Value: uint32);
function GetID: uint32;
public
constructor Create;
property FirstName: string read FFirstName write FFirstName;
property LastName: string read FLastName write FLastName;
property Address1: string read FAddress1 write FAddress1;
property Address2: string read FAddress2 write FAddress2;
property State: string read FState write FState;
property Zip: string read FZip write FZip;
property ID: uint32 read GetID write SetID;
end;
TContactsAdapter = class(TListBindSourceAdapter<TContact>)
private
FLoaded: Boolean;
FLoading: Boolean;
FHasUpdates: Boolean;
FFileName: TFileName;
FAutoLoad: Boolean; // TFileName supports file open in object inspector
function GetList: TList<TContact>;
procedure SetFileName(const Value: TFileName);
function QueryCancelUpdates: Boolean;
procedure SetAutoLoad(const Value: Boolean);
protected
procedure DoBeforeOpen; override;
procedure DoOnAfterSetList; override;
function GetCanActivate: Boolean; override;
public
constructor Create(AOwner: TComponent); override;
procedure ApplyUpdates; override;
procedure CancelUpdates; override;
function GetCanApplyUpdates: Boolean; override;
function GetCanCancelUpdates: Boolean; override;
procedure Insert; override;
procedure Post; override;
procedure Delete; override;
procedure Load; overload;
procedure Save; overload;
procedure SaveAs(const AFileName: string);
procedure LoadFrom(const AFileName: string);
property List: TList<TContact> read GetList;
property HasUpdates: Boolean read FHasUpdates write FHasUpdates;
published
property Options;
property FileName: TFileName read FFileName write SetFileName;
property AutoLoad: Boolean read FAutoLoad write SetAutoLoad;
property AutoEdit;
property Active;
property BeforeOpen;
property AfterOpen;
property BeforeClose;
property AfterClose;
property BeforeInsert;
property AfterInsert;
property BeforeEdit;
property AfterEdit;
property BeforePost;
property AfterPost;
property BeforeCancel;
property AfterCancel;
property BeforeDelete;
property AfterDelete;
property BeforeScroll;
property AfterScroll;
property BeforeRefresh;
property AfterRefresh;
property OnDeleteError;
property OnInsertError;
property OnEditError;
property OnPostError;
property OnApplyUpdates;
property OnCancelUpdates;
end;
implementation
uses
Xml.XmlDoc, XML.XMLIntf;
type
TCustomerDocumentService = class
private const
sXMLCustomer = 'customer';
sXMLCustomers = 'customers';
sXMLFirstName = 'firstname';
sXMLLastName = 'lastname';
sXMLAddress1 = 'address1';
sXMLAddress2 = 'address2';
sXMLState = 'state';
sXMLZip = 'zip';
sXMLID = 'id';
public
class procedure Save(const AFileName: string; AList: TList<TContact>); static;
class function Load(const AFileName: string): TList<TContact>; static;
end;
{ TCustomerAdapter }
procedure TContactsAdapter.ApplyUpdates;
begin
Save;
end;
function TContactsAdapter.GetCanApplyUpdates: Boolean;
begin
Result := FLoaded and FHasUpdates;
end;
function TContactsAdapter.GetCanCancelUpdates: Boolean;
begin
Result := FLoaded and FHasUpdates;
end;
function TContactsAdapter.QueryCancelUpdates: Boolean;
begin
Result := True; // TODO: Need event handler here
end;
function TContactsAdapter.GetCanActivate: Boolean;
begin
// Allow even if no list because we create it on demand
Result := True;
end;
procedure TContactsAdapter.CancelUpdates;
begin
if QueryCancelUpdates then
begin
Load;
Active := True;
end;
end;
constructor TContactsAdapter.Create(AOwner: TComponent);
//var
// LList: TList<TContact>;
begin
inherited Create(AOwner);
Options := Options + [loptAllowApplyUpdates, loptAllowCancelUpdates];
// LList := TObjectList<TContact>.Create;
// SetList(LList);
end;
procedure TContactsAdapter.Delete;
begin
FHasUpdates := True;
inherited;
end;
procedure TContactsAdapter.DoBeforeOpen;
begin
inherited;
if GetList = nil then
begin
if AutoLoad and (FFileName <> '') then
Load
else
SetList(TObjectList<TContact>.Create);
end;
end;
procedure TContactsAdapter.DoOnAfterSetList;
begin
inherited;
FHasUpdates := False;
if FLoading then
begin
FLoaded := GetList <> nil;
end;
DataSetChanged; // Update navigator
end;
function TContactsAdapter.GetList: TList<TContact>;
begin
Result := inherited List as TList<TContact>;
end;
procedure TContactsAdapter.Insert;
begin
FHasUpdates := True;
inherited;
end;
procedure TContactsAdapter.Load;
var
LList: TList<TContact>;
begin
FLoading := True;
try
LList := TCustomerDocumentService.Load(FFileName);
if LList <> nil then
begin
FHasUpdates := False;
SetList(LList);
if not FLoaded then
begin
FLoaded := True;
DataSetChanged;
end;
end;
finally
FLoading := False;
end;
end;
procedure TContactsAdapter.Save;
begin
CheckList;
TCustomerDocumentService.Save(FFileName, GetList);
if FHasUpdates then
begin
FHasUpdates := False;
DataSetChanged; //Update navigator
end;
end;
procedure TContactsAdapter.SaveAs(const AFileName: string);
begin
CheckList;
TCustomerDocumentService.Save(AFileName, GetList);
FFileName := AFileName;
if FHasUpdates then
begin
FHasUpdates := False;
DataSetChanged; //Update navigator
end;
end;
procedure TContactsAdapter.LoadFrom(const AFileName: string);
var
LList: TList<TContact>;
begin
FLoading := True;
try
LList := TCustomerDocumentService.Load(AFileName);
try
if LList <> nil then
begin
FFileName := AFileName;
SetList(LList);
end;
except
LList.Free;
end;
finally
FLoading := False;
end;
end;
procedure TContactsAdapter.Post;
begin
FHasUpdates := True;
inherited;
end;
procedure TContactsAdapter.SetAutoLoad(const Value: Boolean);
begin
if FAutoLoad <> Value then
begin
FAutoLoad := Value;
if (csDesigning in ComponentState) and not (csLoading in ComponentState) then
begin
SetList(nil);
end;
end;
end;
procedure TContactsAdapter.SetFileName(const Value: TFileName);
begin
if FFileName <> Value then
begin
Active := False;
SetList(nil);
FFileName := Value;
end;
end;
{ TCustomerDocument }
class function TCustomerDocumentService.Load(const AFileName: string): TList<TContact>;
var
LDocument: IXMLDocument;
LList: TList<TContact>;
LCustomer: TContact;
LRoot: IXMLNode;
LNode: IXMLNode;
begin
Assert(AFileName <> '');
if not FileExists(AFileName) then
raise EFileNotFoundException.CreateFmt('File "%s" not found', [AFileName]);
LList := TObjectList<TContact>.Create;
try
LDocument := TXMLDocument.Create(nil) as IXMLDocument;
LDocument.LoadFromFile(AFileName);
begin
LRoot := LDocument.Node.ChildNodes.First;
Assert(LRoot.NodeName = sXMLCustomers);
LNode := LRoot.ChildNodes.First;
while LNode <> nil do
begin
Assert(LNode.NodeName = sXMLCustomer);
LCustomer := TContact.Create;
try
LCustomer.FirstName := LNode.GetAttribute(sXMLFirstName);
LCustomer.LastName := LNode.GetAttribute(sXMLLastName);
LCustomer.Address1 := LNode.GetAttribute(sXMLAddress1);
LCustomer.Address2 := LNode.GetAttribute(sXMLAddress2);
LCustomer.State := LNode.GetAttribute(sXMLState);
LCustomer.Zip := LNode.GetAttribute(sXMLZip);
LCustomer.ID := LNode.GetAttribute(sXMLID);
except
LCustomer.Free;
raise;
end;
LList.Add(LCustomer);
LNode := LNode.NextSibling;
end;
end;
Result := LList;
except
LList.Free;
raise;
end;
end;
class procedure TCustomerDocumentService.Save(const AFileName: string; AList: TList<TContact>);
var
LDocument: IXMLDocument;
LCustomer: TContact;
LRoot: IXMLNode;
LRecordNode: IXMLNode;
begin
Assert(AFileName <> '');
LDocument := TXMLDocument.Create(nil) as IXMLDocument;
LDocument.Active := True;
LRoot := LDocument.AddChild(sXMLCustomers);
for LCustomer in AList do
begin
LRecordNode := LRoot.AddChild(sXMLCustomer);
LRecordNode.SetAttribute(sXMLFirstName, LCustomer.FirstName);
LRecordNode.SetAttribute(sXMLLastName, LCustomer.LastName);
LRecordNode.SetAttribute(sXMLAddress1, LCustomer.Address1);
LRecordNode.SetAttribute(sXMLAddress2, LCustomer.Address2);
LRecordNode.SetAttribute(sXMLState, LCustomer.State);
LRecordNode.SetAttribute(sXMLZip, LCustomer.Zip);
LRecordNode.SetAttribute(sXMLID, LCustomer.ID);
end;
LDocument.SaveToFile(AFileName);
end;
{ TContact }
constructor TContact.Create;
begin
//
end;
function TContact.GetID: uint32;
begin
Result := FID;
end;
procedure TContact.SetID(const Value: uint32);
begin
FID := Value;
end;
end.
|
//*******************************************************//
// //
// DelphiFlash.com //
// Copyright (c) 2004-2007 FeatherySoft, Inc. //
// info@delphiflash.com //
// //
//*******************************************************//
// Description: text constants indicated of SWF vocabulary
// Last update: 10 jan 2007
unit SWFStrings;
interface
Uses Windows, SysUtils, Classes, SWFConst;
{ for XML}
const
sc_SWF = 'SWF';
sc_Flash = 'Flash';
sc_FPS = 'FPS';
sc_Version = 'Version';
sc_SysCoord = 'SystemCoord';
sc_Compressed = 'Compressed';
sc_Pix = 'Pix';
sc_Twips = 'Twips';
sc_Color = 'Color';
sc_BGColor = 'BgColor';
sc_Name = 'Name';
sc_isAnchor = 'isAnchor';
sc_Hash = 'Hash';
sc_Object = 'Object';
sc_ID = 'ID';
sc_URL = 'URL';
sc_MaxRecursionDepth = 'MaxRecursionDepth';
sc_ScriptTimeoutSeconds = 'ScriptTimeoutSeconds';
sc_Depth = 'Depth';
sc_RemoveDepth = 'Remove' + sc_Depth;
sc_TabIndex = 'TabIndex';
sc_Ratio = 'Ratio';
sc_Actions = 'Actions';
sc_InitActions = 'Init' + sc_Actions;
sc_ClipDepth = 'Clip' + sc_Depth;
sc_Fill = 'Fill';
sc_Style = 'Style';
sc_Styles = sc_Style + 's';
sc_FillStyles = sc_Fill +sc_Styles;
sc_LineStyles = 'Line' + sc_Styles;
sc_New = 'New';
sc_NewLineStyles = sc_New + sc_LineStyles;
sc_NewFillStyles = sc_New + sc_FillStyles;
sc_Width = 'Width';
sc_Height = 'Height';
sc_Item = 'Item';
sc_Gradient = 'Gradient';
sc_Edges = 'Edges';
sc_End = 'End';
sc_MoveTo = 'MoveTo';
sc_Curve = 'Curve';
sc_Line = 'Line';
sc_LineTo = 'LineTo';
sc_MoveDelta = 'MoveDelta';
sc_CurveTo = 'CurveTo';
sc_LineDelta = 'LineDelta';
sc_CloseShape = 'CloseShape';
sc_Rectangle = 'Rectangle';
sc_RoundRect = 'RoundRect';
sc_Radius = 'Radius';
sc_Ellipse = 'Ellipse';
sc_Circle = 'Circle';
sc_Ring = 'Ring';
sc_Center = 'Center';
sc_Pie = 'Pie';
sc_StartAngle = 'StartAngle';
sc_EndAngle = 'EndAngle';
sc_Arc = 'Arc';
sc_Closed = 'Closed';
sc_ClockWise = 'ClockWise';
sc_Diamond = 'Diamond';
sc_Star ='Star';
sc_R1 = 'R1';
sc_R2 = 'R2';
sc_NumberOfPoints = 'Points';
sc_CubicBezier = 'CubicBezier';
sc_Polyline = 'Polyline';
sc_Polygon = 'Polygon';
sc_PolyBezier = 'PolyBezier';
sc_Point = 'Point';
sc_Mirror = 'Mirror';
sc_Horz = 'Horz';
sc_Vert = 'Vert';
sc_OffsetEdges = 'OffsetEdges';
sc_X0 = 'X0';
sc_Square = 'Square';
sc_Side = 'Side';
sc_StyleChange = 'StyleChange';
sc_Anchor = 'Anchor';
sc_Control = 'Control';
sc_Glyph = 'Glyph';
sc_Num = 'Num';
sc_FontFlagsSmallText = 'SmallText';
sc_FontFlagsShiftJIS ='ShiftJIS';
sc_FontFlagsANSI = 'ANSI';
sc_FontFlagsItalic = 'Italic';
sc_FontFlagsBold = 'Bold';
sc_Code = 'Code';
sc_FontFlagsWideCodes = 'Wide'+sc_Code+'s';
sc_LanguageCode = 'LanguageCode';
sc_FontAscent = 'Ascent';
sc_FontDescent = 'Descent';
sc_FontLeading = 'Leading';
sc_Advance = 'Advance';
sc_Kerning = 'Kerning';
sc_FontKerningCode = sc_Kerning + sc_Code;
sc_FontKerningAdjustment = sc_Kerning +'Adjustment';
sc_Index = 'Index';
sc_Type = 'Type';
sc_Font = 'Font';
sc_FontCopyright = 'Copyright';
sc_FontId = sc_Font + sc_ID;
sc_TextRecord = 'TextRecord';
sc_AutoSize = 'AutoSize';
sc_WordWrap = 'WordWrap';
sc_Multiline = 'Multiline';
sc_Password = 'Password';
sc_ReadOnly = 'ReadOnly';
sc_NoSelect = 'NoSelect';
sc_Border = 'Border';
sc_HTML = 'HTML';
sc_UseOutlines = 'UseOutlines';
sc_MaxLength = 'MaxLength';
sc_Layout = 'Layout';
sc_Align = 'Align';
sc_LeftMargin = 'LeftMargin';
sc_Value = 'Value';
sc_Variable = 'Variable';
sc_AVarType: array [0..10] of pchar =
('str', 'float', 'null', 'undef', 'reg', 'bool', 'double',
'int', 'const8', 'const16', 'def');
sc_RightMargin = 'RightMargin';
sc_Indent = 'Indent';
sc_Leading = 'Leading';
sc_SoundFormat = 'SoundFormat';
sc_SoundRate = 'SoundRate';
sc_SoundSize = 'SoundSize';
sc_SoundType = 'SoundType';
sc_SampleCount = 'SampleCount';
sc_SoundCompression = 'SoundCompression';
sc_SeekSamples = 'SeekSamples';
sc_Data = 'Data';
sc_AlphaData = 'AlphaData';
sc_SyncStop = 'SyncStop';
sc_SyncNoMultiple = 'SyncNoMultiple';
sc_LoopCount = 'LoopCount';
sc_InPoint = 'InPoint';
sc_OutPoint = 'OutPoint';
sc_Envelope = 'Envelope';
sc_Pos44 = 'Pos44';
sc_LeftLevel = 'LeftLevel';
sc_RightLevel = 'RightLevel';
sc_Playback = 'Playback';
sc_Stream = 'Stream';
sc_LatencySeek = 'LatencySeek';
sc_ButtonRecord = 'ButtonRecord';
sc_State = 'State';
sc_TrackAsMenu = 'TrackAsMenu';
sc_OverUpToIdle = 'OverUpToIdle';
sc_IdleToOverUp = 'IdleToOverUp';
sc_OverUpToOverDown = 'OverUpToOverDown';
sc_OverDownToOverUp = 'OverDownToOverUp';
sc_BitmapFormat = 'BitmapFormat';
sc_BitmapColorTableSize = 'BitmapColorTableSize';
sc_Start = 'Start';
sc_StartShape = 'StartShape';
sc_EndShape = 'EndShape';
sc_StartColor = 'StartColor';
sc_EndColor = 'EndColor';
sc_StartWidth = sc_Start + sc_Width;
sc_EndWidth = sc_End + sc_Width;
sc_StartMatrix = sc_Start + 'Matrix';
sc_EndMatrix = sc_End + 'Matrix';
sc_Label = 'Label';
sc_Frame = 'Frame';
sc_FrameNum = sc_Frame+'Num';
sc_Target = 'Target';
sc_SkipCount = 'SkipCount';
sc_TargetName = 'TargetName';
sc_SendVarsMethod = 'Method';
sc_LoadTargetFlag = 'LoadTargetFlag';
sc_LoadVariablesFlag = 'LoadVariablesFlag';
sc_PlayFlag = 'PlayFlag';
sc_Scene = 'Scene';
sc_SceneBias = sc_Scene+'Bias';
sc_Register = 'Register';
sc_RegisterNumber = 'RegisterNumber';
sc_RegisterCount = 'RegisterCount';
sc_PreloadParentFlag = 'PreloadParent';
sc_PreloadRootFlag = 'PreloadRoot';
sc_SuppressSuperFlag = 'SuppressSuper';
sc_PreloadSuperFlag = 'PreloadSuper';
sc_SuppressArgumentsFlag = 'SuppressArguments';
sc_PreloadArgumentsFlag = 'PreloadArguments';
sc_SuppressThisFlag = 'SuppressThis';
sc_PreloadThisFlag = 'PreloadThis';
sc_PreloadGlobalFlag = 'PreloadGlobal';
sc_Catch = 'Catch';
sc_TryLabel = 'TryLabel';
sc_CatchLabel = 'CatchLabel';
sc_FinallyLabel = 'FinallyLabel';
sc_Event = 'Event';
sc_KeyCode = 'KeyCode';
sc_Offset = 'Offset';
sc_APostMethod: array [0..2] of pchar = ('', 'GET', 'POST');
sc_AClipEvents: array[TSWFClipEvent] of pchar =
('KeyUp', 'KeyDown', 'MouseUp', 'MouseDown', 'MouseMove', 'Unload',
'EnterFrame', 'Load', 'DragOver', 'RollOut', 'RollOver',
'ReleaseOutside', 'Release', 'Press', 'Initialize', 'Data',
'Construct', 'KeyPress', 'DragOut');
sc_AStateTransition: array [TSWFStateTransition] of pchar =
('IdleToOverUp', 'OverUpToIdle', 'OverUpToOverDown', 'OverDownToOverUp',
'OutDownToOverDown', 'OverDownToOutDown', 'OutDownToIdle',
'IdleToOverDown', 'OverDownToIdle');
sc_NumFrames = 'NumFrames';
sc_VideoFlagsDeblocking = 'VideoFlagsDeblocking';
sc_VideoFlagsSmoothing = 'VideoFlagsSmoothing';
sc_CodecID = 'Codec';
sc_Repeat = 'Repeat';
sc_Time = 'Time';
sc_IDStr = 'IDStr';
sc_XMin = 'XMin';
sc_XMax = 'XMax';
sc_YMin = 'YMin';
sc_YMax = 'YMax';
sc_Matrix = 'Matrix';
sc_Scale = 'Scale';
sc_Skew = 'Skew';
sc_Translate = 'Translate';
sc_Add = 'Add';
sc_Mult = 'Mult';
sc_ColorTransform = 'ColorTransform';
sc_Alpha = 'Alpha';
sc_EventActions = 'EventActions';
sc_File = 'File';
sc_CodeType = 'CodeType';
sc_lpImage = 'image';
sc_lpSound = 'sound';
sc_lpVideo = 'video';
sc_lpFont = 'font';
sc_lpActions = 'actions';
sc_lpNotIdentified = 'notident';
sc_FileType = 'FileType';
sc_XML = 'XML';
sc_bytecode = 'bytecode';
sc_AC = 'AC';
sc_RadialGradient = 'RadialGradient';
sc_LinearGradient = 'LinearGradient';
sc_SolidColor = 'SolidColor';
sc_Angle = 'Angle';
sc_AlphaColor = 'AlphaColor';
sc_AlphaFile = 'AlphaFile';
sc_AlphaIndex = 'AlphaIndex';
sc_ImageFill = 'ImageFill';
sc_LineStyle = 'LineStyle';
sc_Ext = 'Ext';
sc_Device = 'Device';
sc_FontSize = 'Size';
sc_EncodingType = 'EncodingType';
sc_SWFFormat = 'SWFFormat';
sc_DynamicText = 'Dynamic';
sc_CharSpacing = 'CharSpacing';
sc_FontIDStr = 'FontIDStr';
sc_AsBackground = 'AsBackground';
sc_SndPress = 'SndPress';
sc_SndRelease = 'SndRelease';
sc_SndRollOut = 'SndRollOut';
sc_SndRollOver = 'SndRollOver';
sc_Renum = 'Renum';
sc_HasMetadata = 'HasMetadata';
sc_UseNetwork = 'UseNetwork';
sc_AFilterNames: array [0..7] of PChar =
('DropShadow','Blur','Glow','Bevel','GradientGlow','Convolution','ColorMatrix','GradientBevel');
sc_BlendMode = 'BlendMode';
sc_CacheAsBitmap = 'CacheAsBitmap';
sc_HasImage = 'HasImage';
sc_ClassName = 'ClassName';
sc_HasClassName = 'Has'+sc_ClassName;
sc_Filters = 'Filters';
sc_Passes = 'Passes';
sc_BlurX = 'BlurX';
sc_BlurY = 'BlurY';
sc_Bias = 'Bias';
sc_Clamp = 'Clamp';
sc_Divisor = 'Divisor';
sc_PreserveAlpha = 'PreserveAlpha';
sc_Distance = 'Distance';
sc_Strength = 'Strength';
sc_InnerShadow = 'InnerShadow';
sc_Knockout = 'Knockout';
sc_CompositeSource = 'CompositeSource';
sc_OnTop = 'OnTop';
sc_InnerGlow = 'InnerGlow';
sc_NumColors = 'NumColors';
sc_AQuality: array [0..2] of pchar = ('Low', 'Medium', 'High');
sc_UsesNonScalingStrokes = 'UsesNonScalingStrokes';
sc_UsesScalingStrokes = 'UsesScalingStrokes';
sc_FocalPoint = 'FocalPoint';
sc_InterpolationMode = 'InterpolationMode';
sc_SpreadMode = 'SpreadMode';
sc_HasFillFlag = 'HasFillFlag';
sc_CapStyle = 'CapStyle';
sc_StartCapStyle = 'Start'+sc_CapStyle;
sc_EndCapStyle = 'End'+sc_CapStyle;
sc_JoinStyle = 'JoinStyle';
sc_NoClose = 'NoClose';
sc_NoHScaleFlag = 'NoHScaleFlag';
sc_NoVScaleFlag = 'NoVScaleFlag';
sc_PixelHintingFlag = 'PixelHintingFlag';
sc_MiterLimitFactor = 'MiterLimitFactor';
sc_CSMTableHint = 'CSMTableHint';
sc_ZoneRecord = 'ZoneRecord';
sc_NumZoneData = 'NumZoneData';
sc_MaskX = 'MaskX';
sc_MaskY = 'MaskY';
sc_Range = 'Range';
sc_UseFlashType = 'UseFlashType';
sc_GridFit = 'GridFit';
sc_Thickness = 'Thickness';
sc_Sharpness = 'Sharpness';
sc_ButtonHasBlendMode = 'Has' + sc_BlendMode;
sc_ButtonHasFilterList = 'Has' + sc_Filters;
sc_Brightness = 'Brightness';
sc_Contrast = 'Contrast';
sc_Saturation = 'Saturation';
sc_Hue = 'Hue';
sc_WaveCompressBit = 'WaveCompressBit';
sc_LazyInitializeFlag = 'LazyInitializeFlag';
sc_int = 'Int';
sc_uint = 'UInt';
sc_double = 'Double';
sc_Strings = 'Strings';
sc_NameSpace = 'NameSpace';
sc_NameSpaceSET = sc_NameSpace+ 'SET';
sc_Kind = 'Kind';
sc_Multiname = 'Multiname';
sc_Method = 'Method';
sc_Methods = sc_Method + 's';
sc_ReturnType = 'ReturnType';
sc_Param = 'Param';
sc_NeedArguments = 'NeedArguments';
sc_NeedActivation = 'NeedActivation';
sc_NeedRest = 'NeedRest';
sc_SetDxns = 'SetDxns';
sc_Option = 'Option';
sc_Metadata = 'Metadata';
sc_MetadataInfo = sc_Metadata+'Info';
sc_Key = 'Key';
sc_Trait = 'Trait';
sc_Instance = 'Instance';
sc_Instances = sc_Instance + 's';
sc_SuperName = 'SuperName';
sc_ProtectedNs = 'ProtectedNs';
sc_Init = 'Init';
sc_Iinit = 'Iinit';
sc_Class = 'Class';
sc_ClassFinal = sc_Class + 'Final';
sc_ClassInterface = sc_Class + 'Interface';
sc_ClassProtectedNs = sc_Class + 'ProtectedNs';
sc_ClassSealed = sc_Class + 'Sealed';
sc_Classes = 'Classes';
sc_TraitType = 'TraitType';
sc_IsFinal = 'IsFinal';
sc_SpecID = 'SpecID';
sc_VIndex = 'VIndex';
sc_VKind = 'VKind';
sc_IsOverride = 'IsOverride';
sc_Script = 'Script';
sc_Scripts = sc_Script + 's';
sc_MethodBodies = 'MethodBodies';
sc_MethodBody = 'MethodBody';
sc_MaxStack = 'MaxStack';
sc_LocalCount = 'LocalCount';
sc_InitScopeDepth = 'InitScopeDepth';
sc_MaxScopeDepth = 'MaxScopeDepth';
sc_Exception = 'Exception';
sc_From = 'From';
sc_To = 'To';
sc_ExcType = 'ExcType';
sc_VarName = 'VarName';
sc_ConstantPool = 'ConstantPool';
sc_FLVMetaData: array [0..19] of PChar = ('duration', 'lasttimestamp', 'lastkeyframetimestamp', 'width', 'height',
'videodatarate', 'audiodatarate', 'framerate', 'creationdate', 'filesize', 'videosize', 'audiosize', 'datasize',
'metadatacreator', 'metadatadate', 'videocodecid', 'audiocodecid', 'audiodelay', 'canseektoend', 'keyframes');
sc_ProductId = 'ProductId';
sc_Edition = 'Edition';
sc_BuildNumber = 'BuildNumber';
sc_Date = 'Date';
sc_Interfaces = 'Interfaces';
function StringFromArray(n: integer; Arr: array of string): string; overload;
function StringFromArray(nn: array of integer; Arr: array of string): string; overload;
function StringPosInArray(s: string; Arr: array of string): integer;
function PCharPosInArray(s: pchar; Arr: array of pchar): integer;
Function GetTagName(ID: word): string;
Function GetTagID(name: string): integer;
Function GetActionName(ID: word; prefix: boolean = true): string;
Function GetInstructionName(ID: byte; prefix: string = ''): string; // for AVM2
Function GetActionID(name: string): integer;
function GetClipEventFlagsName(EF: TSWFClipEvents):string;
function GetButtonEventFlagsName(EF: TSWFStateTransitions): string;
Function GetFilterFromName(s: string): TSWFFilterID;
function GetFillTypeName(FT: TSWFFillType; prefix: boolean = true): string;
function GetFillTypeFromName(s: string): TSWFFillType;
implementation
function StringFromArray(n: integer; Arr: array of string): string;
begin
result := Arr[n];
end;
function StringPosInArray(s: string; Arr: array of string): integer;
var il:integer;
begin
Result := -1;
for il := 0 to High(Arr) do
if AnsiSameText(s, Arr[il]) then
begin
Result := il;
Break;
end;
end;
function PCharPosInArray(s: pchar; Arr: array of pchar): integer;
var il:integer;
begin
result := -1;
for il := 0 to High(Arr) do
if AnsiSameText(s, Arr[il]) then
begin
Result := il;
Break;
end;
end;
function StringFromArray(nn: array of integer; Arr: array of string): string;
var il: integer;
begin
Result := '';
if (High(nn)-Low(nn) + 1) > 0 then
for il := Low(nn) to High(nn) do
if Result = '' then Result := Arr[il] else Result := Result + ', ' + Arr[il];
end;
type
ATagRec = Record
ID: word;
Name: PChar;
end;
const
ATagCount = 65;
ATags: array [0..ATagCount - 1] of ATagRec = (
(ID: tagShowFrame; Name: 'ShowFrame'),
(ID: tagDefineShape; Name: 'DefineShape'),
(ID: tagDefineShape2; Name: 'DefineShape2'),
(ID: tagDefineShape3; Name: 'DefineShape3'),
(ID: tagPlaceObject2; Name: 'PlaceObject2'),
(ID: tagRemoveObject2; Name: 'RemoveObject2'),
(ID: tagPlaceObject; Name: 'PlaceObject'),
(ID: tagRemoveObject; Name: 'RemoveObject'),
(ID: tagDoAction; Name: 'DoAction'),
(ID: tagDefineBits; Name: 'DefineBits'),
(ID: tagDefineButton; Name: 'DefineButton'),
(ID: tagJPEGTables; Name: 'JPEGTables'),
(ID: tagDefineFont; Name: 'DefineFont'),
(ID: tagDefineText; Name: 'DefineText'),
(ID: tagDefineFontInfo; Name: 'DefineFontInfo'),
(ID: tagDefineFontInfo2; Name: 'DefineFontInfo2'),
(ID: tagDefineSound; Name: 'DefineSound'),
(ID: tagStartSound; Name: 'StartSound'),
(ID: tagDefineButtonSound; Name: 'DefineButtonSound'),
(ID: tagSoundStreamHead; Name: 'SoundStreamHead'),
(ID: tagSoundStreamBlock; Name: 'SoundStreamBlock'),
(ID: tagDefineBitsLossless; Name: 'DefineBitsLossless'),
(ID: tagDefineBitsJPEG2; Name: 'DefineBitsJPEG2'),
(ID: tagDefineButtonCxform; Name: 'DefineButtonCxform'),
(ID: tagDefineText2; Name: 'DefineText2'),
(ID: tagDefineButton2; Name: 'DefineButton2'),
(ID: tagDefineBitsJPEG3; Name: 'DefineBitsJPEG3'),
(ID: tagDefineBitsLossless2; Name: 'DefineBitsLossless2'),
(ID: tagDefineEditText; Name: 'DefineEditText'),
(ID: tagDefineSprite; Name: 'DefineSprite'),
(ID: tagNameCharacter; Name: 'NameCharacter'),
(ID: tagFrameLabel; Name: 'FrameLabel'),
(ID: tagSoundStreamHead2; Name: 'SoundStreamHead2'),
(ID: tagDefineMorphShape; Name: 'DefineMorphShape'),
(ID: tagDefineFont2; Name: 'DefineFont2'),
(ID: tagExportAssets; Name: 'ExportAssets'),
(ID: tagImportAssets; Name: 'ImportAssets'),
(ID: tagDoInitAction; Name: 'DoInitAction'),
(ID: tagDefineVideoStream; Name: 'DefineVideoStream'),
(ID: tagVideoFrame; Name: 'VideoFrame'),
(ID: tagEnd; Name: 'End'),
(ID: tagProtect; Name: 'Protect'),
(ID: tagSetBackgroundColor; Name: 'SetBackgroundColor'),
(ID: tagEnableDebugger; Name: 'EnableDebugger'),
(ID: tagEnableDebugger2; Name: 'EnableDebugger2'),
(ID: tagScriptLimits; Name: 'ScriptLimits'),
(ID: tagSetTabIndex; Name: 'SetTabIndex'),
(ID: tagDefineShape4; Name: 'DefineShape4'),
(ID: tagFileAttributes; Name: 'FileAttributes'),
(ID: tagPlaceObject3; Name: 'PlaceObject3'),
(ID: tagImportAssets2; Name: 'ImportAssets2'),
(ID: tagDefineFontAlignZones;Name: 'DefineFontAlignZones'),
(ID: tagCSMTextSettings; Name: 'CSMTextSettings'),
(ID: tagDefineFont3; Name: 'DefineFont3'),
(ID: tagMetadata; Name: 'Metadata'),
(ID: tagDefineScalingGrid; Name: 'DefineScalingGrid'),
(ID: tagDefineMorphShape2; Name: 'DefineMorphShape2'),
(ID: tagProductInfo; Name: 'ProductInfo'),
(ID: tagDoABC; Name: 'DoABC'),
(ID: tagSymbolClass; Name: 'SymbolClass'),
(ID: tagStartSound2; Name: 'StartSound2'),
(ID: tagDefineBinaryData; Name: 'DefineBinaryData'),
(ID: tagDefineFontName; Name: 'DefineFontName'),
(ID: tagDefineSceneAndFrameLabelData; Name: 'DefineSceneAndFrameLabelData'),
(ID: tagErrorTag; Name: 'Error Tag')
);
Function GetTagName(ID: word): string;
var il: integer;
begin
Result := '';
for il := 0 to ATagCount - 1 do
if ATags[il].ID = ID then
begin
Result := ATags[il].Name;
Break;
end;
if Result = '' then Result := 'Unknown ' + IntToStr(ID);
end;
Function GetTagID(name: string): integer;
var il: integer;
begin
Result := -1;
for il := 0 to ATagCount - 1 do
if AnsiSameText(ATags[il].Name, name) then
begin
Result := ATags[il].ID;
Break;
end;
if (Result = -1) and (Pos('tag', name) = 1) then
try
Result := StrToInt(Copy(name, 4, 255));
except
Result := -1;
end;
if (Result = tagErrorTag) then Result := -1;
end;
const
AActCount = 102;
AActions: array [0..AActCount - 1] of ATagRec = (
// SWF 3
(ID: ActionPlay; Name: 'Play'),
(ID: ActionStop; Name: 'Stop'),
(ID: ActionNextFrame; Name: 'NextFrame'),
(ID: ActionPreviousFrame; Name: 'PreviousFrame'),
(ID: ActionGotoFrame; Name: 'GotoFrame'),
(ID: ActionGoToLabel; Name: 'GoToLabel'),
(ID: ActionWaitForFrame; Name: 'WaitForFrame'),
(ID: ActionGetURL; Name: 'GetURL'),
(ID: ActionStopSounds; Name: 'StopSounds'),
(ID: ActionToggleQuality; Name: 'ToggleQuality'),
(ID: ActionSetTarget; Name: 'SetTarget'),
//SWF 4
(ID: ActionAdd; Name: 'Add'),
(ID: ActionDivide; Name: 'Divide'),
(ID: ActionMultiply; Name: 'Multiply'),
(ID: ActionSubtract; Name: 'Subtract'),
(ID: ActionEquals; Name: 'Equals'),
(ID: ActionLess; Name: 'Less'),
(ID: ActionAnd; Name: 'And'),
(ID: ActionNot; Name: 'Not'),
(ID: ActionOr; Name: 'Or'),
(ID: ActionStringAdd; Name: 'StringAdd'),
(ID: ActionStringEquals; Name: 'StringEquals'),
(ID: ActionStringExtract; Name: 'StringExtract'),
(ID: ActionStringLength; Name: 'StringLength'),
(ID: ActionMBStringExtract; Name: 'MBStringExtract'),
(ID: ActionMBStringLength; Name: 'MBStringLength'),
(ID: ActionStringLess; Name: 'StringLess'),
(ID: ActionPop; Name: 'Pop'),
(ID: ActionPush; Name: 'Push'),
(ID: ActionAsciiToChar; Name: 'AsciiToChar'),
(ID: ActionCharToAscii; Name: 'CharToAscii'),
(ID: ActionToInteger; Name: 'ToInteger'),
(ID: ActionMBAsciiToChar; Name: 'MBAsciiToChar'),
(ID: ActionMBCharToAscii; Name: 'MBCharToAscii'),
(ID: ActionCall; Name: 'Call'),
(ID: ActionIf; Name: 'If'),
(ID: ActionJump; Name: 'Jump'),
(ID: ActionGetVariable; Name: 'GetVariable'),
(ID: ActionSetVariable; Name: 'SetVariable'),
(ID: ActionGetURL2; Name: 'GetURL2'),
(ID: ActionGetProperty; Name: 'GetProperty'),
(ID: ActionGotoFrame2; Name: 'GotoFrame2'),
(ID: ActionRemoveSprite; Name: 'RemoveSprite'),
(ID: ActionSetProperty; Name: 'SetProperty'),
(ID: ActionSetTarget2; Name: 'SetTarget2'),
(ID: ActionStartDrag; Name: 'StartDrag'),
(ID: ActionWaitForFrame2; Name: 'WaitForFrame2'),
(ID: ActionCloneSprite; Name: 'CloneSprite'),
(ID: ActionEndDrag; Name: 'EndDrag'),
(ID: ActionGetTime; Name: 'GetTime'),
(ID: ActionRandomNumber; Name: 'RandomNumber'),
(ID: ActionTrace; Name: 'Trace'),
(ID: ActionFSCommand2; Name: 'FSCommand2'),
//SWF 5
(ID: ActionCallFunction; Name: 'CallFunction'),
(ID: ActionCallMethod; Name: 'CallMethod'),
(ID: ActionConstantPool; Name: 'ConstantPool'),
(ID: ActionDefineFunction; Name: 'DefineFunction'),
(ID: ActionDefineLocal; Name: 'DefineLocal'),
(ID: ActionDefineLocal2; Name: 'DefineLocal2'),
(ID: ActionDelete; Name: 'Delete'),
(ID: ActionDelete2; Name: 'Delete2'),
(ID: ActionEnumerate; Name: 'Enumerate'),
(ID: ActionEquals2; Name: 'Equals2'),
(ID: ActionGetMember; Name: 'GetMember'),
(ID: ActionInitArray; Name: 'InitArray'),
(ID: ActionInitObject; Name: 'InitObject'),
(ID: ActionNewMethod; Name: 'NewMethod'),
(ID: ActionNewObject; Name: 'NewObject'),
(ID: ActionSetMember; Name: 'SetMember'),
(ID: ActionTargetPath; Name: 'TargetPath'),
(ID: ActionWith; Name: 'With'),
(ID: ActionToNumber; Name: 'ToNumber'),
(ID: ActionToString; Name: 'ToString'),
(ID: ActionTypeOf; Name: 'TypeOf'),
(ID: ActionAdd2; Name: 'Add2'),
(ID: ActionLess2; Name: 'Less2'),
(ID: ActionModulo; Name: 'Modulo'),
(ID: ActionBitAnd; Name: 'BitAnd'),
(ID: ActionBitLShift; Name: 'BitLShift'),
(ID: ActionBitOr; Name: 'BitOr'),
(ID: ActionBitRShift; Name: 'BitRShift'),
(ID: ActionBitURShift; Name: 'BitURShift'),
(ID: ActionBitXor; Name: 'BitXor'),
(ID: ActionDecrement; Name: 'Decrement'),
(ID: ActionIncrement; Name: 'Increment'),
(ID: ActionPushDuplicate; Name: 'PushDuplicate'),
(ID: ActionReturn; Name: 'Return'),
(ID: ActionStackSwap; Name: 'StackSwap'),
(ID: ActionStoreRegister; Name: 'StoreRegister'),
//SWF 6
(ID: ActionInstanceOf; Name: 'InstanceOf'),
(ID: ActionEnumerate2; Name: 'Enumerate2'),
(ID: ActionStrictEquals; Name: 'StrictEquals'),
(ID: ActionGreater; Name: 'Greater'),
(ID: ActionStringGreater; Name: 'StringGreater'),
//SWF 7
(ID: ActionDefineFunction2; Name: 'DefineFunction2'),
(ID: ActionExtends; Name: 'Extends'),
(ID: ActionCastOp; Name: 'CastOp'),
(ID: ActionImplementsOp; Name: 'ImplementsOp'),
(ID: ActionTry; Name: 'Try'),
(ID: ActionThrow; Name: 'Throw'),
(ID: ActionByteCode; Name: 'ByteCode'),
(ID: actionOffsetWork; Name: 'Offset marker (only for work)')
);
Function GetActionName(ID: word; prefix: boolean = true): string;
var il: integer;
begin
Result := '';
for il := 0 to AActCount - 1 do
if AActions[il].ID = ID then
begin
Result := AActions[il].Name;
Break;
end;
if Result = '' then Result := 'Unknown ' + IntToStr(ID) else
if prefix and (ID <> actionOffsetWork) then
Result := 'Action' + Result;
end;
Function GetActionID(name: string): integer;
var il: integer;
begin
Result := -1;
if AnsiSameText(sc_Offset, name) then Result := actionOffsetWork else
begin
for il := 0 to AActCount - 1 do
if AnsiSameText(AActions[il].Name, name) then
begin
Result := AActions[il].ID;
Break;
end;
end;
end;
function GetButtonEventFlagsName(EF: TSWFStateTransitions): string;
begin
if IdleToOverUp in EF then result := 'OnRollOverActions, ' else result := '';
if OverUpToIdle in EF then result := result + 'OnRollOutActions, ';
if OverUpToOverDown in EF then result := result + 'OnPressActions, ';
if OverDownToOverUp in EF then result := result + 'OnReleaseActions, ';
if OutDownToOverDown in EF then result := result + 'OnDragOverActions, ';
if OverDownToOutDown in EF then result := result + 'OnDragOutActions, ';
if OutDownToIdle in EF then result := result + 'OnReleaseOutsideActions, ';
if IdleToOverDown in EF then result := result + 'OnMenuDragOverActions, ';
if OverDownToIdle in EF then result := result + 'OnMenuDragOutActions, ';
if Result<>'' then Delete(Result, Length(Result)-1, 2);
end;
function GetClipEventFlagsName(EF: TSWFClipEvents):string;
begin
if ceKeyUp in EF then result := 'OnKeyUp, ' else result := '';
if ceKeyDown in EF then result := result + 'OnKeyDown, ';
if ceMouseUp in EF then result := result + 'OnMouseUp, ';
if ceMouseDown in EF then result := result + 'OnMouseDown, ';
if ceMouseMove in EF then result := result + 'OnMouseMove, ';
if ceUnload in EF then result := result + 'OnUnload, ';
if ceEnterFrame in EF then result := result + 'OnEnterFrame, ';
if ceLoad in EF then result := result + 'OnLoad, ';
if ceDragOver in EF then result := result + 'OnDragOver, ';
if ceRollOut in EF then result := result + 'OnRollOut, ';
if ceRollOver in EF then result := result + 'OnRollOver, ';
if ceReleaseOutside in EF then result := result + 'OnReleaseOutside, ';
if ceRelease in EF then result := result + 'OnRelease, ';
if cePress in EF then result := result + 'OnPress, ';
if ceInitialize in EF then result := result + 'OnInitialize, ';
if ceData in EF then result := result + 'OnData, ';
if ceConstruct in EF then result := result + 'OnConstruct, ';
if ceKeyPress in EF then result := result + 'OnKeyPress, ';
if ceDragOut in EF then result := result + 'OnDragOut, ';
if Result<>'' then Delete(Result, Length(Result)-1, 2);
end;
Function GetFilterFromName(s: string): TSWFFilterID;
var il: byte;
begin
Result := fidDropShadow;
for il := 0 to 7 do
if AnsiSameText(sc_AFilterNames[il], S) then Result := TSWFFilterID(il);
end;
Function GetFillTypeName(FT: TSWFFillType; prefix: boolean = true): string;
begin
Case FT of
SWFFillSolid: Result := 'Solid';
SWFFillLinearGradient: Result := 'LinearGradient';
SWFFillRadialGradient: Result := 'RadialGradient';
SWFFillFocalGradient: Result := 'FocalGradient';
SWFFillTileBitmap: Result := 'TileBitmap';
SWFFillClipBitmap: Result := 'ClipBitmap';
SWFFillNonSmoothTileBitmap: Result := 'NonSmoothTileBitmap';
SWFFillNonSmoothClipBitmap: Result := 'NonSmoothClipBitmap';
end;
if prefix then Result := 'SWFFill' + Result;
end;
function GetFillTypeFromName(s: string): TSWFFillType;
begin
if AnsiSameText(S, 'Solid') then Result := SWFFillSolid else
if AnsiSameText(S, 'LinearGradient') then Result := SWFFillLinearGradient else
if AnsiSameText(S, 'RadialGradient') then Result := SWFFillRadialGradient else
if AnsiSameText(S, 'FocalGradient') then Result := SWFFillFocalGradient else
if AnsiSameText(S, 'TileBitmap') then Result := SWFFillTileBitmap else
if AnsiSameText(S, 'ClipBitmap') then Result := SWFFillClipBitmap else
if AnsiSameText(S, 'NonSmoothTileBitmap') then Result := SWFFillNonSmoothTileBitmap else
if AnsiSameText(S, 'NonSmoothClipBitmap') then Result := SWFFillNonSmoothClipBitmap
else Result := SWFFillSolid;
end;
const
AInstructCount = 158;
AInstrucs: array [0..AInstructCount - 1] of ATagRec = (
(ID: opBkpt; Name: 'Bkpt'),
(ID: opNop; Name: 'Nop'),
(ID: opThrow; Name: 'Throw'),
(ID: opGetSuper; Name: 'GetSuper'),
(ID: opSetSuper; Name: 'SetSuper'),
(ID: opDxns; Name: 'Dxns'),
(ID: opDxnsLate; Name: 'DxnsLate'),
(ID: opKill; Name: 'Kill'),
(ID: opLabel; Name: 'Label'),
(ID: opIfNlt; Name: 'IfNlt'),
(ID: opIfNle; Name: 'IfNle'),
(ID: opIfNgt; Name: 'IfNgt'),
(ID: opIfNge; Name: 'IfNge'),
(ID: opJump; Name: 'Jump'),
(ID: opIfTrue; Name: 'IfTrue'),
(ID: opIfFalse; Name: 'IfFalse'),
(ID: opIfEq; Name: 'IfEq'),
(ID: opIfNe; Name: 'IfNe'),
(ID: opIfLt; Name: 'IfLt'),
(ID: opIfLe; Name: 'IfLe'),
(ID: opIfGt; Name: 'IfGt'),
(ID: opIfGe; Name: 'IfGe'),
(ID: opIfStrictEq; Name: 'IfStrictEq'),
(ID: opIfStrictNe; Name: 'IfStrictNe'),
(ID: opLookupSwitch; Name: 'LookupSwitch'),
(ID: opPushWith; Name: 'PushWith'),
(ID: opPopScope; Name: 'PopScope'),
(ID: opNextName; Name: 'NextName'),
(ID: opHasNext; Name: 'HasNext'),
(ID: opPushNull; Name: 'PushNull'),
(ID: opPushUndefined; Name: 'PushUndefined'),
(ID: opPushConstant; Name: 'PushConstant'),
(ID: opNextValue; Name: 'NextValue'),
(ID: opPushByte; Name: 'PushByte'),
(ID: opPushShort; Name: 'PushShort'),
(ID: opPushTrue; Name: 'PushTrue'),
(ID: opPushFalse; Name: 'PushFalse'),
(ID: opPushNan; Name: 'PushNan'),
(ID: opPop; Name: 'Pop'),
(ID: opDup; Name: 'Dup'),
(ID: opSwap; Name: 'Swap'),
(ID: opPushString; Name: 'PushString'),
(ID: opPushInt; Name: 'PushInt'),
(ID: opPushUInt; Name: 'PushUInt'),
(ID: opPushDouble; Name: 'PushDouble'),
(ID: opPushScope; Name: 'PushScope'),
(ID: opPushNameSpace; Name: 'PushNameSpace'),
(ID: opHasNext2; Name: 'HasNext2'),
(ID: opNewFunction; Name: 'NewFunction'),
(ID: opCall; Name: 'Call'),
(ID: opConstruct; Name: 'Construct'),
(ID: opCallMethod; Name: 'CallMethod'),
(ID: opCallStatic; Name: 'CallStatic'),
(ID: opCallSuper; Name: 'CallSuper'),
(ID: opCallProperty; Name: 'CallProperty'),
(ID: opReturnVoid; Name: 'ReturnVoid'),
(ID: opReturnValue; Name: 'ReturnValue'),
(ID: opConstructSuper; Name: 'ConstructSuper'),
(ID: opConstructProp; Name: 'ConstructProp'),
(ID: opCallSuperId; Name: 'CallSuperId'),
(ID: opCallPropLex; Name: 'CallPropLex'),
(ID: opCallInterface; Name: 'CallInterface'),
(ID: opCallSuperVoid; Name: 'CallSuperVoid'),
(ID: opCallPropVoid; Name: 'CallPropVoid'),
(ID: opNewObject; Name: 'NewObject'),
(ID: opNewArray; Name: 'NewArray'),
(ID: opNewActivation; Name: 'NewActivation'),
(ID: opNewClass; Name: 'NewClass'),
(ID: opGetDescendants; Name: 'GetDescendants'),
(ID: opNewCatch; Name: 'NewCatch'),
(ID: opFindPropStrict; Name: 'FindPropStrict'),
(ID: opFindProperty; Name: 'FindProperty'),
(ID: opFindDef; Name: 'FindDef'),
(ID: opGetLex; Name: 'GetLex'),
(ID: opSetProperty; Name: 'SetProperty'),
(ID: opGetLocal; Name: 'GetLocal'),
(ID: opSetLocal; Name: 'SetLocal'),
(ID: opGetGlobalScope; Name: 'GetGlobalScope'),
(ID: opGetScopeObject; Name: 'GetScopeObject'),
(ID: opGetProperty; Name: 'GetProperty'),
(ID: opGetPropertyLate; Name: 'GetPropertyLate'),
(ID: opInitProperty; Name: 'InitProperty'),
(ID: opSetPropertyLate; Name: 'SetPropertyLate'),
(ID: opDeleteProperty; Name: 'DeleteProperty'),
(ID: opDeletePropertyLate; Name: 'DeletePropertyLate'),
(ID: opGetSlot; Name: 'GetSlot'),
(ID: opSetSlot; Name: 'SetSlot'),
(ID: opGetGlobalSlot; Name: 'GetGlobalSlot'),
(ID: opSetGlobalSlot; Name: 'SetGlobalSlot'),
(ID: opConvert_s; Name: 'Convert_s'),
(ID: opEsc_xelem; Name: 'Esc_xelem'),
(ID: opEsc_xattr; Name: 'Esc_xattr'),
(ID: opConvert_i; Name: 'Convert_i'),
(ID: opConvert_u; Name: 'Convert_u'),
(ID: opConvert_d; Name: 'Convert_d'),
(ID: opConvert_b; Name: 'Convert_b'),
(ID: opConvert_o; Name: 'Convert_o'),
(ID: opCoerce; Name: 'Coerce'),
(ID: opCoerce_b; Name: 'Coerce_b'),
(ID: opCoerce_a; Name: 'Coerce_a'),
(ID: opCoerce_i; Name: 'Coerce_i'),
(ID: opCoerce_d; Name: 'Coerce_d'),
(ID: opCoerce_s; Name: 'Coerce_s'),
(ID: opAsType; Name: 'AsType'),
(ID: opAsTypeLate; Name: 'AsTypeLate'),
(ID: opCoerce_u; Name: 'Coerce_u'),
(ID: opCoerce_o; Name: 'Coerce_o'),
(ID: opNegate; Name: 'Negate'),
(ID: opIncrement; Name: 'Increment'),
(ID: opIncLocal; Name: 'IncLocal'),
(ID: opDecrement; Name: 'Decrement'),
(ID: opDecLocal; Name: 'DecLocal'),
(ID: opTypeOf; Name: 'TypeOf'),
(ID: opNot; Name: 'Not'),
(ID: opBitNot; Name: 'BitNot'),
(ID: opConcat; Name: 'Concat'),
(ID: opAdd_d; Name: 'Add_d'),
(ID: opAdd; Name: 'Add'),
(ID: opSubTract; Name: 'SubTract'),
(ID: opMultiply; Name: 'Multiply'),
(ID: opDivide; Name: 'Divide'),
(ID: opModulo; Name: 'Modulo'),
(ID: opLShift; Name: 'LShift'),
(ID: opRShift; Name: 'RShift'),
(ID: opURShift; Name: 'URShift'),
(ID: opBitAnd; Name: 'BitAnd'),
(ID: opBitOr; Name: 'BitOr'),
(ID: opBitXor; Name: 'BitXor'),
(ID: opEquals; Name: 'Equals'),
(ID: opStrictEquals; Name: 'StrictEquals'),
(ID: opLessThan; Name: 'LessThan'),
(ID: opLessEquals; Name: 'LessEquals'),
(ID: opGreaterThan; Name: 'GreaterThan'),
(ID: opGreaterEquals; Name: 'GreaterEquals'),
(ID: opInstanceOf; Name: 'InstanceOf'),
(ID: opIsType; Name: 'IsType'),
(ID: opIsTypeLate; Name: 'IsTypeLate'),
(ID: opIn; Name: 'In'),
(ID: opIncrement_i; Name: 'Increment_i'),
(ID: opDecrement_i; Name: 'Decrement_i'),
(ID: opInclocal_i; Name: 'Inclocal_i'),
(ID: opDeclocal_i; Name: 'Declocal_i'),
(ID: opNegate_i; Name: 'Negate_i'),
(ID: opAdd_i; Name: 'Add_i'),
(ID: opSubtract_i; Name: 'Subtract_i'),
(ID: opMultiply_i; Name: 'Multiply_i'),
(ID: opGetLocal0; Name: 'GetLocal0'),
(ID: opGetLocal1; Name: 'GetLocal1'),
(ID: opGetLocal2; Name: 'GetLocal2'),
(ID: opGetLocal3; Name: 'GetLocal3'),
(ID: opSetLocal0; Name: 'SetLocal0'),
(ID: opSetLocal1; Name: 'SetLocal1'),
(ID: opSetLocal2; Name: 'SetLocal2'),
(ID: opSetLocal3; Name: 'SetLocal3'),
(ID: opDebug; Name: 'Debug'),
(ID: opDebugLine; Name: 'DebugLine'),
(ID: opDebugFile; Name: 'DebugFile'),
(ID: opBkptLine; Name: 'BkptLine')
);
Function GetInstructionName(ID: byte; prefix: string = ''): string;
var il: integer;
begin
Result := '';
for il := 0 to AInstructCount - 1 do
if AInstrucs[il].ID = ID then
begin
Result := AInstrucs[il].Name;
Break;
end;
if Result = '' then Result := '$' + IntToHex(ID, 2) else
if prefix <> '' then
Result := prefix + Result;
end;
end.
|
unit uDBThread;
interface
uses
Winapi.Windows,
System.Classes,
System.SysUtils,
System.SyncObjs,
Vcl.Forms,
Dmitry.Utils.System,
{$IFNDEF EXTERNAL}
uTranslate,
uAssociations,
uPortableDeviceManager,
{$ENDIF}
uGOM,
uDBForm,
uIME,
uTime,
uDBCustomThread;
type
TDBThread = class(TDBCustomThread)
private
FSupportedExt: string;
FMethod: TThreadMethod;
FProcedure: TThreadProcedure;
FCallResult: Boolean;
FOwnerForm: TDBForm;
{$IFNDEF EXTERNAL}
function GetSupportedExt: string;
{$ENDIF}
procedure CallMethod;
procedure CallProcedure;
protected
function L(TextToTranslate: string): string; overload;
function L(TextToTranslate, Scope: string): string; overload;
function GetThreadID: string; virtual;
function SynchronizeEx(Method: TThreadMethod): Boolean; overload; virtual;
function SynchronizeEx(Proc: TThreadProcedure): Boolean; overload; virtual;
{$IFNDEF EXTERNAL}
property SupportedExt: string read GetSupportedExt;
{$ENDIF}
property OwnerForm: TDBForm read FOwnerForm;
procedure Execute; override;
public
constructor Create(OwnerForm: TDBForm; CreateSuspended: Boolean);
destructor Destroy; override;
end;
implementation
{ TThreadEx }
function TDBThread.L(TextToTranslate: string): string;
begin
Result := {$IFDEF EXTERNAL}TextToTranslate{$ELSE}TA(TextToTranslate, GetThreadID){$ENDIF};
end;
procedure TDBThread.CallMethod;
begin
FCallResult := GOM.IsObj(FOwnerForm) or (FOwnerForm = nil);
if FCallResult then
FMethod
else
Terminate;
end;
procedure TDBThread.CallProcedure;
begin
FCallResult := GOM.IsObj(FOwnerForm) or (FOwnerForm = nil);
if FCallResult then
FProcedure
else
Terminate;
end;
constructor TDBThread.Create(OwnerForm: TDBForm; CreateSuspended: Boolean);
begin
inherited Create(CreateSuspended);
FOwnerForm := OwnerForm;
GOM.AddObj(Self);
end;
destructor TDBThread.Destroy;
begin
GOM.RemoveObj(Self);
{$IFNDEF EXTERNAL}
ThreadCleanUp(ThreadID);
{$ENDIF}
inherited;
end;
procedure TDBThread.Execute;
begin
DisableIME;
end;
{$IFNDEF EXTERNAL}
function TDBThread.GetSupportedExt: string;
begin
if FSupportedExt = '' then
FSupportedExt := TFileAssociations.Instance.ExtensionList;
Result := FSupportedExt;
end;
{$ENDIF}
function TDBThread.GetThreadID: string;
begin
Result := ClassName;
end;
function TDBThread.L(TextToTranslate, Scope: string): string;
begin
Result := {$IFDEF EXTERNAL}TextToTranslate{$ELSE}TA(TextToTranslate, Scope){$ENDIF};
end;
function TDBThread.SynchronizeEx(Proc: TThreadProcedure): Boolean;
begin
FProcedure := Proc;
FCallResult := False;
Synchronize(CallProcedure);
Result := FCallResult;
end;
function TDBThread.SynchronizeEx(Method: TThreadMethod): Boolean;
begin
FMethod := Method;
FCallResult := False;
Synchronize(CallMethod);
Result := FCallResult;
end;
procedure FormsWaitProc;
begin
Application.ProcessMessages;
CheckSynchronize();
end;
initialization
CustomWaitProc := FormsWaitProc;
end.
|
unit fi_common;
interface
type
TFontInfo = record
family,
style,
fullName,
psName,
version,
copyright,
uniqueId,
trademark,
manufacturer,
designer,
description,
vendorUrl,
designerUrl,
license,
licenseUrl,
format: String;
variationAxisTags: array of LongWord;
numFonts: LongInt;
end;
const
FONT_WEIGHT_REGULAR = 400;
function GetWeightName(weight: Word): String;
// Extract style from fullName using familyName.
function ExtractStyle(const fullName, familyName: String;
const fallback: String = 'Regular'): String;
implementation
uses
strutils;
function GetWeightName(weight: Word): String;
const NAMES: array [0..9] of String = (
'Thin',
'ExtraLight',
'Light',
'Regular',
'Medium',
'SemiBold',
'Bold',
'ExtraBold',
'Black',
'ExtraBlack'
);
begin
if weight > 0 then
begin
if weight > 1000 then
// Map to Regular
weight := FONT_WEIGHT_REGULAR - 1
else
Dec(weight);
end;
result := NAMES[weight div 100];
end;
function ExtractStyle(const fullName, familyName: String;
const fallback: String): String;
var
styleStart,
styleLen,
fullNameLen: SizeInt;
begin
result := fallback;
if fullName = familyName then
exit;
if (fullName = '')
or (familyName = '')
or not StartsStr(familyName, fullName) then
exit;
styleStart := Length(familyName) + 1;
fullNameLen := Length(fullName);
if styleStart = fullNameLen then
exit;
if fullName[styleStart] in [' ', '-'] then
Inc(styleStart);
styleLen := fullNameLen - styleStart + 1;
if styleLen < 1 then
exit;
result := Copy(fullName, styleStart, styleLen);
end;
end.
|
//---------------------------------------------------------------------------
// Copyright 2014 The Open Source Electronic Health Record Alliance
//
// 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.
//---------------------------------------------------------------------------
{$Optimization off}
unit UTWinSCard;
interface
uses UnitTest, TestFrameWork, WinSCard, SysUtils, Windows, Registry, Dialogs,
Classes, Forms, Controls, StdCtrls, XuDsigConst;
implementation
type
UTWinSCardTests=class(TTestCase)
private
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestSCardEstablishContext;
procedure TestSCardListReaders;
procedure TestSCardReleaseContext;
procedure TestSCardConnectA;
procedure TestSCardDisconnect;
procedure TestSCardReconnect;
end;
procedure UTWinSCardTests.SetUp;
begin
end;
procedure UTWinSCardTests.TearDown;
begin
end;
procedure UTWinSCardTests.TestSCardEstablishContext;
var
result: ULONG;
outpointer:DWORD;
begin
WriteLn(Output,'Start EstablishContext');
result := WinSCard.SCardEstablishContext(SCARD_SCOPE_USER, nil,nil, @outpointer);
if(not (result = 0)) then WriteLn(Output,'SCard Establish Context' + IntToStr(GetLastError()));
CheckEquals(result,SCARD_S_SUCCESS,'SCard Establish Context failed') ;
WriteLn(Output,'Stop EstablishContext');
end;
procedure UTWinSCardTests.TestSCardReleaseContext;
var
result: ULONG;
outpointer:DWORD;
begin
WriteLn(Output,'Start ReleaseContext');
result := WinSCard.SCardEstablishContext(SCARD_SCOPE_USER, nil,nil, @outpointer);
result := WinSCard.SCardReleaseContext(outpointer);
if(not (result = 0)) then WriteLn(Output,'SCard Establish Context' + IntToStr(GetLastError()));
CheckEquals(result,SCARD_S_SUCCESS,'SCard Establish Context failed') ;
WriteLn(Output,'Stop ReleaseContext');
end;
procedure UTWinSCardTests.TestSCardListReaders;
var
result: integer;
outpointer:DWORD;
readerlength : integer;
readerList : string;
begin
WriteLn(Output,'Start ListReaders');
result := WinSCard.SCardEstablishContext(
SCARD_SCOPE_USER,
nil,nil,
@outpointer);
result := WinSCard.SCardListReadersA(outpointer,nil,nil,readerlength);
setLength(readerList,readerLength);
result := WinSCard.SCardListReadersA(outpointer,nil,pChar(readerList),readerlength);
if(not (result = 0)) then WriteLn(Output,'SCard Establish Context' + IntToStr(GetLastError()));
CheckEquals(result,0,'SCard List Readers failed. If result is 8010002E (2148532270):'+
' No SCard readers were found on the system');
WinSCard.SCardReleaseContext(outpointer) ;
WriteLn(Output,'Stop ListReaders');
end;
procedure UTWinSCardTests.TestSCardConnectA;
var
result: ULONG;
outpointer: sCardContext;
scHandle: DWORD;
ActiveProtocol: longint;
readerlength : integer;
readerList,Str : string;
begin
WriteLn(Output,'Start ConnectA');
result := WinSCard.SCardEstablishContext(SCARD_SCOPE_USER, nil,nil, @outpointer);
WinSCard.SCardListReadersA(outpointer,nil,nil,readerlength);
setLength(readerList,readerLength);
WinSCard.SCardListReadersA(outpointer,nil,pChar(readerList),readerlength);
Str := StrPas(PChar(readerList));
result := WinSCard.SCardConnectA(outpointer,
pChar(Str),
SCARD_SHARE_SHARED,
SCARD_PROTOCOL_T1 or SCARD_PROTOCOL_T0,
scHandle,
@ActiveProtocol);
CheckEquals(result,0,'SCardConnect a did not return success,2148532329 ' +
'signifies that a card is not found in the ' + Str + ' reader. ' +
'All subsequent tests will return "6" due to the connection failing');
WinSCard.SCardDisconnect(scHandle,SCARD_LEAVE_CARD);
WinSCard.SCardReleaseContext(outpointer) ;
WriteLn(Output,'Stop ConnectA');
end;
procedure UTWinSCardTests.TestSCardDisconnect;
var
result: ULONG;
outpointer: sCardContext;
scHandle: DWORD;
ActiveProtocol: longint;
readerlength : integer;
readerList,Str : string;
begin
WriteLn(Output,'Start Disconnect');
result := WinSCard.SCardEstablishContext(SCARD_SCOPE_USER, nil,nil, @outpointer);
WinSCard.SCardListReadersA(outpointer,nil,nil,readerlength);
setLength(readerList,readerLength);
WinSCard.SCardListReadersA(outpointer,nil,pChar(readerList),readerlength);
Str := StrPas(PChar(readerList));
result := WinSCard.SCardConnectA(outpointer,
pChar(Str),
SCARD_SHARE_SHARED,
SCARD_PROTOCOL_T1 or SCARD_PROTOCOL_T0,
scHandle,
@ActiveProtocol);
result := WinSCard.SCardDisconnect(scHandle,SCARD_LEAVE_CARD);
CheckEquals(result,0,'SCardDisconnect did not return success');
WinSCard.SCardReleaseContext(outpointer);
WriteLn(Output,'Stop Disconnect');
end;
procedure UTWinSCardTests.TestSCardReconnect;
var
result: ULONG;
outpointer: sCardContext;
scHandle: DWORD;
ActiveProtocol: longint;
readerlength : integer;
readerList,Str : string;
begin
WriteLn(Output,'Start Reconnect');
result := WinSCard.SCardEstablishContext(SCARD_SCOPE_USER, nil,nil, @outpointer);
WinSCard.SCardListReadersA(outpointer,nil,nil,readerlength);
setLength(readerList,readerLength);
WinSCard.SCardListReadersA(outpointer,nil,pChar(readerList),readerlength);
Str := StrPas(PChar(readerList));
result := WinSCard.SCardConnectA(outpointer,
pChar(Str),
SCARD_SHARE_SHARED,
SCARD_PROTOCOL_T1 or SCARD_PROTOCOL_T0,
scHandle,
@ActiveProtocol);
result := WinSCard.SCardReconnect(scHandle,
SCARD_SHARE_SHARED,
SCARD_PROTOCOL_T1 or SCARD_PROTOCOL_T0,
SCARD_RESET_CARD,
ActiveProtocol);
CheckEquals(result,0,'SCardReconnectA did not return success');
WinSCard.SCardReleaseContext(outpointer);
WinSCard.SCardDisconnect(scHandle,SCARD_LEAVE_CARD);
WriteLn(Output,'Stop Reconnect');
end;
begin
UnitTest.addSuite(UTWinSCardTests.Suite);
end. |
unit uSign;
interface
uses
JsonDataObjects, Ils.Json.Names, Ils.Json.Utils, Geo.Hash.Search, System.SysUtils,
System.Generics.Collections, System.Classes, Ils.Logger, UFiles, System.IniFiles,
uZC, AStar64.Files, AStar64.Areas, AStar64.Extra, Geo.Hash, AStar64.FileStructs,
System.Types, uGeneral;
const
CSignsFile = 'RouteSigns.txt';
CSignTypesFile = 'SignTypes.txt';
CHashChars: string = '0123456789bcdefghjkmnpqrstuvwxyz';
PathDelim = '\';
type
TSignTypeInfo = record
Alias: string;
//! наименование
Name: string;
Include: string;
end;
TSignInfo = record
//! AccountID
Account: Integer;
//! маска знаков
Sign: UInt64;
end;
TRouteSign = record
RouteID: TIDLines;
Sign: UInt64;
end;
TSignTypeDictionary = TDictionary<Byte,TSignTypeInfo>;
TSignDictionary = TDictionary<TIDLines,TSignInfo>;
TRouteSignArray = array of TRouteSign;
TSign = class
private
FDetailLog: Boolean;
FProgress: Integer;
FRequestNo: Cardinal;
class var FStop: Boolean;
public
FSignType : TDictionary<Byte,TSignTypeInfo>;
constructor Create(ARequestNo: Cardinal; ADetailLog: Boolean = False); overload;
destructor Destroy(); override;
class procedure Stop;
function LoadSignTypeFile(const ARootPath: string): TJsonObject;
function LoadSignFile(const ARootPath: string;
const AAccounts: TIntegerDynArray): TSignDictionary;
function LoadSignFileOne(const ARootPath: string;
const AAccount: integer): TSignDictionary;
function SaveSignFile(const ARootPath: string;
const AAccount: integer;
const ARouteSignArr: TRouteSignArray): boolean;
function SaveSignTypes(const ARootPath: string; AAccount: integer; ASignTypes: TSignTypeDictionary): Boolean;
function DeleteAllSign(const ARootPath: string;
const AAccounts: TIntegerDynArray): Boolean;
function LoadProgress(AAccount: integer): Integer;
procedure SaveProgress(AAccount: integer);
function CreateSignAll(const ARootPath: string;
const AAccounts: TIntegerDynArray; ADetailLog: Boolean = false): Boolean;
procedure SetBit(var AValue: UInt64; BitNum: Byte);
procedure ClearBit(var AValue: UInt64; BitNum: Byte);
procedure ToggleBit(var AValue: UInt64; BitNum: Byte);
function GetBitStat(AValue: UInt64; BitNum: Byte): Boolean;
end;
implementation
{ TSign }
procedure TSign.SetBit(var AValue: UInt64; BitNum: Byte);
var
Bit64: UInt64;
begin
Bit64 := 1;
Bit64 := Bit64 shl BitNum;
AValue := AValue or Bit64; { Устанавливаем бит }
end;
class procedure TSign.Stop;
begin
FStop := True;
ToLog('TSign Manual Stop');
end;
procedure TSign.ClearBit(var AValue: UInt64; BitNum: Byte);
var
Bit64: UInt64;
begin
Bit64 := 1;
Bit64 := Bit64 shl BitNum;
AValue := AValue or Bit64; { Устанавливаем бит }
AValue := AValue xor Bit64; { Переключаем бит }
end;
procedure TSign.ToggleBit(var AValue: UInt64; BitNum: Byte);
var
Bit64: UInt64;
begin
Bit64 := 1;
Bit64 := Bit64 shl BitNum;
AValue := AValue xor Bit64; { Переключаем бит }
end;
constructor TSign.Create(ARequestNo: Cardinal; ADetailLog: Boolean);
begin
FStop := False;
FDetailLog := ADetailLog;
FRequestNo := ARequestNo;
FSignType := TDictionary<Byte,TSignTypeInfo>.Create;
if FDetailLog then
ToLog('TSign Start');
end;
function TSign.CreateSignAll(const ARootPath: string;
const AAccounts: TIntegerDynArray; ADetailLog: Boolean): Boolean;
var
i, j, iCount: Integer;
SignDictionary: TSignDictionary;
SignInfo: TSignInfo;
RouteID: TIDLines;
HashStartStr, HashEndStr, sFile: string;
Holder: THoldRec;
FileList : TDictionary<string, Integer>;
begin
ToLog('TSign.CreateSignAll. Start create sign files');
Result := False;
FProgress := 0;
SaveProgress(AAccounts[0]);
//удаляем файлы знаков
DeleteAllSign(ARootPath, AAccounts);
//получаем список дорог
SignDictionary := LoadSignFileOne(ARootPath, AAccounts[0]);
//формируем список файлов
FileList := TDictionary<string, Integer>.Create;
try
for RouteID in SignDictionary.Keys do
begin
HashStartStr := TGeoHash.ConvertBinToString(RouteID.HashStart and CAreaHashMask, 5);
HashEndStr := TGeoHash.ConvertBinToString(RouteID.HashEnd and CAreaHashMask, 5);
if not FileList.ContainsKey(HashStartStr) then
begin
FileList.Add(HashStartStr, 0);
end;
if HashStartStr<>HashEndStr then
if not FileList.ContainsKey(HashEndStr) then
FileList.Add(HashEndStr, 0);
end;
i := 0;
iCount := FileList.Count;
//загружаем файлы, проставляем знаки, сохраняем
for sFile in FileList.Keys do
begin
if FStop then
begin
ToLog('TSign.CreateSignAll. Прервано пользователем');
Exit;
end;
TGFAdapter.Load(ARootPath, AAccounts, sFile, Holder);
if Length(Holder.SCForward) <> Length(Holder.EdgeForward) then
SetLength(Holder.SCForward, Length(Holder.EdgeForward));
if Length(Holder.SCBackward) <> Length(Holder.EdgeBackward) then
SetLength(Holder.SCBackward, Length(Holder.EdgeBackward));
for j := Low(Holder.EdgeForward) to High(Holder.EdgeForward) do
begin
RouteID.OSM_ID := Holder.EdgeForward[j].ID;
RouteID.HashStart := Holder.EdgeForward[j].HashVector.HashFrom;
RouteID.HashEnd := Holder.EdgeForward[j].HashVector.HashTo;
if SignDictionary.TryGetValue(RouteID, SignInfo) then
Holder.SCForward[j] := SignInfo.Sign;
end;
for j := Low(Holder.EdgeBackward) to High(Holder.EdgeBackward) do
begin
RouteID.OSM_ID := Holder.EdgeBackward[j].ID;
RouteID.HashStart := Holder.EdgeBackward[j].HashVector.HashFrom;
RouteID.HashEnd := Holder.EdgeBackward[j].HashVector.HashTo;
if SignDictionary.TryGetValue(RouteID, SignInfo) then
Holder.SCBackward[j] := SignInfo.Sign;
end;
TGFAdapter.Save(ARootPath, AAccounts[0], sFile, Holder, C9FileTypes);
Inc(i);
FProgress := (i*100) div iCount;
SaveProgress(AAccounts[0]);
end;
ToLog('TSign.CreateSignAll. Finish create sign files. Files count = ' + IntToStr(FileList.Count));
FProgress := 100;
SaveProgress(AAccounts[0]);
Result := True;
finally
FileList.Free;
end;
end;
function TSign.DeleteAllSign(const ARootPath: string;
const AAccounts: TIntegerDynArray): Boolean;
var
I, J, K, L: Char;
Acc: Integer;
HashPathStr: string;
FullPath: string;
SR: TSearchRec;
begin
Result := False;
Acc := AAccounts[0];
ToLog('Start delete all sign files. Account='+IntToStr(Acc));
for I in CHashChars do
begin
HashPathStr := I + '\';
FullPath := ARootPath + IntToStr(Acc) + PathDelim + HashPathStr;
if not DirectoryExists(FullPath) then Continue;
ToLog('TSign.DeleteAllSign. Delete SC files in folder ' + FullPath + '..');
for J in CHashChars do
begin
HashPathStr := I + '\' + I + J + '\';
FullPath := ARootPath + IntToStr(Acc) + PathDelim+ {'igf\' + }HashPathStr;
if not DirectoryExists(FullPath) then Continue;
for K in CHashChars do
begin
HashPathStr := I + '\' + I + J + '\' + I + J + K + '\';
FullPath := ARootPath + IntToStr(Acc) + PathDelim+ {'igf\' + }HashPathStr;
if not DirectoryExists(FullPath) then Continue;
for L in CHashChars do
begin
// u\uc\ucf\ucft\
HashPathStr := I + '\' + I + J + '\' + I + J + K + '\' + I + J + K + L + '\';
FullPath := ARootPath + IntToStr(Acc) + PathDelim+ {'igf\' + }HashPathStr;
if not DirectoryExists(FullPath) then Continue;
// составляем список файлов edge_f
if FStop then
begin
ToLog('TSign.DeleteAllSign. Прервано пользователем');
Exit;
end;
try
if (FindFirst(FullPath + '*.signs_f', faNormal, SR) = 0) then
begin
repeat
if (SR.Name = '') then Continue;
if not TFileHandler.DeleteFile(FullPath + SR.Name) then Continue;
if not TFileHandler.DeleteFile(ChangeFileExt(FullPath + SR.Name, '.signs_b')) then Continue;
until (FindNext(SR) <> 0);
FindClose(SR);
end;
except on E : Exception do
ToLog('TSign.DeleteAllSign. Error:'+E.Message);
end;
end; // K
end; // L
end; // J
end; // I
ToLog('All signs file deleted. Account='+IntToStr(Acc));
Result := True;
end;
destructor TSign.Destroy;
begin
FSignType.Free;
if FDetailLog then
ToLog('TSign Stop');
inherited;
end;
function TSign.GetBitStat(AValue: UInt64; BitNum: Byte): Boolean;
var
Bit64: UInt64;
begin
Bit64 := 1;
Bit64 := Bit64 shl BitNum;
GetBitStat := (AValue and Bit64) = Bit64 { Если бит установлен }
end;
function TSign.LoadProgress(AAccount: integer): Integer;
var
FIni: TIniFile;
sAcc: string;
begin
FIni := TIniFile.Create(ChangeFileExt(GetModuleName(HInstance) + TGeneral.FSuffix, '.ini'));
try
sAcc := IntToStr(AAccount);
try
FProgress := FIni.ReadInteger('main','progresssc'+sAcc, 0);
Result := FProgress;
except
Result := -1;
end;
finally
FIni.Free;
end;
end;
function TSign.LoadSignFile(const ARootPath: string;
const AAccounts: TIntegerDynArray): TSignDictionary;
var
RouteSignFile: TFileStream;
RouteSignArr: TRouteSignArray;
sFileName: string;
I, j: Integer;
SignInfo: TSignInfo;
begin
Result := TDictionary<TIDLines,TSignInfo>.Create;
for j := High(AAccounts) downto 0 do
begin
sFileName := ARootPath + IntToStr(AAccounts[j]) + PathDelim + CSignsFile;
if FileExists(sFileName) then
begin
RouteSignFile := TFileStream.Create(sFileName, fmOpenRead + fmShareDenyNone);
try
SetLength(RouteSignArr, RouteSignFile.Size div SizeOf(TRouteSign));
for I := Low(RouteSignArr) to High(RouteSignArr) do
begin
if FStop then
begin
ToLog('TSign.LoadSignFile. Прервано пользователем');
Exit;
end;
SignInfo.Account := AAccounts[j];
SignInfo.Sign := RouteSignArr[i].Sign;
Result.AddOrSetValue(RouteSignArr[i].RouteID, SignInfo);
end;
finally
RouteSignFile.Free();
end;
end;
end;
end;
function TSign.LoadSignFileOne(const ARootPath: string;
const AAccount: integer): TSignDictionary;
var
RouteSignFile: TFileStream;
RouteSignArr: TRouteSignArray;
sFileName: string;
I: Integer;
SignInfo: TSignInfo;
begin
Result := TDictionary<TIDLines,TSignInfo>.Create;
sFileName := ARootPath + IntToStr(AAccount) + PathDelim + CSignsFile;
if FileExists(sFileName) then
begin
RouteSignFile := TFileStream.Create(sFileName, fmOpenRead + fmShareDenyNone);
try
SetLength(RouteSignArr, RouteSignFile.Size div SizeOf(TRouteSign));
RouteSignFile.ReadBuffer(RouteSignArr[0], RouteSignFile.Size);
for I := Low(RouteSignArr) to High(RouteSignArr) do
begin
if FStop then
begin
ToLog('TSign.LoadSignFileOne. Прервано пользователем');
Exit;
end;
SignInfo.Account := AAccount;
SignInfo.Sign := RouteSignArr[i].Sign;
Result.AddOrSetValue(RouteSignArr[i].RouteID, SignInfo);
end;
finally
RouteSignFile.Free();
end;
end;
end;
function TSign.LoadSignTypeFile(const ARootPath: string): TJsonObject;
var
SignList: TStringList;
TempStr, sFileName: string;
TabPos: Integer;
I: Integer;
ID: Byte;
keyArray: TArray<Byte>;
SignTypeInfo: TSignTypeInfo;
begin
Result := TJsonObject.Create;
SignList := TStringList.Create();
sFileName := ARootPath + PathDelim + CSignTypesFile;
try
if FileExists(sFileName) then
begin
SignList.LoadFromFile(sFileName);
for I := 0 to SignList.Count - 1 do
begin
TempStr := SignList[I];
// ID
TabPos := Pos(#9, TempStr);
ID := StrToInt(Copy(TempStr, 1, TabPos - 1));
Delete(TempStr, 1, TabPos);
// name
TabPos := Pos(#9, TempStr);
SignTypeInfo.Name := Copy(TempStr, 1, TabPos - 1);
if SignTypeInfo.Name = '' then
Continue;
Delete(TempStr, 1, TabPos);
// alias
TabPos := Pos(#9, TempStr);
SignTypeInfo.Alias := Copy(TempStr, 1, TabPos - 1);
Delete(TempStr, 1, TabPos);
// alias
SignTypeInfo.Include := TempStr;
FSignType.AddOrSetValue(ID, SignTypeInfo);
end;
end;
keyArray := FSignType.Keys.ToArray;
TArray.Sort<Byte>(KeyArray);
for ID in KeyArray do
begin
FSignType.TryGetValue(ID, SignTypeInfo);
with Result.A['SignTypes'].AddObject do
begin
I['ID'] := ID;
S['Name'] := SignTypeInfo.Name;
S['Alias'] := SignTypeInfo.Alias;
A['Include'].Add(SignTypeInfo.Include);
end;
end;
finally
SignList.Free();
end;
end;
procedure TSign.SaveProgress(AAccount: integer);
var
FIni: TIniFile;
sAcc: string;
begin
FIni := TIniFile.Create(ChangeFileExt(GetModuleName(HInstance) + TGeneral.FSuffix, '.ini'));
try
ToLog('SC progress for Account = ' + IntToStr(AAccount) + ' is '+IntToStr(FProgress));
sAcc := IntToStr(AAccount);
FIni.WriteInteger('main','progresssc'+sAcc, FProgress);
finally
FIni.Free;
end;
end;
function TSign.SaveSignFile(const ARootPath: string;
const AAccount: integer;
const ARouteSignArr: TRouteSignArray): boolean;
var
RouteSignFile: TFileStream;
sFileName: string;
begin
try
sFileName := ARootPath + IntToStr(AAccount) + PathDelim + CSignsFile;
RouteSignFile := TFileStream.Create(sFileName, fmCreate);
try
RouteSignFile.WriteBuffer(ARouteSignArr[0], Length(ARouteSignArr)*SizeOf(TRouteSign));
Result := True;
finally
RouteSignFile.Free();
end;
except
Result := False;
end;
end;
function TSign.SaveSignTypes(const ARootPath: string; AAccount: integer;
ASignTypes: TSignTypeDictionary): Boolean;
var
ID: Byte;
List: TStringList;
s: string;
SignInfo: TSignTypeInfo;
AccDir: string;
begin
List := TStringList.Create;
try
Result := False;
for ID in ASignTypes.Keys do
begin
ASignTypes.TryGetValue(ID,SignInfo);
s := IntToStr(ID) + #9 + SignInfo.Name + #9 + SignInfo.Alias;
List.Add(s);
end;
AccDir := IntToStr(AAccount) + PathDelim;
// каталог
ForceDirectories(ARootPath + AccDir);
List.SaveToFile(ARootPath + AccDir + CSignTypesFile, TEncoding.UTF8);
Result := True;
finally
List.Free;
end;
end;
end.
|
unit uPlot_ResultWriter;
{
*****************************************************************************
* This file is part of Multiple Acronym Math and Audio Plot - MAAPlot *
* *
* See the file COPYING. *
* for details about the copyright. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* *
* MAAplot for Lazarus/fpc *
* (C) 2014 Stefan Junghans *
*****************************************************************************
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, dateutils, uPlotDataTypes;
type
TExportResultType = (ertMAAResult);
PExportHeader = ^TExportHeader;
TExportHeader = record
dwNumResults: Integer;
dwDate: TDateTime;
dwDescription: ShortString;
dwReserved: ShortString;
dwVersion: Integer;
dwResultType: TExportResultType;
end;
PExportResult_MaaResult = ^TExportResult_MAAResult;
TExportResult_MAAResult = record
dwHeader: TExportHeader;
dwResultArray: array of TMeasResult;
end;
{ TPlot_ResultWriter }
TPlot_ResultWriter = class
private
function GetDataDateTime: TDateTime;
function GetDataDescription: ShortString;
procedure SetDataDateTime(AValue: TDateTime);
procedure SetDataDescription(AValue: ShortString);
protected
FDataType: TExportResultType;
FDataHeader: TExportHeader;
public
constructor Create; virtual;
destructor Destroy; override;
function WriteToFile(AFileName: TFilename): Integer; virtual;abstract;
procedure ReSet;virtual;
property DataDescription: ShortString read GetDataDescription write SetDataDescription;
property DataDateTime: TDateTime read GetDataDateTime write SetDataDateTime;
end;
{ TPlot_ResultWriterMAAResult }
TPlot_ResultWriterMAAResult = class (TPlot_ResultWriter)
private
FData: TExportResult_MAAResult;
protected
function PrepareWrite: Integer;
public
constructor Create; override;
destructor Destroy; override;
procedure ReSet;override;
function WriteToFile(AFileName: TFilename): Integer; override;
function AddResultRecord(AResultRecord: TMeasResult): Integer;
end;
{ TPlot_ResultReader }
TPlot_ResultReader = class
private
function GetDataDateTime: TDateTime;
function GetDataDescription: ShortString;
function GetNumResults: Integer;
function GetResultType: TExportResultType;
protected
FDataHeader: TExportHeader;
public
constructor Create; virtual;
destructor Destroy; override;
function LoadFromFile(AFileName: TFilename): Integer; virtual;abstract;
procedure ReSet;virtual;
property DataDescription: ShortString read GetDataDescription;
property DataDateTime: TDateTime read GetDataDateTime;
property ResultType: TExportResultType read GetResultType;
property NumResults: Integer read GetNumResults;
end;
{ TPlot_ResultReaderMAAResult }
TPlot_ResultReaderMAAResult = class (TPlot_ResultReader)
private
FData : TExportResult_MAAResult;
protected
public
constructor Create; override;
destructor Destroy; override;
function LoadFromFile(AFileName: TFilename): Integer; override;
procedure ReSet;override;
// not dll safe, use only within plot (there is no data handshake. datapointer in handeled inside this funtion)
function GetResultRecord(AResultIndex: Integer; var AResultRecord: TMeasResult): Integer;
end;
implementation
{ TPlot_ResultReaderMAAResult }
constructor TPlot_ResultReaderMAAResult.Create;
begin
inherited Create;
end;
destructor TPlot_ResultReaderMAAResult.Destroy;
var
vLoop: Integer;
begin
IF length(FData.dwResultArray) = 0 then exit;
for vLoop := 0 to length(FData.dwResultArray)-1 do begin
setlength(FData.dwResultArray[vLoop].lpMeasData^, 0, 0);
Dispose(FData.dwResultArray[vLoop].lpMeasData);
end;
setlength(FData.dwResultArray, 0);
inherited Destroy;
end;
function TPlot_ResultReaderMAAResult.LoadFromFile(AFileName: TFilename
): Integer;
var
vStream: TFileStream;
vFileName: TFilename;
vLoop, vLoopRow, vLoopDim: Integer;
vHeaderItem: TExportHeader;
vDataItem: PMeasArray;
vIdentItem: TMeasResultIdent;
//vHeaderSize, vItemSize: Integer;
//vValueCount: Integer;
//vDataSize: Integer;
//vWriteCount: Integer;
vReadCount: Integer;
vNumResults: Integer;
begin
Result := 0;
vFileName := AFileName;
vReadCount:=0;
vStream := nil;
with vHeaderItem do begin // init for safety only
dwNumResults := 0;
dwDate := Today;
dwDescription := 'empty';
dwReserved := '';
dwVersion := 0;
dwResultType := ertMAAResult;
end;
with vIdentItem do begin
dwResultType:= mrtGenResult;
diDimensions:= 0;
diPoints:= 0;
diMeasurement:= 0;
dwTimeStamp:= DateTimeToTimeStamp(Now);
end;
// clear Data
for vLoop := 0 to length(FData.dwResultArray)-1 do begin
setlength(FData.dwResultArray[vLoop].lpMeasData^, 0, 0);
Dispose(FData.dwResultArray[vLoop].lpMeasData);
end;
setlength(FData.dwResultArray, 0);
try
if FileExists(vFileName) then
vStream := TFileStream.Create(vFileName, fmOpenRead)
else vStream := nil;
except vStream := nil; end;
if vStream = nil then exit;
//vHeaderSize := SizeOf(TExportHeader);
try
// cannot check this as items have different sizes ;-)
//try
// if (vStream.Size MOD vItemSize) <>0 then
// raise Exception.Create('stored plotdata is corrupted ..');
//except
// Application.HandleException(Self);
// vStream.Free;
// vStream := TFileStream.Create(vFileName, fmCreate or fmOpenWrite);
// vStream.Size := 0;
//end;
// load items
vStream.Position := 0;
// load header
vStream.Read(vHeaderItem, SizeOf(TExportHeader));
vReadCount := vReadCount + SizeOf(TExportHeader);
FDataHeader := vHeaderItem;
vNumResults := vHeaderItem.dwNumResults;
// prepare FData strructire
setlength(FData.dwResultArray, vNumResults);
for vLoop := 0 to vNumResults-1 do begin
// read ident
vStream.Read(vIdentItem, SizeOf(TMeasResultIdent));
vReadCount := vReadCount + SizeOf(TMeasResultIdent);
// prepare FData structire
New(vDataItem);
try
SetLength(vDataItem^, vIdentItem.diPoints, vIdentItem.diDimensions);
// read data
for vLoopRow :=0 to vIdentItem.diPoints-1 do
for vLoopDim :=0 to vIdentItem.diDimensions-1 do
vStream.Read(vDataItem^[vLoopRow, vLoopDim], SizeOf(TValue));;
// store
FData.dwResultArray[vLoop].dwResultIdent := vIdentItem;
FData.dwResultArray[vLoop].lpMeasData := vDataItem;
FData.dwHeader := FDataHeader;
except
SetLength(vDataItem^, 0, 0);
Dispose(vDataItem);
end;
end;
finally
{$IFDEF DEBUG}OutputDebugString(PChar('Headers loaded bytes/elements: ' + IntToStr(vStream.Size) + ' / ' + IntToStr(Result) ));{$ENDIF}
FreeAndNil(vStream);
end;
Result := vReadCount;
end;
procedure TPlot_ResultReaderMAAResult.ReSet;
begin
inherited ReSet;
end;
function TPlot_ResultReaderMAAResult.GetResultRecord(AResultIndex: Integer;
var AResultRecord: TMeasResult): Integer;
var
vLoopDim, vLoopRow: Integer; // vLoop
//vMeasResult: TMeasResult;
//vData: PMeasArray;
//vValueCount, vItemSize: Integer;
begin
Result := 0;
IF AResultIndex > (length(FData.dwResultArray) -1) THEN begin
Result := -1;
exit;
END;
//New(vMeasResult.lpMeasData); // already created in caller
try
SetLength(AResultRecord.lpMeasData^, FData.dwResultArray[AResultIndex].dwResultIdent.diPoints, FData.dwResultArray[AResultIndex].dwResultIdent.diDimensions);
AResultRecord.dwResultIdent := FData.dwResultArray[AResultIndex].dwResultIdent;
for vLoopRow :=0 to FData.dwResultArray[AResultIndex].dwResultIdent.diPoints-1 do
for vLoopDim :=0 to FData.dwResultArray[AResultIndex].dwResultIdent.diDimensions-1 do
AResultRecord.lpMeasData^[vLoopRow, vLoopDim] := FData.dwResultArray[AResultIndex].lpMeasData^[vLoopRow, vLoopDim];
AResultRecord.dwResultIdent := FData.dwResultArray[AResultIndex].dwResultIdent;
except
setlength(AResultRecord.lpMeasData^, 0, 0);
Dispose(AResultRecord.lpMeasData);
Result := -1;
end;
end;
{ TPlot_ResultReader } //=======================================================
function TPlot_ResultReader.GetDataDateTime: TDateTime;
begin
Result := FDataHeader.dwDate;
end;
function TPlot_ResultReader.GetDataDescription: ShortString;
begin
Result := FDataHeader.dwDescription;
end;
function TPlot_ResultReader.GetNumResults: Integer;
begin
Result := FDataHeader.dwNumResults;
end;
function TPlot_ResultReader.GetResultType: TExportResultType;
begin
Result := FDataHeader.dwResultType;
end;
constructor TPlot_ResultReader.Create;
begin
inherited Create;
ReSet;
end;
destructor TPlot_ResultReader.Destroy;
begin
ReSet;
inherited Destroy;
end;
procedure TPlot_ResultReader.ReSet;
begin
with FDataHeader do begin
dwNumResults := 0;
dwDescription := 'nothing loaded';
dwDate := Now;
dwReserved := '';
dwVersion := -1;
dwResultType := ertMAAResult;
end;
end;
{ TPlot_ResultWriterMAAResult } //=============================================
function TPlot_ResultWriterMAAResult.PrepareWrite: Integer;
begin
FDataHeader.dwNumResults := length(FData.dwResultArray);
FData.dwHeader := FDataHeader;
Result := FDataHeader.dwNumResults;
end;
constructor TPlot_ResultWriterMAAResult.Create;
begin
inherited Create;
end;
destructor TPlot_ResultWriterMAAResult.Destroy;
begin
inherited Destroy;
end;
procedure TPlot_ResultWriterMAAResult.ReSet;
var
vLoop: Integer;
begin
for vLoop := 0 to length(FData.dwResultArray)-1 do begin
setlength(FData.dwResultArray[vLoop].lpMeasData^, 0, 0);
Dispose(FData.dwResultArray[vLoop].lpMeasData);
end;
setlength(FData.dwResultArray, 0);
//
with FDataHeader do begin
dwNumResults := 0;
dwDescription := 'MAA export';
dwDate := Now;
dwReserved := '2secnutw3tchndagckluehlasti87l339p6czn93vnrelc83o52p0z7'; // write a sync structure, costs nothing, might help in the future
dwVersion := 0;
dwResultType := ertMAAResult;
end;
end;
function TPlot_ResultWriterMAAResult.WriteToFile(AFileName: TFilename): Integer;
var
vStream: TFileStream;
vLoop, vLoopDim, vLoopRow: Integer;
vFileName: TFilename;
//vItem: TMeasResult;
vHeaderSize: Integer;
vIdentSize, vRowSize: Integer;
//vValueCount: Integer;
vWriteCount: Integer;
begin
// writes as follows:
// <GlobalHeader><ResultIdent><ResultData><ResultIdent><ResultData><ResultIdent><ResultData> ....
vFileName:=AFileName;
Result := 0;
vWriteCount:=0;
//vFileName := FMsgPath + cPATHDELIMITER + cHEADERFILENAME + cCONTENTEXTENSION;
PrepareWrite;
vStream := TFileStream.Create(vFileName, fmCreate);
vStream.Position := 0; // TODO: not needed
try
// write Header
vHeaderSize := sizeof(TExportHeader);
vStream.Write(FData.dwHeader, vHeaderSize);
vWriteCount := vWriteCount + vHeaderSize;
vIdentSize := SizeOf(TMeasResultIdent);
for vLoop := 0 to FData.dwHeader.dwNumResults-1 do begin
//vValueCount := FData.dwResultArray[vLoop].dwResultIdent.diPoints * FData.dwResultArray[vLoop].dwResultIdent.diDimensions;
vRowSize := FData.dwResultArray[vLoop].dwResultIdent.diPoints;
// write ResultIdent
vStream.Write(FData.dwResultArray[vLoop].dwResultIdent, vIdentSize);
// write Data
for vLoopRow := 0 to vRowSize-1 do
for vLoopDim := 0 to FData.dwResultArray[vLoop].dwResultIdent.diDimensions-1 do
vStream.Write(FData.dwResultArray[vLoop].lpMeasData^[vLoopRow, vLoopDim], SizeOf(TValue));
vWriteCount := vWriteCount + vIdentSize + vRowSize * FData.dwResultArray[vLoop].dwResultIdent.diDimensions * SizeOf(TValue);
end;
Result := vWriteCount;
finally
FreeAndNil(vStream);
end;
ReSet;
end;
function TPlot_ResultWriterMAAResult.AddResultRecord(AResultRecord: TMeasResult
): Integer;
var
vLoopDim, vLoopRow: Integer; // vLoop
vMeasResult: TMeasResult;
//vValueCount, vItemSize: Integer;
begin
Result := 0;
IF (AResultRecord.dwResultIdent.diPoints < 1) OR (AResultRecord.dwResultIdent.diDimensions < 1) THEN begin
Result := -1;
exit;
END;
SetLength(FData.dwResultArray, length(FData.dwResultArray) + 1);
vMeasResult.dwResultIdent := AResultRecord.dwResultIdent;
New(vMeasResult.lpMeasData);
setlength(vMeasResult.lpMeasData^, AResultRecord.dwResultIdent.diPoints, AResultRecord.dwResultIdent.diDimensions);
try
vMeasResult.dwResultIdent := AResultRecord.dwResultIdent;
for vLoopRow :=0 to vMeasResult.dwResultIdent.diPoints-1 do
for vLoopDim :=0 to vMeasResult.dwResultIdent.diDimensions-1 do
vMeasResult.lpMeasData^[vLoopRow, vLoopDim] := AResultRecord.lpMeasData^[vLoopRow, vLoopDim];
//vValueCount := vMeasResult.dwResultIdent.diPoints * vMeasResult.dwResultIdent.diDimensions;
//vItemSize := SizeOf(TMeasResultIdent) + vValueCount * SizeOf(TValue);
FData.dwResultArray[length(FData.dwResultArray)-1] := vMeasResult;
except
setlength(vMeasResult.lpMeasData^, 0, 0);
Dispose(vMeasResult.lpMeasData);
end;
end;
{ TPlot_ResultWriter } //=======================================================
function TPlot_ResultWriter.GetDataDateTime: TDateTime;
begin
Result := FDataHeader.dwDate;
end;
function TPlot_ResultWriter.GetDataDescription: ShortString;
begin
Result := FDataHeader.dwDescription;
end;
procedure TPlot_ResultWriter.SetDataDateTime(AValue: TDateTime);
begin
FDataHeader.dwDate := AValue;
end;
procedure TPlot_ResultWriter.SetDataDescription(AValue: ShortString);
begin
FDataHeader.dwDescription := AValue;
end;
constructor TPlot_ResultWriter.Create;
begin
inherited Create;
ReSet;
end;
destructor TPlot_ResultWriter.Destroy;
begin
ReSet;
inherited Destroy;
end;
procedure TPlot_ResultWriter.ReSet;
begin
with FDataHeader do begin
dwNumResults := 0;
dwDescription := 'MAA export';
dwDate := Now;
dwReserved := '2secnutw3tchndagckluehlasti87l339p6czn93vnrelc83o52p0z7'; // write a sync structure, costs nothing, might help in the future
dwVersion := 0;
dwResultType := ertMAAResult;
end;
end;
end.
|
unit pBTGridToExcel;
interface
uses
Windows, SysUtils, Variants, Classes, ComObj,Graphics,DB,Dialogs,DBGridEh;
type
TCallBackGridToExcelProc=
procedure (Row:integer; var Stop:boolean) of object;
function GridToExcel(Grid:TDBGridEh;MsExcel,Sheet:Variant;
const BegRow,BegCol:integer;CreateTitle:boolean; CallBack:TCallBackGridToExcelProc=nil ):integer; overload;
function GridToExcel2(Grid:TDBGridEh;const SheetName:string;
const BegRow,BegCol:integer; CallBack:TCallBackGridToExcelProc=nil;CreateTitle:boolean=True):integer; overload;
function GridToExcel1(Grid:TDBGridEh;const FileName,SheetName:string;
const BegRow,BegCol:integer;var LastRow:integer; CreateTitle:boolean=True ):variant;
function ExecExcel(const SheetName:string =''):variant;
function FieldToVariant(Field: TField): OLEVariant;
function ExcelNumericFormat(MSExcel:Variant;const DelphiFormat:string):string;
function ExcelFileOpen(const FileName,SheetName:string;DoVisible:boolean ):variant;
function XLSGetCell(MSExcel:variant;Row,Col:integer):Variant;
function XLSGetCellByName(MSExcel:variant;const Name:string):Variant;
procedure XLSSetCell(MSExcel:variant;Row,Col:integer;Value:variant);
procedure XLSSetFormula(MSExcel:variant;BegRow,BegCol,EndRow,EndCol:integer;const Value:string);
procedure XLSInsertRow(MSExcel:variant;BegRow,EndRow:integer);
procedure XLSSetRowsSize(MSExcel:variant;RowNum:integer; Size:Extended);
procedure XLSSetColsSize(MSExcel:variant;ColNum:integer; Size:Extended);
procedure XLSSetColsAutoFit(MSExcel:variant;ColNum:integer);
procedure XLSSetColor(MSExcel:variant;BegRow,BegCol,EndRow,EndCol:integer;
Value:integer
);
procedure XLSSetFontColor(MSExcel:variant;BegRow,BegCol,EndRow,EndCol:integer;
Value:integer
);
procedure XLSSetFontStyle(MSExcel:variant;BegRow,BegCol,EndRow,EndCol:integer;
aStyle:TFontStyles
);
procedure XLSSetFont(Range:Variant;SourceFont:TFont);
procedure XLSSetBorder(MSExcel:variant;BegRow,BegCol,EndRow,EndCol:integer;
Value:integer
);
implementation
const
RowCountLimit=65530;
// RowCountLimit=11;
xlNone =-4142;
var
DefaultLCID: Integer;
SysDecimalSeparator:Char;
SysThousandSeparator:Char;
function ExcelNumericFormat(MSExcel:Variant;const DelphiFormat:string):string;
var
ExcelVer:variant;
b:Boolean;
begin
ExcelVer:=MSExcel.Version;
if DecimalSeparator='.' then
ExcelVer:=StrToFloat(Copy(ExcelVer,1,2))
else
if Pos('.',ExcelVer)=0 then
ExcelVer:=StrToFloat(Copy(ExcelVer,1,2))
else
ExcelVer:=StrToFloat(Copy(ExcelVer,1,1));
b:=(ExcelVer>=10);
if b then
b:=not MSExcel.UseSystemSeparators;
if b then
begin
Result:=StringReplace(DelphiFormat,',', MSExcel.ThousandsSeparator,[rfReplaceAll]);
Result:=StringReplace(Result,'.',MSExcel.DecimalSeparator,[rfReplaceAll]);
end
else
begin
Result:=StringReplace(DelphiFormat,',', SysThousandSeparator,[rfReplaceAll]);
Result:=StringReplace(Result,'.',SysDecimalSeparator,[rfReplaceAll]);
end;
end;
function FieldToVariant(Field: TField): OLEVariant;
begin
Result := '';
if Field.IsNull then
begin
Result:=NULL; Exit;
end;
case Field.DataType of
ftWideString:
// Result := '''' + TWideStringField(Field).Value;
if (Field.AsString<>'') and (Field.AsString[1] in ['0'..'9']) then
Result := '''' + TWideStringField(Field).Value
else
Result := TWideStringField(Field).Value;
ftString, ftFixedChar, ftMemo, ftFmtMemo:
if (Field.AsString<>'') and (Field.AsString[1] in ['0'..'9']) then
Result := '''' + Field.AsString
else
Result := Field.AsString;
ftSmallint, ftInteger, ftWord, ftLargeint, ftAutoInc: Result := Field.AsInteger;
ftFloat, ftCurrency, ftBCD: Result := Field.AsFloat;
ftBoolean: Result := Field.AsBoolean;
ftDate, ftTime, ftDateTime: Result := Field.AsDateTime;
end;
end;
function ExcelFileOpen(const FileName,SheetName:string;DoVisible:boolean ):variant;
var s:string;
Sheet : variant;
begin
// Открывает файл и переименовывает страницу.
try
Result:= CreateOleObject('excel.application');
except
raise Exception.Create('Не могу запустить MS Excel!.');
end;
try
Result.WorkBooks.Open(FileName);
if Trim(SheetName)<>'' then
begin
Sheet:= Result.ActiveSheet;
s:=StringReplace(SheetName,':','-',[]);
s:=StringReplace(s,'/','-',[]);
s:=StringReplace(s,'\','-',[]);
s:=StringReplace(s,'*','-',[]);
s:=StringReplace(s,'?','-',[]);
if Length(SheetName)<=31 then
Sheet.Name:=s
else
Sheet.Name:=Copy(s,1,28)+'...';
end;
finally
Result.Visible := DoVisible;
end
end;
procedure XLSSetCell(MSExcel:variant;Row,Col:integer;Value:variant);
var
Sheet : variant;
begin
Sheet:= MSExcel.ActiveSheet;
Sheet.Cells[Row,Col]:=Value
end;
function XLSGetCellByName(MSExcel:variant;const Name:string):Variant;
var
Sheet : variant;
begin
Sheet:= MSExcel.ActiveSheet;
Result:= Sheet.Range[Name].Value
end;
function XLSGetCell(MSExcel:variant;Row,Col:integer):Variant;
var
Sheet : variant;
begin
Sheet:= MSExcel.ActiveSheet;
Result:= Sheet.Cells[Row,Col].Value
end;
procedure XLSSetFormula(MSExcel:variant;BegRow,BegCol,EndRow,EndCol:integer;const Value:string);
var
Sheet : variant;
Range : variant;
begin
Sheet:= MSExcel.ActiveSheet;
Range:=Sheet.Range[Sheet.Cells[BegRow,BegCol], Sheet.Cells[EndRow,EndCol]];
Range.Formula := '='+Value
// Sheet.Cells[Row,Col].Formula := '='+Value
end;
procedure XLSInsertRow(MSExcel:variant;BegRow,EndRow:integer);
var
Sheet : variant;
begin
Sheet:= MSExcel.ActiveSheet;
// Sheet.Range['A' + IntToStr(BegRow) + ':GZ' +IntToStr(EndRow)].Insert;
Sheet.Rows[IntToStr(BegRow)+':'+IntToStr(EndRow)].Insert;
end;
procedure XLSSetRowsSize(MSExcel:variant;RowNum:integer; Size:Extended);
var
Sheet : variant;
begin
Sheet:= MSExcel.ActiveSheet;
Sheet.Rows[RowNum].RowHeight := Size;
end;
procedure XLSSetColsSize(MSExcel:variant;ColNum:integer; Size:Extended);
var
Sheet : variant;
begin
Sheet:= MSExcel.ActiveSheet;
Sheet.Columns[ColNum].ColumnWidth := Size;
end;
procedure XLSSetColsAutoFit(MSExcel:variant;ColNum:integer);
var
Sheet : variant;
begin
Sheet:= MSExcel.ActiveSheet;
Sheet.Columns[ColNum].AutoFit
end;
procedure XLSSetColor(MSExcel:variant;BegRow,BegCol,EndRow,EndCol:integer;
Value:integer
);
var
Sheet : variant;
Range : variant;
RGB:LongInt;
begin
Sheet:= MSExcel.ActiveSheet;
Range:=Sheet.Range[Sheet.Cells[BegRow,BegCol], Sheet.Cells[EndRow,EndCol]];
case Value of
clNone: Range.Interior.ColorIndex:=xlNone;
else
RGB:=ColorToRGB(Value);
Range.Interior.Color:=RGB;
end;
end;
procedure XLSSetFontColor(MSExcel:variant;BegRow,BegCol,EndRow,EndCol:integer;
Value:integer
);
var
Sheet : variant;
Range : variant;
begin
// Value : TColor
Sheet:= MSExcel.ActiveSheet;
Range:=Sheet.Range[Sheet.Cells[BegRow,BegCol], Sheet.Cells[EndRow,EndCol]];
Range.Font.Color:=Value;
end;
procedure XLSSetFontStyle(MSExcel:variant;BegRow,BegCol,EndRow,EndCol:integer;
aStyle:TFontStyles
);
var
Sheet : variant;
Range : variant;
begin
// Value : TColor
Sheet:= MSExcel.ActiveSheet;
Range:=Sheet.Range[Sheet.Cells[BegRow,BegCol], Sheet.Cells[EndRow,EndCol]];
Range.Font.Bold:=fsBold in aStyle;
Range.Font.Italic:=fsItalic in aStyle;
if fsUnderline in aStyle then
Range.Font.Underline:=2
else
Range.Font.Underline:=1
end;
procedure XLSSetFont(Range:Variant;SourceFont:TFont);
begin
Range.Font.Bold:=fsBold in SourceFont.Style;
Range.Font.Italic:=fsItalic in SourceFont.Style;
if fsUnderline in SourceFont.Style then
Range.Font.Underline:=2
else
Range.Font.Underline:=1;
Range.Font.Color:=ColorToRGB(SourceFont.Color);
Range.Font.Name :=SourceFont.Name;
Range.Font.Size :=SourceFont.Size;
end;
procedure XLSSetBorder(MSExcel:variant;BegRow,BegCol,EndRow,EndCol:integer;
Value:integer
);
var
Sheet : variant;
Range : variant;
begin
Sheet:= MSExcel.ActiveSheet;
Range:=Sheet.Range[Sheet.Cells[BegRow,BegCol], Sheet.Cells[EndRow,EndCol]];
// Недоделано. Надоело.
end;
function ExecExcel(const SheetName:string =''):variant;
var
Sheet : variant;
s :string;
begin
try
Result := CreateOleObject('excel.application');
except
raise Exception.Create('Не могу запустить MS Excel!.');
end;
if SheetName<>'' then
try
Result.WorkBooks.Add.Activate;
// MsExcel.ActiveWorkBook.Activate;
Sheet:= Result.ActiveSheet;
s:=StringReplace(SheetName,':','-',[]);
s:=StringReplace(s,'/','-',[]);
s:=StringReplace(s,'\','-',[]);
s:=StringReplace(s,'*','-',[]);
s:=StringReplace(s,'?','-',[]);
if Length(SheetName)<=31 then
Sheet.Name:=s
else
Sheet.Name:=Copy(s,1,28)+'...';
except
end;
end;
function GridToExcel2(Grid:TDBGridEh;const SheetName:string;
const BegRow,BegCol:integer; CallBack:TCallBackGridToExcelProc=nil;CreateTitle:boolean=True):integer;
var
MSExcel: variant;
begin
MsExcel := ExecExcel(SheetName);
Result:=GridToExcel(Grid,MSExcel,MsExcel.ActiveSheet, BegRow,BegCol,CreateTitle,CallBack);
end;
function GridToExcel1(Grid:TDBGridEh;const FileName,SheetName:string;
const BegRow,BegCol:integer; var LastRow:integer;CreateTitle:boolean=True ):variant; overload;
begin
Result:= ExcelFileOpen(FileName,SheetName,False);
LastRow:=GridToExcel(Grid,Result,Result.ActiveSheet, BegRow,BegCol,CreateTitle);
Result.Visible:=True
end;
type
TArrData = array [1..1] of variant;
PArrData =^TArrData;
function GridToExcel(Grid:TDBGridEh;MSExcel,Sheet:Variant;
const BegRow,BegCol:integer;CreateTitle:boolean ; CallBack:TCallBackGridToExcelProc=nil):integer;
var
verStr:string;
i,j,sc : integer;
BM:TBookMark;
ColH:string;
BegRowStr :string;
CurObject : variant;
TitleRange,DataRange: variant;
Arr: OLEVariant;
rc :integer;
vRowCount,ColCount:integer;
Row1,Column:integer;
EndCol,RowData :integer;
Stop:boolean;
FrmtStr:string;
ArrData:PArrData;
Sheet1:Variant;
shName:string;
TitleCreated:boolean;
v:Variant;
procedure DoTitle;
begin
if CreateTitle and not TitleCreated then
begin
TitleRange.Interior.ColorIndex:= 15;
TitleRange.Interior.Pattern := 1 ; //xlSolid
TitleRange.Interior.PatternColorIndex := -4105 ;// xlAutomatic;}
CurObject:=TitleRange.Font;
CurObject.Name := 'Arial Cyr';
CurObject.Size := 11;
CurObject.Strikethrough := False;
CurObject.Superscript := False;
CurObject.OutlineFont := False;
CurObject.Shadow := True;
CurObject.Underline := -4142; //xlUnderlineStyleNone
CurObject.ColorIndex := -4105 ;// xlAutomatic;}
TitleRange.HorizontalAlignment:=3; // center
if StrToInt(verStr)>=8 then
begin
TitleRange.Borders[5{xlDiagonalDown}].LineStyle := xlNone;//xlNone;
TitleRange.Borders[6{xlDiagonalUp}].LineStyle := xlNone;//xlNone;
TitleRange.Borders[7{xlEdgeLeft}].LineStyle := 1; //xlContinuous
TitleRange.Borders[7{xlEdgeLeft}].Weight := 2; // xlThin
TitleRange.Borders[7{xlEdgeLeft}].ColorIndex:=-4105 ; // xlAutomatic;
TitleRange.Borders[8{xlEdgeTop}].LineStyle := 1; //xlContinuous
TitleRange.Borders[8{xlEdgeTop}].Weight := 2; // xlThin
TitleRange.Borders[8{xlEdgeTop}].ColorIndex:=-4105 ; // xlAutomatic;
TitleRange.Borders[9{xlEdgeBottom}].LineStyle := 1; //xlContinuous
TitleRange.Borders[9{xlEdgeBottom}].Weight := 2; // xlThin
TitleRange.Borders[9{xlEdgeBottom}].ColorIndex:=-4105 ; // xlAutomatic;
TitleRange.Borders[10{xlEdgeRight}].LineStyle := 1; //xlContinuous
TitleRange.Borders[10{xlEdgeRight}].Weight := 2; // xlThin
TitleRange.Borders[10{xlEdgeRight}].ColorIndex:=-4105 ; // xlAutomatic;
XLSSetFont(TitleRange,Grid.TitleFont);
end
else
begin
// Если Excel 5.0
TitleRange.BorderAround(1, 2{xlThin}, -4105{xlAutomatic},0);
end;
end;
Sheet.Columns.Autofit;
end ;
begin
MsExcel.ScreenUpdating:=false;
MsExcel.Application.EnableEvents := False;
Result:=BegRow;
Arr:=Null;
shName:=Sheet.Name;
try
verStr:=MsExcel.Version;
BegRowStr:=IntToStr(BegRow);
i:=Pos('.',VerStr);
if i>0 then
Delete(verStr,i,MaxInt);
ColCount:=0;
with Grid do
for i := 0 to Grid.Columns.Count - 1 do
begin
if (not Columns[i].Visible) or (not Assigned(Columns[i].Field))then Continue;
if CreateTitle then
Sheet.Cells(BegRow,BegCol+ColCount) := Columns[i].Title.Caption;
Inc(ColCount);
end;
if ColCount=0 then Exit;
EndCol:=BegCol+ColCount-1;
TitleRange:= Sheet.Range[Sheet.Cells[BegRow,BegCol], Sheet.Cells[BegRow,EndCol]];
TitleCreated:=False;
with Grid,Grid.DataSource.DataSet do
begin
BM:=GetBookmark;
DisableControls;
Last; // Fetch all
rc := RecordCount;
if rc=0 then
begin
Next;
rc := RecordCount;
end;
if rc>0 then
begin
if rc+BegRow<=RowCountLimit then
begin
vRowCount:=rc;
end
else
begin
vRowCount:=RowCountLimit-BegRow;
end;
Arr := VarArrayCreate([1, vRowCount,1, ColCount], varVariant);
ArrData:=VarArrayLock(Arr) ;
end
else
begin
DoTitle;
ArrData:=nil;
Exit;
end;
try
First;
Row1:=1;
RowData :=0;
if (BegRow+rc<=RowCountLimit) then
begin
XLSInsertRow(MsExcel,BegRow+1,BegRow+rc);
DataRange:=
Sheet.Range[Sheet.Cells[BegRow+1,BegCol], Sheet.Cells[BegRow+rc,EndCol]]
end
else
begin
XLSInsertRow(MsExcel,BegRow+1,RowCountLimit);
DataRange:=
Sheet.Range[Sheet.Cells[BegRow+1,BegCol], Sheet.Cells[RowCountLimit,EndCol]];
end;
sc:=1;
while not EOF do
begin
Column:=0;
for i := 0 to Columns.Count - 1 do
begin
if (not Columns[i].Visible) or (not Assigned(Columns[i].Field))then
Continue;
PArrData(ArrData)^[Row1+vRowCount*Column]:=FieldToVariant(Columns[i].Field);
v:=Arr[Row1,Column+1];
Inc(Column)
end;
Inc(Row1);
if Assigned(CallBack) then
begin
Stop:=False;
// CallBack(Row1+RowData-BegRow,Stop);
if Stop then Break;
end;
if Row1>RowCountLimit-BegRow then
begin
VarArrayUnLock(Arr);
DataRange.Value:=Arr;
XLSSetFont(DataRange,Grid.Font);
if rc-RowData-BegRow>RowCountLimit then
vRowCount:=RowCountLimit-BegRow
else
vRowCount:=rc-RowData-BegRow;
if vRowCount<=0 then
begin
ArrData:= VarArrayLock(Arr) ;
Break;
end;
RowData:=RowData+Row1;
Arr:= VarArrayCreate([1, vRowCount ,1, ColCount], varVariant);
ArrData:=VarArrayLock(Arr) ;
Row1:=1;
MSExcel.Sheets.Add.Activate;
if Length(shName+IntToStr(sc))<=31 then
MSExcel.ActiveSheet.Name:=shName+IntToStr(sc)
else
MSExcel.ActiveSheet.Name:=Copy(shName,1,28)+IntToStr(sc);
Inc(sc);
Sheet1:=MSExcel.ActiveSheet;
Sheet.Activate;
Sheet.Move(Sheet1);
Sheet1.Activate;
DoTitle;
TitleRange.Copy(Sheet1.Range[Sheet1.Cells[BegRow,BegCol], Sheet1.Cells[BegRow,EndCol]]);
Sheet:=Sheet1;
DataRange:=
Sheet.Range[Sheet.Cells[BegRow+1,BegCol], Sheet.Cells[vRowCount,EndCol]];
end;
Next;
end;
VarArrayUnLock(Arr);
if (Row1=rc) and (RecordCount>1) then
begin
RowData:=RowData+rc;
DataRange.Value:=Arr;
XLSSetFont(DataRange,Grid.Font);
end
else
if (Row1<>1) then
begin
DataRange.Value:=Arr;
XLSSetFont(DataRange,Grid.Font);
end;
Result:=RowData;
if vRowCount<=0 then
Exit;
ColH:=Chr(Ord('A')+BegCol-1);
j:=0;
for i := 0 to Grid.Columns.Count - 1 do
begin
if (not Columns[i].Visible) or not Assigned(Columns[i].Field) then
Continue;
case Columns[i].Alignment of //
taLeftJustify :
Sheet.Range[Sheet.Cells[BegRow,BegCol+j], Sheet.Cells[vRowCount+BegRow,BegCol+j]]
.HorizontalAlignment:=2;
taRightJustify:
Sheet.Range[Sheet.Cells[BegRow,BegCol+j], Sheet.Cells[vRowCount+BegRow,BegCol+j]]
.HorizontalAlignment:=4;
taCenter :
Sheet.Range[Sheet.Cells[BegRow,BegCol+j], Sheet.Cells[vRowCount+BegRow,BegCol+j]]
.HorizontalAlignment:=3;
end;
if Columns[i].Field is TNumericField then
if TNumericField(Columns[i].Field).DisplayFormat<>'' then
begin
FrmtStr:=ExcelNumericFormat(MSExcel,TNumericField(Columns[i].Field).DisplayFormat);
Sheet.Range[Sheet.Cells[BegRow,BegCol+j], Sheet.Cells[vRowCount+BegRow,BegCol+j]]
.NumberFormat:=FrmtStr;
end;
Inc(j);
if CreateTitle then
begin
CurObject:=Sheet.Range[ColH+BegRowStr].Borders[10{xlEdgeRight}];
CurObject.LineStyle := 1; //xlContinuous
CurObject.Weight := 2; // xlThin
CurObject.ColorIndex:=-4105 ; // xlAutomatic;
end;
if ColH[Length(ColH)]<'Z' then
ColH[Length(ColH)]:=Chr(Ord(ColH[Length(ColH)])+1)
else
begin
ColH[Length(ColH)]:='A';
ColH:=ColH+'A';
end;
end;
DoTitle;
finally
GotoBookMark(BM);
FreeBookMark(BM);
EnableControls
end;
end;
finally
MsExcel.Application.EnableEvents := True;
MsExcel.ScreenUpdating:=true;
MsExcel.WindowState:=-4137;//XlMaximazied;
MsExcel.Visible := True;
// VarArrayUnLock(Arr);
Arr:=null;
MsExcel:=null;
end
// MsExcel.ActiveWorkbook.SaveAs('c:\3.xls', -4143{xlNormal},'','', false, false);
end;
initialization
DefaultLCID := GetThreadLocale;
{$WARNINGS OFF}
SysThousandSeparator := GetLocaleChar(DefaultLCID, LOCALE_STHOUSAND, ',');
SysDecimalSeparator := GetLocaleChar(DefaultLCID, LOCALE_SDECIMAL, '.');
{$WARNINGS ON}
end.
|
unit UnitEditor;
// ------------------------------------------------------------------------------
//
// SVG Control Package 2.0
// Copyright (c) 2015 Bruno Verhue
//
// ------------------------------------------------------------------------------
// This editor is not meant to be a finished product, although it might some day
// be one. It's use is primarily to show some practical solutions for
// programming with the SVG library
// The SVG Editor need at least version v2.40 update 9 of the SVG library
interface
uses
Winapi.Windows,
Winapi.Messages,
System.Types,
System.Classes,
System.Actions,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ToolWin,
Vcl.ActnMan,
Vcl.ActnCtrls,
Vcl.ActnList,
Vcl.ExtCtrls,
Vcl.PlatformDefaultStyleActnCtrls,
Vcl.StdCtrls,
Vcl.ComCtrls,
Vcl.ActnMenus,
Vcl.Grids,
Vcl.ValEdit,
Vcl.ImgList,
BVE.SVG2Intf,
BVE.SVG2Types,
BVE.SVGEditorVCL,
BVE.SVG2ImageList.VCL,
BVE.SVGEditorFormVCL;
type
TfrmEditor = class(TSVGEditorForm)
ActionManager1: TActionManager;
OpenDialog1: TOpenDialog;
Panel1: TPanel;
Splitter1: TSplitter;
TreeView1: TTreeView;
SaveDialog1: TSaveDialog;
ValueListEditor1: TValueListEditor;
Splitter2: TSplitter;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ActionMainMenuBar1: TActionMainMenuBar;
aOpen: TAction;
aZoom1to1: TAction;
aZoom1to2: TAction;
aSaveAs: TAction;
aAddRect: TAction;
aAddSVG: TAction;
aUndo: TAction;
aRedo: TAction;
aCut: TAction;
aCopy: TAction;
aPaste: TAction;
aDelete: TAction;
aToolShape: TAction;
aToolTransform: TAction;
aNew: TAction;
aPrint: TAction;
aExit: TAction;
aAddCircle: TAction;
aAddEllipse: TAction;
aAddLine: TAction;
aAddPolyline: TAction;
aAddPolygon: TAction;
aAddPath: TAction;
aAddText: TAction;
aAddImage: TAction;
aAddGroup: TAction;
SVG2ImageList1: TSVG2ImageList;
ilNormal: TSVG2LinkedImageList;
ilDisabled: TSVG2LinkedImageList;
procedure FormCreate(Sender: TObject);
end;
var
frmEditor: TfrmEditor;
implementation
{$R *.dfm}
uses UnitPrintPreview;
procedure TfrmEditor.FormCreate(Sender: TObject);
begin
ActionOpen := aOpen;
ActionSaveAs := aSaveAs;
ActionUndo := aUndo;
ActionRedo := aRedo;
ActionCut := aCut;
ActionCopy := aCopy;
ActionPaste := aPaste;
ActionDelete := aDelete;
ActionZoom1to1 := aZoom1to1;
ActionZoom1to2 := aZoom1to2;
ActionToolShape := aToolShape;
ActionToolTransform := aToolTransform;
ActionNew := aNew;
ActionPrint := aPrint;
ActionExit := aExit;
ActionAddRect := aAddRect;
ActionAddSVG := aAddSVG;
ActionAddCircle := aAddCircle;
ActionAddEllipse := aAddEllipse;
ActionAddLine := aAddLine;
ActionAddPolyline := aAddPolyline;
ActionAddPolygon := aAddPolygon;
ActionAddPath := aAddPath;
ActionAddText := aAddText;
ActionAddImage := aAddImage;
ActionAddGroup := aAddGroup;
TreeviewXML := Treeview1;
ValueListEditorAttribute := ValueListEditor1;
end;
end.
|
library ganesaIPEx;
{$mode objfpc}{$H+}
uses
Classes, SysUtils, fphttpclient, RegexPr;
function GetExternalIPAddress: string;
var
HTTPClient: TFPHTTPClient;
IPRegex: TRegExpr;
RawData: string;
begin
try
HTTPClient := TFPHTTPClient.Create(nil);
IPRegex := TRegExpr.Create;
try
//returns something like:
{
<html><head><title>Current IP Check</title></head><body>Current IP Address: 44.151.191.44</body></html>
}
RawData:=HTTPClient.Get('http://checkip.dyndns.org');
// adjust for expected output; we just capture the first IP address now:
IPRegex.Expression := RegExprString('\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b');
//or
//\b(?:\d{1,3}\.){3}\d{1,3}\b
if IPRegex.Exec(RawData) then
begin
result := IPRegex.Match[0];
end
else
begin
result := 'Got invalid results getting external IP address. Details:'+LineEnding+
RawData;
end;
except
on E: Exception do
begin
result := 'Error retrieving external IP address: '+E.Message;
end;
end;
finally
HTTPClient.Free;
IPRegex.Free;
end;
end;
exports GetExternalIPAddress;
begin
end.
|
//
// Generated by JavaToPas v1.5 20150830 - 104045
////////////////////////////////////////////////////////////////////////////////
unit android.test.MoreAsserts;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
java.util.regex.MatchResult;
type
JMoreAsserts = interface;
JMoreAssertsClass = interface(JObjectClass)
['{312DD875-1A8D-486F-9D97-FF09507CAF73}']
function assertContainsRegex(&message : JString; expectedRegex : JString; actual : JString) : JMatchResult; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/util/regex/MatchResult; A: $9
function assertContainsRegex(expectedRegex : JString; actual : JString) : JMatchResult; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;)Ljava/util/regex/MatchResult; A: $9
function assertMatchesRegex(&message : JString; expectedRegex : JString; actual : JString) : JMatchResult; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/util/regex/MatchResult; A: $9
function assertMatchesRegex(expectedRegex : JString; actual : JString) : JMatchResult; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;)Ljava/util/regex/MatchResult; A: $9
procedure assertAssignableFrom(expected : JClass; actual : JClass) ; cdecl; overload;// (Ljava/lang/Class;Ljava/lang/Class;)V A: $9
procedure assertAssignableFrom(expected : JClass; actual : JObject) ; cdecl; overload;// (Ljava/lang/Class;Ljava/lang/Object;)V A: $9
procedure assertContentsInAnyOrder(&message : JString; actual : JIterable; expected : TJavaArray<JObject>) ; cdecl; overload;// (Ljava/lang/String;Ljava/lang/Iterable;[Ljava/lang/Object;)V A: $89
procedure assertContentsInAnyOrder(actual : JIterable; expected : TJavaArray<JObject>) ; cdecl; overload;// (Ljava/lang/Iterable;[Ljava/lang/Object;)V A: $89
procedure assertContentsInOrder(&message : JString; actual : JIterable; expected : TJavaArray<JObject>) ; cdecl; overload;// (Ljava/lang/String;Ljava/lang/Iterable;[Ljava/lang/Object;)V A: $89
procedure assertContentsInOrder(actual : JIterable; expected : TJavaArray<JObject>) ; cdecl; overload;// (Ljava/lang/Iterable;[Ljava/lang/Object;)V A: $89
procedure assertEmpty(&message : JString; iterable : JIterable) ; cdecl; overload;// (Ljava/lang/String;Ljava/lang/Iterable;)V A: $9
procedure assertEmpty(&message : JString; map : JMap) ; cdecl; overload; // (Ljava/lang/String;Ljava/util/Map;)V A: $9
procedure assertEmpty(iterable : JIterable) ; cdecl; overload; // (Ljava/lang/Iterable;)V A: $9
procedure assertEmpty(map : JMap) ; cdecl; overload; // (Ljava/util/Map;)V A: $9
procedure assertEquals(&message : JString; expected : JSet; actual : JSet) ; cdecl; overload;// (Ljava/lang/String;Ljava/util/Set;Ljava/util/Set;)V A: $9
procedure assertEquals(&message : JString; expected : TJavaArray<Byte>; actual : TJavaArray<Byte>) ; cdecl; overload;// (Ljava/lang/String;[B[B)V A: $9
procedure assertEquals(&message : JString; expected : TJavaArray<Double>; actual : TJavaArray<Double>) ; cdecl; overload;// (Ljava/lang/String;[D[D)V A: $9
procedure assertEquals(&message : JString; expected : TJavaArray<Integer>; actual : TJavaArray<Integer>) ; cdecl; overload;// (Ljava/lang/String;[I[I)V A: $9
procedure assertEquals(&message : JString; expected : TJavaArray<JObject>; actual : TJavaArray<JObject>) ; cdecl; overload;// (Ljava/lang/String;[Ljava/lang/Object;[Ljava/lang/Object;)V A: $9
procedure assertEquals(expected : JSet; actual : JSet) ; cdecl; overload; // (Ljava/util/Set;Ljava/util/Set;)V A: $9
procedure assertEquals(expected : TJavaArray<Byte>; actual : TJavaArray<Byte>) ; cdecl; overload;// ([B[B)V A: $9
procedure assertEquals(expected : TJavaArray<Double>; actual : TJavaArray<Double>) ; cdecl; overload;// ([D[D)V A: $9
procedure assertEquals(expected : TJavaArray<Integer>; actual : TJavaArray<Integer>) ; cdecl; overload;// ([I[I)V A: $9
procedure assertEquals(expected : TJavaArray<JObject>; actual : TJavaArray<JObject>) ; cdecl; overload;// ([Ljava/lang/Object;[Ljava/lang/Object;)V A: $9
procedure assertNotContainsRegex(&message : JString; expectedRegex : JString; actual : JString) ; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V A: $9
procedure assertNotContainsRegex(expectedRegex : JString; actual : JString) ; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;)V A: $9
procedure assertNotEmpty(&message : JString; iterable : JIterable) ; cdecl; overload;// (Ljava/lang/String;Ljava/lang/Iterable;)V A: $9
procedure assertNotEmpty(&message : JString; map : JMap) ; cdecl; overload; // (Ljava/lang/String;Ljava/util/Map;)V A: $9
procedure assertNotEmpty(iterable : JIterable) ; cdecl; overload; // (Ljava/lang/Iterable;)V A: $9
procedure assertNotEmpty(map : JMap) ; cdecl; overload; // (Ljava/util/Map;)V A: $9
procedure assertNotEqual(&message : JString; unexpected : JObject; actual : JObject) ; cdecl; overload;// (Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V A: $9
procedure assertNotEqual(unexpected : JObject; actual : JObject) ; cdecl; overload;// (Ljava/lang/Object;Ljava/lang/Object;)V A: $9
procedure assertNotMatchesRegex(&message : JString; expectedRegex : JString; actual : JString) ; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V A: $9
procedure assertNotMatchesRegex(expectedRegex : JString; actual : JString) ; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;)V A: $9
procedure checkEqualsAndHashCodeMethods(&message : JString; lhs : JObject; rhs : JObject; expectedResult : boolean) ; cdecl; overload;// (Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Z)V A: $9
procedure checkEqualsAndHashCodeMethods(lhs : JObject; rhs : JObject; expectedResult : boolean) ; cdecl; overload;// (Ljava/lang/Object;Ljava/lang/Object;Z)V A: $9
end;
[JavaSignature('android/test/MoreAsserts')]
JMoreAsserts = interface(JObject)
['{E0872FAD-E432-4454-82D5-9475C32949C2}']
end;
TJMoreAsserts = class(TJavaGenericImport<JMoreAssertsClass, JMoreAsserts>)
end;
implementation
end.
|
unit IntegerSquareRootTest;
interface
uses
DUnitX.TestFramework,
uIntXLibTypes,
uIntX;
type
[TestFixture]
TIntegerSquareRootTest = class(TObject)
public
[Test]
procedure SquareRootOfZero();
[Test]
procedure SquareRootOfOne();
[Test]
procedure SquareRootof4();
[Test]
procedure SquareRootof25();
[Test]
procedure SquareRootof27();
[Test]
procedure SquareRootofVeryBigValue();
procedure SquareRootofNull();
[Test]
procedure CallSquareRootofNull();
procedure SquareRootofNegativeNumber();
[Test]
procedure CallSquareRootofNegativeNumber();
end;
implementation
[Test]
procedure TIntegerSquareRootTest.SquareRootOfZero();
var
int1: TIntX;
begin
int1 := TIntX.Create(0);
Assert.IsTrue(TIntX.IntegerSquareRoot(int1) = 0);
end;
[Test]
procedure TIntegerSquareRootTest.SquareRootOfOne();
var
int1: TIntX;
begin
int1 := TIntX.Create(1);
Assert.IsTrue(TIntX.IntegerSquareRoot(int1) = 1);
end;
[Test]
procedure TIntegerSquareRootTest.SquareRootof4();
var
int1: TIntX;
begin
int1 := TIntX.Create(4);
Assert.IsTrue(TIntX.IntegerSquareRoot(int1) = 2);
end;
[Test]
procedure TIntegerSquareRootTest.SquareRootof25();
var
int1, res: TIntX;
begin
int1 := TIntX.Create(25);
res := TIntX.IntegerSquareRoot(int1);
Assert.IsTrue(res = 5);
end;
[Test]
procedure TIntegerSquareRootTest.SquareRootof27();
var
int1, res: TIntX;
begin
int1 := TIntX.Create(27);
res := TIntX.IntegerSquareRoot(int1);
Assert.IsTrue(res = 5);
end;
[Test]
procedure TIntegerSquareRootTest.SquareRootofVeryBigValue();
var
int1: TIntX;
begin
int1 := TIntX.Create
('783648276815623658365871365876257862874628734627835648726');
Assert.AreEqual(TIntX.IntegerSquareRoot(int1).ToString,
'27993718524262253829858552106');
end;
procedure TIntegerSquareRootTest.SquareRootofNull();
begin
TIntX.Create(Default (TIntX));
end;
[Test]
procedure TIntegerSquareRootTest.CallSquareRootofNull();
var
TempMethod: TTestLocalMethod;
begin
TempMethod := SquareRootofNull;
Assert.WillRaise(TempMethod, EArgumentNilException);
end;
procedure TIntegerSquareRootTest.SquareRootofNegativeNumber();
var
int1: TIntX;
begin
int1 := TIntX.Create(-25);
TIntX.IntegerSquareRoot(int1);
end;
[Test]
procedure TIntegerSquareRootTest.CallSquareRootofNegativeNumber();
var
TempMethod: TTestLocalMethod;
begin
TempMethod := SquareRootofNegativeNumber;
Assert.WillRaise(TempMethod, EArgumentException);
end;
initialization
TDUnitX.RegisterTestFixture(TIntegerSquareRootTest);
end.
|
unit E_FileVersionUtils;
interface
uses
Windows, System.SysUtils;
type
TVersionInfo = record
Major, Minor, Release, Build: Integer;
FileVersion,
ProductVersion: string;
ProductName: string;
end;
function GetApplicationVersion: string;
function GetFileTextVersion(const aExeFileName: TFileName): string;
function GetFileVersion(const aExeFileName: TFileName): string;
implementation
function GetApplicationVersion: string;
begin
result := GetFileTextVersion(GetModuleName(HInstance));
end;
function GetVersionInfo(aExeFilePath: string; out aVersionInfo: TVersionInfo): Boolean;
var
VerInfoSize: Cardinal;
Dummy: Cardinal;
PVerInfo, Translation: PChar;
Value: PChar;
p: integer;
LangCharSet: string;
begin
Result := False;
aVersionInfo.Major := 0;
aVersionInfo.Minor := 0;
aVersionInfo.Release := 0;
aVersionInfo.Build := 0;
aVersionInfo.ProductVersion:='0.0.0.0';
aVersionInfo.ProductName:='';
aVersionInfo.FileVersion := '';
VerInfoSize := GetFileVersionInfoSize(PChar(aExeFilePath), Dummy);
if VerInfoSize <= 0 then
Exit;
PVerInfo := AllocMem(VerInfoSize);
try
// определим язык CalcLangCharSet
// CalcLangCharSet:='040904E3';
if not GetFileVersionInfo(PChar(aExeFilePath), 0, VerInfoSize, PVerInfo) then
Exit;
if not VerQueryValue(PVerInfo, '\VarFileInfo\Translation', Pointer(Translation), VerInfoSize) then
Exit;
if VerInfoSize < 4 then
Exit;
p := 0;
StrLCopy(@p, Translation, 1);
LangCharSet := IntToHex(p, 4);
StrLCopy(@p, Translation + 1, 1);
LangCharSet := LangCharSet + IntToHex(p, 4);
aVersionInfo.ProductName := '';
if VerQueryValue(PVerInfo, PChar('StringFileInfo\'+LangCharSet+'\ProductName'), Pointer(Value), VerInfoSize) then
aVersionInfo.ProductName := Value;
aVersionInfo.ProductVersion := '';
if VerQueryValue(PVerInfo, PChar('StringFileInfo\'+LangCharSet+'\ProductVersion'), Pointer(Value), VerInfoSize) then
aVersionInfo.ProductVersion := Value;
aVersionInfo.FileVersion := '';
if VerQueryValue(PVerInfo, PChar('StringFileInfo\'+LangCharSet+'\FileVersion'), Pointer(Value), VerInfoSize) then
aVersionInfo.FileVersion := Value;
if not VerQueryValue(PVerInfo, '\', Pointer(Value), VerInfoSize) then
begin
aVersionInfo.Major := HiWord(PVSFixedFileInfo(Value).dwFileVersionMS);
aVersionInfo.Minor := LoWord(PVSFixedFileInfo(Value).dwFileVersionMS);
aVersionInfo.Release := HiWord(PVSFixedFileInfo(Value).dwFileVersionLS);
aVersionInfo.Build := LoWord(PVSFixedFileInfo(Value).dwFileVersionLS);
end;
Result := True;
finally
FreeMem(PVerInfo, VerInfoSize);
end;
end;
function GetFileTextVersion(const aExeFileName: TFileName): string;
var
VerInfo: TVersionInfo;
begin
if GetVersionInfo(aExeFileName, VerInfo) then
Result := VerInfo.FileVersion;
end;
function GetFileVersion(const aExeFileName: TFileName): string;
var
VerInfoSize: Cardinal;
VerValueSize: Cardinal;
Dummy: Cardinal;
PVerInfo: Pointer;
PVerValue: PVSFixedFileInfo;
begin
Result := '';
VerInfoSize := GetFileVersionInfoSize(PChar(aExeFileName), Dummy);
GetMem(PVerInfo, VerInfoSize);
try
if GetFileVersionInfo(PChar(aExeFileName), 0, VerInfoSize, PVerInfo) then
if VerQueryValue(PVerInfo, '\', Pointer(PVerValue), VerValueSize) then
with PVerValue^ do
Result := Format('v%d.%d.%d.%d', [
HiWord(dwFileVersionMS), //Major
LoWord(dwFileVersionMS), //Minor
HiWord(dwFileVersionLS), //Release
LoWord(dwFileVersionLS)]); //Build
finally
FreeMem(PVerInfo, VerInfoSize);
end;
end;
end.
|
unit uModContrabonSales;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, uModApp,
uModRekening, uModOrganization, uModUnit;
type
TModContrabonSales = class(TModApp)
private
FCONT_IS_CONTRABON: Integer;
FCONT_NET_SALES: Double;
FCONT_DATE_SALES: TDatetime;
FCONT_IS_CLAIM: Integer;
FCONT_ORGANIZATION: TModOrganization;
FCONT_DISC_AMOUNT: Double;
FCONT_IS_VALIDATED: Integer;
FCONT_TOTAL_SALES: Double;
FCONT_FEE: Double;
FCONT_GROSS_SALES: double;
FCONT_TAX_AMOUNT: Double;
public
class function GetTableName: String; override;
published
property CONT_IS_CONTRABON: Integer read FCONT_IS_CONTRABON write
FCONT_IS_CONTRABON;
property CONT_NET_SALES: Double read FCONT_NET_SALES write FCONT_NET_SALES;
property CONT_DATE_SALES: TDatetime read FCONT_DATE_SALES write
FCONT_DATE_SALES;
property CONT_IS_CLAIM: Integer read FCONT_IS_CLAIM write FCONT_IS_CLAIM;
[AttributeOfForeign('CONT_ORGANIZATION_ID')]
property CONT_ORGANIZATION: TModOrganization read FCONT_ORGANIZATION write
FCONT_ORGANIZATION;
property CONT_DISC_AMOUNT: Double read FCONT_DISC_AMOUNT write
FCONT_DISC_AMOUNT;
property CONT_IS_VALIDATED: Integer read FCONT_IS_VALIDATED write
FCONT_IS_VALIDATED;
property CONT_TOTAL_SALES: Double read FCONT_TOTAL_SALES write
FCONT_TOTAL_SALES;
property CONT_FEE: Double read FCONT_FEE write FCONT_FEE;
property CONT_GROSS_SALES: double read FCONT_GROSS_SALES write
FCONT_GROSS_SALES;
property CONT_TAX_AMOUNT: Double read FCONT_TAX_AMOUNT write FCONT_TAX_AMOUNT;
end;
implementation
class function TModContrabonSales.GetTableName: String;
begin
Result := 'CONTRABON_SALES';
end;
end.
|
unit
cmdcvrt;
(*##*)
(***************************************************************************
* *
* c m d c v r t *
* *
* Copyright © 2002 Andrei Ivanov. All rights reserved. *
* wbmp image convertor console win32 main procedure *
* Conditional defines: *
* *
* Registry: *
* HKEY_LOCAL_MACHINE\Software\ensen\i2wbmp\1.0\ *
* DefDitherMode, as dither parameter, default 'nearest' *
* *
* *
* \Virtual Roots - contains aliases in addition ti IIS (PWS) *
* Usage *
* i2wbmp [-?][-r][-m DitherMode][-o Path][-v] File(s)|FileMask|Directory*
* FileMask - file name or mask *
* Path - output folder path *
* Options: *
* ? - this screen *
* r - recurse subfolders *
* o - output folder path *
* v - verbose output *
* c - send to output (do not store output files) *
* m - dithering mode: *
* Nearest|FloydSteinberg|Stucki|Sierra|JaJuNI|SteveArche|Burkes *
* default nearest *
* g - get command line options from QUERY_STRING environment var *
* p - get command line options from input *
* h - create HTTP header *
* d - skip default settings (don''t load i2wbmp.ini) *
* 8 - no 8 bit align *
* s - print output to console *
* n - invert image (negative) *
* *
* *
* Configuration file i2wbmp.ini can keep defaults. *
* Revisions : Apr 15 2002 *
* Last fix : Apr 17 2002 *
* Lines : 697 *
* History : *
* Printed : --- *
* *
***************************************************************************)
(*##*)
interface
uses
SysUtils, Types, Classes, Graphics, WBMPImage;
function DoCmd(AIsRegistered: Boolean): Boolean;
implementation
uses
GIFImage, util1, wmleditutil;
type
TCvrtEnv = class(TObject)
private
IsRegistered: Boolean;
DitherMode: TDitherMode;
outputpath: String;
send2output,
recurse,
verbose,
getQUERY_STRING,
getInput,
createHTTPheader,
SkipIni,
Print2Console,
NoAlign,
Negative,
showhelp: Boolean;
filelist: TStrings;
public
Count: Integer;
constructor Create(AIsRegistered: Boolean);
destructor Destroy; override;
procedure Clear;
end;
const
DEF_BITMAPEXTS = '.ico.bmp.dib.jpeg.jpg.gif.wmf.emf';
DEF_HTTPHEADER: String = 'HTTP/1.0 200 Ok'#13#10 +
'Content-Type: image/vnd.wap.wbmp'#13#10#13#10;
procedure RaiseError(ACode: Integer; ACodeS: String);
begin
Writeln(output, #13#10'Error ', ACode, ': ', ACodeS);
Halt(ACode);
end;
function PrintCopyright(AIsRegistered: Boolean): String;
const
R: array[Boolean] of String = ('evaluation version', 'Registered version');
begin
Result:=
'i2wbmp, wbmp file convertor. Copyright (c) 2002 Andrei Ivanov.'#13#10 +
R[AIsRegistered] + #13#10+
' Should you have any questions concerning this program, please contact:'#13#10+
' ensen_andy@yahoo.com. Type i2wbmp -h to get list of command line options.'#13#10;
end;
function PrintUsage: String;
begin
Result:=
'Usage: i2wbmp [-?][-r][-m DitherMode][-o Path][-v] File(s)|FileMask|Directory'#13#10 +
' FileMask - file name/directory or mask; Path - output folder path'#13#10 +
' Options: ? - this screen'#13#10 +
' r - recurse subfolders'#13#10 +
' o - output folder path'#13#10 +
' v - verbose output'#13#10 +
' c - send to output (do not store output files)'#13#10 +
' m - dithering mode:'#13#10 +
' Nearest(default)|FloydSteinberg|Stucki|Sierra|JaJuNI|SteveArche|Burkes'#13#10+
' g - get command line options from QUERY_STRING environment variable'#13#10 +
' p - get command line options from input'#13#10 +
' h - create HTTP header'#13#10 +
' d - skip default settings (don''t load i2wbmp.ini)'#13#10 +
' s - print result image to console'#13#10 +
' n - invert image (negative)'#13#10 +
' 8 - no 8 bit align'#13#10 +
' i - reserved'#13#10 +
'Configuration file i2wbmp.ini can keep defaults.';
end;
const
DitherModeStr: array[TDitherMode] of String[15] =
('Nearest', // Nearest color matching w/o error correction
'FloydSteinberg', // Floyd Steinberg Error Diffusion dithering
'Stucki', // Stucki Error Diffusion dithering
'Sierra', // Sierra Error Diffusion dithering
'JaJuNI', // Jarvis, Judice & Ninke Error Diffusion dithering
'SteveArche', // Stevenson & Arche Error Diffusion dithering
'Burkes' // Burkes Error Diffusion dithering
);
function GetDitherModeByName(const S: String; ADefDitherMode: TDitherMode): TDitherMode;
begin
Result:= ADefDitherMode;
if CompareText(s, 'Nearest') = 0
then Result:= dmNearest; // Nearest color matching w/o error correction
if CompareText(s, 'FloydSteinberg') = 0
then Result:= dmFloydSteinberg; // Floyd Steinberg Error Diffusion dithering
if CompareText(s, 'Stucki') = 0
then Result:= dmStucki; // Stucki Error Diffusion dithering
if CompareText(s, 'Sierra') = 0
then Result:= dmSierra; // Sierra Error Diffusion dithering
if CompareText(s, 'JaJuNI') = 0
then Result:= dmJaJuNI; // Jarvis, Judice & Ninke Error Diffusion dithering
if CompareText(s, 'SteveArche') = 0
then Result:= dmSteveArche; // Stevenson & Arche Error Diffusion dithering
if CompareText(s, 'Burkes') = 0
then Result:= dmBurkes; // Stevenson & Arche Error Diffusion dithering
end;
function GetDitherModeName(ADitherMode: TDitherMode): String;
begin
case ADitherMode of
dmNearest: // Nearest color matching w/o error correction
Result:= 'Nearest';
dmFloydSteinberg: // Floyd Steinberg Error Diffusion dithering
Result:= 'FloydSteinberg';
dmStucki: // Stucki Error Diffusion dithering
Result:= 'Stucki';
dmSierra: // Sierra Error Diffusion dithering
Result:= 'Sierra';
dmJaJuNI: // Jarvis, Judice & Ninke Error Diffusion dithering
Result:= 'JaJuNI';
dmSteveArche: // Stevenson & Arche Error Diffusion dithering
Result:= 'SteveArche';
dmBurkes: // Burkes Error Diffusion dithering
Result:= 'Burkes';
end; { case }
end;
const
OptionsHasExt: TSysCharSet = ['m', 'o', 'M', 'O'];
function ParseCmd(const AConfig: String; AOptionsHasExt: TSysCharSet; Rslt: TStrings): String;
var
S, os: String;
o: Char;
filecount, p, i, L: Integer;
state: Integer;
Quoted: Boolean;
begin
Rslt.Clear;
S:= AConfig;
state:= 0;
i:= 1;
filecount:= 0;
L:= Length(S);
// skip program name
while i <= L do begin
if S[i] = #32 then begin
Inc(i);
Break;
end;
Inc(i);
end;
Result:= Copy(S, 1, i - 2);
Quoted:= False;
// parse
while i <= L do begin
o:= S[i];
case o of
'''', '"': begin
Quoted:= not Quoted;
Inc(i);
end;
'-': begin
case state of
0: state:= 1; // option started
end;
Inc(i);
end;
#0..#32: begin
state:= 0;
Inc(i);
end;
else begin
case state of
0:begin // file name or mask
p:= i;
if Quoted then begin
repeat
Inc(i);
until (i > L) or (S[i] in ['''', '"', #0]);
Quoted:= False;
end else begin
repeat
Inc(i);
until (i > L) or (S[i] in [#0..#32, '-']);
end;
os:= Copy(s, p, i - p);
Inc(filecount);
Rslt.AddObject('=' + os, TObject(filecount));
end;
1: begin // option
if S[i] in AOptionsHasExt then begin // option has next parameter
//
// skip spaces if exists
Inc(i);
while (i <= L) and (S[i] <= #32) do Inc(i);
// get option's parameter
p:= i;
Quoted:= (i <= L) and (s[i] in ['''', '"']);
if Quoted then begin
Inc(p);
repeat
Inc(i);
until (i > L) or (S[i] in [#0, '''', '"']);
os:= Copy(s, p, i - p);
Inc(i);
Quoted:= False;
end else begin
repeat
Inc(i);
until (i > L) or (S[i] in [#0..#32, '-']);
os:= Copy(s, p, i - p);
end;
// add option
Rslt.Add(o + '=' + os);
end else begin
// add option
Rslt.Add(o + '=');
Inc(i);
end;
end;
else begin
Inc(i);
end;
end; { case state }
//
end; { else case }
end; { case }
end;
end;
{ calc count of switches
}
function GetSwitchesCount(const ASwitches: TSysCharSet; opts: TStrings): Integer;
var
i: Integer;
s: String;
begin
Result:= 0;
for i:= 0 to opts.Count - 1 do begin
s:= opts.Names[i];
if (Length(s) > 0) and (s[1] in ASwitches)
then Result:= Result + 1;
end;
end;
{ extract switch values
}
function ExtractSwitchValue(ASwitches: TSysCharSet; opts: TStrings): String;
var
i, l: Integer;
s: String;
begin
Result:= '';
for i:= 0 to opts.Count - 1 do begin
s:= opts.Names[i];
l:= Length(s);
if ((l > 0) and (s[1] in ASwitches))
or ((l = 0) and (ASwitches = [])) then begin
Result:= Copy(opts[i], l + 2, MaxInt);
end;
end;
end;
{ extract switch values
}
function ExtractSwitchValues(ASwitches: TSysCharSet; opts: TStrings; ARslt: TStrings): Integer;
var
i, l: Integer;
s: String;
begin
Result:= 0;
for i:= 0 to opts.Count - 1 do begin
s:= opts.Names[i];
l:= Length(s);
if ((l > 0) and (s[1] in ASwitches))
or ((l = 0) and (ASwitches = [])) then begin
s:= Copy(opts[i], l + 2, MaxInt);
ARslt.AddObject(s, opts.Objects[i]);
Result:= Result + 1;
end;
end;
end;
function HTTPDecode(const AStr: String): String;
var
Sp, Rp, Cp: PChar;
S: String;
begin
SetLength(Result, Length(AStr));
Sp := PChar(AStr);
Rp := PChar(Result);
// Cp := Sp;
try
while Sp^ <> #0 do
begin
case Sp^ of
'+': Rp^ := ' ';
'%': begin
// Look for an escaped % (%%) or %<hex> encoded character
Inc(Sp);
if Sp^ = '%' then
Rp^ := '%'
else
begin
Cp := Sp;
Inc(Sp);
if (Cp^ <> #0) and (Sp^ <> #0) then
begin
S := '$' + Cp^ + Sp^;
Rp^ := Chr(StrToInt(S));
end
else
RaiseError(3, 'Invalid encoded URL');
end;
end;
else
Rp^ := Sp^;
end;
Inc(Rp);
Inc(Sp);
end;
except
on E:EConvertError do
RaiseError(3, 'Invalid encoded URL');
end;
SetLength(Result, Rp - PChar(Result));
end;
procedure ExtractHeaderFields(Separators, WhiteSpace: TSysCharSet; Content: PChar;
Strings: TStrings; Decode: Boolean; StripQuotes: Boolean = False);
var
Head, Tail: PChar;
EOS, InQuote, LeadQuote: Boolean;
QuoteChar: Char;
function DoStripQuotes(const S: string): string;
var
I: Integer;
begin
Result := S;
if StripQuotes then
for I := Length(Result) downto 1 do
if Result[I] in ['''', '"'] then
Delete(Result, I, 1);
end;
begin
if (Content = nil) or (Content^ = #0) then Exit;
Tail := Content;
QuoteChar := #0;
repeat
while Tail^ in WhiteSpace + [#13, #10] do Inc(Tail);
Head := Tail;
InQuote := False;
LeadQuote := False;
while True do
begin
while (InQuote and not (Tail^ in [#0, #13, #10, '"'])) or
not (Tail^ in Separators + [#0, #13, #10, '"']) do Inc(Tail);
if Tail^ = '"' then
begin
if (QuoteChar <> #0) and (QuoteChar = Tail^) then
QuoteChar := #0
else
begin
LeadQuote := Head = Tail;
QuoteChar := Tail^;
if LeadQuote then Inc(Head);
end;
InQuote := QuoteChar <> #0;
if InQuote then
Inc(Tail)
else Break;
end else Break;
end;
if not LeadQuote and (Tail^ <> #0) and (Tail^ = '"') then
Inc(Tail);
EOS := Tail^ = #0;
Tail^ := #0;
if Head^ <> #0 then
if Decode then
Strings.Add(DoStripQuotes(HTTPDecode(Head)))
else Strings.Add(DoStripQuotes(Head));
Inc(Tail);
until EOS;
end;
procedure EmptyNames(AName: String; AStrings: TStrings);
var
i: Integer;
p: Integer;
s: String;
begin
for i:= 0 to AStrings.Count - 1 do begin
s:= AStrings[i];
p:= Pos('=', s);
if p = 0 then begin
s:= s + '=';
AStrings[i]:= s;
end else begin
if CompareText(AName, Copy(s, 1, p - 1)) = 0 then begin
Delete(s, 1, p);
AStrings[i]:= '=' + s;
end;
end;
end;
end;
procedure Print2Output(const AFileIn: String;
ADitherMode: TDitherMode; ATransformOptions: TTransformOptions);
var
wbmpImg: TWBMPImage;
Picture: TPicture;
y, x: Integer;
begin
Picture:= TPicture.Create;
wbmpImg:= TWBMPImage.Create;
wbmpImg.TransformOptions:= ATransformOptions;
try
Picture.LoadFromFile(AFileIn);
with wbmpImg do begin
DitherMode:= ADitherMode;
Assign(Picture.Graphic);
for y:= 0 to Height - 1 do begin
for x:= 0 to Width - 1 do begin
with wbmpImg.Bitmap.Canvas, CR(Pixels[x, y]) do begin
if v[0]+v[1]+v[3] >= 3 * $FF div 2
then Write(output, '*')
else Write(output, ' ');
end;
end;
Writeln(output);
end;
end;
except
end;
wbmpImg.Free;
Picture.Free;
end;
function ProcessFile(const AFN: String; AEnv: TObject): Boolean;
var
fn, ext, op, np: String;
StrmWBMP: TStream;
ImageSize: TPoint;
TransformOptions: TTransformOptions;
begin
Result:= True;
//DEF_BITMAPEXTS
ext:= ExtractFileExt(AFN);
if Pos(LowerCase(ext), DEF_BITMAPEXTS) = 0
then Exit;
fn:= util1.ReplaceExt('wbmp', AFN);
if (Length(TCvrtEnv(AEnv).outputpath) = 0) or (TCvrtEnv(AEnv).outputpath = '.')
then op:= ''
else op:= TCvrtEnv(AEnv).outputpath;
fn:= ConcatPath(op, fn, '\');
np:= ExtractFilePath(fn);
if (Length(np) = 0) or DirectoryExists(np) then begin
// folder exists
end else begin
// create folder
if CreateDir(np) then begin
if TCvrtEnv(AEnv).verbose
then Writeln(output, Format(' Folder %s created.', [np]));
end else begin
if TCvrtEnv(AEnv).verbose
then RaiseError(2, Format('Cannot create folder %s.', [np]));
end;
end;
if TCvrtEnv(AEnv).verbose then begin
Write(output, Format(' %s -> %s', [AFN, fn]));
end;
TCvrtEnv(AEnv).Count:= TCvrtEnv(AEnv).Count + 1;
if not TCvrtEnv(AEnv).IsRegistered
then TransformOptions:= TransformOptions + [toUnregistered];
if TCvrtEnv(AEnv).Negative
then TransformOptions:= TransformOptions + [toNegative];
if TCvrtEnv(AEnv).NoAlign
then TransformOptions:= TransformOptions - [toAlign8];
try
if TCvrtEnv(AEnv).send2output
then StrmWBMP:= TStringStream.Create('')
else StrmWBMP:= TFileStream.Create(fn, fmCreate);
except
RaiseError(4, Format('Cannot create file %s', [fn]));
end;
if TCvrtEnv(AEnv).createHTTPheader then begin
StrmWBMP.Write(DEF_HTTPHEADER[1], Length(DEF_HTTPHEADER));
end;
if ConvertImage2WBMP(Afn, StrmWBMP, TCvrtEnv(AEnv).DitherMode, TransformOptions, ImageSize) then begin
end;
if TCvrtEnv(AEnv).send2output then begin
Write(output, TStringStream(StrmWBMP).DataString);
end else begin
end;
if TCvrtEnv(AEnv).verbose then begin
Writeln(output, Format(' Size: %dx%d, %d bytes', [ImageSize.x, ImageSize.y, StrmWBMP.Size]));
end;
if TCvrtEnv(AEnv).Print2Console then begin
Print2Output(Afn, TCvrtEnv(AEnv).DitherMode, TransformOptions);
end;
StrmWBMP.Free;
end;
function PrintSettings(AEnv: TCvrtEnv): String;
const
R: array[Boolean] of String = ('', 'recurse subdirectories, ');
V: array[Boolean] of String = ('', 'verbose output, ');
G: array[Boolean] of String = ('', 'get options from QUERY_STRING, ');
I: array[Boolean] of String = ('', 'read options from input, ');
H: array[Boolean] of String = ('', 'create HTTP header, ');
D: array[Boolean] of String = ('', 'ini file settings skipped, ');
N: array[Boolean] of String = ('', 'negative, ');
NA8: array[Boolean] of String = ('align 8 bit, ', 'no align, ');
C: array[Boolean] of String = ('store files.', 'send to output.');
var
p: Integer;
begin
Result:=
'Switches:'#13#10+
' output folder: ' + AEnv.outputpath + #13#10 +
' Dithering: ' + GetDitherModeName(AEnv.DitherMode) +#13#10 +
' ' + R[AEnv.recurse] + V[AEnv.verbose] + G[AEnv.getQUERY_STRING] +
D[AEnv.SkipIni] + N[AEnv.Negative] + NA8[AEnv.NoAlign] +
I[AEnv.getInput] + H[AEnv.createHTTPheader] + C[AEnv.send2output] + #13#10 +
'File(s) or file mask:'#13#10;
for p:= 0 to AEnv.filelist.Count - 1 do begin
Result:= Result + ' ' + AEnv.filelist[p] + #13#10;
end;
end;
function CheckParameters(AOpts: TStrings; AEnv: TCvrtEnv): Boolean;
var
i: Integer;
s: String;
begin
ExtractSwitchValues([], Aopts, AEnv.filelist);
{ check '.', '..' and other directory specs }
for i:= 0 to AEnv.filelist.Count - 1 do begin
if DirectoryExists(AEnv.filelist[i]) then begin
s:= ConcatPath(AEnv.filelist[i], '*.*', '\');
AEnv.filelist[i]:= s;
end;
end;
AEnv.outputpath:= ExtractSwitchValue(['o', 'O'], AOpts);
AEnv.DitherMode:= GetDitherModeByName(ExtractSwitchValue(['m', 'M'], AOpts), dmNearest);
AEnv.recurse:= GetSwitchesCount(['r', 'R'], AOpts) > 0;
AEnv.verbose:= GetSwitchesCount(['v', 'V'], AOpts) > 0;
AEnv.showhelp:= GetSwitchesCount(['?'], AOpts) > 0;
AEnv.Print2Console:= GetSwitchesCount(['s', 'S'], AOpts) > 0;
AEnv.send2output:= GetSwitchesCount(['c', 'C'], AOpts) > 0;
AEnv.getQUERY_STRING:= GetSwitchesCount(['g', 'G'], AOpts) > 0;
AEnv.getInput:= GetSwitchesCount(['p', 'P'], AOpts) > 0;
AEnv.createHTTPheader:= GetSwitchesCount(['h', 'H'], AOpts) > 0;
AEnv.SkipIni:= GetSwitchesCount(['d', 'D'], AOpts) > 0;
AEnv.Negative:= GetSwitchesCount(['n', 'N'], AOpts) > 0;
AEnv.NoAlign:= GetSwitchesCount(['8'], AOpts) > 0;
if Length(AEnv.outputpath) = 0
then AEnv.outputpath:= '.';
Result:= DirectoryExists(AEnv.outputpath);
if not Result
then Writeln(output, Format('output folder %s does not exists', [AEnv.outputpath]))
else Result:= (AEnv.filelist.Count > 0) or (AEnv.getQUERY_STRING or AEnv.getInput);
end;
constructor TCvrtEnv.Create(AIsRegistered: Boolean);
begin
inherited Create;
Count:= 0;
filelist:= TStringList.Create;
IsRegistered:= AIsRegistered;
end;
procedure TCvrtEnv.Clear;
begin
Count:= 0;
filelist.Clear;
end;
destructor TCvrtEnv.Destroy;
begin
filelist.Free;
inherited Destroy;
end;
function DoCmd(AIsRegistered: Boolean): Boolean;
label
LSkipIni;
var
f: Integer;
config,
configfn: String;
cvrtEnv: TCvrtEnv;
opts: TStrings;
skipinicount: Integer;
begin
skipinicount:= 0;
cvrtEnv:= TCvrtEnv.Create(AIsRegistered);
opts:= TStringList.Create;
configfn:= ConcatPath(ExtractFilePath(ParamStr(0)), 'i2wbmp.ini', '\');
if FileExists(configfn) then begin
config:= util1.File2String(configfn);
end else config:= '';
LSkipIni:
Inc(skipinicount);
f:= Pos(#32, CmdLine);
if f = 0
then f:= Length(CmdLine)+1;
config:= Copy(CmdLine, 1, f - 1) + #32 + config + #32 + Copy(CmdLine, f + 1, MaxInt);
ParseCmd(config, OptionsHasExt, opts);
if (not CheckParameters(opts, cvrtEnv)) or (cvrtEnv.showhelp) then begin
Writeln(output, PrintCopyright(AIsRegistered) + PrintUsage);
cvrtEnv.Free;
Result:= False;
Exit;
end;
if cvrtEnv.SkipIni and (skipinicount = 1) then begin
opts.Clear;
cvrtEnv.Clear;
config:= '';
goto LSkipIni;
end;
if cvrtEnv.getQUERY_STRING then begin
// read QUERY_STRING
ExtractHeaderFields(['&'], [], PChar(GetEnvironmentVariable('QUERY_STRING')), opts, True, True);
EmptyNames('src', opts);
if not CheckParameters(opts, cvrtEnv) then begin
RaiseError(6, 'Invalid parameters');
end;
cvrtEnv.verbose:= false;
// cvrtEnv.send2output:= true;
//Writeln(output, '(((', opts.Text, ')))');
end;
if cvrtEnv.getInput then begin
// read input
f:= 1;
while not EOF(input) do begin
SetLength(config, f);
Read(input, config[f]);
Inc(f);
end;
ExtractHeaderFields(['&'], [], PChar(config), opts, True, True);
EmptyNames('src', opts);
if not CheckParameters(opts, cvrtEnv) then begin
RaiseError(7, 'Invalid parameters');
end;
cvrtEnv.verbose:= false;
// cvrtEnv.send2output:= true;
end;
if cvrtEnv.send2output
then cvrtEnv.verbose:= false
else Writeln(output, PrintCopyright(AIsRegistered));
if cvrtEnv.verbose then begin
Writeln(output, PrintSettings(cvrtEnv));
Writeln('Process file(s):');
end;
for f:= 0 to cvrtEnv.filelist.Count - 1 do begin
if cvrtEnv.verbose then Writeln(output, ' ', cvrtEnv.filelist[f]);
if DirectoryExists(cvrtEnv.filelist[f]) then begin
// directory
Walk_Tree('*.*', cvrtEnv.filelist[f], faAnyFile, cvrtEnv.Recurse, ProcessFile, cvrtEnv);
end else begin
if FileExists(cvrtEnv.filelist[f]) then begin
// file
ProcessFile(cvrtEnv.filelist[f], cvrtEnv);
end else begin
// mask ?
Walk_Tree(ExtractFileName(cvrtEnv.filelist[f]),
ExtractFilePath(cvrtEnv.filelist[f]), faAnyFile, cvrtEnv.Recurse, ProcessFile, cvrtEnv);
end;
end;
end;
if not cvrtEnv.send2output
then Writeln(output, #13#10, cvrtEnv.Count, ' file(s) done.');
cvrtEnv.Free;
opts.Free;
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.StdCtrls;
const
ENGLISH_ALPHABET_SHIFT = 65;
RUSSIAN_ALPHABET_SHIFT = 128;
type
TLanguageForm = class(TForm)
EnglishBtn: TRadioButton;
RussianBtn: TRadioButton;
LanguageCheckLbl: TLabel;
CloseBtn: TButton;
Nextbtn: TButton;
procedure RussianBtnClick(Sender: TObject);
procedure EnglishBtnClick(Sender: TObject);
procedure CloseBtnClick(Sender: TObject);
procedure NextbtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
type
TLanguage = (english, russian);
var
language : TLanguage;
procedure SetLanguage(const languageIsEnglish : boolean);
public
function GetLanguage : TLanguage;
end;
var
LanguageForm: TLanguageForm;
implementation
{$R *.dfm}
Uses
KeyCheck, Results;
procedure TLanguageForm.CloseBtnClick(Sender: TObject);
begin
Close;
end;
procedure TLanguageForm.EnglishBtnClick(Sender: TObject);
begin
LanguageForm.LanguageCheckLbl.Caption := 'Choose your language';
LanguageForm.CloseBtn.Caption := 'Close';
LanguageForm.Nextbtn.Caption := 'Next';
KeyCheck.KeyCheckForm.KeyCheckLbl.Caption := 'Choose a key';
KeyCheck.KeyCheckForm.InorderRBtn.Caption := 'Inorder';
KeyCheck.KeyCheckForm.ProgressiveRBtn.Caption := 'Progressive';
KeyCheck.KeyCheckForm.SelfGeneratedRBtn.Caption := 'Self-generated';
KeyCheck.KeyCheckForm.CancelBtn.Caption := 'Cancel';
KeyCheck.KeyCheckForm.NextBtn.Caption := 'Cipher';
KeyCheck.KeyCheckForm.CloseBtn.Caption := 'Close';
Results.ResultsForm.EncipheredLbl.Caption := 'Enciphered text';
Results.ResultsForm.DecipheredLbl.Caption := 'Deciphered text';
Results.ResultsForm.EncipherButton.Caption := 'Encipher';
Results.ResultsForm.DecipherButton.Caption := 'Decipher';
Results.ResultsForm.ClearButton.Caption := 'Clear';
Results.ResultsForm.KasiskiButton.Caption := 'Kasiski';
Results.ResultsForm.BackButton.Caption := 'Back';
Results.ResultsForm.CloseButton.Caption := 'Close';
language := english;
end;
procedure TLanguageForm.FormCreate(Sender: TObject);
begin
language := english;
end;
procedure TLanguageForm.NextbtnClick(Sender: TObject);
begin
LanguageForm.Visible := false;
KeyCheck.KeyCheckForm.Visible := true;
end;
procedure TLanguageForm.RussianBtnClick(Sender: TObject);
begin
LanguageCheckLbl.Caption := 'Выберите язык';
LanguageForm.CloseBtn.Caption := 'Закрыть';
LanguageForm.Nextbtn.Caption := 'Далее';
KeyCheck.KeyCheckForm.KeyCheckLbl.Caption := 'Выберите ключ';
KeyCheck.KeyCheckForm.InorderRBtn.Caption := 'Прямой';
KeyCheck.KeyCheckForm.ProgressiveRBtn.Caption := 'Прогрессивный';
KeyCheck.KeyCheckForm.SelfGeneratedRBtn.Caption := 'Самогенер-ся';
KeyCheck.KeyCheckForm.CancelBtn.Caption := 'Назад';
KeyCheck.KeyCheckForm.NextBtn.Caption := 'Шифровать';
KeyCheck.KeyCheckForm.CloseBtn.Caption := 'Закрыть';
Results.ResultsForm.SourceLbl.Caption := 'Исходный текст';
Results.ResultsForm.EncipheredLbl.Caption := 'Шифротекст';
Results.ResultsForm.DecipheredLbl.Caption := 'Расшифровка';
Results.ResultsForm.EncipherButton.Caption := 'Шифровать';
Results.ResultsForm.DecipherButton.Caption := 'Дешифровать';
Results.ResultsForm.ClearButton.Caption := 'Очистить';
Results.ResultsForm.KasiskiButton.Caption := 'Касиски';
Results.ResultsForm.BackButton.Caption := 'Назад';
Results.ResultsForm.CloseButton.Caption := 'Закрыть';
language := russian;
end;
function TLanguageForm.GetLanguage : TLanguage;
begin
Result := self.language;
end;
procedure TLanguageForm.SetLanguage(const languageIsEnglish : Boolean);
begin
if languageIsEnglish then self.language := english
else self.language := russian;
end;
end.
|
unit frmOTDReason;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, Buttons, ExtCtrls, StdCtrls;
type
TOTDReasonForm = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
sbAdd: TSpeedButton;
sbEdit: TSpeedButton;
sbDelete: TSpeedButton;
sbSave: TSpeedButton;
edtFirstReason: TEdit;
edtSecondReason: TEdit;
edtThirdReason: TEdit;
edtFourReason: TEdit;
edtRemark: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
lvDetail: TListView;
procedure lvDetailChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure sbAddClick(Sender: TObject);
procedure sbEditClick(Sender: TObject);
procedure sbDeleteClick(Sender: TObject);
procedure sbSaveClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
private
IsNew : Boolean;
{ Private declarations }
public
{ Public declarations }
end;
var
OTDReasonForm: TOTDReasonForm;
implementation
uses cxDropDownEdit, uDictionary, ServerDllPub, uGlobal, uLogin, UGridDecorator, uShowMessage, uFNMArtInfo, StrUtils;
{$R *.dfm}
procedure TOTDReasonForm.lvDetailChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
begin
if lvDetail.ItemIndex = -1 then Exit;
IsNew := False;
edtFirstReason.Enabled := False;
edtSecondReason.Enabled := False;
edtThirdReason.Enabled := False;
edtFourReason.Enabled := False;
edtRemark.Enabled := False;
sbAdd.Enabled := True;
sbEdit.Enabled := True;
sbDelete.Enabled := True;
sbSave.Enabled := False;
edtFirstReason.Text := lvDetail.Selected.SubItems[0];
edtSecondReason.Text := lvDetail.Selected.SubItems[1];
edtThirdReason.Text := lvDetail.Selected.SubItems[2];
edtFourReason.Text := lvDetail.Selected.SubItems[3];
edtRemark.Text := lvDetail.Selected.SubItems[4];
end;
procedure TOTDReasonForm.sbAddClick(Sender: TObject);
begin
IsNew := True;
edtFirstReason.Enabled := sbAdd.Caption = '新增';
edtSecondReason.Enabled := sbAdd.Caption = '新增';
edtThirdReason.Enabled := sbAdd.Caption = '新增';
edtFourReason.Enabled := sbAdd.Caption = '新增';
edtRemark.Enabled := sbAdd.Caption = '新增';
edtFirstReason.Clear;
edtSecondReason.Clear;
edtThirdReason.Clear;
edtFourReason.Clear;
edtRemark.Clear;
lvDetail.Enabled := sbAdd.Caption = '放弃';
sbEdit.Enabled := sbAdd.Caption = '放弃';
sbDelete.Enabled := sbAdd.Caption = '放弃';
sbSave.Enabled := sbAdd.Caption = '新增';
if sbAdd.Caption = '放弃' then
sbAdd.Caption := '新增'
else
sbAdd.Caption := '放弃';
end;
procedure TOTDReasonForm.sbEditClick(Sender: TObject);
begin
IsNew := False;
edtFirstReason.Enabled := sbEdit.Caption = '编辑';
edtSecondReason.Enabled := sbEdit.Caption = '编辑';
edtThirdReason.Enabled := sbEdit.Caption = '编辑';
edtFourReason.Enabled := sbEdit.Caption = '编辑';
edtRemark.Enabled := sbEdit.Caption = '编辑';
lvDetail.Enabled := sbEdit.Caption = '放弃';
sbAdd.Enabled := sbEdit.Caption = '放弃';
sbDelete.Enabled := sbEdit.Caption = '放弃';
sbSave.Enabled := sbEdit.Caption = '编辑';
if sbEdit.Caption = '放弃' then
sbEdit.Caption := '编辑'
else
sbEdit.Caption := '放弃';
end;
procedure TOTDReasonForm.sbDeleteClick(Sender: TObject);
var
vData: OleVariant;
sErrorMsg: WideString;
begin
if lvDetail.SelCount = 0 then Exit;
if MessageDlg('你确认要删除此条回修原因明细记录吗?', mtConfirmation, [mbYes, mbNo], 0) = mrNo then Exit;
try
TStatusBarMessage.ShowMessageOnMainStatsusBar('正在删除数据稍等!', crHourGlass);
vData := VarArrayCreate([0, 1], VarVariant);
vData[0] := varArrayOf([lvDetail.Selected.Caption]);
FNMServerObj.SaveOTDReason(vData,2,sErrorMsg);
if sErrorMsg <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrorMsg,mtError);
Exit;
end;
lvDetail.DeleteSelected;
TMsgDialog.ShowMsgDialog('删除数据成功',mtInformation);
finally
TStatusBarMessage.ShowMessageOnMainStatsusBar('', crDefault);
end;
end;
procedure TOTDReasonForm.sbSaveClick(Sender: TObject);
var
vData: OleVariant;
sErrorMsg: WideString;
iType : Integer;
begin
vData := VarArrayCreate([0, 1], VarVariant);
if IsNew then
begin
iType := 0;
vData[0] := varArrayOf(['0',
edtFirstReason.Text,
edtSecondReason.Text,
edtThirdReason.Text,
edtFourReason.Text,
edtRemark.Text,
Login.LoginName]);
end else
begin
iType := 1;
vData[0] := varArrayOf([lvDetail.Selected.Caption,
edtFirstReason.Text,
edtSecondReason.Text,
edtThirdReason.Text,
edtFourReason.Text,
edtRemark.Text,
Login.LoginName]);
end;
FNMServerObj.SaveOTDReason(vData,iType,sErrorMsg);
if sErrorMsg <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrorMsg,mtError);
Exit;
end;
if IsNew then
begin
with lvDetail.Items.Add do
begin
Caption := '0';
SubItems.Add(edtFirstReason.Text);
SubItems.Add(edtSecondReason.Text);
SubItems.Add(edtThirdReason.Text);
SubItems.Add(edtFourReason.Text);
SubItems.Add(edtRemark.Text);
end;
end else
begin
with lvDetail.Selected do
begin
SubItems[0] := edtFirstReason.Text;
SubItems[1] := edtSecondReason.Text;
SubItems[2] := edtThirdReason.Text;
SubItems[3] := edtFourReason.Text;
SubItems[4] := edtRemark.Text;
end;
end;
edtFirstReason.Enabled := False;
edtSecondReason.Enabled := False;
edtThirdReason.Enabled := False;
edtFourReason.Enabled := False;
edtRemark.Enabled := False;
sbAdd.Caption := '新增';
sbAdd.Enabled := True;
sbEdit.Caption := '编辑';
sbEdit.Enabled := True;
sbDelete.Enabled := True;
lvDetail.Enabled := True;
sbSave.Enabled := False;
TMsgDialog.ShowMsgDialog('保存数据成功', mtInformation);
end;
procedure TOTDReasonForm.FormActivate(Sender: TObject);
begin
with Dictionary.cds_OTDReasonList do
begin
Filtered := False;
First;
while not Eof do
begin
with lvDetail.Items.Add do
begin
Caption := FieldByName('Iden').AsString;
SubItems.Add(FieldByName('First_Reason').AsString);
SubItems.Add(FieldByName('Second_Reason').AsString);
SubItems.Add(FieldByName('Third_Reason').AsString);
SubItems.Add(FieldByName('Four_Reason').AsString);
SubItems.Add(FieldByName('Remark').AsString);
end;
Next;
end;
end;
edtFirstReason.Enabled := False;
edtSecondReason.Enabled := False;
edtThirdReason.Enabled := False;
edtFourReason.Enabled := False;
edtRemark.Enabled := False;
sbSave.Enabled := False;
end;
procedure TOTDReasonForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TOTDReasonForm.FormDestroy(Sender: TObject);
begin
OTDReasonForm := nil;
end;
end.
|
unit abBackupWizard;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, abWizardTemplate, ComCtrls, StdCtrls, ExtCtrls,
CommCtrl, ImgList, nsGlobals, nsTypes, ShellAPI, ActnList, Menus,
nsProcessFrm, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnPopup;
type
TTreeView = class(ComCtrls.TTreeView)
private
procedure UpdateNodeState(const ANode: TTreeNode);
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: integer); override;
procedure KeyDown(var Key: word; Shift: TShiftState); override;
end;
TfrmBackupWizard = class(TfrmWizardTemplate)
ts1: TTabSheet;
ts2: TTabSheet;
ts4: TTabSheet;
Panel3: TPanel;
Label34: TLabel;
Label35: TLabel;
tvBackup: TTreeView;
imlStateImages: TImageList;
imlSys16: TImageList;
btnAddFolder: TButton;
btnAddFiles: TButton;
btnDelete: TButton;
OpenDialog: TOpenDialog;
acContext: TActionList;
acDelete: TAction;
acCheckAll: TAction;
acUncheckAll: TAction;
pnlScan: TPanel;
Label1: TLabel;
pbxFileName: TLabel;
Label9: TLabel;
Label10: TLabel;
aniProgress: TAnimate;
chkProcessImmediately: TCheckBox;
Panel5: TPanel;
lblContains: TLabel;
Label2: TLabel;
Label4: TLabel;
ts3: TTabSheet;
Panel1: TPanel;
Label7: TLabel;
Label8: TLabel;
pnlProcess: TPanel;
pmContext: TPopupActionBar;
CheckAll2: TMenuItem;
UncheckAll2: TMenuItem;
Delete2: TMenuItem;
N2: TMenuItem;
procedure FormShow(Sender: TObject);
procedure btnAddFolderClick(Sender: TObject);
procedure tvBackupGetImageIndex(Sender: TObject; Node: TTreeNode);
procedure btnAddFilesClick(Sender: TObject);
procedure acDeleteExecute(Sender: TObject);
procedure acCheckAllExecute(Sender: TObject);
procedure acUncheckAllExecute(Sender: TObject);
procedure PopupMenu1Popup(Sender: TObject);
procedure tvBackupExpanding(Sender: TObject; Node: TTreeNode; var AllowExpansion: Boolean);
procedure FormCreate(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
private
{ Private declarations }
FProject: TNSProject;
FOldProcess: TfrmProcess;
FIntProcess: TfrmProcess;
FNumberOfProcessed: integer;
procedure ScanDir(const ADirectory: string; const AParentNode: TTreeNode);
procedure AddFolder(const AName: string);
procedure AddFiles(const AFileList: TStrings);
procedure AddFile(const AFileName: string);
function GetFullPath(const ANode: TTreeNode): string;
function NodeExists(const APath: string): Boolean;
function DoScan: Boolean;
function DoBackup: Boolean;
function DoFinish: Boolean;
procedure SetCurFile(const Value: string);
protected
procedure UpdateActions; override;
function GoForward: integer; override;
function GoBack: integer; override;
public
{ Public declarations }
property CurFile: string write SetCurFile;
end;
var
frmBackupWizard: TfrmBackupWizard;
function BackupWizard(const AProject: TNSProject; const AList: TStrings): Boolean;
implementation
uses
nsUtils,
nsActions;
{$R *.dfm}
const
NSI_UNCHECKED = 1;
NSI_CHECKED = 2;
NSI_UNDEFINED = 3;
function BackupWizard(const AProject: TNSProject; const AList: TStrings): Boolean;
var
I: integer;
begin
frmBackupWizard := TfrmBackupWizard.Create(Application);
with frmBackupWizard do
try
FProject := AProject;
if AList <> nil then
begin
for I := 0 to AList.Count - 1 do
begin
if DirectoryExists(AList[I]) then
AddFolder(AList[I])
else if FileExists(AList[I]) then
AddFile(AList[I]);
end;
if tvBackup.Items.Count = 0 then
begin
MessageBox(GetActiveWindow, PChar(sNoValidItems), PChar(Application.Title), MB_ICONINFORMATION or MB_OK);
Result := False;
Exit;
end;
end;
if FProject <> nil then
begin
FOldProcess := FProject.FProgress;
FProject.FProgress := FIntProcess;
end;
Result := ShowModal = mrOk;
finally
if FProject <> nil then
FProject.FProgress := FOldProcess;
Free;
end;
end;
{ TTreeView }
procedure TTreeView.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
// Params.Style := Params.Style or TVS_CHECKBOXES;
end;
procedure TfrmBackupWizard.acCheckAllExecute(Sender: TObject);
var
Node: TTreeNode;
begin
Node := tvBackup.Items.GetFirstNode;
while Node <> nil do
begin
Node.StateIndex := NSI_CHECKED;
Node := Node.GetNext;
end;
end;
procedure TfrmBackupWizard.acDeleteExecute(Sender: TObject);
begin
if tvBackup.Selected = nil then
Exit;
tvBackup.Items.Delete(tvBackup.Selected);
end;
procedure TfrmBackupWizard.acUncheckAllExecute(Sender: TObject);
var
Node: TTreeNode;
begin
Node := tvBackup.Items.GetFirstNode;
while Node <> nil do
begin
Node.StateIndex := NSI_UNCHECKED;
Node := Node.GetNext;
end;
end;
procedure TfrmBackupWizard.AddFile(const AFileName: string);
var
Node: TTreeNode;
begin
tvBackup.Items.BeginUpdate;
try
if NodeExists(AFileName) then
Exit;
if (FProject <> nil) and not FProject.IsValidExt(AFileName) then
Exit;
Node := tvBackup.Items.AddChildObject(nil, AFileName, nil);
Node.StateIndex := NSI_CHECKED;
finally
tvBackup.Items.EndUpdate;
end;
end;
procedure TfrmBackupWizard.AddFiles(const AFileList: TStrings);
var
I: integer;
sName: string;
Node: TTreeNode;
begin
tvBackup.Items.BeginUpdate;
try
for I := 0 to AFileList.Count - 1 do
begin
sName := AFileList[I];
if NodeExists(sName) then
Continue;
if (FProject <> nil) and not FProject.IsValidExt(sName) then
Continue;
Node := tvBackup.Items.AddChildObject(nil, sName, nil);
Node.StateIndex := NSI_CHECKED;
end;
finally
tvBackup.Items.EndUpdate;
end;
end;
procedure TfrmBackupWizard.AddFolder(const AName: string);
var
RootNode: TTreeNode;
begin
tvBackup.Items.BeginUpdate;
try
if NodeExists(AName) then
Exit;
RootNode := tvBackup.Items.AddChildObject(nil, AName, Pointer(1));
RootNode.StateIndex := NSI_CHECKED;
ScanDir(AName, RootNode);
finally
tvBackup.Items.EndUpdate;
end;
end;
procedure TfrmBackupWizard.btnAddFolderClick(Sender: TObject);
var
sFolder: String;
begin
if SelectDir(sAddFolderToProject, sFolder) then
AddFolder(sFolder);
end;
procedure TfrmBackupWizard.btnCancelClick(Sender: TObject);
begin
if PageControl.ActivePageIndex in [1, 2] then
begin
ModalResult := mrNone;
g_AbortScan := True;
g_AbortProcess := True;
Application.ProcessMessages;
end;
end;
function TfrmBackupWizard.DoBackup: Boolean;
begin
Result := False;
if g_AbortScan or g_AbortProcess then
Exit;
PageControl.ActivePageIndex := 2;
UpdateActions;
Self.Update;
Application.ProcessMessages;
CurProject.ExecuteExternal(True);
FNumberOfProcessed := ProcessProject(CurProject, csBackup);
CurProject.ExecuteExternal(False);
Result := DoFinish;
end;
function TfrmBackupWizard.DoFinish: Boolean;
begin
UpdateActions;
lblContains.Caption := Format(sFilesProcessed, [FNumberOfProcessed]);
lblContains.Visible := chkProcessImmediately.Checked;
PageControl.ActivePageIndex := 3;
Self.Update;
Result := True;
end;
function TfrmBackupWizard.DoScan: Boolean;
var
st: TStringList;
Node: TTreeNode;
begin
Result := False;
g_AbortScan := False;
g_AbortProcess := False;
AniProgress.Active := True;
PageControl.ActivePageIndex := 1;
Application.ProcessMessages;
try
st := TStringList.Create;
tvBackup.Items.BeginUpdate;
try
Node := tvBackup.Items.GetFirstNode;
while Node <> nil do
begin
if Node.StateIndex = NSI_CHECKED then
st.Add(GetFullPath(Node));
Node := Node.GetNext;
end;
UpdateActions;
if g_AbortScan or g_AbortProcess then
Abort;
InsertItemsToProject(FProject, st, nil, 2);
if g_AbortScan or g_AbortProcess then
Abort;
UpdateActions;
Application.ProcessMessages;
if g_AbortScan or g_AbortProcess then
Abort;
if chkProcessImmediately.Checked then
DoBackup
else
DoFinish;
finally
st.Free;
tvBackup.Items.EndUpdate;
AniProgress.Active := False;
Result := True;
end;
except
PageControl.ActivePageIndex := 0;
Application.ProcessMessages;
UpdateActions;
end;
end;
procedure TfrmBackupWizard.btnAddFilesClick(Sender: TObject);
begin
if OpenDialog.Execute then
AddFiles(OpenDialog.Files);
end;
procedure TfrmBackupWizard.FormCreate(Sender: TObject);
begin
inherited;
aniProgress.ResName := AVI_PROCESS;
aniProgress.ResHandle := hInstance;
aniProgress.Active := False;
pnlScan.DoubleBuffered := True;
FIntProcess := TfrmProcess.Create(Self);
with FIntProcess do
begin
Color := clWhite;
Parent := pnlProcess;
BorderStyle := bsNone;
Align := alClient;
pnlBottom.Visible := False;
Visible := True;
end;
end;
procedure TfrmBackupWizard.FormShow(Sender: TObject);
begin
inherited;
imlSys16.Handle := g_himlSysSmall;
end;
function TfrmBackupWizard.GetFullPath(const ANode: TTreeNode): string;
var
Node: TTreeNode;
begin
Result := EmptyStr;
Node := ANode;
while Node <> nil do
begin
Result := Node.Text + sBackslash + Result;
Node := Node.Parent;
end;
Result := ExcludeTrailingPathDelimiter(Result);
end;
function TfrmBackupWizard.GoBack: integer;
begin
case PageControl.ActivePageIndex of
2: Result := 2;
3: Result := 3;
else
Result := 1;
end;
end;
function TfrmBackupWizard.GoForward: integer;
begin
Result := 0;
case PageControl.ActivePageIndex of
0:
begin
DoScan;
end;
end;
end;
function TfrmBackupWizard.NodeExists(const APath: string): Boolean;
var
Node: TTreeNode;
begin
Node := tvBackup.Items.GetFirstNode;
while Node <> nil do
begin
if SameFileName(GetFullPath(Node), APath) then
begin
tvBackup.Selected := Node;
Result := True;
Exit;
end;
Node := Node.GetNext;
end;
Result := False;
end;
procedure TfrmBackupWizard.PopupMenu1Popup(Sender: TObject);
begin
UpdateActions;
end;
procedure TfrmBackupWizard.ScanDir(const ADirectory: string; const AParentNode: TTreeNode);
var
SR: TSearchRec;
Node: TTreeNode;
begin
AParentNode.DeleteChildren;
FillChar(SR, SizeOf(TSearchRec), #0);
if FindFirst(IncludeTrailingPathDelimiter(ADirectory) + sFileMask, faAnyFile, SR) <> ERROR_SUCCESS then
Exit;
repeat
if (SR.Name = sDot) or (SR.Name = sDoubleDot) then
Continue;
if (SR.Attr and faDirectory = 0) then
begin
if (FProject <> nil) and not FProject.IsValidExt(SR.Name) then
Continue;
Node := tvBackup.Items.AddChildObject(AParentNode, SR.Name, nil);
Node.StateIndex := AParentNode.StateIndex;
end
else
begin
Node := tvBackup.Items.AddChildObject(AParentNode, SR.Name, Pointer(1));
Node.StateIndex := AParentNode.StateIndex;
tvBackup.Items.AddChildFirst(Node, EmptyStr);
// ScanDir(IncludeTrailingBackslash(ADirectory) + SR.Name, Node);
end;
until FindNext(SR) <> ERROR_SUCCESS;
FindClose(SR);
end;
procedure TfrmBackupWizard.SetCurFile(const Value: string);
begin
pbxFileName.Caption := Value;
end;
procedure TfrmBackupWizard.tvBackupExpanding(Sender: TObject; Node: TTreeNode; var AllowExpansion: Boolean);
begin
ScanDir(GetFullPath(Node), Node);
end;
procedure TfrmBackupWizard.tvBackupGetImageIndex(Sender: TObject; Node: TTreeNode);
var
FileInfo: TSHFileInfo;
pszName: PChar;
begin
pszName := PChar(Node.Text);
if Node.Data <> nil then
SHGetFileInfo(pszName, FILE_ATTRIBUTE_DIRECTORY, FileInfo, SizeOf(FileInfo), SHGFI_SMALLICON or
SHGFI_SYSICONINDEX or SHGFI_USEFILEATTRIBUTES)
else
SHGetFileInfo(pszName, FILE_ATTRIBUTE_NORMAL, FileInfo, SizeOf(FileInfo), SHGFI_SMALLICON or
SHGFI_SYSICONINDEX or SHGFI_USEFILEATTRIBUTES);
Node.ImageIndex := FileInfo.iIcon;
Node.SelectedIndex := FileInfo.iIcon;
end;
procedure TfrmBackupWizard.UpdateActions;
begin
inherited;
case PageControl.ActivePageIndex of
0:
begin
acDelete.Enabled := tvBackup.Selected <> nil;
acCheckAll.Enabled := tvBackup.Items.Count > 0;
acUncheckAll.Enabled := tvBackup.Items.Count > 0;
btnNext.Enabled := acUncheckAll.Enabled;
end;
1, 2:
begin
btnBack.Enabled := False;
btnNext.Enabled := False;
end;
3:
begin
btnBack.Enabled := True;
btnNext.Enabled := True;
end;
end;
end;
procedure TTreeView.KeyDown(var Key: word; Shift: TShiftState);
var
Node: TTreeNode;
begin
if (Key = VK_SPACE) and (Selected <> nil) then
begin
Node := Selected;
if Node.StateIndex = NSI_UNCHECKED then
Node.StateIndex := NSI_CHECKED
else
Node.StateIndex := NSI_UNCHECKED;
UpdateNodeState(Node);
end
else
inherited;
end;
procedure TTreeView.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: integer);
var
Node: TTreeNode;
begin
if (Button = mbLeft) and (htOnStateIcon in GetHitTestInfoAt(X, Y)) then
begin
Node := GetNodeAt(X, Y);
if Node.StateIndex = NSI_UNCHECKED then
Node.StateIndex := NSI_CHECKED
else
Node.StateIndex := NSI_UNCHECKED;
UpdateNodeState(Node);
end
else
inherited;
end;
procedure TTreeView.UpdateNodeState(const ANode: TTreeNode);
procedure UpdateChildren(const ANode: TTreeNode);
var
Node: TTreeNode;
begin
Node := ANode.GetFirstChild;
while Node <> nil do
begin
Node.StateIndex := ANode.StateIndex;
if Node.HasChildren then
UpdateChildren(Node);
Node := Node.getNextSibling;
end;
end;
procedure UpdateParent(const ANode: TTreeNode);
var
Parent: TTreeNode;
Node: TTreeNode;
Flag: Boolean;
begin
Parent := ANode.Parent;
if Parent = nil then
Exit;
Flag := True;
Node := Parent.GetFirstChild;
while (Node <> nil) and Flag do
begin
Flag := Flag and (ANode.StateIndex = Node.StateIndex);
Node := Node.getNextSibling;
end;
if Flag then
Parent.StateIndex := ANode.StateIndex
else
Parent.StateIndex := NSI_UNDEFINED;
UpdateParent(Parent);
end;
begin
UpdateChildren(ANode);
UpdateParent(ANode);
end;
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: LocalDeformablePRTunit.pas,v 1.10 2007/02/05 22:21:09 clootie Exp $
*----------------------------------------------------------------------------*)
//--------------------------------------------------------------------------------------
// File: LocalDeformablePRT.cpp
//
// Desc: This sample demonstrates a simple usage of Local-deformable precomputed
// radiance transfer (LDPRT). This implementation does not require an offline
// simulator for calulcating PRT coefficients; instead, the coefficients are
// calculated from a 'thickness' texture. This allows an artist to create and
// tweak sub-surface scattering PRT data in an intuitive way.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
{$I DirectX.inc}
{$B-}
unit LocalDeformablePRTunit;
interface
uses
Windows, SysUtils, Math,
DXTypes, Direct3D9, D3DX9, dxerr9, StrSafe,
DXUT, DXUTcore, DXUTenum, DXUTmisc, DXUTgui, DXUTSettingsDlg,
Skybox, SkinMesh;
{.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders
{.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
var
g_pFont: ID3DXFont; // Font for drawing text
g_pTextSprite: ID3DXSprite; // Sprite for batching draw text calls
g_pEffect: ID3DXEffect; // D3DX effect interface
g_Camera: CModelViewerCamera; // A model viewing camera
g_bShowHelp: Boolean = True; // If true, it renders the UI control text
g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs
g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog
g_HUD: CDXUTDialog; // dialog for standard controls
g_SampleUI: CDXUTDialog; // dialog for sample specific controls
g_bWireFrame: Boolean;
g_fmtCubeMap: TD3DFormat = D3DFMT_UNKNOWN;
g_fmtTexture: TD3DFormat = D3DFMT_UNKNOWN;
g_Skybox: CSkybox;
// Skinning
g_pFrameRoot: PD3DXFrame = nil;
g_pAnimController: ID3DXAnimationController;
// Lights
g_LightControl: CDXUTDirectionWidget;
g_vLightDirection: TD3DXVector3;
g_fLightIntensity: Single;
g_fEnvIntensity: Single;
g_fSkyBoxLightSH: array[0..2, 0..D3DXSH_MAXORDER*D3DXSH_MAXORDER-1] of Single;
m_fRLC: array[0..D3DXSH_MAXORDER*D3DXSH_MAXORDER-1] of Single;
m_fGLC: array[0..D3DXSH_MAXORDER*D3DXSH_MAXORDER-1] of Single;
m_fBLC: array[0..D3DXSH_MAXORDER*D3DXSH_MAXORDER-1] of Single;
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
const
IDC_TOGGLEFULLSCREEN = 1;
IDC_TOGGLEREF = 2;
IDC_CHANGEDEVICE = 3;
IDC_TECHNIQUE = 4;
IDC_RED_TRANSMIT_SLIDER = 5;
IDC_GREEN_TRANSMIT_SLIDER = 6;
IDC_BLUE_TRANSMIT_SLIDER = 7;
IDC_RED_TRANSMIT_LABEL = 8;
IDC_GREEN_TRANSMIT_LABEL = 9;
IDC_BLUE_TRANSMIT_LABEL = 10;
IDC_LIGHT_SLIDER = 11;
IDC_ENV_SLIDER = 12;
IDC_ENV_LABEL = 13;
IDC_ANIMATION_SPEED = 14;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
procedure OnLostDevice(pUserContext: Pointer); stdcall;
procedure OnDestroyDevice(pUserContext: Pointer); stdcall;
procedure InitApp;
procedure GetSupportedTextureFormat(const pD3D: IDirect3D9; const pCaps: TD3DCaps9;
AdapterFormat: TD3DFormat; out fmtTexture: TD3DFormat; out fmtCubeMap: TD3DFormat);
function LoadLDPRTData(const pd3dDevice: IDirect3DDevice9; strFilePrefixIn: PWideChar): HRESULT;
procedure SHCubeFill(out pOut: TD3DXVector4; const pTexCoord, pTexelSize: TD3DXVector3; var pData); stdcall;
function LoadTechniqueObjects(const szMedia: PChar): HRESULT;
procedure UpdateLightingEnvironment;
procedure DrawFrame(const pd3dDevice: IDirect3DDevice9; pFrame: PD3DXFrame);
procedure DrawMeshContainer(const pd3dDevice: IDirect3DDevice9; pMeshContainerBase: PD3DXMeshContainer; pFrameBase: PD3DXFrame);
procedure RenderText;
procedure CreateCustomDXUTobjects;
procedure DestroyCustomDXUTobjects;
implementation
type
PSingleArray = ^TSingleArray;
TSingleArray = Array[0..MaxInt div Sizeof(Single)-1] of Single;
//--------------------------------------------------------------------------------------
// struct SHCubeProj
// Used to generate lighting coefficients to match the skybox's light probe
//--------------------------------------------------------------------------------------
type
PSHCubeProj = ^TSHCubeProj;
TSHCubeProj = record
pRed, pGreen, pBlue: PSingle;
iOrderUse: Integer; // order to use
fConvCoeffs: array[0..5] of Single; // convolution coefficients
end;
procedure TSHCubeProj_InitDiffCubeMap(var _: TSHCubeProj; pR, pG, pB: PSingle);
begin
_.pRed := pR;
_.pGreen := pG;
_.pBlue := pB;
_.iOrderUse := 3; // go to 5 is a bit more accurate...
_.fConvCoeffs[0] := 1.0;
_.fConvCoeffs[1] := 2.0/3.0;
_.fConvCoeffs[2] := 1.0/4.0;
_.fConvCoeffs[3] := 0.0;
_.fConvCoeffs[4] := -6.0/144.0; //
_.fConvCoeffs[5] := 0.0;
end;
procedure TSHCubeProj_Init(var _: TSHCubeProj; pR, pG, pB: PSingle);
var
i: Integer;
begin
_.pRed := pR;
_.pGreen := pG;
_.pBlue := pB;
_.iOrderUse := 6;
for i := 0 to 5 do _.fConvCoeffs[i] := 1.0;
end;
const
cLDPRT: PChar = 'LDPRT';
cNdotL: PChar = 'NdotL';
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
procedure InitApp;
var
iX, iY: Integer;
pElement: CDXUTElement;
begin
//g_LightControl.SetLightDirection( D3DXVECTOR3(-0.29f, 0.557f, 0.778f));
g_LightControl.SetLightDirection(D3DXVector3(-0.789, 0.527, 0.316));
g_LightControl.SetButtonMask(MOUSE_MIDDLE_BUTTON);
// Initialize dialogs
g_SettingsDlg.Init(g_DialogResourceManager);
g_HUD.Init(g_DialogResourceManager);
g_SampleUI.Init(g_DialogResourceManager);
g_HUD.SetCallback(OnGUIEvent); iX := 15;
iY := 10; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', iX, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', iX, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', iX, iY, 125, 22, VK_F2);
g_SampleUI.SetCallback(OnGUIEvent);
iX := 15; iY := 10;
// Title font for static
g_SampleUI.SetFont(1, 'Arial', 14, FW_NORMAL);
pElement := g_SampleUI.GetDefaultElement(DXUT_CONTROL_STATIC, 0);
if Assigned(pElement) then
begin
pElement.iFont := 1;
pElement.dwTextFormat := DT_RIGHT or DT_VCENTER;
end;
// Technique
Inc(iY, 24);
g_SampleUI.AddStatic(-1, 'Technique', iX, iY, 115, 22);
g_SampleUI.AddComboBox(IDC_TECHNIQUE, iX + 125, iY, 150, 22);
g_SampleUI.GetComboBox(IDC_TECHNIQUE).SetScrollBarWidth(0);
g_SampleUI.GetComboBox(IDC_TECHNIQUE).AddItem('Local-deformable PRT', cLDPRT);
g_SampleUI.GetComboBox(IDC_TECHNIQUE).AddItem('N dot L lighting', cNdotL);
// Animation speed
Inc(iY, 10);
Inc(iY, 24);
g_SampleUI.AddStatic(-1, 'Animation Speed', iX, iY, 115, 22);
g_SampleUI.AddSlider(IDC_ANIMATION_SPEED, iX + 125, iY, 125, 22, 0, 3000, 700);
// Light intensity
Inc(iY, 10);
Inc(iY, 24);
g_SampleUI.AddStatic(-1, 'Light Intensity', iX, iY, 115, 22);
g_SampleUI.AddSlider(IDC_LIGHT_SLIDER, iX + 125, iY, 125, 22, 0, 1000, 500);
Inc(iY, 24);
g_SampleUI.AddStatic(IDC_ENV_LABEL, 'Env Intensity', iX, iY, 115, 22);
g_SampleUI.AddSlider(IDC_ENV_SLIDER, iX + 125, iY, 125, 22, 0, 3000, 600);
// Color transmission
Inc(iY, 10);
Inc(iY, 24);
g_SampleUI.AddStatic(IDC_RED_TRANSMIT_LABEL, 'Transmit Red', iX, iY, 115, 22);
g_SampleUI.AddSlider(IDC_RED_TRANSMIT_SLIDER, iX + 125, iY, 125, 22, 0, 3000, 1200);
Inc(iY, 24);
g_SampleUI.AddStatic(IDC_GREEN_TRANSMIT_LABEL, 'Transmit Green', iX, iY, 115, 22);
g_SampleUI.AddSlider(IDC_GREEN_TRANSMIT_SLIDER, iX + 125, iY, 125, 22, 0, 3000, 800);
Inc(iY, 24);
g_SampleUI.AddStatic(IDC_BLUE_TRANSMIT_LABEL, 'Transmit Blue', iX, iY, 115, 22);
g_SampleUI.AddSlider(IDC_BLUE_TRANSMIT_SLIDER, iX + 125, iY, 125, 22, 0, 3000, 350);
end;
//--------------------------------------------------------------------------------------
// Called during device initialization, this code checks the device for some
// minimum set of capabilities, and rejects those that don't pass by returning false.
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
var
pD3D: IDirect3D9;
fmtTexture, fmtCubeMap: TD3DFormat;
begin
Result := False;
// Skip backbuffer formats that don't support alpha blending
pD3D := DXUTGetD3DObject;
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat))
then Exit;
// Determine texture support. Fail if not good enough
GetSupportedTextureFormat(pD3D, pCaps, AdapterFormat, fmtTexture, fmtCubeMap);
if (D3DFMT_UNKNOWN = fmtTexture) or (D3DFMT_UNKNOWN = fmtCubeMap) then Exit;
// This sample requires pixel shader 2.0, but does showcase techniques which will
// perform well on shader model 1.1 hardware.
if (pCaps.PixelShaderVersion < D3DPS_VERSION(2,0)) then Exit;
Result := True;
end;
//--------------------------------------------------------------------------------------
procedure GetSupportedTextureFormat(const pD3D: IDirect3D9; const pCaps: TD3DCaps9;
AdapterFormat: TD3DFormat; out fmtTexture: TD3DFormat; out fmtCubeMap: TD3DFormat);
begin
fmtTexture := D3DFMT_UNKNOWN;
fmtCubeMap := D3DFMT_UNKNOWN;
// check for linear filtering support of signed formats
fmtTexture := D3DFMT_UNKNOWN;
if SUCCEEDED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,AdapterFormat,D3DUSAGE_QUERY_FILTER,D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F))
then fmtTexture := D3DFMT_A16B16G16R16F
else if SUCCEEDED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,AdapterFormat,D3DUSAGE_QUERY_FILTER,D3DRTYPE_TEXTURE, D3DFMT_Q16W16V16U16))
then fmtTexture := D3DFMT_Q16W16V16U16
else if SUCCEEDED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType, AdapterFormat,D3DUSAGE_QUERY_FILTER,D3DRTYPE_TEXTURE, D3DFMT_Q8W8V8U8))
then fmtTexture := D3DFMT_Q8W8V8U8
// no support for linear filtering of signed, just checking for format support now
else if SUCCEEDED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType, AdapterFormat, 0, D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F))
then fmtTexture := D3DFMT_A16B16G16R16F
else if SUCCEEDED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType, AdapterFormat, 0, D3DRTYPE_TEXTURE, D3DFMT_Q16W16V16U16))
then fmtTexture := D3DFMT_Q16W16V16U16
else if SUCCEEDED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType, AdapterFormat, 0, D3DRTYPE_TEXTURE, D3DFMT_Q8W8V8U8))
then fmtTexture := D3DFMT_Q8W8V8U8;
// check for support linear filtering of signed format cubemaps
fmtCubeMap := D3DFMT_UNKNOWN;
if SUCCEEDED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,AdapterFormat,D3DUSAGE_QUERY_FILTER, D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F))
then fmtCubeMap := D3DFMT_A16B16G16R16F
else if SUCCEEDED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,AdapterFormat,D3DUSAGE_QUERY_FILTER,D3DRTYPE_CUBETEXTURE, D3DFMT_Q16W16V16U16))
then fmtCubeMap := D3DFMT_Q16W16V16U16
else if SUCCEEDED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,AdapterFormat,D3DUSAGE_QUERY_FILTER,D3DRTYPE_CUBETEXTURE, D3DFMT_Q8W8V8U8))
then fmtCubeMap := D3DFMT_Q8W8V8U8
// no support for linear filtering of signed formats, just checking for format support now
else if SUCCEEDED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,AdapterFormat, 0,D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F))
then fmtCubeMap := D3DFMT_A16B16G16R16F
else if SUCCEEDED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,AdapterFormat, 0,D3DRTYPE_CUBETEXTURE, D3DFMT_Q16W16V16U16))
then fmtCubeMap := D3DFMT_Q16W16V16U16
else if SUCCEEDED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,AdapterFormat, 0,D3DRTYPE_CUBETEXTURE, D3DFMT_Q8W8V8U8))
then fmtCubeMap := D3DFMT_Q8W8V8U8;
end;
//--------------------------------------------------------------------------------------
// This callback function is called immediately before a device is created to allow the
// application to modify the device settings. The supplied pDeviceSettings parameter
// contains the settings that the framework has selected for the new device, and the
// application can make any desired changes directly to this structure. Note however that
// DXUT will not correct invalid device settings so care must be taken
// to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail.
//--------------------------------------------------------------------------------------
{static} var s_bFirstTime: Boolean = True;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
begin
// Turn vsync off
pDeviceSettings.pp.PresentationInterval := D3DPRESENT_INTERVAL_IMMEDIATE;
g_SettingsDlg.DialogControl.GetComboBox(DXUTSETTINGSDLG_PRESENT_INTERVAL).Enabled := False;
// If device doesn't support HW T&L or doesn't support 2.0 vertex shaders in HW
// then switch to SWVP.
if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or
(pCaps.VertexShaderVersion < D3DVS_VERSION(2,0))
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// Debugging vertex shaders requires either REF or software vertex processing
// and debugging pixel shaders requires REF.
{$IFDEF DEBUG_VS}
if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then
with pDeviceSettings do
begin
BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING;
BehaviorFlags := BehaviorFlags and not D3DCREATE_MIXED_VERTEXPROCESSING;
BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE;
BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING;
end;
{$ENDIF}
{$IFDEF DEBUG_PS}
pDeviceSettings.DeviceType := D3DDEVTYPE_REF;
{$ENDIF}
if (pCaps.MaxVertexBlendMatrices < 2)
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// For the first device created if its a REF device, optionally display a warning dialog box
if s_bFirstTime then
begin
s_bFirstTime := False;
if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning;
end;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// created, which will happen during application initialization and windowed/full screen
// toggles. This is the best location to create D3DPOOL_MANAGED resources since these
// resources need to be reloaded whenever the device is destroyed. Resources created
// here should be released in the OnDestroyDevice callback.
//--------------------------------------------------------------------------------------
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
dwShaderFlags: DWORD;
pD3D: IDirect3D9;
Caps: TD3DCaps9;
DisplayMode: D3DDISPLAYMODE;
pSHCubeTex: IDirect3DCubeTexture9;
projData: TSHCubeProj;
str: array[0..MAX_PATH-1] of WideChar;
vecEye: TD3DXVector3;
vecAt: TD3DXVector3;
quatRotation: TD3DXQuaternion;
begin
Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
// Initialize the font
Result := D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
'Arial', g_pFont);
if V_Failed(Result) then Exit;
// Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the
// shader debugger. Debugging vertex shaders requires either REF or software vertex
// processing, and debugging pixel shaders requires REF. The
// D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the
// shader debugger. It enables source level debugging, prevents instruction
// reordering, prevents dead code elimination, and forces the compiler to compile
// against the next higher available software target, which ensures that the
// unoptimized shaders do not exceed the shader model limitations. Setting these
// flags will cause slower rendering since the shaders will be unoptimized and
// forced into software. See the DirectX documentation for more information about
// using the shader debugger.
dwShaderFlags := D3DXFX_NOT_CLONEABLE;
{$IFDEF DEBUG}
// Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG;
{$ENDIF}
{$IFDEF DEBUG_VS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
{$ENDIF}
{$IFDEF DEBUG_PS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
{$ENDIF}
// Determine which LDPRT texture and SH coefficient cubemap formats are supported
pD3D := DXUTGetD3DObject;
pd3dDevice.GetDeviceCaps(Caps);
pd3dDevice.GetDisplayMode(0, DisplayMode);
GetSupportedTextureFormat(pD3D, Caps, DisplayMode.Format, g_fmtTexture, g_fmtCubeMap);
if (D3DFMT_UNKNOWN = g_fmtTexture) or (D3DFMT_UNKNOWN = g_fmtCubeMap) then
begin
Result:= E_FAIL;
Exit;
end;
// Create the skybox
g_Skybox.OnCreateDevice(pd3dDevice, 50, 'Light Probes\rnl_cross.dds', 'SkyBox.fx');
V(D3DXSHProjectCubeMap(6, g_Skybox.EnvironmentMap, @g_fSkyBoxLightSH[0], @g_fSkyBoxLightSH[1], @g_fSkyBoxLightSH[2]));
// Now compute the SH projection of the skybox...
V(D3DXCreateCubeTexture(pd3dDevice, 256, 1, 0, D3DFMT_A16B16G16R16F, D3DPOOL_MANAGED, pSHCubeTex));
TSHCubeProj_Init(projData, @g_fSkyBoxLightSH[0],@g_fSkyBoxLightSH[1],@g_fSkyBoxLightSH[2]);
V(D3DXFillCubeTexture(pSHCubeTex, SHCubeFill, @projData));
g_Skybox.InitSH(pSHCubeTex);
// Read the D3DX effect file
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'LocalDeformablePRT.fx');
if V_Failed(Result) then Exit;
// If this fails, there should be debug output as to they the .fx file failed to compile
Result:= D3DXCreateEffectFromFileW(pd3dDevice, str, nil, nil, dwShaderFlags, nil, g_pEffect, nil);
if V_Failed(Result) then Exit;
Result:= LoadTechniqueObjects('bat');
if V_Failed(Result) then Exit;
Result:= g_LightControl.StaticOnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
g_LightControl.Radius := 2.0;
// Setup the camera's view parameters
vecEye := D3DXVector3(0.0, 0.0, -5.0);
vecAt := D3DXVector3(0.0, 0.0, 0.0);
g_Camera.SetViewParams(vecEye, vecAt);
// Set the model's initial orientation
D3DXQuaternionRotationYawPitchRoll(quatRotation, -0.5, 0.7, 0.0);
g_Camera.SetWorldQuat(quatRotation);
end;
//--------------------------------------------------------------------------------------
procedure SHCubeFill(out pOut: TD3DXVector4; const pTexCoord, pTexelSize: TD3DXVector3; var pData); stdcall;
var
pCP: PSHCubeProj;
vDir: TD3DXVector3;
fVals: array[0..35] of Single;
l, m, uIndex: Integer;
fConvUse: Single;
begin
pCP := PSHCubeProj(@pData);
D3DXVec3Normalize(vDir, pTexCoord);
D3DXSHEvalDirection(@fVals, pCP.iOrderUse, vDir);
pOut := D3DXVector4(0,0,0,0); // just clear it out...
uIndex := 0;
for l := 0 to pCP.iOrderUse - 1 do
begin
fConvUse := pCP.fConvCoeffs[l];
for m := 0 to 2*l do
begin
pOut.x := pOut.x + fConvUse*fVals[uIndex]*PSingleArray(pCP.pRed)[uIndex];
pOut.y := pOut.y + fConvUse*fVals[uIndex]*PSingleArray(pCP.pGreen)[uIndex];
pOut.z := pOut.z + fConvUse*fVals[uIndex]*PSingleArray(pCP.pBlue)[uIndex];
pOut.w := 1;
Inc(uIndex);
end;
end;
end;
//--------------------------------------------------------------------------------------
procedure myFillBF(out pOut: TD3DXVector4; const pTexCoord, pTexelSize: TD3DXVector3; var pData); stdcall;
var
vDir: TD3DXVector3;
iBase: Integer;
fVals: array[0..15] of Single;
begin
iBase := INT_PTR(@pData);
D3DXVec3Normalize(vDir, pTexCoord);
D3DXSHEvalDirection(@fVals, 4, vDir);
pOut := D3DXVector4(fVals[iBase+0], fVals[iBase+1], fVals[iBase+2], fVals[iBase+3]);
end;
//--------------------------------------------------------------------------------------
// This function loads a new technique and all device objects it requires.
//--------------------------------------------------------------------------------------
function LoadTechniqueObjects(const szMedia: PChar): HRESULT;
const
pNames: array[0..3] of PChar = ('YlmCoeff0','YlmCoeff4','YlmCoeff8','YlmCoeff12');
var
pTexture: IDirect3DTexture9;
pCubeTexture: IDirect3DCubeTexture9;
pDevice: IDirect3DDevice9;
strFileName: array[0..MAX_PATH] of WideChar;
strPath: array[0..MAX_PATH] of WideChar;
strTechnique: array[0..MAX_PATH-1] of AnsiChar;
strComboTech: PAnsiChar;
hTechnique: TD3DXHandle;
bLDPRT: Boolean;
i: Integer;
begin
if (nil = g_pEffect) then
begin
Result:= D3DERR_INVALIDCALL;
Exit;
end;
pDevice := DXUTGetD3DDevice;
// Make sure the technique works
strComboTech := PAnsiChar(g_SampleUI.GetComboBox(IDC_TECHNIQUE).GetSelectedData);
StringCchCopy(strTechnique, MAX_PATH, strComboTech);
bLDPRT := {Assigned(strTechnique) and }(0 = lstrcmp(strTechnique, 'LDPRT'));
// If we're not a signed format, make sure we use a technnique that will unbias
if (D3DFMT_Q16W16V16U16 <> g_fmtTexture) and (D3DFMT_Q8W8V8U8 <> g_fmtTexture)
then StringCchCat(strTechnique, MAX_PATH, '_Unbias');
hTechnique := g_pEffect.GetTechniqueByName(strTechnique);
Result:= g_pEffect.SetTechnique(hTechnique);
if V_Failed(Result) then Exit;
// Enable/disable LDPRT-only items
g_SampleUI.GetStatic(IDC_ENV_LABEL).Enabled := bLDPRT;
g_SampleUI.GetSlider(IDC_ENV_SLIDER).Enabled := bLDPRT;
g_SampleUI.GetSlider(IDC_RED_TRANSMIT_SLIDER).Enabled := bLDPRT;
g_SampleUI.GetSlider(IDC_GREEN_TRANSMIT_SLIDER).Enabled := bLDPRT;
g_SampleUI.GetSlider(IDC_BLUE_TRANSMIT_SLIDER).Enabled := bLDPRT;
g_SampleUI.GetStatic(IDC_RED_TRANSMIT_LABEL).Enabled := bLDPRT;
g_SampleUI.GetStatic(IDC_GREEN_TRANSMIT_LABEL).Enabled := bLDPRT;
g_SampleUI.GetStatic(IDC_BLUE_TRANSMIT_LABEL).Enabled := bLDPRT;
// Load the mesh
StringCchFormat(strFileName, MAX_PATH, 'media\%S', [szMedia]);
Result:= LoadLDPRTData(pDevice, strFileName);
if V_Failed(Result) then Exit;
// Albedo texture
StringCchFormat(strFileName, MAX_PATH, 'media\%SAlbedo.dds', [szMedia]);
DXUTFindDXSDKMediaFile(strPath, MAX_PATH, strFileName);
V(D3DXCreateTextureFromFileW(pDevice, strPath, pTexture));
g_pEffect.SetTexture('Albedo', pTexture);
SAFE_RELEASE(pTexture);
// Normal map
StringCchFormat(strFileName, MAX_PATH, 'media\%SNormalMap.dds', [szMedia]);
DXUTFindDXSDKMediaFile(strPath, MAX_PATH, strFileName);
V(D3DXCreateTextureFromFileExW(pDevice, strPath, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0,
g_fmtTexture, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0,
nil, nil, pTexture));
g_pEffect.SetTexture('NormalMap', pTexture);
SAFE_RELEASE(pTexture);
// Spherical harmonic basic functions
for i := 0 to 3 do
begin
D3DXCreateCubeTexture(pDevice, 32, 1, 0, g_fmtCubeMap, D3DPOOL_MANAGED, pCubeTexture);
D3DXFillCubeTexture(pCubeTexture, myFillBF, Pointer(INT_PTR(i*4)));
g_pEffect.SetTexture(TD3DXHandle(pNames[i]), pCubeTexture);
SAFE_RELEASE(pCubeTexture);
end;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This function loads the mesh and LDPRT data. It also centers and optimizes the
// mesh for the graphics card's vertex cache.
//--------------------------------------------------------------------------------------
function LoadLDPRTData(const pd3dDevice: IDirect3DDevice9; strFilePrefixIn: PWideChar): HRESULT;
var
Alloc: CAllocateHierarchy;
str, strFileName: WideString;
begin
Alloc := CAllocateHierarchy.Create;
try
// Load the mesh with D3DX and get back a ID3DXMesh*. For this
// sample we'll ignore the X file's embedded materials since we know
// exactly the model we're loading. See the mesh samples such as
// "OptimizedMesh" for a more generic mesh loading example.
strFileName:= WideFormat('%s.x', [strFilePrefixIn]);
Result:= DXUTFindDXSDKMediaFile(str, PWideChar(strFileName)); //this is for FPC compatibility
if V_Failed(Result) then Exit;
// Delete existing resources
if Assigned(g_pFrameRoot) then
begin
D3DXFrameDestroy(g_pFrameRoot, Alloc);
g_pFrameRoot := nil;
end;
// Create hierarchy
Result:= D3DXLoadMeshHierarchyFromXW(PWideChar(str), D3DXMESH_MANAGED, pd3dDevice,
Alloc, nil, g_pFrameRoot, g_pAnimController);
if V_Failed(Result) then Exit;
SetupBoneMatrixPointers(g_pFrameRoot, g_pFrameRoot);
finally
FreeAndNil(Alloc);
end;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// reset, which will happen after a lost device scenario. This is the best location to
// create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever
// the device is lost. Resources created here should be released in the OnLostDevice
// callback.
//--------------------------------------------------------------------------------------
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
fAspectRatio: Single;
begin
Result:= g_DialogResourceManager.OnResetDevice;
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnResetDevice;
if V_Failed(Result) then Exit;
if Assigned(g_pFont) then
begin
Result:= g_pFont.OnResetDevice;
if V_Failed(Result) then Exit;
end;
if Assigned(g_pEffect) then
begin
Result:= g_pEffect.OnResetDevice;
if V_Failed(Result) then Exit;
end;
g_LightControl.OnResetDevice(pBackBufferSurfaceDesc);
g_Skybox.OnResetDevice(pBackBufferSurfaceDesc);
// Create a sprite to help batch calls when drawing many lines of text
Result:= D3DXCreateSprite(pd3dDevice, g_pTextSprite);
if V_Failed(Result) then Exit;
// Setup the camera's projection parameters
fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.001, 1000.0);
g_Camera.SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height);
g_Camera.SetButtonMasks(MOUSE_LEFT_BUTTON, MOUSE_WHEEL, MOUSE_RIGHT_BUTTON);
g_Camera.SetAttachCameraToModel(True);
g_Camera.SetRadius(5.0, 0.1, 20.0);
g_HUD.SetLocation( pBackBufferSurfaceDesc.Width-170, 0);
g_HUD.SetSize(170, 170);
g_SampleUI.SetLocation(pBackBufferSurfaceDesc.Width-300, pBackBufferSurfaceDesc.Height-245);
g_SampleUI.SetSize(300, 300);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called once at the beginning of every frame. This is the
// best location for your application to handle updates to the scene, but is not
// intended to contain actual rendering calls, which should instead be placed in the
// OnFrameRender callback.
//--------------------------------------------------------------------------------------
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
begin
// Update the camera's position based on user input
g_Camera.FrameMove(fElapsedTime);
UpdateLightingEnvironment;
if (g_pAnimController <> nil) then
begin
g_pAnimController.SetTrackSpeed(0, g_SampleUI.GetSlider(IDC_ANIMATION_SPEED).Value / 1000.0);
g_pAnimController.AdvanceTime(fElapsedTime, nil);
end;
UpdateFrameMatrices( g_pFrameRoot, g_Camera.GetWorldMatrix);
end;
//--------------------------------------------------------------------------------------
procedure UpdateLightingEnvironment;
var
fSkybox: array[0..2, 0..D3DXSH_MAXORDER*D3DXSH_MAXORDER-1] of Single;
begin
// Gather lighting options from the HUD
g_vLightDirection := g_LightControl.LightDirection;
g_fLightIntensity := g_SampleUI.Slider[IDC_LIGHT_SLIDER].Value / 100.0;
g_fEnvIntensity := g_SampleUI.Slider[IDC_ENV_SLIDER].Value / 1000.0;
// Create the spotlight
D3DXSHEvalConeLight(D3DXSH_MAXORDER, g_vLightDirection, D3DX_PI/8.0,
g_fLightIntensity, g_fLightIntensity, g_fLightIntensity,
@m_fRLC, @m_fGLC, @m_fBLC);
// Scale the light probe environment contribution based on input options
D3DXSHScale(@fSkybox[0], D3DXSH_MAXORDER, @g_fSkyBoxLightSH[0], g_fEnvIntensity);
D3DXSHScale(@fSkybox[1], D3DXSH_MAXORDER, @g_fSkyBoxLightSH[1], g_fEnvIntensity);
D3DXSHScale(@fSkybox[2], D3DXSH_MAXORDER, @g_fSkyBoxLightSH[2], g_fEnvIntensity);
// Combine the environment and the spotlight
D3DXSHAdd(@m_fRLC, D3DXSH_MAXORDER, @m_fRLC, @fSkybox[0]);
D3DXSHAdd(@m_fGLC, D3DXSH_MAXORDER, @m_fGLC, @fSkybox[1]);
D3DXSHAdd(@m_fBLC, D3DXSH_MAXORDER, @m_fBLC, @fSkybox[2]);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called at the end of every frame to perform all the
// rendering calls for the scene, and it will also be called if the window needs to be
// repainted. After this function has returned, DXUT will call
// IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain
//--------------------------------------------------------------------------------------
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
const
IsWireframe: array[False..True] of DWORD = (D3DFILL_SOLID, D3DFILL_WIREFRAME);
var
mViewProjection: TD3DXMatrixA16;
vColorTransmit: TD3DXVector3;
begin
// If the settings dialog is being shown, then
// render it instead of rendering the app's scene
if g_SettingsDlg.Active then
begin
g_SettingsDlg.OnRender(fElapsedTime);
Exit;
end;
// Clear the render target and the zbuffer
V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 50, 50, 50), 1.0, 0));
// Render the scene
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
// Get the projection & view matrix from the camera class
// mViewProjection := g_Camera.GetViewMatrix * g_Camera.GetProjMatrix;
D3DXMatrixMultiply(mViewProjection, g_Camera.GetViewMatrix^, g_Camera.GetProjMatrix^);
g_Skybox.DrawSH := False;
g_Skybox.Render(mViewProjection, 1.0, 1.0);
V(g_pEffect.SetMatrix('g_mViewProjection', mViewProjection));
V(g_pEffect.SetFloat('g_fTime', fTime));
// Set the amount of transmitted light per color channel
vColorTransmit.x := g_SampleUI.GetSlider(IDC_RED_TRANSMIT_SLIDER).Value / 1000.0;
vColorTransmit.y := g_SampleUI.GetSlider(IDC_GREEN_TRANSMIT_SLIDER).Value / 1000.0;
vColorTransmit.z := g_SampleUI.GetSlider(IDC_BLUE_TRANSMIT_SLIDER).Value / 1000.0;
V(g_pEffect.SetFloatArray('g_vColorTransmit', @vColorTransmit, 3));
// for Cubic degree rendering
V(g_pEffect.SetFloat('g_fLightIntensity', g_fLightIntensity));
V(g_pEffect.SetFloatArray('g_vLightDirection', @g_vLightDirection, 3 * SizeOf(Single)));
V(g_pEffect.SetFloatArray('g_vLightCoeffsR', @m_fRLC, 4 * SizeOf(Single)));
V(g_pEffect.SetFloatArray('g_vLightCoeffsG', @m_fGLC, 4 * SizeOf(Single)));
V(g_pEffect.SetFloatArray('g_vLightCoeffsB', @m_fBLC, 4 * SizeOf(Single)));
pd3dDevice.SetRenderState(D3DRS_FILLMODE, IsWireframe[g_bWireFrame]);
DrawFrame(pd3dDevice, g_pFrameRoot);
DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, 'HUD / Stats'); // These events are to help PIX identify what the code is doing
RenderText;
V(g_HUD.OnRender(fElapsedTime));
V(g_SampleUI.OnRender(fElapsedTime));
V(g_LightControl.OnRender(D3DXColor(1, 1, 1, 1), g_Camera.GetViewMatrix^, g_Camera.GetProjMatrix^, g_Camera.GetEyePt^));
DXUT_EndPerfEvent;
V(pd3dDevice.EndScene);
end;
end;
//--------------------------------------------------------------------------------------
// Called to render a frame in the hierarchy
//--------------------------------------------------------------------------------------
procedure DrawFrame(const pd3dDevice: IDirect3DDevice9; pFrame: PD3DXFrame);
var
pMeshContainer: PD3DXMeshContainer;
begin
pMeshContainer := pFrame.pMeshContainer;
while (pMeshContainer <> nil) do
begin
DrawMeshContainer(pd3dDevice, pMeshContainer, pFrame);
pMeshContainer := pMeshContainer.pNextMeshContainer;
end;
if (pFrame.pFrameSibling <> nil) then DrawFrame(pd3dDevice, pFrame.pFrameSibling);
if (pFrame.pFrameFirstChild <> nil) then DrawFrame(pd3dDevice, pFrame.pFrameFirstChild);
end;
//--------------------------------------------------------------------------------------
// Called to render a mesh in the hierarchy
//--------------------------------------------------------------------------------------
procedure DrawMeshContainer(const pd3dDevice: IDirect3DDevice9; pMeshContainerBase: PD3DXMeshContainer; pFrameBase: PD3DXFrame);
var
pMeshContainer: PD3DXMeshContainerDerived;
iMaterial, iAttrib, iPaletteEntry, iPass: Integer;
pBoneComb: PD3DXBoneCombination;
BoneMatrices: array[0..MAX_BONES-1] of TD3DXMatrixA16;
iMatrixIndex: LongWord;
numPasses: LongWord;
begin
pMeshContainer := PD3DXMeshContainerDerived(pMeshContainerBase);
// If there's no skinning information just draw the mesh
if (nil = pMeshContainer.pSkinInfo) then
begin
for iMaterial := 0 to pMeshContainer.NumMaterials - 1 do
V(ID3DXMesh(pMeshContainer.MeshData.pMesh).DrawSubset(iMaterial));
Exit;
end;
pBoneComb := PD3DXBoneCombination(pMeshContainer.pBoneCombinationBuf.GetBufferPointer);
for iAttrib := 0 to pMeshContainer.NumAttributeGroups - 1 do
begin
// first calculate all the world matrices
for iPaletteEntry := 0 to pMeshContainer.NumPaletteEntries - 1 do
begin
// iMatrixIndex := pBoneComb[iAttrib].BoneId[iPaletteEntry]; -- We instead do Inc at the end of cycle
iMatrixIndex := pBoneComb.BoneId[iPaletteEntry];
if (iMatrixIndex <> High(LongWord){UINT_MAX}) then
D3DXMatrixMultiply(BoneMatrices[iPaletteEntry],
pMeshContainer.pBoneOffsetMatrices[iMatrixIndex],
pMeshContainer.ppBoneMatrixPtrs[iMatrixIndex]^);
end;
V(g_pEffect.SetMatrixArray('g_mWorldMatrixArray', @BoneMatrices, pMeshContainer.NumPaletteEntries));
// Set CurNumBones to select the correct vertex shader for the number of bones
V(g_pEffect.SetInt('g_NumBones', pMeshContainer.NumInfl -1));
// Start the effect now all parameters have been updated
V(g_pEffect._Begin(@numPasses, D3DXFX_DONOTSAVESTATE ));
for iPass := 0 to numPasses - 1 do
begin
V(g_pEffect.BeginPass(iPass));
// Draw the subset with the current world matrix palette and material state
V(ID3DXMesh(pMeshContainer.MeshData.pMesh).DrawSubset(iAttrib));
V(g_pEffect.EndPass);
end;
V(g_pEffect._End);
Inc(pBoneComb);
end;
end;
//--------------------------------------------------------------------------------------
// Render the help and statistics text. This function uses the ID3DXFont interface for
// efficient text rendering.
//--------------------------------------------------------------------------------------
procedure RenderText;
var
txtHelper: CDXUTTextHelper;
pd3dsdBackBuffer: PD3DSurfaceDesc;
begin
// The helper object simply helps keep track of text position, and color
// and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr );
// If NULL is passed in as the sprite object, then it will work however the
// pFont->DrawText() will not be batched together. Batching calls will improves performance.
pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc;
txtHelper := CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15);
// Output statistics
txtHelper._Begin;
txtHelper.SetInsertionPos(5, 5);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0));
txtHelper.DrawTextLine(DXUTGetFrameStats(True)); // Show FPS
txtHelper.DrawTextLine(DXUTGetDeviceStats);
// Draw help
if g_bShowHelp then
begin
txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-15*8);
txtHelper.SetForegroundColor(D3DXCOLOR( 1.0, 0.75, 0.0, 1.0 ));
txtHelper.DrawTextLine('Controls (F1 to hide):');
txtHelper.SetInsertionPos(40, pd3dsdBackBuffer.Height-15*7);
txtHelper.DrawTextLine('Rotate Model: Left Mouse');
txtHelper.DrawTextLine('Rotate Light: Middle Mouse');
txtHelper.DrawTextLine('Rotate Camera and Model: Right Mouse');
txtHelper.DrawTextLine('Rotate Camera: Ctrl + Right Mouse');
txtHelper.DrawTextLine('Wireframe: W');
txtHelper.DrawTextLine('Quit: ESC');
end else
begin
txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-15*2);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
txtHelper.DrawTextLine('Press F1 for help');
end;
txtHelper._End;
txtHelper.Free;
end;
//--------------------------------------------------------------------------------------
// Before handling window messages, DXUT passes incoming windows
// messages to the application through this callback function. If the application sets
// *pbNoFurtherProcessing to TRUE, then DXUT will not process this message.
//--------------------------------------------------------------------------------------
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
begin
Result:= 0;
// Always allow dialog resource manager calls to handle global messages
// so GUI state is updated correctly
pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
if g_SettingsDlg.IsActive then
begin
g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam);
Exit;
end;
// Give the dialogs a chance to handle the message first
pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
// Pass all remaining windows messages to camera so it can respond to user input
g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam);
g_LightControl.HandleMessages(hWnd, uMsg, wParam, lParam);
end;
//--------------------------------------------------------------------------------------
// As a convenience, DXUT inspects the incoming windows messages for
// keystroke messages and decodes the message parameters to pass relevant keyboard
// messages to the application. The framework does not remove the underlying keystroke
// messages, which are still passed to the application's MsgProc callback.
//--------------------------------------------------------------------------------------
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
begin
if bKeyDown then
begin
case nChar of
VK_F1: g_bShowHelp := not g_bShowHelp;
Ord('W'): g_bWireFrame := not g_bWireFrame;
end;
end;
end;
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
begin
case nControlID of
IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen;
IDC_TOGGLEREF: DXUTToggleREF;
IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active;
IDC_TECHNIQUE: LoadTechniqueObjects('bat');
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// entered a lost state and before IDirect3DDevice9::Reset is called. Resources created
// in the OnResetDevice callback should be released here, which generally includes all
// D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for
// information about lost devices.
//--------------------------------------------------------------------------------------
procedure OnLostDevice; stdcall;
begin
g_DialogResourceManager.OnLostDevice;
g_SettingsDlg.OnLostDevice;
if Assigned(g_pFont) then g_pFont.OnLostDevice;
if Assigned(g_pEffect) then g_pEffect.OnLostDevice;
g_LightControl.StaticOnLostDevice;
g_Skybox.OnLostDevice;
SAFE_RELEASE(g_pTextSprite);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// been destroyed, which generally happens as a result of application termination or
// windowed/full screen toggles. Resources created in the OnCreateDevice callback
// should be released here, which generally includes all D3DPOOL_MANAGED resources.
//--------------------------------------------------------------------------------------
procedure OnDestroyDevice; stdcall;
var
Alloc: CAllocateHierarchy;
begin
g_DialogResourceManager.OnDestroyDevice;
g_SettingsDlg.OnDestroyDevice;
SAFE_RELEASE(g_pEffect);
SAFE_RELEASE(g_pFont);
g_LightControl.StaticOnDestroyDevice;
g_Skybox.OnDestroyDevice;
if Assigned(g_pFrameRoot) then
begin
Alloc := CAllocateHierarchy.Create;
D3DXFrameDestroy(g_pFrameRoot, Alloc);
FreeAndNil(Alloc);
g_pFrameRoot := nil;
end;
SAFE_RELEASE(g_pAnimController);
end;
procedure CreateCustomDXUTobjects;
begin
g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs
g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog
g_Camera:= CModelViewerCamera.Create;
g_HUD:= CDXUTDialog.Create;
g_SampleUI:= CDXUTDialog.Create;
g_Skybox:= CSkybox.Create;
g_LightControl:= CDXUTDirectionWidget.Create;
end;
procedure DestroyCustomDXUTobjects;
begin
FreeAndNil(g_DialogResourceManager);
FreeAndNil(g_SettingsDlg);
FreeAndNil(g_Camera);
FreeAndNil(g_HUD);
FreeAndNil(g_SampleUI);
FreeAndNil(g_Skybox);
FreeAndNil(g_LightControl);
end;
end.
|
unit RobotUnit;
// verzia 030910
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls;
type
TRobot = class
private
FX, FY, FH: Real;
FDown: Boolean;
FPC: TColor;
FPW: Integer;
public
Value: Integer;
constructor Create;
constructor Create(NewX, NewY: Real; Angle: Real = 0);
procedure Fd(D: Real); virtual;
procedure Rt(Angle: Real); virtual;
procedure Lt(Angle: Real); virtual;
procedure SetH(Angle: Real); virtual;
procedure SetXY(NewX, NewY: Real); virtual;
procedure SetX(NewX: Real); virtual;
procedure SetY(NewY: Real); virtual;
procedure MoveXY(NewX, NewY: Real); virtual;
procedure PU; virtual;
procedure PD; virtual;
procedure SetPen(Down: Boolean); virtual;
procedure SetPC(NewColor: TColor); virtual;
procedure SetPW(NewWidth: Integer); virtual;
procedure Point(NewWidth: Real = 0); virtual;
procedure Text(NewText: string); virtual;
procedure Towards(AnyX, AnyY: Real); virtual;
procedure Fill(NewColor: TColor); virtual;
function Dist(AnyX, AnyY: Real): Real; virtual;
function IsNear(AnyX, AnyY: Real): Boolean; virtual;
procedure Draw; virtual;
procedure Action; virtual;
property X: Real read FX write SetX;
property Y: Real read FY write SetY;
property H: Real read FH write SetH;
property IsPD: Boolean read FDown write SetPen;
property PC: TColor read FPC write SetPC;
property PW: Integer read FPW write SetPW;
end;
//////////////////////////////////////////////////////////////////////////////////////////
const
Rad = Pi/180;
Deg = 180/Pi;
procedure CS(NewColor: TColor = clWhite);
procedure Wait(MilliSec: Integer);
procedure SetImage(Image: TImage = nil);
//////////////////////////////////////////////////////////////////////////////////////////
implementation
var
MyImage: TImage = nil;
//////////////////////////////////////////////////////////////////////////////////////////
constructor TRobot.Create;
begin
SetImage;
Create(MyImage.Width/2, MyImage.Height/2);
end;
constructor TRobot.Create(NewX, NewY, Angle: Real);
begin
SetImage;
FX := NewX;
FY := NewY;
FH := Angle;
FPC := clBlack;
FPW := 1;
FDown := True;
end;
procedure TRobot.Rt(Angle: Real);
begin
SetH(FH + Angle);
end;
procedure TRobot.Lt(Angle: Real);
begin
SetH(FH - Angle);
end;
procedure TRobot.SetH(Angle: Real);
begin
FH := Angle;
while FH < 0 do
FH := FH + 360;
while FH >= 360 do
FH := FH - 360;
end;
procedure TRobot.Fd(D: Real);
begin
SetXY(FX + Sin(FH*Rad)*D, FY - Cos(FH*Rad)*D);
end;
procedure TRobot.SetXY(NewX, NewY: Real);
begin
if not FDown then
MoveXY(NewX, NewY)
else
with MyImage.Canvas do
begin
Brush.Style := bsSolid;
Pen.Color := FPC;
Pen.Width := FPW;
MoveTo(Round(FX), Round(FY));
LineTo(Round(NewX), Round(NewY));
FX := NewX;
FY := NewY;
end;
end;
procedure TRobot.MoveXY(NewX, NewY: Real);
begin
FX := NewX;
FY := NewY;
MyImage.Canvas.MoveTo(Round(FX), Round(FY));
end;
procedure TRobot.PU;
begin
FDown := False;
end;
procedure TRobot.PD;
begin
FDown := True;
end;
procedure TRobot.SetPen(Down: Boolean);
begin
if Down then
PD
else
PU;
end;
procedure TRobot.SetPC(NewColor: TColor);
begin
FPC := NewColor;
end;
procedure TRobot.SetPW(NewWidth: Integer);
begin
FPW := NewWidth;
end;
procedure TRobot.SetX(NewX: Real);
begin
SetXY(NewX, FY);
end;
procedure TRobot.SetY(NewY: Real);
begin
SetXY(FX, NewY);
end;
//////////////////////////////////////////////////////////////////////////////////////////
procedure TRobot.Point(NewWidth: Real);
var
AnyX, AnyY, R1, R2: Integer;
begin
NewWidth := Round(Abs(NewWidth));
if NewWidth = 0 then
NewWidth := FPW;
R1 := (Trunc(NewWidth)+1) div 2;
R2 := Trunc(NewWidth)-R1+1;
with MyImage.Canvas do
begin
AnyX := Round(FX);
AnyY := Round(FY);
Brush.Color := FPC;
Brush.Style := bsSolid;
Pen.Color := FPC;
Pen.Style := psSolid;
Pen.Width := 1;
Ellipse(AnyX-R1, AnyY-R1, AnyX+R2, AnyY+R2);
end;
end;
procedure TRobot.Fill(NewColor: TColor);
var
AnyX, AnyY: Integer;
begin
with MyImage.Canvas do
begin
AnyX := Round(FX);
AnyY := Round(FY);
Brush.Color := NewColor;
Brush.Style := bsSolid;
FloodFill(AnyX, AnyY, Pixels[AnyX, AnyY], fsSurface);
end;
end;
procedure TRobot.Towards(AnyX, AnyY: Real);
var
Angle: Real;
begin
AnyX := AnyX - FX;
AnyY := FY - AnyY;
if AnyY = 0 then
if AnyX = 0 then
Angle := 0
else if AnyX < 0 then
Angle := 270
else
Angle := 90
else if AnyY > 0 then
if AnyX >= 0 then
Angle := ArcTan(AnyX/AnyY)*Deg
else
Angle := 360 - ArcTan(-AnyX/AnyY)*Deg
else if AnyX >= 0 then
Angle := 180 - ArcTan(-AnyX/AnyY)*Deg
else
Angle := 180 + ArcTan(AnyX/AnyY)*Deg;
SetH(Angle);
end;
function TRobot.Dist(AnyX, AnyY: Real): Real;
begin
Result := Sqrt(Sqr(AnyX-FX) + Sqr(AnyY-FY));
end;
function TRobot.IsNear(AnyX, AnyY: Real): Boolean;
begin
Result := Sqr(AnyX-FX) + Sqr(AnyY-FY) < 100;
end;
procedure TRobot.Text(NewText: string);
begin
MyImage.Canvas.Font.Color := FPC;
MyImage.Canvas.Brush.Style := bsClear;
MyImage.Canvas.TextOut(Round(FX), Round(FY), NewText);
end;
procedure TRobot.Action;
begin
end;
procedure TRobot.Draw;
begin
Point;
end;
//////////////////////////////////////////////////////////////////////////////////////////
procedure CS(NewColor: TColor);
begin
SetImage;
with MyImage, Canvas do
begin
Brush.Color := NewColor;
Brush.Style := bsSolid;
FillRect(ClientRect);
end;
end;
procedure Wait(MilliSec: Integer);
begin
if MyImage <> nil then
MyImage.Repaint;
Sleep(MilliSec);
end;
//////////////////////////////////////////////////////////////////////////////////////
procedure SetImage(Image: TImage);
var
I, N: Integer;
Form: TForm;
begin
if MyImage <> nil then
Exit;
if Image = nil then
begin
Form := Application.MainForm;
if Form = nil then
begin
N := Application.ComponentCount;
I := 0;
while (I < N) and not (Application.Components[I] is TForm) do
Inc(I);
if I = N then
begin
ShowMessage('vadná aplikácia - Robot nenašiel formulár');
Halt;
end;
Form := TForm(Application.Components[I]);
end;
N := Form.ControlCount;
I := 0;
while (I < N) and not (Form.Controls[I] is TImage) do
Inc(I);
if I >= N then
begin
ShowMessage('vadná aplikácia - Robot nenašiel grafickú plochu');
Halt;
end;
Image := TImage(Form.Controls[I]);
end;
with Image, Canvas do
begin
Brush.Color := clWhite;
Brush.Style := bsSolid;
FillRect(ClientRect);
end;
if Image.Owner is TForm then
TForm(Image.Owner).DoubleBuffered := True;
MyImage := Image;
end;
end.
|
unit URecalThread;
interface
uses
Classes, ReCountListUnit, cxContainer, cxProgressBar, ZProc,pFibDataSet, dxStatusBar,
Variants, zMessages, Dialogs, cxmemo ;
type
TRecalcThread = class(TThread)
private
{ Private declarations }
FForm:TReCountListForm;
FProgressBar:TcxProgressBar;
FProgressbarPosition:Integer;
FStatusPanel:TdxStatusBarPanel;
FErrorLog:TcxMemo;
FStatusPanelText:string;
FErrorLogString:string;
procedure UpdateProgressBar;
procedure UpdateStatusPanelText;
procedure UpdateErrorLog;
procedure ClearErrorLog;
protected
procedure Execute; override;
public
constructor Create(CreateSuspended:Boolean;Form:TReCountListForm); reintroduce;
end;
implementation
uses SysUtils, FIBDataSet;
{ TRecalThread }
constructor TRecalcThread.Create(CreateSuspended: Boolean; Form: TReCountListForm);
begin
inherited Create(true);
FForm:=Form;
FProgressBar:=Form.ProgressBar;
FErrorLog :=Form.cxMemo1;
FStatusPanel:=Form.StatusBar.Panels[0];
end;
procedure TRecalcThread.Execute;
var GetListForcalc:TpFibDataSet;
I:Integer;
begin
Synchronize(ClearErrorLog);
if(ZProc.SetBeginAction(FForm.MainDataBase.Handle,1))then
begin
FForm.WriteTransaction.StartTransaction;
GetListForcalc :=TpFibDataSet.Create(nil);
GetListForcalc.Database :=FForm.ListDataSet.Database;
GetListForcalc.Transaction:=FForm.ListDataSet.Transaction;
GetListForcalc.SelectSQL.Text:='SELECT * FROM Z_RE_COUNT_LIST_SELECT_EX ORDER BY TN ASC';
GetListForcalc.Open;
FProgressBar.Properties.Max:=GetListForcalc.RecordCountFromSrv;
GetListForcalc.FetchAll;
GetListForcalc.First;
FProgressbarPosition:=0;
for i:=1 to GetListForcalc.RecordCount do
begin
FStatusPanelText:='ТН:'+VarToStr(GetListForcalc['TN']);
Synchronize(UpdateStatusPanelText);
FForm.RecountProc.ParamByName('ID_MAN').Value :=GetListForcalc['ID_MAN'];
try
FForm.RecountProc.ExecProc;
except on E:Exception do
begin
if FForm.WriteTransaction.InTransaction then FForm.WriteTransaction.Rollback;
FErrorLogString:='Помилка при роботі з '+FStatusPanelText+' '+Trim(E.Message);
StringReplace(FErrorLogString,#10#13,' ', [rfReplaceAll, rfIgnoreCase]);
Synchronize(UpdateErrorLog);
FForm.SelectBtn.Enabled:=True;
Break;
end;
end;
GetListForcalc.Next;
FProgressbarPosition:=FProgressbarPosition+1;
Synchronize(UpdateProgressBar);
end;
if FForm.WriteTransaction.InTransaction then FForm.WriteTransaction.Commit;
GetListForcalc.Close;
GetListForcalc.Free;
ZProc.SetEndAction(FForm.MainDataBase.Handle,'T');
end;
end;
procedure TRecalcThread.UpdateProgressBar;
begin
FProgressBar.Position:=FProgressbarPosition;
FProgressBar.Update;
end;
procedure TRecalcThread.UpdateStatusPanelText;
begin
FStatusPanel.Text:=FStatusPanelText;
end;
procedure TRecalcThread.UpdateErrorLog;
begin
FErrorLog.Lines.Add(FErrorLogString);
end;
procedure TRecalcThread.ClearErrorLog;
begin
FErrorLog.Lines.Clear;
FErrorLog.Clear;
end;
end.
|
{
Библиотека дополнительных компонентов
Регистрация компонента TGridView в Delphi IDE
© Роман М. Мочалов, 1997-2001
E-mail: roman@sar.nnov.ru
}
unit Ex_RegGrid;
{$I EX.INC}
interface
uses
Windows, SysUtils, Classes, Forms, Dialogs, TypInfo,
{$IFDEF EX_D6_UP} DesignIntf, DesignEditors {$ELSE} DsgnIntf {$ENDIF};
type
{ TGridEditor }
TGridEditor = class(TDefaultEditor)
private
FCollection: TCollection;
{$IFDEF EX_D6_UP}
procedure FindCollectionEditor(const PropertyEditor: IProperty);
{$ELSE}
procedure FindCollectionEditor(PropertyEditor: TPropertyEditor);
{$ENDIF}
protected
{$IFDEF EX_D6_UP}
procedure EditProperty(const PropertyEditor: IProperty;
var Continue: Boolean); override;
{$ELSE}
procedure EditProperty(PropertyEditor: TPropertyEditor;
var Continue, FreeEditor: Boolean); override;
{$ENDIF}
procedure ShowCollectionEditor(ACollection: TCollection);
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
{ TGridColumnsProperty }
TGridColumnsProperty = class(TClassProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
{ TGridHeaderProperty }
TGridHeaderProperty = class(TClassProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
{ TDBGridFieldNameProperty }
TDBGridFieldNameProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
procedure Register;
implementation
uses
Ex_Grid, Ex_GridC, Ex_GridH, Ex_Inspector, Ex_DBGrid;
{ TGridEditor }
{$IFDEF EX_D6_UP}
procedure TGridEditor.FindCollectionEditor(const PropertyEditor: IProperty);
{$ELSE}
procedure TGridEditor.FindCollectionEditor(PropertyEditor: TPropertyEditor);
{$ENDIF}
var
P: PTypeInfo;
begin
{ если редактор свойства найден, то значение FCollection будет
сброшено в nil }
if FCollection <> nil then
begin
P := PropertyEditor.GetPropType;
{ проверяем тип и название свойства }
if (P <> nil) and (P.Kind = tkClass) and (CompareText(P.Name, FCollection.ClassName) = 0) then
begin
PropertyEditor.Edit;
FCollection := nil;
end;
end;
{$IFNDEF EX_D6_UP}
{ об освобождении редактора свойства необходимо заботится самим }
PropertyEditor.Free;
{$ENDIF}
end;
{$IFDEF EX_D6_UP}
procedure TGridEditor.EditProperty(const PropertyEditor: IProperty;
var Continue: Boolean);
{$ELSE}
procedure TGridEditor.EditProperty(PropertyEditor: TPropertyEditor;
var Continue, FreeEditor: Boolean);
{$ENDIF}
begin
inherited;
{ Двойной щелчок на компоненте в дизайнере Delphi приводит к вызову
метода Edit у TDefaultEditor. TDefaultEditor перебирает внутри Edit
все свойства компонента, ищет свойство-метод с именем OnCreate,
OnChange или OnClick (или первый попавшийся, если указанных нет) и
вызывает Edit соответствующего редактор свойства. Редактор свойтва в
свою очередь ставит курсор на обработчик данного метода в тексте.
Поэтому, если мы хотим, чтобы двойной щелчок на таблице автоматически
ставил курсор на OnGetCellText, то нам необходимо самим найти редактор
свойства этого свойства и "выполнить" его. }
if CompareText(PropertyEditor.GetName, 'ONGETCELLTEXT') = 0 then
begin
PropertyEditor.Edit;
{ говорим стандартному обработчику, что исполнять найденный им
редактор свойства не надо }
Continue := False;
end;
end;
procedure TGridEditor.ShowCollectionEditor(ACollection: TCollection);
var
{$IFDEF EX_D6_UP}
List: IDesignerSelections;
{$ELSE}
{$IFDEF EX_D5_UP}
List: TDesignerSelectionList;
{$ELSE}
List: TComponentList;
{$ENDIF}
{$ENDIF}
begin
FCollection := ACollection;
{ перебираем список свойств, ищем и показываем стандартный редактор
для указанной коллекции }
{$IFDEF EX_D6_UP}
List := TDesignerSelections.Create;
{$ELSE}
{$IFDEF EX_D5_UP}
List := TDesignerSelectionList.Create;
{$ELSE}
List := TComponentList.Create;
{$ENDIF}
{$ENDIF}
try
List.Add(Self.Component);
GetComponentProperties(List, [tkClass], Self.Designer, FindCollectionEditor);
finally
{$IFNDEF EX_D6_UP}
List.Free;
{$ENDIF}
end;
end;
procedure TGridEditor.ExecuteVerb(Index: Integer);
begin
case Index of
{$IFDEF VER90}
0: if EditGridColumns(TCustomGridView(Component)) then Designer.Modified;
{$ELSE}
0: ShowCollectionEditor(TCustomGridView(Component).Columns);
{$ENDIF}
1: if EditGridHeader(TCustomGridView(Component)) then Designer.Modified;
end;
end;
function TGridEditor.GetVerb(Index: Integer): AnsiString;
begin
case Index of
0: Result := 'Columns Editor...';
1: Result := 'Header Editor...';
end;
end;
function TGridEditor.GetVerbCount: Integer;
begin
Result := 2;
end;
{ TGridColumnsProperty }
procedure TGridColumnsProperty.Edit;
begin
if EditGridColumns(TGridColumns(GetOrdValue).Grid) then Modified;
end;
function TGridColumnsProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paReadOnly];
end;
{ TGridHeaderProperty }
procedure TGridHeaderProperty.Edit;
begin
if EditGridHeader(TGridHeaderSections(GetOrdValue).Header.Grid) then Modified;
end;
function TGridHeaderProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paReadOnly];
end;
{ TDBGridFieldNameProperty }
function TDBGridFieldNameProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList, paSortList, paMultiSelect];
end;
procedure TDBGridFieldNameProperty.GetValues(Proc: TGetStrProc);
var
Grid: TCustomDBGridView;
Values: TStringList;
I: Integer;
begin
Grid := TDBGridColumn(GetComponent(0)).Grid;
if (Grid <> nil) and (Grid.DataLink.DataSet <> nil) then
begin
Values := TStringList.Create;
try
Grid.DataLink.DataSet.GetFieldNames(Values);
for I := 0 to Values.Count - 1 do Proc(Values[I]);
finally
Values.Free;
end;
end;
end;
procedure Register;
begin
RegisterComponents('Extended', [TGridView]);
RegisterComponents('Extended', [TExInspector]);
RegisterComponents('Extended', [TDBGridView]);
RegisterComponentEditor(TGridView, TGridEditor);
RegisterPropertyEditor(TypeInfo(TGridHeaderSections), TGridHeader, 'Sections', TGridHeaderProperty);
{$IFDEF VER90}
RegisterPropertyEditor(TypeInfo(TGridColumns), TGridView, 'Columns', TGridColumnsProperty);
{$ENDIF}
RegisterComponentEditor(TDBGridView, TGridEditor);
RegisterPropertyEditor(TypeInfo(string), TDBGridColumn, 'FieldName', TDBGridFieldNameProperty);
end;
end.
|
// Copyright 2014 Asbjørn Heid
//
// 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 Compute.OpenCL.KernelGenerator;
interface
uses
Compute.ExprTrees;
type
IKernelGenerator = interface
['{D631B32B-C71A-4580-9508-AB9DAEDC2737}']
// return kernel with signature
// transform(double* src, double* res, uint count)
function GenerateDoubleTransformKernel(const Expression: Compute.ExprTrees.Expr; const NumInputs: integer = 1): string;
end;
function DefaultKernelGenerator(const VectorWidth: UInt32 = 0): IKernelGenerator;
implementation
uses
System.SysUtils,
Compute.Common,
Compute.Functions;
var
OpenCLFormatSettings: TFormatSettings;
type
IStringList = IList<string>;
TStringListImpl = TListImpl<string>;
IExprFunctionCollector = interface
['{325538EC-0FC7-4753-A920-585B30DEDD33}']
function GetFunctions: TArray<Expr.NaryFunc>;
property Functions: TArray<Expr.NaryFunc> read GetFunctions;
end;
TExprFunctionCollector = class(TInterfacedObject, IExprFunctionCollector, IExprNodeVisitor)
private
FFunctions: IList<Expr.NaryFunc>;
FKnownFunctions: IDictionary<string, integer>;
public
constructor Create;
destructor Destroy; override;
procedure Visit(const Node: IConstantNode); overload;
procedure Visit(const Node: IVariableNode); overload;
procedure Visit(const Node: IArrayElementNode); overload;
procedure Visit(const Node: IUnaryOpNode); overload;
procedure Visit(const Node: IBinaryOpNode); overload;
procedure Visit(const Node: IFuncNode); overload;
procedure Visit(const Node: ILambdaParamNode); overload;
function GetFunctions: TArray<Expr.NaryFunc>;
end;
TExpressionGeneratorBase = class(TInterfacedObject, IExprNodeVisitor)
strict private
FOutput: string;
protected
procedure Emit(const s: string);
procedure Clear;
procedure Visit(const Node: IConstantNode); overload; virtual;
procedure Visit(const Node: IVariableNode); overload; virtual;
procedure Visit(const Node: IArrayElementNode); overload; virtual;
procedure Visit(const Node: IUnaryOpNode); overload; virtual;
procedure Visit(const Node: IBinaryOpNode); overload; virtual;
procedure Visit(const Node: IFuncNode); overload; virtual;
procedure Visit(const Node: ILambdaParamNode); overload; virtual;
property Output: string read FOutput;
public
constructor Create;
end;
IUserFuncBodyGenerator = interface
['{A18ECAD5-7F4B-4D47-A606-2FACBA5AF3C3}']
function GenerateUserFuncBody(const FuncBody: Compute.ExprTrees.Expr): string;
end;
TUserFuncBodyGenerator = class(TExpressionGeneratorBase, IUserFuncBodyGenerator)
strict private
function GenerateUserFuncBody(const FuncBody: Compute.ExprTrees.Expr): string;
protected
procedure Visit(const Node: IVariableNode); override;
procedure Visit(const Node: ILambdaParamNode); override;
public
constructor Create;
end;
TKernelGeneratorBase = class(TInterfacedObject, IKernelGenerator)
strict private
FVectorWidth: UInt32;
procedure GenerateStandardFunctions(const Lines: IStringList; const DataType: string);
procedure GenerateUserFunctions(const Expression: Compute.ExprTrees.Expr; const Lines: IStringList; const DataType: string);
function GenerateDoubleTransformKernel(const Expression: Compute.ExprTrees.Expr; const NumInputs: integer): string;
protected
procedure GenerateDoubleTransformKernelBody(const Expression: Compute.ExprTrees.Expr; const Lines: IStringList); virtual; abstract;
property VectorWidth: UInt32 read FVectorWidth;
public
constructor Create(const VectorWidth: UInt32);
end;
IGPUTransformKernelGenerator = interface
['{A18ECAD5-7F4B-4D47-A606-2FACBA5AF3C3}']
function TransformDouble(const Expression: Compute.ExprTrees.Expr): string;
end;
TGPUTransformKernelGenerator = class(TExpressionGeneratorBase, IGPUTransformKernelGenerator)
strict private
function TransformDouble(const Expression: Compute.ExprTrees.Expr): string;
protected
procedure Visit(const Node: IVariableNode); override;
procedure Visit(const Node: IArrayElementNode); override;
procedure Visit(const Node: ILambdaParamNode); override;
public
constructor Create;
end;
TGPUKernelGeneratorImpl = class(TKernelGeneratorBase)
protected
procedure GenerateDoubleTransformKernelBody(const Expression: Compute.ExprTrees.Expr; const Lines: IStringList); override;
public
constructor Create(const VectorWidth: UInt32);
end;
function DefaultKernelGenerator(const VectorWidth: UInt32): IKernelGenerator;
begin
result := TGPUKernelGeneratorImpl.Create(VectorWidth);
end;
{ TExprFunctionCollector }
constructor TExprFunctionCollector.Create;
begin
inherited Create;
FFunctions := TListImpl<Expr.NaryFunc>.Create;
FKnownFunctions := TDictionaryImpl<string, integer>.Create;
end;
destructor TExprFunctionCollector.Destroy;
begin
inherited;
end;
function TExprFunctionCollector.GetFunctions: TArray<Expr.NaryFunc>;
begin
result := FFunctions.ToArray();
end;
procedure TExprFunctionCollector.Visit(const Node: IUnaryOpNode);
begin
Node.ChildNode.Accept(Self);
end;
procedure TExprFunctionCollector.Visit(const Node: IBinaryOpNode);
begin
Node.ChildNode1.Accept(Self);
Node.ChildNode2.Accept(Self);
end;
procedure TExprFunctionCollector.Visit(const Node: IFuncNode);
var
i: integer;
begin
if Node.Data.IsBuiltIn and (Node.Data.Name <> 'ifthen') then
exit;
// make sure functions referenced
for i := 0 to Node.Data.ParamCount-1 do
Node.Data.Params[i].Accept(Self);
if Node.Data.IsBuiltIn or FKnownFunctions.Contains[Node.Data.Name] then
exit;
// go through body, adding any functions referenced there
// but make sure we don't recurse
FKnownFunctions[Node.Data.Name] := 1;
Node.Data.Body.Accept(Self);
// add current function after any referenced
FFunctions.Add(Node.Data);
end;
procedure TExprFunctionCollector.Visit(const Node: IArrayElementNode);
begin
Node.Data.Index.Accept(Self);
end;
procedure TExprFunctionCollector.Visit(const Node: IConstantNode);
begin
end;
procedure TExprFunctionCollector.Visit(const Node: IVariableNode);
begin
end;
procedure TExprFunctionCollector.Visit(const Node: ILambdaParamNode);
begin
end;
{ TExpressionGeneratorBase }
procedure TExpressionGeneratorBase.Clear;
begin
FOutput := '';
end;
constructor TExpressionGeneratorBase.Create;
begin
inherited Create;
end;
procedure TExpressionGeneratorBase.Emit(const s: string);
begin
FOutput := FOutput + s;
end;
procedure TExpressionGeneratorBase.Visit(const Node: IArrayElementNode);
begin
Emit(Node.Data.Name + '[');
Node.Data.Index.Accept(Self);
Emit(']');
end;
procedure TExpressionGeneratorBase.Visit(const Node: IVariableNode);
begin
Emit(Node.Data.Name);
end;
procedure TExpressionGeneratorBase.Visit(const Node: IConstantNode);
begin
Emit(FloatToStr(Node.Data.Value, OpenCLFormatSettings));
end;
procedure TExpressionGeneratorBase.Visit(const Node: IUnaryOpNode);
begin
Emit('(');
case Node.Op of
uoNot: Emit('!');
uoNegate: Emit('-');
else
raise ENotImplemented.Create('Unknown unary operator');
end;
Node.ChildNode.Accept(Self);
Emit(')');
end;
procedure TExpressionGeneratorBase.Visit(const Node: ILambdaParamNode);
begin
Emit(Node.Data.Name);
end;
procedure TExpressionGeneratorBase.Visit(const Node: IFuncNode);
var
i: integer;
begin
// ifthen is special
if Node.Data.IsBuiltIn and (Node.Data.Name = 'ifthen') then
begin
Emit('(');
Node.Data.Params[0].Accept(Self);
Emit(') ? (');
Node.Data.Params[1].Accept(Self);
Emit(') : (');
Node.Data.Params[2].Accept(Self);
Emit(')');
end
else
begin
Emit(Node.Data.Name + '(');
for i := 0 to Node.Data.ParamCount-1 do
begin
if (i > 0) then
Emit(', ');
Node.Data.Params[i].Accept(Self);
end;
Emit(')');
end;
end;
procedure TExpressionGeneratorBase.Visit(const Node: IBinaryOpNode);
begin
Emit('(');
Node.ChildNode1.Accept(Self);
case Node.Op of
boAdd: Emit(' + ');
boSub: Emit(' - ');
boMul: Emit(' * ');
boDiv: Emit(' / ');
boAnd: Emit(' & ');
boOr: Emit(' | ');
boXor: Emit(' ^ ');
boEq: Emit(' == ');
boNotEq: Emit(' != ');
boLess: Emit(' < ');
boLessEq: Emit(' <= ');
boGreater: Emit(' > ');
boGreaterEq: Emit(' >= ');
else
raise ENotImplemented.Create('Unknown binary operator');
end;
Node.ChildNode2.Accept(Self);
Emit(')');
end;
{ TUserFuncBodyGenerator }
constructor TUserFuncBodyGenerator.Create;
begin
inherited Create;
end;
function TUserFuncBodyGenerator.GenerateUserFuncBody(
const FuncBody: Compute.ExprTrees.Expr): string;
begin
Clear;
FuncBody.Accept(Self);
result := Output;
end;
procedure TUserFuncBodyGenerator.Visit(const Node: ILambdaParamNode);
begin
Emit('arg' + Node.Data.Name);
end;
procedure TUserFuncBodyGenerator.Visit(const Node: IVariableNode);
begin
raise ENotImplemented.Create('Variables in functions not implemented');
end;
{ TKernelGeneratorBase }
constructor TKernelGeneratorBase.Create(const VectorWidth: UInt32);
begin
inherited Create;
FVectorWidth := VectorWidth;
end;
function TKernelGeneratorBase.GenerateDoubleTransformKernel(
const Expression: Compute.ExprTrees.Expr; const NumInputs: integer): string;
var
dataType, getIdx: string;
logWidth: integer;
lines: IStringList;
i: integer;
begin
lines := TStringListImpl.Create;
if (VectorWidth > 1) then
begin
dataType := 'double' + IntToStr(VectorWidth);
logWidth := Round(Ln(VectorWidth) / Ln(2.0));
getIdx := 'gid >> ' + IntToStr(logWidth);
end
else
begin
dataType := 'double';
getIdx := 'gid';
end;
lines.Add('#pragma OPENCL EXTENSION cl_khr_fp64 : enable');
lines.Add('');
GenerateUserFunctions(Expression, lines, dataType);
lines.Add('__kernel');
lines.Add('__attribute__((vec_type_hint(' + dataType + ')))');
lines.Add('void transform_double_' + IntToStr(NumInputs) +'(');
for i := 1 to NumInputs do
lines.Add(' __global const ' + dataType + '* src_' + IntToStr(i) + ',');
lines.Add(' __global ' + dataType + '* res,');
lines.Add(' const unsigned long num)');
lines.Add('{');
lines.Add(' const size_t gid = get_global_id(0);');
lines.Add(' if (gid >= num)');
lines.Add(' return;');
lines.Add(' const size_t idx = ' + getIdx + ';');
for i := 1 to NumInputs do
lines.Add(' const ' + dataType + ' src_value_' + IntToStr(i) + ' = src_' + IntToStr(i) + '[idx];');
GenerateDoubleTransformKernelBody(Expression, lines);
lines.Add('}');
result := StringListToStr(lines);
end;
procedure TKernelGeneratorBase.GenerateStandardFunctions(
const Lines: IStringList; const DataType: string);
begin
end;
procedure TKernelGeneratorBase.GenerateUserFunctions(
const Expression: Compute.ExprTrees.Expr; const Lines: IStringList;
const DataType: string);
var
visitor: IExprNodeVisitor;
fcol: IExprFunctionCollector;
funcs: TArray<Expr.NaryFunc>;
bodyGen: IUserFuncBodyGenerator;
f: Expr.NaryFunc;
i: integer;
s: string;
begin
visitor := TExprFunctionCollector.Create;
Expression.Accept(visitor);
fcol := visitor as IExprFunctionCollector;
funcs := fcol.Functions;
visitor := nil;
fcol := nil;
bodyGen := TUserFuncBodyGenerator.Create;
for f in funcs do
begin
s := DataType + ' ' + f.Name + '(';
for i := 1 to f.ParamCount do
begin
if i > 1 then
s := s + ', ';
s := s + DataType + ' arg_' + IntToStr(i);
end;
s := s + ')';
lines.Add(s);
lines.Add('{');
s := ' return ' + bodyGen.GenerateUserFuncBody(f.Body) + ';';
lines.Add(s);
lines.Add('}');
lines.Add('');
end;
end;
{ TGPUKernelGeneratorImpl }
constructor TGPUKernelGeneratorImpl.Create(const VectorWidth: UInt32);
begin
inherited Create(VectorWidth);
end;
procedure TGPUKernelGeneratorImpl.GenerateDoubleTransformKernelBody(
const Expression: Compute.ExprTrees.Expr; const Lines: IStringList);
var
transformGenerator: IGPUTransformKernelGenerator;
exprStr: string;
begin
transformGenerator := TGPUTransformKernelGenerator.Create;
exprStr := transformGenerator.TransformDouble(Expression);
Lines.Add(' res[idx] = ' + exprStr + ';');
end;
{ TGPUTransformKernelGenerator }
constructor TGPUTransformKernelGenerator.Create;
begin
inherited Create;
end;
function TGPUTransformKernelGenerator.TransformDouble(
const Expression: Compute.ExprTrees.Expr): string;
begin
Clear;
Expression.Accept(Self);
result := Output;
end;
procedure TGPUTransformKernelGenerator.Visit(const Node: ILambdaParamNode);
begin
Emit('src_value' + Node.Data.Name);
end;
procedure TGPUTransformKernelGenerator.Visit(const Node: IArrayElementNode);
begin
raise ENotSupportedException.Create('Arrays not supported in transform kernel');
end;
procedure TGPUTransformKernelGenerator.Visit(const Node: IVariableNode);
begin
raise ENotSupportedException.Create('Variable not supported in transform kernel');
end;
initialization
OpenCLFormatSettings := TFormatSettings.Create('en-US');
OpenCLFormatSettings.DecimalSeparator := '.';
OpenCLFormatSettings.ThousandSeparator := #0;
end.
|
{$I CetusOptions.inc}
unit ctsBaseClasses;
interface
uses
ctsTypesDef,
ctsBaseInterfaces;
type
TctsBaseClass = TInterfacedObject;
TctsNamedClass = class(TctsBaseClass)
private
FName: TctsNameString;
protected
function GetName: TctsNameString;
procedure SetName(const AValue: TctsNameString);
public
property Name: TctsNameString read GetName write SetName;
end;
TctsContainer = class(TctsNamedClass, IctsContainer)
protected
function GetCount: LongInt; virtual; abstract;
function GetReference: TObject;
procedure SetCount(const AValue: LongInt); virtual; abstract;
public
constructor Create; virtual;
function IsEmpty: Boolean; virtual;
property Count: LongInt read GetCount write SetCount;
end;
TctsContainerClass = class of TctsContainer;
implementation
// ===== TctsNamedClass =====
function TctsNamedClass.GetName: TctsNameString;
begin
Result := FName;
end;
procedure TctsNamedClass.SetName(const AValue: TctsNameString);
begin
if FName <> AValue then
begin
FName := AValue;
end;
end;
// ===== TctsContainer =====
constructor TctsContainer.Create;
begin
end;
function TctsContainer.GetReference: TObject;
begin
Result := Self;
end;
function TctsContainer.IsEmpty: Boolean;
begin
Result := Count = 0;
end;
end.
|
/// <summary> 使用Prim算法求图的最小生成树 </summary>
unit DSA.Graph.LazyPrimMST;
interface
uses
System.SysUtils,
System.Rtti,
DSA.Tree.Heap,
DSA.Interfaces.DataStructure,
DSA.Interfaces.Comparer,
DSA.List_Stack_Queue.ArrayList,
DSA.Graph.Edge;
type
TLazyPrimMST<T> = class
private type
TArr_bool = TArray<boolean>;
TEdge_T = TEdge<T>;
TMinHeap = THeap<TEdge_T>;
TList_Edge = TArrayList<TEdge_T>;
TArrEdge = TArray<TEdge_T>;
TWeightGraph_T = TWeightGraph<T>;
var
__g: TWeightGraph_T;
__pq: TMinHeap; // 最小堆, 算法辅助数据结构
// 标记数组, 在算法运行过程中标记节点i是否被访问
__marked: TArr_bool;
__mstList: TList_Edge; // 最小生成树所包含的所有边
__mstWeight: T; // 最小生成树的权值
/// <summary> 访问节点v </summary>
procedure __visit(v: integer);
public
constructor Create(g: TWeightGraph_T);
destructor Destroy; override;
/// <summary> 返回最小生成树的所有边 </summary>
function MstEdges: TArrEdge;
/// <summary> 返回最小生成树的权值 </summary>
function Weight: T;
end;
procedure Main;
implementation
uses
DSA.Graph.DenseWeightedGraph,
DSA.Graph.SparseWeightedGraph,
DSA.Utils;
type
TDenseWeightedGraph_dbl = TDenseWeightedGraph<double>;
TSparseWeightedGraph_dbl = TSparseWeightedGraph<double>;
TWeightGraph_dbl = TWeightGraph<double>;
TReadGraphWeight_dbl = TReadGraphWeight<double>;
TLazyPrimMST_dbl = TLazyPrimMST<double>;
procedure Main;
var
fileName: string;
v, i: integer;
g: TWeightGraph_dbl;
LazyPrimMST: TLazyPrimMST_dbl;
mst: TLazyPrimMST_dbl.TArrEdge;
begin
fileName := WEIGHT_GRAPH_FILE_NAME_1;
v := 8;
begin
g := TDenseWeightedGraph_dbl.Create(v, False);
TReadGraphWeight_dbl.Execute(g, FILE_PATH + fileName);
// Test Lazy Prim MST
WriteLn('Test Lazy Prim MST:');
LazyPrimMST := TLazyPrimMST_dbl.Create(g);
mst := LazyPrimMST.MstEdges;
for i := 0 to high(mst) do
WriteLn(mst[i].ToString);
WriteLn('The MST weight is: ', LazyPrimMST.Weight.ToString);
FreeAndNil(g);
end;
TDSAUtils.DrawLine;
begin
g := TSparseWeightedGraph_dbl.Create(v, False);
TReadGraphWeight_dbl.Execute(g, FILE_PATH + fileName);
// Test Lazy Prim MST
WriteLn('Test Lazy Prim MST:');
LazyPrimMST := TLazyPrimMST_dbl.Create(g);
mst := LazyPrimMST.MstEdges;
for i := 0 to high(mst) do
WriteLn(mst[i].ToString);
WriteLn('The MST weight is: ', LazyPrimMST.Weight.ToString);
FreeAndNil(g);
end;
end;
{ TLazyPrimMST }
constructor TLazyPrimMST<T>.Create(g: TWeightGraph_T);
var
i: integer;
e: TEdge_T;
a: Variant;
begin
__g := g;
__mstList := TList_Edge.Create;
__pq := TMinHeap.Create(g.Edge);
__pq.SetComparer(TEdge_T.TEdgeComparer.Default);
// 算法初始化
SetLength(__marked, g.Vertex);
for i := 0 to Pred(g.Vertex) do
__marked[i] := False;
// Lazy Prim
__visit(0);
while not __pq.IsEmpty do
begin
// 使用最小堆找出已经访问的边中权值最小的边
e := __pq.ExtractFirst;
// 如果这条边的两端都已经访问过了, 则扔掉这条边
if __marked[e.VertexA] = __marked[e.VertexB] then
Continue;
// 这条边存于最小生成树中
__mstList.AddLast(e);
// 访问和这条边连接的还没有被访问过的节点
if __marked[e.VertexA] = False then
__visit(e.VertexA)
else
__visit(e.VertexB);
end;
// 计算最小生成树的权值
__mstWeight := default (T);
a := TValue.From<T>(__mstWeight).AsVariant;
for i := 0 to __mstList.GetSize - 1 do
begin
a := a + TValue.From<T>(__mstList[i].Weight).AsVariant;
end;
TValue.FromVariant(a).ExtractRawData(@__mstWeight);
end;
destructor TLazyPrimMST<T>.Destroy;
begin
FreeAndNil(__pq);
FreeAndNil(__mstList);
inherited Destroy;
end;
function TLazyPrimMST<T>.MstEdges: TArrEdge;
begin
Result := __mstList.ToArray;
end;
function TLazyPrimMST<T>.Weight: T;
begin
Result := __mstWeight;
end;
procedure TLazyPrimMST<T>.__visit(v: integer);
var
e: TEdge_T;
begin
Assert(__marked[v] = False);
__marked[v] := True;
for e in __g.AdjIterator(v) do
begin
if (__marked[e.OtherVertex(v)] = False) then
__pq.Add(e);
end;
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* 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.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFv8StackFrame;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes;
type
TCefV8StackFrameRef = class(TCefBaseRefCountedRef, ICefV8StackFrame)
protected
function IsValid: Boolean;
function GetScriptName: ustring;
function GetScriptNameOrSourceUrl: ustring;
function GetFunctionName: ustring;
function GetLineNumber: Integer;
function GetColumn: Integer;
function IsEval: Boolean;
function IsConstructor: Boolean;
public
class function UnWrap(data: Pointer): ICefV8StackFrame;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions;
function TCefV8StackFrameRef.GetColumn: Integer;
begin
Result := PCefV8StackFrame(FData).get_column(FData);
end;
function TCefV8StackFrameRef.GetFunctionName: ustring;
begin
Result := CefStringFreeAndGet(PCefV8StackFrame(FData).get_function_name(FData));
end;
function TCefV8StackFrameRef.GetLineNumber: Integer;
begin
Result := PCefV8StackFrame(FData).get_line_number(FData);
end;
function TCefV8StackFrameRef.GetScriptName: ustring;
begin
Result := CefStringFreeAndGet(PCefV8StackFrame(FData).get_script_name(FData));
end;
function TCefV8StackFrameRef.GetScriptNameOrSourceUrl: ustring;
begin
Result := CefStringFreeAndGet(PCefV8StackFrame(FData).get_script_name_or_source_url(FData));
end;
function TCefV8StackFrameRef.IsConstructor: Boolean;
begin
Result := PCefV8StackFrame(FData).is_constructor(FData) <> 0;
end;
function TCefV8StackFrameRef.IsEval: Boolean;
begin
Result := PCefV8StackFrame(FData).is_eval(FData) <> 0;
end;
function TCefV8StackFrameRef.IsValid: Boolean;
begin
Result := PCefV8StackFrame(FData).is_valid(FData) <> 0;
end;
class function TCefV8StackFrameRef.UnWrap(data: Pointer): ICefV8StackFrame;
begin
if data <> nil then
Result := Create(data) as ICefV8StackFrame else
Result := nil;
end;
end.
|
{
publish with BSD Licence.
Copyright (c) Terry Lao
}
unit createCB;
{$MODE Delphi}
interface
uses iLBC_define,constants,C2Delphi_header;
procedure filteredCBvecs(
cbvectors:pareal; { (o) Codebook vectors for the
higher section }
mem:pareal; { (i) Buffer to create codebook
vector from }
lMem:integer { (i) Length of buffer }
);
procedure searchAugmentedCB(
low:integer; { (i) Start index for the search }
high:integer; { (i) End index for the search }
stage:integer; { (i) Current stage }
startIndex:integer; { (i) Codebook index for the first
aug vector }
target:PAreal; { (i) Target vector for encoding }
buffer:pareal; { (i) Pointer to the end of the buffer for
augmented codebook construction }
max_measure:pareal; { (i/o) Currently maximum measure }
best_index:painteger;{ (o) Currently the best index }
gain:pareal; { (o) Currently the best gain }
energy:PAreal; { (o) Energy of augmented codebook
vectors }
invenergy:PAreal{ (o) Inv energy of augmented codebook
vectors }
);
procedure createAugmentedVec(
index:integer; { (i) Index for the augmented vector
to be created }
buffer:pareal; { (i) Pointer to the end of the buffer for
augmented codebook construction }
cbVec:PAreal{ (o) The construced codebook vector }
);
implementation
{----------------------------------------------------------------*
* Construct an additional codebook vector by filtering the
* initial codebook buffer. This vector is then used to expand
* the codebook with an additional section.
*---------------------------------------------------------------}
procedure filteredCBvecs(
cbvectors:pareal; { (o) Codebook vectors for the
higher section }
mem:pareal; { (i) Buffer to create codebook
vector from }
lMem:integer { (i) Length of buffer }
);
var
j,k:integer;
pp, pp1:^real;
tempbuff2:array [0..CB_MEML+CB_FILTERLEN-1] of real;
pos:^real;
begin
fillchar(tempbuff2,(CB_HALFFILTERLEN-1)*sizeof(real),0);
move( mem[0],tempbuff2[CB_HALFFILTERLEN-1], lMem*sizeof(real));
fillchar(tempbuff2[lMem+CB_HALFFILTERLEN-1],(CB_HALFFILTERLEN+1)*sizeof(real), 0);
{ Create codebook vector for higher section by filtering }
{ do filtering }
pos:=@cbvectors[0];
fillchar(pos^, lMem*sizeof(real), 0);
for k:=0 to lMem-1 do
begin
pp:=@tempbuff2[k];
pp1:=@cbfiltersTbl[CB_FILTERLEN-1];
for j:=0 to CB_FILTERLEN-1 do
begin
pos^:=pos^+pp^*pp1^;
inc(pp);
dec(pp1);
end;
inc(pos);
end;
end;
{----------------------------------------------------------------*
* Search the augmented part of the codebook to find the best
* measure.
*----------------------------------------------------------------}
procedure searchAugmentedCB(
low:integer; { (i) Start index for the search }
high:integer; { (i) End index for the search }
stage:integer; { (i) Current stage }
startIndex:integer; { (i) Codebook index for the first
aug vector }
target:PAreal; { (i) Target vector for encoding }
buffer:pareal; { (i) Pointer to the end of the buffer for
augmented codebook construction }
max_measure:pareal; { (i/o) Currently maximum measure }
best_index:painteger;{ (o) Currently the best index }
gain:pareal; { (o) Currently the best gain }
energy:PAreal; { (o) Energy of augmented codebook
vectors }
invenergy:PAreal{ (o) Inv energy of augmented codebook
vectors }
);
var
icount, ilow, j, tmpIndex:integer;
pp, ppo, ppi, ppe:^real;
crossDot, alfa:real;
weighted, measure, nrjRecursive:real;
ftmp:real;
begin
{ Compute the energy for the first (low-5)
noninterpolated samples }
nrjRecursive := 0.0;
pp := @buffer[ - low + 1];
for j:=0 to low - 6 do
begin
nrjRecursive := nrjRecursive+( (pp^)*(pp^) );
inc(pp);
end;
ppe := @buffer[ - low];
for icount:=low to high do
begin
{ Index of the codebook vector used for retrieving
energy values }
tmpIndex := startIndex+icount-20;
ilow := icount-4;
{ Update the energy recursively to save complexity }
nrjRecursive := nrjRecursive + (ppe^)*(ppe^);
dec(ppe);
energy[tmpIndex] := nrjRecursive;
{ Compute cross dot product for the first (low-5)
samples }
crossDot := 0.0;
pp := @buffer[-icount];
for j:=0 to ilow-1 do
begin
crossDot := crossDot+target[j]*(pp^);
inc(pp);
end;
{ interpolation }
alfa := 0.2;
j:=0;
ppo := @buffer[j-4];
ppi := @buffer[-icount-4];
for j:=ilow to icount-1 do
begin
weighted := (1.0-alfa)*(ppo^)+alfa*(ppi^);
inc(ppo);
inc(ppi);
energy[tmpIndex] := energy[tmpIndex]+weighted*weighted;
crossDot := crossDot+target[j]*weighted;
alfa :=alfa+ 0.2;
end;
{ Compute energy and cross dot product for the
remaining samples }
pp := @buffer[ - icount];
for j:=icount to SUBL-1 do
begin
energy[tmpIndex] := energy[tmpIndex]+(pp^)*(pp^);
crossDot :=crossDot+ target[j]*(pp^);
inc(pp);
end;
if (energy[tmpIndex]>0.0) then
begin
invenergy[tmpIndex]:=1.0/(energy[tmpIndex]+EPS);
end
else
begin
invenergy[tmpIndex] := 0.0;
end;
if (stage=0) then
begin
measure := -10000000.0;
if (crossDot > 0.0) then
begin
measure := crossDot*crossDot*invenergy[tmpIndex];
end;
end
else
begin
measure := crossDot*crossDot*invenergy[tmpIndex];
end;
{ check if measure is better }
ftmp := crossDot*invenergy[tmpIndex];
if ((measure>max_measure[0]) and (abs(ftmp)<CB_MAXGAIN)) then
begin
best_index[0] := tmpIndex;
max_measure[0] := measure;
gain[0] := ftmp;
end;
end;
end;
{----------------------------------------------------------------*
* Recreate a specific codebook vector from the augmented part.
*
*----------------------------------------------------------------}
procedure createAugmentedVec(
index:integer; { (i) Index for the augmented vector
to be created }
buffer:pareal; { (i) Pointer to the end of the buffer for
augmented codebook construction }
cbVec:PAreal{ (o) The construced codebook vector }
);
var
ilow, j:integer;
pp, ppo, ppi:^real;
alfa, alfa1, weighted:real;
begin
ilow := index-5;
{ copy the first noninterpolated part }
pp := @buffer[-index];
move(pp^,cbVec^,sizeof(real)*index);
{ interpolation }
alfa1 := 0.2;
alfa := 0.0;
j:=0;
ppo := @buffer[j-5];
ppi := @buffer[-index-5];
for j:=ilow to index-1 do
begin
weighted := (1.0-alfa)*(ppo^)+alfa*(ppi^);
inc(ppo);
inc(ppi);
cbVec[j] := weighted;
alfa :=alfa + alfa1;
end;
{ copy the second noninterpolated part }
pp := @buffer[ - index];
move(pp^,cbVec[index],sizeof(real)*(SUBL-index));
end;
end.
|
unit ufrmDialogActionList;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls, SUIForm,
uActionListCust, StdCtrls, System.Actions, Vcl.ActnList,
ufraFooterDialog3Button;
type
TfrmDialogActionList = class(TfrmMasterDialog)
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure footerDialogMasterbtnSaveClick(Sender: TObject);
private
{ Private declarations }
FActID : Integer;
FActLst : TActionListCust;
procedure ClearData;
procedure SetData;
public
procedure ShowWithID(aUnitId: integer; aLoginID: integer; aActID: integer = 0);
{ Public declarations }
end;
var
frmDialogActionList: TfrmDialogActionList;
implementation
{$R *.dfm}
uses
uRMSUnit, uGTSUICommonDlg;
procedure TfrmDialogActionList.ClearData;
begin
edtID.Clear;
edtNm.Clear;
edtDesc.Clear;
end;
procedure TfrmDialogActionList.SetData;
begin
if FActID <> 0 then
begin
if FActLst.LoadByID(FActID, DialogUnit) then
begin
edtID.Text := IntToStr(FActLst.ActID);
edtNm.Text := FActLst.ActNm;
edtDesc.Text := FActLst.ActDesc;
end;
end;
end;
procedure TfrmDialogActionList.ShowWithID(aUnitId: integer; aLoginID: integer;
aActID: integer = 0);
begin
DialogUnit := aUnitId;
FLoginID := aLoginID;
FActID := aActID;
SetData;
Self.ShowModal;
end;
procedure TfrmDialogActionList.FormCreate(Sender: TObject);
begin
inherited;
FActLst := TActionListCust.Create(nil);
end;
procedure TfrmDialogActionList.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TfrmDialogActionList.FormDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(FActLst);
frmDialogActionList := nil;
end;
procedure TfrmDialogActionList.footerDialogMasterbtnSaveClick(
Sender: TObject);
begin
inherited;
FActLst.UpdateData(edtDesc.Text, FActID, edtNm.Text, DialogUnit);
if FActLst.SaveToDB then
begin
cCommitTrans;
CommonDlg.ShowMessage('Sukses menyimpan data');
if FActID <> 0 then
Self.Close
else
ClearData;
end
else
begin
cRollbackTrans;
CommonDlg.ShowError('Gagal menyimpan data!!');
end;
end;
end.
|
//******************************************************************************
// Проект "Контракты"
// Справочник групп пользователей
// Чернявский А.Э. 2005г.
// последние изменения Перчак А.Л. 29/10/2008
//******************************************************************************
unit cn_Roles_Unit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, dxBar, dxBarExtItems, ImgList, cxGraphics, cxContainer, cxEdit,
cxProgressBar, dxStatusBar, cxControls, IBase,
cn_DM_Roles, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, DB,
cxDBData, cxGridLevel, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, cxClasses, cxTextEdit,
cn_Common_Funcs, cnConsts, cxSplitter, StdCtrls, cxGroupBox, cn_Roles_AE,
cn_Common_Messages, cnConsts_Messages;
type
TfrmRoles = class(TForm)
BarManager: TdxBarManager;
AddButton: TdxBarLargeButton;
EditButton: TdxBarLargeButton;
DeleteButton: TdxBarLargeButton;
RefreshButton: TdxBarLargeButton;
ExitButton: TdxBarLargeButton;
PopupImageList: TImageList;
LargeImages: TImageList;
DisabledLargeImages: TImageList;
StatusBar: TdxStatusBar;
Styles: TcxStyleRepository;
BackGround: TcxStyle;
FocusedRecord: TcxStyle;
Header: TcxStyle;
DesabledRecord: TcxStyle;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
cxStyle15: TcxStyle;
cxStyle16: TcxStyle;
Default_StyleSheet: TcxGridTableViewStyleSheet;
DevExpress_Style: TcxGridTableViewStyleSheet;
Grid: TcxGrid;
GridDBView: TcxGridDBTableView;
GridLevel: TcxGridLevel;
name: TcxGridDBColumn;
full_name: TcxGridDBColumn;
SelectButton: TdxBarLargeButton;
cxSplitter1: TcxSplitter;
Grid_Spec: TcxGrid;
TableView_Smets: TcxGridDBTableView;
cxGridLevel1: TcxGridLevel;
SMETA_TITLE: TcxGridDBColumn;
SMETA_KOD: TcxGridDBColumn;
cxGroupBox1: TcxGroupBox;
Group_Label: TLabel;
Smeta_Label: TLabel;
procedure ExitButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure RefreshButtonClick(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
procedure TableView_SmetsDblClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
private
PLanguageIndex: byte;
DM, DM_Detail_1:TDM_ROLES;
DB_sp_Handle:TISC_DB_HANDLE;
procedure FormIniLanguage;
public
res:Variant;
Is_admin:Boolean;
constructor Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE;Is_admin:boolean);reintroduce;
end;
implementation
{$R *.dfm}
constructor TfrmRoles.Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE;Is_admin:boolean);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AOwner);
DB_sp_Handle :=DB_Handle;
DM:=TDM_ROLES.Create(Self);
DM.DataSet.SQLs.SelectSQL.Text := 'select * from CN_ROLES_SELECT';
DM.DB.Handle:=DB_Handle;
DM.DataSet.Open;
GridDBView.DataController.DataSource := DM.DataSource;
DM_Detail_1:=TDM_ROLES.Create(Self);
DM_Detail_1.DataSet.SQLs.SelectSQL.Text := 'SELECT * FROM CN_ROLES_BY_SMET_SELECT_MD (?ID_ROLE ) order by SMETA_KOD';
DM_Detail_1.DataSet.DataSource:= DM.DataSource;
DM_Detail_1.DB.Handle:=DB_Handle;
DM_Detail_1.DataSet.Open;
TableView_Smets.DataController.DataSource := DM_Detail_1.DataSource;
FormIniLanguage();
Self.Is_admin:=is_admin;
Screen.Cursor:=crDefault;
end;
procedure TfrmRoles.FormIniLanguage;
begin
PLanguageIndex:= cn_Common_Funcs.cnLanguageIndex();
//кэпшн формы
Caption:= cnConsts.cn_Main_SpRoles[PLanguageIndex];
//названия кнопок
AddButton.Caption := cnConsts.cn_InsertBtn_Caption[PLanguageIndex];
EditButton.Caption := cnConsts.cn_EditBtn_Caption[PLanguageIndex];
DeleteButton.Caption := cnConsts.cn_DeleteBtn_Caption[PLanguageIndex];
RefreshButton.Caption := cnConsts.cn_RefreshBtn_Caption[PLanguageIndex];
ExitButton.Caption := cnConsts.cn_ExitBtn_Caption[PLanguageIndex];
name.Caption := cnConsts.cn_Name_Column[PLanguageIndex];
full_name.Caption := cnConsts.cn_FullName[PLanguageIndex];
SMETA_KOD.Caption := cnConsts.cn_roles_Kod[PLanguageIndex];
SMETA_TITLE.Caption := cnConsts.cn_Name_Column[PLanguageIndex];
Group_Label.Caption := cnConsts.cn_roles_Group[PLanguageIndex];
Smeta_Label.Caption := cnConsts.cn_roles_Smets[PLanguageIndex];
//статусбар
StatusBar.Panels[0].Text:= cnConsts.cn_InsertBtn_ShortCut[PLanguageIndex] + cnConsts.cn_InsertBtn_Caption[PLanguageIndex];
StatusBar.Panels[1].Text:= cnConsts.cn_EditBtn_ShortCut[PLanguageIndex] + cnConsts.cn_EditBtn_Caption[PLanguageIndex];
StatusBar.Panels[2].Text:= cnConsts.cn_DeleteBtn_ShortCut[PLanguageIndex] + cnConsts.cn_DeleteBtn_Caption[PLanguageIndex];
StatusBar.Panels[3].Text:= cnConsts.cn_RefreshBtn_ShortCut[PLanguageIndex] + cnConsts.cn_RefreshBtn_Caption[PLanguageIndex];
StatusBar.Panels[4].Text:= cnConsts.cn_ExitBtn_ShortCut[PLanguageIndex] + cnConsts.cn_ExitBtn_Caption[PLanguageIndex];
end;
procedure TfrmRoles.ExitButtonClick(Sender: TObject);
begin
close;
end;
procedure TfrmRoles.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if FormStyle = fsMDIChild then action:=caFree
else
DM.Free;
end;
procedure TfrmRoles.FormShow(Sender: TObject);
begin
if FormStyle = fsMDIChild then SelectButton.Enabled:=false;
end;
procedure TfrmRoles.RefreshButtonClick(Sender: TObject);
begin
DM.DataSet.CloseOpen(True);
DM_Detail_1.DataSet.CloseOpen(True);
end;
procedure TfrmRoles.AddButtonClick(Sender: TObject);
var
frmAddEdit: TfrmAddEdit;
begin
if not Is_Admin then
if CheckPermission('/ROOT/Contracts/Cn_Sp','Edit') <> 0
then
begin
messagebox(handle,
pchar(cnConsts_Messages.cn_NotHaveRights[PLanguageIndex]
+#13+ cnConsts_Messages.cn_GoToAdmin[PLanguageIndex]),
pchar(cnConsts_Messages.cn_ActionDenied[PLanguageIndex]), MB_ICONWARNING or mb_Ok);
exit;
end;
frmAddEdit := TfrmAddEdit.Create(self, DB_sp_Handle, PLanguageIndex);
frmAddEdit.Caption :=cnConsts.cn_InsertBtn_Caption[PLanguageIndex];
frmAddEdit.TextEdit.Text := DM.DataSet['Full_Name'];
if frmAddEdit.ShowModal = mrOk then
begin
DM.StProc.StoredProcName := 'CN_ROLES_BY_SMET_INSERT';
DM.StProc.Transaction.StartTransaction;
DM.StProc.Prepare;
DM.StProc.ParamByName('ID_ROLE').AsInt64 := DM.DataSet['ID_ROLE'];
DM.StProc.ParamByName('ID_SMETA').AsInt64 := frmAddEdit.ID_SMET;
DM.StProc.ExecProc;
DM.StProc.Transaction.Commit;
DM_Detail_1.DataSet.CloseOpen(True);
end;
frmAddEdit.Free;
end;
procedure TfrmRoles.EditButtonClick(Sender: TObject);
var
frmAddEdit: TfrmAddEdit;
begin
if not Is_Admin then
if CheckPermission('/ROOT/Contracts/Cn_Sp','Edit') <> 0
then
begin
messagebox(handle,
pchar(cnConsts_Messages.cn_NotHaveRights[PLanguageIndex]
+#13+ cnConsts_Messages.cn_GoToAdmin[PLanguageIndex]),
pchar(cnConsts_Messages.cn_ActionDenied[PLanguageIndex]), MB_ICONWARNING or mb_Ok);
exit;
end;
if TableView_Smets.DataController.RecordCount = 0 then exit;
frmAddEdit := TfrmAddEdit.Create(self, DB_sp_Handle, PLanguageIndex);
frmAddEdit.Caption :=cnConsts.cn_EditBtn_Caption[PLanguageIndex];
frmAddEdit.TextEdit.Text := DM.DataSet['Full_Name'];
frmAddEdit.Smeta_Edit.Text := DM_Detail_1.DataSet['SMETA_KOD'];
frmAddEdit.Smeta_description_Label.Caption := DM_Detail_1.DataSet['SMETA_TITLE'];
frmAddEdit.ID_SMET := DM_Detail_1.DataSet['ID_SMETA'];
if frmAddEdit.ShowModal = mrOk then
begin
DM.StProc.StoredProcName := 'CN_ROLES_BY_SMET_DELETE';
DM.StProc.Transaction.StartTransaction;
DM.StProc.Prepare;
DM.StProc.ParamByName('ID_ROLE').AsInt64 := DM.DataSet['ID_ROLE'];
DM.StProc.ParamByName('ID_SMETA').AsInt64 := DM_Detail_1.DataSet['ID_SMETA'];
DM.StProc.ExecProc;
DM.StProc.StoredProcName := 'CN_ROLES_BY_SMET_INSERT';
DM.StProc.Transaction.StartTransaction;
DM.StProc.Prepare;
DM.StProc.ParamByName('ID_ROLE').AsInt64 := DM.DataSet['ID_ROLE'];
DM.StProc.ParamByName('ID_SMETA').AsInt64 := frmAddEdit.ID_SMET;
DM.StProc.ExecProc;
DM.StProc.Transaction.Commit;
DM_Detail_1.DataSet.CloseOpen(True);
end;
frmAddEdit.Free;
end;
procedure TfrmRoles.TableView_SmetsDblClick(Sender: TObject);
begin
EditButtonClick(Sender);
end;
procedure TfrmRoles.DeleteButtonClick(Sender: TObject);
var i: integer;
begin
if not Is_Admin then
if CheckPermission('/ROOT/Contracts/Cn_Sp','Edit') <> 0
then
begin
messagebox(handle,
pchar(cnConsts_Messages.cn_NotHaveRights[PLanguageIndex]
+#13+ cnConsts_Messages.cn_GoToAdmin[PLanguageIndex]),
pchar(cnConsts_Messages.cn_ActionDenied[PLanguageIndex]), MB_ICONWARNING or mb_Ok);
exit;
end;
if TableView_Smets.DataController.RecordCount = 0 then exit;
i:= cn_Common_Messages.cnShowMessage(cnConsts.cn_Confirmation_Caption[PLanguageIndex], cnConsts.cn_DeletePromt[PLanguageIndex], mtConfirmation, [mbYes, mbNo]);
if ((i = 7) or (i= 2)) then exit;
DM.StProc.StoredProcName := 'CN_ROLES_BY_SMET_DELETE';
DM.StProc.Transaction.StartTransaction;
DM.StProc.Prepare;
DM.StProc.ParamByName('ID_ROLE').AsInt64 := DM.DataSet['ID_ROLE'];
DM.StProc.ParamByName('ID_SMETA').AsInt64 := DM_Detail_1.DataSet['ID_SMETA'];
DM.StProc.ExecProc;
DM.StProc.Transaction.Commit;
DM_Detail_1.DataSet.CloseOpen(True);
end;
end.
|
{ *
* Copyright (C) 2014-2015 ozok <ozok26@gmail.com>
*
* This file is part of InstagramSaver.
*
* InstagramSaver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* InstagramSaver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with InstagramSaver. If not, see <http://www.gnu.org/licenses/>.
*
* }
unit UnitPhotoDownloaderThread;
interface
uses Classes, Windows, SysUtils, Messages, StrUtils, Vcl.ComCtrls, Generics.Collections, IdHTTP, IdComponent,
IdBaseComponent, IdIOHandler, IdIOHandlerSocket,
IdIOHandlerStack, IdSSL, IdSSLOpenSSL;
type
TDownloadStatus = (idle = 0, downloading = 1, done = 2, error = 3, gettinginfo = 4);
type
TPhotoDownloadThread = class(TThread)
private
{ Private declarations }
FStatus: TDownloadStatus;
FErrorMsg: string;
FURLs: TStringList;
FOutputFiles: TStringList;
FProgress: Integer;
FURL: string;
FID: Integer;
FDontDoubleDownload: Boolean;
FDownloading: Boolean;
FDownloadedImgCount: Cardinal;
FIgnoredImgCount: Cardinal;
FWaitMS: integer;
FDownloadSize: int64;
// sync
procedure ReportError;
// force directory creation everytime a file is downloaded
procedure CreateOutputFolder(const FileName: string);
procedure DownloadFile(const URL: string; const FileName: string);
procedure Wait;
protected
procedure Execute; override;
public
property Status: TDownloadStatus read FStatus;
property Progress: Integer read FProgress;
property ErrorMsg: string read FErrorMsg;
property CurrentURL: string read FURL;
property ID: Integer read FID write FID;
property DontDoubleDownload: Boolean read FDontDoubleDownload write FDontDoubleDownload;
property DownloadedImgCount: Cardinal read FDownloadedImgCount;
property IgnoredImgCount: Cardinal read FIgnoredImgCount;
property DownloadSize: int64 read FDownloadSize;
constructor Create(const URLs: TStringList; const OutputFiles: TStringList; const WaitMS: integer);
destructor Destroy; override;
procedure Stop();
end;
implementation
{ TPhotoDownloadThread }
uses UnitMain;
constructor TPhotoDownloadThread.Create(const URLs: TStringList; const OutputFiles: TStringList; const WaitMS: integer);
begin
inherited Create(False);
FreeOnTerminate := False;
// defaults
FStatus := idle;
FOutputFiles := TStringList.Create;
FURLs := TStringList.Create;
FURLs.AddStrings(URLs);
FOutputFiles.AddStrings(OutputFiles);
FProgress := 0;
FWaitMS := WaitMS;
end;
procedure TPhotoDownloadThread.CreateOutputFolder(const FileName: string);
begin
if not DirectoryExists(ExtractFileDir(FileName)) then
begin
ForceDirectories(ExtractFileDir(FileName))
end;
end;
destructor TPhotoDownloadThread.Destroy;
begin
inherited Destroy;
FURLs.Free;
FOutputFiles.Free;
end;
procedure TPhotoDownloadThread.DownloadFile(const URL, FileName: string);
var
LMS: TMemoryStream;
LIdHTTP: TIdHTTP;
LSSLHandler: TIdSSLIOHandlerSocketOpenSSL;
begin
LIdHTTP := TIdHTTP.Create(nil);
LSSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
try
LMS := TMemoryStream.Create;
try
try
LIdHTTP.IOHandler := LSSLHandler;
LIdHTTP.Request.UserAgent := 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36';
LIdHTTP.Get(URL, LMS);
FDownloadSize := FDownloadSize + LMS.Size;
LMS.SaveToFile(FileName);
except on E: Exception do
begin
FErrorMsg := LIdHTTP.ResponseText + ' [' + FloatToStr(LIdHTTP.ResponseCode) + '] Error msg: ' + E.Message;
Synchronize(ReportError);
end;
end;
finally
LMS.Free;
end;
finally
LSSLHandler.Free;
LIdHTTP.Free;
end;
end;
procedure TPhotoDownloadThread.Execute;
var
I: Integer;
begin
FDownloadedImgCount := 0;
FIgnoredImgCount := 0;
FDownloadSize := 0;
FDownloading := True;
FStatus := downloading;
try
for I := 0 to FURLs.Count-1 do
begin
FProgress := i;
FURL := FURLs[i];
CreateOutputFolder(FOutputFiles[i]);
if FDownloading then
begin
// do not download twice
if FDontDoubleDownload then
begin
// download only if file doesn't exist
if not FileExists(FOutputFiles[i]) then
begin
DownloadFile(FURLs[i], FOutputFiles[i]);
Inc(FDownloadedImgCount);
end
else
begin
Inc(FIgnoredImgCount);
end;
end
else
begin
// download all the same
DownloadFile(FURLs[i], FOutputFiles[i]);
Inc(FDownloadedImgCount);
end;
end;
Wait;
end;
finally
FStatus := done;
end;
end;
procedure TPhotoDownloadThread.ReportError;
begin
MainForm.ThreadsList.Lines.Add('[PhotoDownloaderThread_' + FloatToStr(FID) + '] ' + FErrorMsg + ' Link: ' + FURLs[FProgress]);
FErrorMsg := '';
end;
procedure TPhotoDownloadThread.Stop;
begin
FDownloading := False;
FStatus := done;
FURL := '';
Self.Terminate;
end;
procedure TPhotoDownloadThread.Wait;
begin
if FWaitMS > 0 then
begin
Sleep(FWaitMS);
end;
end;
end.
|
//This unit is a information class. This class shouldn't be used by itself,
//but rather by descending classes such as TZoneServerInfo. This is designed
//to store a connected server's information, such as WAN AND LAN IPs and their
//cardinal forms, which are used by the client
unit ServerInfo;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
IdContext;
type
TServerInfo = class
protected
fWANIPCard : LongWord;
fLANIPCard : LongWord;
fWAN : String;
fLAN : String;
fLANPartial : String;
procedure SetWANLongWord(const Value : String);
procedure SetLANLongWord(const Value : String);
public
Port : Word;
Connection: TIdContext;
property WAN : String read fWAN write SetWANLongWord;
property LAN : String read fLAN write SetLANLongWord;
function Address(const ClientIP : string) : LongWord;
end;
implementation
uses
StrUtils,
WinLinux;
procedure TServerInfo.SetWANLongWord(const Value : string);
begin
fWAN := Value;
fWANIPCard := GetLongWordFromIPString(GetIPStringFromHostname(Value).Full);
end;
procedure TServerInfo.SetLANLongWord(const Value : string);
var
ReturnedIPs : TIPSet;
begin
fLAN := Value;
ReturnedIPs := GetIPStringFromHostname(Value);
fLANPartial := ReturnedIPs.Partial;
fLANIPCard := GetLongWordFromIPString(ReturnedIPs.Full);
end;
//This routine takes a client's IP, and determines which IP, WAN or LAN in
//integer form.
function TServerInfo.Address(const ClientIP : string) : LongWord;
begin
if AnsiStartsText('127.0.0.', ClientIP) then
begin
Result := GetLongWordFromIPString('127.0.0.1');
end else
if AnsiStartsText(fLANPartial, ClientIP) then
begin
Result := fLANIPCard;
end else
begin
Result := fWANIPCard;
end;
end;
end.
|
{-----------------------------------------------------------------------------
Least-Resistance Designer Library
The Initial Developer of the Original Code is Scott J. Miles
<sjmiles (at) turbophp (dot) com>.
Portions created by Scott J. Miles are
Copyright (C) 2005 Least-Resistance Software.
All Rights Reserved.
-------------------------------------------------------------------------------}
unit DesignClip;
interface
uses
Windows, Classes;
type
TDesignComponentClipboard = class
protected
Stream: TMemoryStream;
procedure Close;
procedure Open;
procedure ReadError(Reader: TReader; const Message: string;
var Handled: Boolean);
public
function GetComponent: TComponent;
procedure CloseRead;
procedure CloseWrite;
procedure OpenRead;
procedure OpenWrite;
procedure SetComponent(inComponent: TComponent);
end;
implementation
uses
Clipbrd, DesignUtils;
var
CF_COMPONENTSTREAM: Cardinal;
{ TDesignComponentClipboard }
procedure TDesignComponentClipboard.Close;
begin
Stream.Free;
Clipboard.Close;
end;
procedure TDesignComponentClipboard.CloseRead;
begin
Close;
end;
procedure TDesignComponentClipboard.CloseWrite;
begin
LrCopyStreamToClipboard(CF_COMPONENTSTREAM, Stream);
Close;
end;
function TDesignComponentClipboard.GetComponent: TComponent;
begin
if Stream.Position < Stream.Size then
Result := LrLoadComponentFromBinaryStream(Stream, nil, ReadError)
else
Result := nil;
end;
procedure TDesignComponentClipboard.Open;
begin
Clipboard.Open;
Stream := TMemoryStream.Create;
end;
procedure TDesignComponentClipboard.OpenRead;
begin
Open;
LrCopyStreamFromClipboard(CF_COMPONENTSTREAM, Stream);
end;
procedure TDesignComponentClipboard.OpenWrite;
begin
Open;
end;
procedure TDesignComponentClipboard.ReadError(Reader: TReader;
const Message: string; var Handled: Boolean);
begin
Handled := true;
end;
procedure TDesignComponentClipboard.SetComponent(inComponent: TComponent);
begin
LrSaveComponentToBinaryStream(Stream, inComponent);
end;
initialization
{ The following string should not be localized }
CF_COMPONENTSTREAM := RegisterClipboardFormat('Delphi Components');
end.
|
unit uFrmMemoriaFiscal;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uPai, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, Mask,
DateBox;
type
TFrmMemoriaFiscal = class(TFrmPai)
GroupNumber: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Edit1: TEdit;
Edit2: TEdit;
optSimplificada: TRadioButton;
optCompleta: TRadioButton;
GroupDate: TGroupBox;
Label3: TLabel;
Label4: TLabel;
rbComplete: TRadioButton;
rbSimple: TRadioButton;
btnOK: TButton;
dt1: TDateBox;
dt2: TDateBox;
procedure btnOKClick(Sender: TObject);
procedure btCloseClick(Sender: TObject);
private
fResult : Boolean;
fStartType : Integer;
function ValidateFields : Boolean;
public
function StartDate(var sDate1, sDate2, sOpt: String; bShowOpt : Boolean) : Boolean;
function StartReducao(var sRet1, sRet2, sOpt: String; bShowOpt : Boolean) : Boolean;
function StartCOO(var sRet1, sRet2, sOpt: String; bShowOpt : Boolean) : Boolean;
end;
implementation
{$R *.dfm}
{ TFrmMemoriaFiscal }
function TFrmMemoriaFiscal.StartDate(var sDate1, sDate2, sOpt: String; bShowOpt : Boolean): Boolean;
begin
fResult := False;
GroupDate.Visible := True;
fStartType := 1;
rbComplete.Visible := bShowOpt;
rbSimple.Visible := bShowOpt;
ShowModal;
Result := fResult;
if Result then
begin
sDate1 := FormatDatetime('dd/mm/yyyy', dt1.Date);
sDate2 := FormatDatetime('dd/mm/yyyy', dt2.Date);
if rbComplete.Checked = true then
sOpt := 'c'
else
sOpt := 's';
end;
end;
procedure TFrmMemoriaFiscal.btnOKClick(Sender: TObject);
begin
inherited;
if not ValidateFields then
ModalResult := mrNone
else
fResult := True;
end;
procedure TFrmMemoriaFiscal.btCloseClick(Sender: TObject);
begin
inherited;
fResult := False;
Close;
end;
function TFrmMemoriaFiscal.ValidateFields: Boolean;
begin
Result := True;
if fStartType = 1 then
begin
end;
end;
function TFrmMemoriaFiscal.StartReducao(var sRet1, sRet2, sOpt: String;
bShowOpt: Boolean): Boolean;
begin
fResult := False;
GroupNumber.Visible := True;
fStartType := 2;
optCompleta.Visible := bShowOpt;
optSimplificada.Visible := bShowOpt;
ShowModal;
Result := fResult;
if Result then
begin
sRet1 := Edit1.Text;
sRet2 := Edit2.Text;
if optCompleta.Checked = true then
sOpt := 'c'
else
sOpt := 's';
end;
end;
function TFrmMemoriaFiscal.StartCOO(var sRet1, sRet2, sOpt: String;
bShowOpt: Boolean): Boolean;
begin
fResult := False;
GroupNumber.Visible := True;
fStartType := 2;
optCompleta.Visible := bShowOpt;
optSimplificada.Visible := bShowOpt;
Label1.Caption := 'COO Inicial:';
Label2.Caption := 'COO Final:';
ShowModal;
Result := fResult;
if Result then
begin
sRet1 := Edit1.Text;
sRet2 := Edit2.Text;
if optCompleta.Checked = true then
sOpt := 'c'
else
sOpt := 's';
end;
end;
end.
|
unit uSprFilter;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, ADODB, StdCtrls, Grids, DBGrids, StrUtils, ImgList, uSprJoin;
type
TsprFilterComparisonOperator = type string;
TsprFilter = class(TCollectionItem)
private
FName: string;
FGroupName: string;
FFieldName: string;
FFilterFieldName: string;
FExpression: string;
FCombineOperator: string;
FComparisionOperator: TsprFilterComparisonOperator;
FValue: Variant;
FEnabled: Boolean;
//FDesc: Boolean;
//FOrder: string;
FJoin: TsprJoin;
//procedure SetFieldName(const Value: string);
procedure Clear;
function CheckRename(const NewName: string): Boolean;
procedure SetName(const Value: string);
procedure SetExpression(const Value: string);
public
procedure Init(AFieldName: string; AFilterValue: Variant;
AFilterComparisionOperator: TsprFilterComparisonOperator; AFilterGroup: string);
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
function GetAsString(IncludeCombineOperator: Boolean = True): string;
function GetJoinAlias: string;
property Join: TsprJoin read FJoin;
property GroupName: string read FGroupName write FGroupName;
property Enabled: Boolean read FEnabled write FEnabled;
property Name: string read FName write SetName;
property Expression: string read FExpression write SetExpression;
//property FieldName: string read FFieldName write
// SetFieldName;
//property Desc: Boolean read FDesc write FDesc;
end;
TsprFilters = class(TOwnedCollection)
private
function GetItem(Index: Integer): TsprFilter;
public
constructor Create(Owner: TPersistent);
destructor Destroy; override;
function Add: TsprFilter;
procedure Clear(AFilterGroup: string = '');
procedure AddCaptionFilter(FieldName: string; FilterValue: Variant;
FilterComparisionOperator: TsprFilterComparisonOperator; FilterGroup: string);
function FindByName(FilterName: string): TsprFilter;
function GetFilterByName(FilterName: string): TsprFilter;
property Items[Index: Integer]: TsprFilter read GetItem; default;
end;
const
sprNoFilter = '1 = 0';
implementation
constructor TsprFilter.Create(Collection: TCollection);
begin
inherited;
FJoin := TsprJoin.Create;
FEnabled := False;
Clear;
end;
destructor TsprFilter.Destroy;
begin
FJoin.Free;
inherited;
end;
procedure TsprFilter.Clear;
begin
FJoin.Clear;
FEnabled := False;
FFieldName := '';
FFilterFieldName := '';
FValue := Null;
FExpression := '';
FCombineOperator := 'and';
end;
function TsprFilter.CheckRename(const NewName: string): Boolean;
var
f: TsprFilter;
begin
f := TsprFilters(Collection).FindByName(NewName);
Result := (f = nil) or (f = Self);
end;
procedure TsprFilter.SetName(const Value: string);
begin
if not CheckRename(Value) then
raise Exception.Create(Format('Фильтр с именем ''%s'' уже существует!',
[Value]));
FName := Value;
end;
procedure TsprFilter.SetExpression(const Value: string);
begin
FExpression := Value;
end;
function TsprFilter.GetJoinAlias: string;
begin
Result := 'spr_f' + IntToStr(Self.ID);
end;
procedure TsprFilter.Init(AFieldName: string; AFilterValue: Variant;
AFilterComparisionOperator: TsprFilterComparisonOperator; AFilterGroup: string);
var
vDS: TDataSet;
vField: TField;
vStr: string;
L: TStringList;
vFieldValueStr: string;
vLength: Integer;
I: Integer;
const
Asterisks = ['*', '%'];
begin
Clear;
vDS := TDataSet(Collection.Owner);
vField := vDS.FindField(AFieldName);
if Assigned(vField) then
begin
if vField.FieldKind in [fkCalculated] then
Exit;
FFieldName := vField.FieldName;
FGroupName := AFilterGroup;
FComparisionOperator := AFilterComparisionOperator;
FEnabled := True;
if vField.Origin <> '' then
vStr := vField.Origin
else
vStr := vField.FieldName;
if vField.DataType in [ftDateTime] then
vStr := Format('format(%s, ''dd.MM.yyyy HH:mm:ss'')', [vStr])
else
if vField.DataType in [ftDate] then
vStr := Format('format(%s, ''dd.MM.yyyy'')', [vStr]);
FJoin.ProcessField(vField, vStr, GetJoinAlias, FFilterFieldName);
if Pos(FComparisionOperator, 'LIKE') > 0 then
begin
vFieldValueStr := VarToStr(AFilterValue);
vLength := Length(vFieldValueStr);
FEnabled := vLength > 0;
if FEnabled and
(((vFieldValueStr[1] in Asterisks) and (vFieldValueStr[vLength] in Asterisks)) or
((vFieldValueStr[1] in Asterisks) and not (vFieldValueStr[vLength] in Asterisks)) or
(not (vFieldValueStr[1] in Asterisks) and (vFieldValueStr[vLength] in Asterisks))) then
FValue := '''' + StringReplace(VarToStr(AFilterValue), '*', '%', [rfReplaceAll, rfIgnoreCase]) + ''''
else
begin
FValue := StringReplace(VarToStr(AFilterValue), '*', '%', [rfReplaceAll, rfIgnoreCase]);
FValue := '''%' + FValue + '%''';
end;
end
else
begin
FValue := AFilterValue;
if VarIsNull(FValue) or VarIsEmpty(FValue) or (AnsiUpperCase(FValue) = 'NULL') or (VarToStr(FValue) = '') then
begin
FValue := 'NULL';
if FComparisionOperator = '=' then
FComparisionOperator := 'is'
else
begin
if FComparisionOperator = '!=' then
FComparisionOperator := 'is not'
else
FEnabled := False;
end;
end
else
if vField.DataType in [ftDate, ftTime, ftDateTime, ftString, ftWideString] then
FValue := '''' + VarToStr(AFilterValue) + ''''
else
FValue := AFilterValue;
end;
end;
end;
function TsprFilter.GetAsString(IncludeCombineOperator: Boolean = True): string;
begin
Result := '';
if FExpression <> '' then
Result := FExpression
else
if FFilterFieldName <> '' then
begin
Result := Format('(%s %s %s)', [
FFilterFieldName,
FComparisionOperator,
FValue
]);
end;
if IncludeCombineOperator and (Result <> '') then
Result := FCombineOperator + ' ' + Result;
end;
//*********************************************************
constructor TsprFilters.Create(Owner: TPersistent);
begin
inherited Create(Owner, TsprFilter);
end;
destructor TsprFilters.Destroy;
begin
inherited;
end;
function TsprFilters.Add: TsprFilter;
begin
Result := TsprFilter(inherited Add);
end;
procedure TsprFilters.AddCaptionFilter(FieldName: string; FilterValue: Variant;
FilterComparisionOperator: TsprFilterComparisonOperator; FilterGroup: string);
var
vFilter: TsprFilter;
begin
vFilter := Add;
vFilter.Init(FieldName, FilterValue,
FilterComparisionOperator, FilterGroup);
end;
function TsprFilters.GetItem(Index: Integer): TsprFilter;
begin
Result := TsprFilter(inherited GetItem(Index));
end;
procedure TsprFilters.Clear(AFilterGroup: string = '');
var
I: Integer;
begin
I := 0;
while I < Count do
begin
if (AFilterGroup = '') or SameText(Self.Items[I].GroupName, AFilterGroup) then
Items[I].Free
else
Inc(I);
end;
end;
function TsprFilters.FindByName(FilterName: string): TsprFilter;
var
i: Integer;
begin
for i := 0 to Count - 1 do
if SameText(Items[i].Name, FilterName) then
begin
Result := Items[i];
Exit;
end;
Result := nil;
end;
function TsprFilters.GetFilterByName(FilterName: string): TsprFilter;
begin
Result := FindByName(FilterName);
if Result = nil then
begin
Result := Add as TsprFilter;
Result.Name := FilterName;
end;
end;
end.
|
////////////////////////////////////////////////////////////////////////////
// PaxCompiler
// Site: http://www.paxcompiler.com
// Author: Alexander Baranovsky (paxscript@gmail.com)
// ========================================================================
// Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved.
// Code Version: 4.2
// ========================================================================
// Unit: PAXCOMP_PASCAL_SCANNER.pas
// ========================================================================
////////////////////////////////////////////////////////////////////////////
{$I PaxCompiler.def}
unit PAXCOMP_PASCAL_SCANNER;
interface
uses {$I uses.def}
SysUtils,
PAXCOMP_CONSTANTS,
PAXCOMP_TYPES,
PAXCOMP_SYS,
PAXCOMP_SCANNER;
type
TPascalScanner = class(TBaseScanner)
procedure ScanCharLiteral;
procedure ScanStringLiteral(ch: Char); override;
procedure ReadCustomToken; override;
function Scan_Expression: Variant; override;
function Scan_SimpleExpression: Variant;
function Scan_Term: Variant;
function Scan_Ident: Variant; override;
end;
implementation
uses
PAXCOMP_KERNEL;
procedure TPascalScanner.ScanCharLiteral;
var
s: String;
I, P1, P2: Integer;
begin
GetNextChar; // #
ScanHexDigits;
Token.TokenClass := tcCharConst;
Token.Tag := 1;
if LA(1) <> '#' then
Exit;
CustomStringVal := '';
Token.TokenClass := tcPCharConst;
Token.Tag := 2;
s := SCopy(Buff, Token.Position + 1, Position - Token.Position);
I := StrToInt(s);
CustomStringVal := CustomStringVal + Chr(I);
while LA(1) = '#' do
begin
GetNextChar; // #
P1 := Position;
if LA(1) = '$' then
GetNextChar;
ScanHexDigits;
P2 := Position;
s := SCopy(Buff, P1 + 1, P2 - P1);
I := StrToInt(s);
CustomStringVal := CustomStringVal + Chr(I);
end;
while ByteInSet(LA(1), [Ord('#'), Ord(CHAR_AP)]) do
begin
GetNextChar; // #
if LA(0) = CHAR_AP then
begin
I := Position + 1;
inherited ScanStringLiteral(CHAR_AP);
s := SCopy(Buff, I, Position - I);
I := PosCh(CHAR_REMOVE, s);
while I > 0 do
begin
Delete(s, I, 1);
I := PosCh(CHAR_REMOVE, s);
end;
CustomStringVal := CustomStringVal + s;
end
else if LA(1) = '$' then
begin
GetNextChar;
I := Position + 1;
ScanHexDigits;
s := SCopy(Buff, I, Position - I + 1);
I := StrToInt('$' + s);
CustomStringVal := CustomStringVal + chr(I);
end
else
begin
I := Position + 1;
ScanDigits;
s := SCopy(Buff, I, Position - I + 1);
I := StrToInt(s);
CustomStringVal := CustomStringVal + chr(I);
end;
end;
end;
procedure TPascalScanner.ScanStringLiteral(ch: Char);
var
s: String;
I: Integer;
begin
inherited;
if LA(1) <> '#' then
Exit;
s := SCopy(Buff, Token.Position + 1, Position - Token.Position - 1);
I := PosCh(CHAR_REMOVE, s);
while I > 0 do
begin
Delete(s, I, 1);
I := PosCh(CHAR_REMOVE, s);
end;
CustomStringVal := s;
while ByteInSet(LA(1), [Ord('#'), Ord(ch)]) do
begin
GetNextChar; // #
if LA(1) = '$' then
begin
GetNextChar;
I := Position + 1;
ScanHexDigits;
s := SCopy(Buff, I, Position - I + 1);
I := StrToInt('$' + s);
CustomStringVal := CustomStringVal + chr(I);
end
else if LA(0) = ch then
begin
I := Position + 1;
inherited ScanStringLiteral(ch);
s := SCopy(Buff, I, Position - I);
CustomStringVal := CustomStringVal + s;
end
else
begin
I := Position + 1;
ScanDigits;
s := SCopy(Buff, I, Position - I + 1);
I := StrToInt(s);
CustomStringVal := CustomStringVal + chr(I);
end;
end;
Token.TokenClass := tcPCharConst;
Token.Tag := 2;
end;
procedure TPascalScanner.ReadCustomToken;
var
c: Char;
S: String;
begin
repeat
GetNextChar;
c := LA(0);
Token.Position := Position;
if IsWhiteSpace(c) then
begin
continue;
end
{$IFDEF LINUX}
else if c = #10 then
ScanSeparator
{$ELSE}
{$IFDEF MACOS}
else if c = #10 then
ScanSeparator
{$ELSE}
else if c = #13 then
ScanSeparator
{$ENDIF}
{$ENDIF}
{$IFDEF ANDROID}
else if c = #10 then
ScanSeparator
{$ENDIF}
else if IsEOF(c) then
ScanEOF
else if IsEOF then
ScanEOF
{$IFDEF HTML}
else if (c = '?') or (c = '%') then
begin
case ScannerState of
ScanText:
RaiseError(errSyntaxError, []);
ScanProg:
if LA(1) = '>' then
begin
ScannerState := scanText;
GetNextChar;
if (LA(1) = '<') and (LA(2) in ['?','%']) then
begin
ScannerState := scanText;
continue;
end;
// GetNextChar;
Token.Position := Position + 1;
ScanHtmlString('');
end
else
begin
{$IFDEF CPP_SYN}
if LA(1) = '=' then
begin
GetNextChar;
ScanSpecial;
Token.Id := OP_ASSIGN;
Exit;
end;
{$ENDIF}
end;
end;
end
else if c = '<' then
begin
case ScannerState of
scanText:
begin
if LA(1) = '?' then
begin
GetNextChar;
GetNextChar;
ScanChars([Ord('a')..Ord('z')] + [Ord('A')..Ord('Z')]);
if not StrEql('pax', Trim(Token.Text)) then
RaiseError(errSyntaxError, []);
ScannerState := scanProg;
Token.TokenClass := tcNone;
Continue;
end
else if LA(1) = '%' then
begin
GetNextChar;
ScannerState := scanProg;
if LA(1) = '=' then
begin
GetNextChar;
InsertText('print');
end;
Continue;
end
else if ByteInSet(LA(1), [Ord('a')..Ord('z'),Ord('A')..Ord('Z'), Ord('!')]) then
ScanHtmlString(c)
else
RaiseError(errSyntaxError, []);
end;
scanProg:
begin
ScanSpecial;
if LA(1) = '=' then
begin
GetNextChar;
ScanSpecial;
Token.Id := OP_LE;
end
else if LA(1) = '>' then
begin
GetNextChar;
ScanSpecial;
Token.Id := OP_NE;
end
else
Token.Id := OP_LT;
end;
end;
end
{$ENDIF}
else if IsAlpha(c) then
begin
ScanIdentifier;
token.Length := Position - token.Position + 1;
S := Token.Text;
if StrEql(S, 'in') then
begin
ScanSpecial;
Token.Id := OP_SET_MEMBERSHIP;
end
else if StrEql(S, 'div') then
begin
ScanSpecial;
Token.Id := OP_IDIV;
end
else if StrEql(S, 'mod') then
begin
ScanSpecial;
Token.Id := OP_MOD;
end
else if StrEql(S, 'shl') then
begin
ScanSpecial;
Token.Id := OP_SHL;
end
else if StrEql(S, 'shr') then
begin
ScanSpecial;
Token.Id := OP_SHR;
end
else if StrEql(S, 'and') then
begin
ScanSpecial;
Token.Id := OP_AND;
end
else if StrEql(S, 'or') then
begin
ScanSpecial;
Token.Id := OP_OR;
end
else if StrEql(S, 'xor') then
begin
ScanSpecial;
Token.Id := OP_XOR;
end
else if StrEql(S, 'not') then
begin
ScanSpecial;
Token.Id := OP_NOT;
end
else if StrEql(S, 'is') then
begin
ScanSpecial;
Token.Id := OP_IS;
end
else if StrEql(S, 'as') then
begin
ScanSpecial;
Token.Id := OP_AS;
end;
end
else if IsDigit(c) then
ScanNumberLiteral
else if c = '$' then
ScanHexLiteral
else if c = CHAR_AP then
ScanStringLiteral(CHAR_AP)
else if c = '+' then
begin
ScanSpecial;
Token.Id := OP_PLUS;
{$IFDEF CPP_SYN}
if LA(1) = '=' then
begin
GetNextChar;
ScanSpecial;
Token.Id := OP_ASSIGN;
end
else if LA(1) = '+' then
begin
GetNextChar;
ScanSpecial;
end;
{$ENDIF}
end
else if c = '-' then
begin
ScanSpecial;
Token.Id := OP_MINUS;
{$IFDEF CPP_SYN}
if LA(1) = '=' then
begin
GetNextChar;
ScanSpecial;
Token.Id := OP_ASSIGN;
end
else if LA(1) = '-' then
begin
GetNextChar;
ScanSpecial;
end;
{$ENDIF}
end
else if c = '*' then
begin
ScanSpecial;
Token.Id := OP_MULT;
{$IFDEF CPP_SYN}
if LA(1) = '=' then
begin
GetNextChar;
ScanSpecial;
Token.Id := OP_ASSIGN;
end;
{$ENDIF}
end
else if c = '/' then
begin
{$IFDEF CPP_SYN}
if LA(1) = '=' then
begin
GetNextChar;
ScanSpecial;
Token.Id := OP_ASSIGN;
end
else
{$ENDIF}
if LA(1) = '/' then
begin
ScanSingleLineComment();
continue;
end
else
begin
ScanSpecial;
Token.Id := OP_DIV;
end;
end
else if ByteInSet(c, [Ord('~'), Ord('%'), Ord('^'), Ord('&'), Ord('|')]) then
begin
{$IFDEF CPP_SYN}
if LA(1) = '=' then
begin
GetNextChar;
ScanSpecial;
Token.Id := OP_ASSIGN;
end
else
if c = '^' then
begin
ScanSpecial;
Exit;
end
else
RaiseError(errSyntaxError, []);
{$ELSE}
if c = '^' then
ScanSpecial
else if c = '&' then
begin
GetNextChar;
continue;
end
else
RaiseError(errSyntaxError, []);
{$ENDIF}
end
else if c = '=' then
begin
ScanSpecial;
Token.Id := OP_EQ;
if LA(1) = '>' then
begin
GetNextChar;
ScanSpecial;
end
end
else if c = '<' then
begin
ScanSpecial;
if LA(1) = '=' then
begin
GetNextChar;
ScanSpecial;
Token.Id := OP_LE;
end
else if LA(1) = '>' then
begin
GetNextChar;
ScanSpecial;
Token.Id := OP_NE;
end
else
Token.Id := OP_LT;
end
else if c = '>' then
begin
ScanSpecial;
if LA(1) = '=' then
begin
GetNextChar;
ScanSpecial;
Token.Id := OP_GE;
end
else
Token.Id := OP_GT;
end
else if c = ':' then
begin
ScanSpecial;
if LA(1) = '=' then
begin
GetNextChar;
ScanSpecial;
Token.Id := OP_ASSIGN;
end;
end
else if c = ',' then
ScanSpecial
else if c = '.' then
begin
if LA(1) = '.' then
GetNextChar;
ScanSpecial;
end
else if c = '#' then
ScanCharLiteral
else if c = '(' then
begin
if LA(1) = '*' then
begin
BeginComment(2);
repeat
GetNextChar;
c := LA(0);
if ByteInSet(c, [10,13]) then
begin
Inc(LineCount);
GenSeparator;
if c = #13 then
GetNextChar;
end;
until ByteInSet(LA(1), [Ord('*'), Ord(CHAR_EOF)]) and
ByteInSet(LA(2), [Ord(')'), Ord(CHAR_EOF)]);
GetNextChar;
GetNextChar;
EndComment(2);
end
else
ScanSpecial;
end
else if c = ')' then
ScanSpecial
else if c = '[' then
ScanSpecial
else if c = ']' then
ScanSpecial
else if c = '^' then
ScanSpecial
else if c = '@' then
ScanSpecial
else if c = ':' then
ScanSpecial
else if c = ';' then
ScanSpecial
else if c = '{' then
begin
if LA(1) = '$' then
begin
if (not LookForward) then
begin
ScanCondDir('{', [Ord('$')]);
Token.TokenClass := tcNone;
continue;
end;
GetNextChar;
if ByteInSet(LA(1), [Ord('b'), Ord('B')]) then
begin
GetNextChar;
if LA(1) = '+' then
begin
GetNextChar;
SetCompleteBooleanEval(true);
end
else if LA(1) = '-' then
begin
GetNextChar;
SetCompleteBooleanEval(false);
end;
end
else if ByteInSet(LA(1), [Ord('a'), Ord('A')]) then
begin
GetNextChar;
if LA(1) = '1' then
begin
GetNextChar;
SetAlignment(1);
end
else if LA(1) = '2' then
begin
GetNextChar;
SetAlignment(2);
end
else if LA(1) = '4' then
begin
GetNextChar;
SetAlignment(4);
end
else if LA(1) = '8' then
begin
GetNextChar;
SetAlignment(8);
end
else if LA(1) = '-' then
begin
GetNextChar;
SetAlignment(1);
end
else
RaiseError(errInvalidCompilerDirective, []);
end;
end;
if LA(1) = '}' then
begin
GetNextChar;
continue;
end;
BeginComment(1);
repeat
GetNextChar;
if IsEOF then
break;
c := LA(0);
if ByteInSet(c, [10,13]) then
begin
Inc(LineCount);
GenSeparator;
if c = #13 then
GetNextChar;
end;
until LA(1) = '}';
GetNextChar;
EndComment(1);
end
else if c = #254 then
begin
raise PaxCancelException.Create(TKernel(kernel).CancelChar);
end
else
begin
if SCAN_EXPR and (c = '}') then
begin
ScanSpecial;
Exit;
end;
RaiseError(errSyntaxError, []);
end;
until Token.TokenClass <> tcNone;
end;
function TPascalScanner.Scan_Expression: Variant;
var
Op: Integer;
begin
result := Scan_SimpleExpression;
while IsCurrText('>') or
IsCurrText('>=') or
IsCurrText('<') or
IsCurrText('<=') or
IsCurrText('=') or
IsCurrText('<>') do
begin
Op := 0;
if IsCurrText('>') then
Op := OP_GT
else if IsCurrText('>=') then
Op := OP_GE
else if IsCurrText('<') then
Op := OP_LT
else if IsCurrText('<=') then
Op := OP_LE
else if IsCurrText('=') then
Op := OP_EQ
else if IsCurrText('<>') then
Op := OP_NE;
ReadToken;
if Op = OP_GT then
result := result > Scan_SimpleExpression
else if Op = OP_GE then
result := result >= Scan_SimpleExpression
else if Op = OP_LT then
result := result < Scan_SimpleExpression
else if Op = OP_LE then
result := result <= Scan_SimpleExpression
else if Op = OP_EQ then
result := result = Scan_SimpleExpression
else if Op = OP_NE then
result := result <> Scan_SimpleExpression;
end;
end;
function TPascalScanner.Scan_SimpleExpression: Variant;
var
Op: Integer;
begin
result := Scan_Term;
while IsCurrText('+') or
IsCurrText('-') or
IsCurrText('or') or
IsCurrText('xor') do
begin
Op := 0;
if IsCurrText('+') then
Op := OP_PLUS
else if IsCurrText('-') then
Op := OP_MINUS
else if IsCurrText('or') then
Op := OP_OR
else if IsCurrText('xor') then
Op := OP_XOR;
ReadToken;
if Op = OP_PLUS then
result := result + Scan_Term
else if Op = OP_MINUS then
result := result - Scan_Term
else if Op = OP_OR then
result := result or Scan_Term
else if Op = OP_XOR then
result := result xor Scan_Term;
end;
end;
function TPascalScanner.Scan_Term: Variant;
var
Op: Integer;
begin
result := Scan_Factor;
while IsCurrText('*') or
IsCurrText('/') or
IsCurrText('div') or
IsCurrText('mod') or
IsCurrText('shl') or
IsCurrText('shr') or
IsCurrText('and') do
begin
Op := 0;
if IsCurrText('*') then
Op := OP_MULT
else if IsCurrText('/') then
Op := OP_DIV
else if IsCurrText('div') then
Op := OP_IDIV
else if IsCurrText('mod') then
Op := OP_MOD
else if IsCurrText('shl') then
Op := OP_SHL
else if IsCurrText('shr') then
Op := OP_SHR
else if IsCurrText('and') then
Op := OP_AND;
ReadToken;
if Op = OP_MULT then
result := result * Scan_Factor
else if Op = OP_DIV then
result := result / Scan_Factor
else if Op = OP_IDIV then
result := result div Scan_Factor
else if Op = OP_MOD then
result := result mod Scan_Factor
else if Op = OP_SHL then
result := result shl Scan_Factor
else if Op = OP_SHR then
result := result shr Scan_Factor
else if Op = OP_AND then
result := result and Scan_Factor;
end;
end;
function TPascalScanner.Scan_Ident: Variant;
var
I, Id: Integer;
DefList: TDefList;
S: String;
begin
DefList := TKernel(kernel).DefList;
S := Token.Text;
I := DefList.IndexOf(S);
if I >= 0 then
begin
result := DefList[I].value;
end
else
begin
with TKernel(kernel).CurrParser do
begin
Id := LookUps(S, levelStack);
if Id = 0 then
Id := LookupInUsingList(S);
if Id = 0 then
RaiseError(errConstantExpressionExpected, []);
if GetSymbolRec(Id).Kind <> KindCONST then
RaiseError(errConstantExpressionExpected, []);
result := GetSymbolRec(Id).Value;
end;
end;
ReadToken;
end;
end.
|
unit GLD3dsAtmosphere;
interface
uses
Classes, GL, GLDTypes, GLDClasses, GLD3dsTypes, GLD3dsChunk;
const
GLD3DS_BOTTOM_FALL_OFF = $00000001;
GLD3DS_TOP_FALL_OFF = $00000002;
GLD3DS_FOG_BACKGROUND = $00100000;
type
TGLD3dsFog = class;
TGLD3dsLayerFog = class;
TGLD3dsDistanceCue = class;
TGLD3dsAtmosphere = class;
TGLD3dsFog = class(TGLDSysClass)
private
FUse: GLboolean;
FCol: TGLDColor4fClass;
FFogBackground: GLboolean;
FNearPlane: GLfloat;
FNearDensity: GLfloat;
FFarPlane: GLfloat;
FFarDensity: GLfloat;
procedure SetUse(Value: GLboolean);
procedure SetCol(Value: TGLDColor4fClass);
procedure SetFogBackGround(Value: GLboolean);
procedure SetNearPlane(Value: GLfloat);
procedure SetNearDensity(Value: GLfloat);
procedure SetFarPlane(Value: GLfloat);
procedure SetFarDensity(Value: GLfloat);
function GetParams: TGLD3dsFogParams;
procedure SetParams(Value: TGLD3dsFogParams);
protected
procedure SetOnChange(Value: TNotifyEvent); override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
function Read(Stream: TStream): GLboolean;
property Params: TGLD3dsFogParams read GetParams write SetParams;
published
property Use: GLboolean read FUse write SetUse;
property Col: TGLDColor4fClass read FCol write SetCol;
property FogBackGround: GLboolean read FFogBackGround write SetFogBackGround;
property NearPlane: GLfloat read FNearPlane write SetNearPlane;
property NearDensity: GLfloat read FNearDensity write SetNearDensity;
property FarPlane: GLfloat read FFarPlane write SetFarPlane;
property FarDensity: GLfloat read FFarDensity write SetFarDensity;
end;
TGLD3dsLayerFog = class(TGLDSysClass)
private
FUse: GLboolean;
FFlags: GLuint;
FCol: TGLDColor4fClass;
FNearY: GLfloat;
FFarY: GLfloat;
FDensity: GLfloat;
procedure SetUse(Value: GLboolean);
procedure SetFlags(Value: GLuint);
procedure SetCol(Value: TGLDColor4fClass);
procedure SetNearY(Value: GLfloat);
procedure SetFarY(Value: GLfloat);
procedure SetDensity(Value: GLfloat);
function GetParams: TGLD3dsLayerFogParams;
procedure SetParams(Value: TGLD3dsLayerFogParams);
protected
procedure SetOnChange(Value: TNotifyEvent); override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
function Read(Stream: TStream): GLboolean;
property Params: TGLD3dsLayerFogParams read GetParams write SetParams;
published
property Use: GLboolean read FUse write SetUse;
property Flags: GLuint read FFlags write SetFlags;
property Col: TGLDColor4fClass read FCol write SetCol;
property NearY: GLfloat read FNearY write SetNearY;
property FarY: GLfloat read FFarY write SetFarY;
property Density: GLfloat read FDensity write SetDensity;
end;
TGLD3dsDistanceCue = class(TGLDSysClass)
private
FUse: GLboolean;
FCueBackground: GLboolean;
FNearPlane: GLfloat;
FNearDimming: GLfloat;
FFarPlane: GLfloat;
FFarDimming: GLfloat;
procedure SetUse(Value: GLboolean);
procedure SetCueBackground(Value: GLboolean);
procedure SetNearPlane(Value: GLfloat);
procedure SetNearDimming(Value: GLfloat);
procedure SetFarPlane(Value: GLfloat);
procedure SetFarDimming(Value: GLfloat);
function GetParams: TGLD3dsDistanceCueParams;
procedure SetParams(Value: TGLD3dsDistanceCueParams);
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
function Read(Stream: TStream): GLboolean;
property Params: TGLD3dsDistanceCueParams read GetParams write SetParams;
published
property Use: GLboolean read FUse write SetUse;
property CueBackground: GLboolean read FCueBackground write SetCueBackground;
property NearPlane: GLfloat read FNearPlane write SetNearPlane;
property NearDimming: GLfloat read FNearDimming write SetNearDimming;
property FarPlane: GLfloat read FFarPlane write SetFarPlane;
property FarDimming: GLfloat read FFarDimming write SetFarDimming;
end;
TGLD3dsAtmosphere = class(TGLDSysClass)
private
FFog: TGLD3dsFog;
FLayerFog: TGLD3dsLayerFog;
FDistCue: TGLD3dsDistanceCue;
procedure SetFog(Value: TGLD3dsFog);
procedure SetLayerFog(Value: TGLD3dsLayerFog);
procedure SetDistCue(Value: TGLD3dsDistanceCue);
function GetParams: TGLD3dsAtmosphereParams;
procedure SetParams(Value: TGLD3dsAtmosphereParams);
protected
procedure SetOnChange(Value: TNotifyEvent); override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
function Read(Stream: TStream): GLboolean;
property Params: TGLD3dsAtmosphereParams read GetParams write SetParams;
published
property Fog: TGLD3dsFog read FFog write SetFog;
property LayerFog: TGLD3dsLayerFog read FLayerFog write SetLayerFog;
property DistCue: TGLD3dsDistanceCue read FDistCue write SetDistCue;
end;
implementation
constructor TGLD3dsAtmosphere.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FFog := TGLD3dsFog.Create(Self);
FLayerFog := TGLD3dsLayerFog.Create(Self);
FDistCue := TGLD3dsDistanceCue.Create(Self);
end;
destructor TGLD3dsAtmosphere.Destroy;
begin
FFog.Free;
FLayerFog.Free;
FDistCue.Free;
inherited Destroy;
end;
procedure TGLD3dsAtmosphere.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLD3dsAtmosphere) then Exit;
SetParams(TGLD3dsAtmosphere(Source).GetParams);
end;
class function TGLD3dsAtmosphere.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_3DS_ATMOSPHERE;
end;
procedure TGLD3dsAtmosphere.LoadFromStream(Stream: TStream);
begin
FFog.LoadFromStream(Stream);
FLayerFog.LoadFromStream(Stream);
FDistCue.LoadFromStream(Stream);
end;
procedure TGLD3dsAtmosphere.SaveToStream(Stream: TStream);
begin
FFog.SaveToStream(Stream);
FLayerFog.SaveToStream(Stream);
FDistCue.SaveToStream(Stream);
end;
function TGLD3dsAtmosphere.Read(Stream: TStream): GLboolean;
var
C: TGLD3dsChunk;
begin
Result := False;
if not GLD3dsChunkReadStart(C, 0, Stream) then Exit;
repeat
GLD3dsChunkRead(C, Stream);
case C.Chunk of
GLD3DS_FOG:
begin
GLD3dsChunkReadReset(Stream);
if not FFog.Read(Stream) then Exit;
end;
GLD3DS_LAYER_FOG:
begin
GLD3dsChunkReadReset(Stream);
if not FLayerFog.Read(Stream) then Exit;
end;
GLD3DS_DISTANCE_CUE:
begin
GLD3dsChunkReadReset(Stream);
if not FDistCue.Read(Stream) then Exit;
end;
GLD3DS_USE_FOG:
begin
FFog.FUse := True;
end;
GLD3DS_USE_LAYER_FOG:
begin
FLayerFog.FUse := True;
end;
GLD3DS_USE_DISTANCE_CUE:
begin
FDistCue.FUse := True;
end;
else
begin
GLD3dsChunkReadReset(Stream);
C.Chunk := 0;
end;
end;
until C.Chunk = 0;
Result := True;
end;
procedure TGLD3dsAtmosphere.SetOnChange(Value: TNotifyEvent);
begin
inherited SetOnChange(Value);
FFog.OnChange := FOnChange;
FLayerFog.OnChange := FOnChange;
FDistCue.OnChange := FOnChange;
end;
procedure TGLD3dsAtmosphere.SetFog(Value: TGLD3dsFog);
begin
FFog.Assign(Value);
end;
procedure TGLD3dsAtmosphere.SetLayerFog(Value: TGLD3dsLayerFog);
begin
FLayerFog.Assign(Value);
end;
procedure TGLD3dsAtmosphere.SetDistCue(Value: TGLD3dsDistanceCue);
begin
FDistCue.Assign(Value);
end;
function TGLD3dsAtmosphere.GetParams: TGLD3dsAtmosphereParams;
begin
Result := GLDX3DSAtmosphereParams(Fog.GetParams,
FLayerFog.GetParams, FDistCue.GetParams);
end;
procedure TGLD3dsAtmosphere.SetParams(Value: TGLD3dsAtmosphereParams);
begin
if GLDX3DSAtmosphereParamsEqual(GetParams, Value) then Exit;
FFog.SetParams(Value.Fog);
FLayerFog.SetParams(Value.LayerFog);
FDistCue.SetParams(Value.DistCue);
end;
constructor TGLD3dsFog.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FUse := False;
FCol := TGLDColor4fClass.Create(Self);
end;
destructor TGLD3dsFog.Destroy;
begin
FCol.Destroy;
inherited Destroy;
end;
procedure TGLD3dsFog.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLD3dsFog) then Exit;
SetParams(TGLD3dsFog(Source).GetParams);
end;
class function TGLD3dsFog.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_3DS_FOG;
end;
procedure TGLD3dsFog.LoadFromStream(Stream: TStream);
begin
Stream.Read(FUse, SizeOf(GLboolean));
Stream.Read(FCol.GetPointer^, SizeOf(TGLDColor3f));
Stream.Read(FFogBackground, SizeOf(GLboolean));
Stream.Read(FNearPlane, SizeOf(GLfloat));
Stream.Read(FNearDensity, SizeOf(GLfloat));
Stream.Read(FFarPlane, SizeOf(GLfloat));
Stream.Read(FFarDensity, SizeOf(GLfloat));
end;
procedure TGLD3dsFog.SaveToStream(Stream: TStream);
begin
Stream.Write(FUse, SizeOf(GLboolean));
Stream.Write(FCol.GetPointer^, SizeOf(TGLDColor3f));
Stream.Write(FFogBackground, SizeOf(GLboolean));
Stream.Write(FNearPlane, SizeOf(GLfloat));
Stream.Write(FNearDensity, SizeOf(GLfloat));
Stream.Write(FFarPlane, SizeOf(GLfloat));
Stream.Write(FFarDensity, SizeOf(GLfloat));
end;
function TGLD3dsFog.Read(Stream: TStream): GLboolean;
var
C: TGLD3dsChunk;
i: GLuint;
begin
Result := False;
if not GLD3dsChunkReadStart(C, GLD3DS_FOG, Stream) then Exit;
Stream.Read(FNearPlane, SizeOf(GLfloat));
Stream.Read(FNearDensity, SizeOf(GLfloat));
Stream.Read(FFarPlane, SizeOf(GLfloat));
Stream.Read(FFarDensity, SizeOf(GLfloat));
repeat
GLD3dsChunkRead(C, Stream);
case C.Chunk of
GLD3DS_LIN_COLOR_F:
begin
for i := 0 to 2 do
Stream.Read(PGLDColor3f(FCol.GetPointer)^.C0[i], SizeOf(GLfloat));
end;
GLD3DS_COLOR_F:
begin
end;
GLD3DS_FOG_BGND:
begin
FFogBackground := True;
end;
else
begin
GLD3dsChunkReadReset(Stream);
C.Chunk := 0;
end;
end;
until C.Chunk = 0;
Result := True;
end;
procedure TGLD3dsFog.SetOnChange(Value: TNotifyEvent);
begin
inherited SetOnChange(Value);
FCol.OnChange := FonChange;
end;
procedure TGLD3dsFog.SetUse(Value: GLboolean);
begin
if FUse = Value then Exit;
FUse := Value;
Change;
end;
procedure TGLD3dsFog.SetCol(Value: TGLDColor4fClass);
begin
FCol.Assign(Value);
end;
procedure TGLD3dsFog.SetFogBackGround(Value: GLboolean);
begin
if FFogBackGround = Value then Exit;
FFogBackGround := Value;
Change;
end;
procedure TGLD3dsFog.SetNearPlane(Value: GLfloat);
begin
if FNearPlane = Value then Exit;
FNearPlane := Value;
Change;
end;
procedure TGLD3dsFog.SetNearDensity(Value: GLfloat);
begin
if FNearDensity = Value then Exit;
FNearDensity := Value;
Change;
end;
procedure TGLD3dsFog.SetFarPlane(Value: GLfloat);
begin
if FFarPlane = Value then Exit;
FFarPlane := Value;
Change;
end;
procedure TGLD3dsFog.SetFarDensity(Value: GLfloat);
begin
if FFarDensity = Value then Exit;
FFarDensity := Value;
Change;
end;
function TGLD3dsFog.GetParams: TGLD3dsFogParams;
begin
Result := GLDX3DSFogParams(FUse, FCol.Color3f, FFogBackGround,
FNearPlane, FNearDensity, FFarPlane, FFarDensity);
end;
procedure TGLD3dsFog.SetParams(Value: TGLD3dsFogParams);
begin
if GLDX3DSFogParamsEqual(GetParams, Value) then Exit;
FUse := Value.Use;
PGLDColor3f(FCol.GetPointer)^ := Value.Col;
FFogBackground := Value.FogBackground;
FNearPlane := Value.NearPlane;
FNearDensity := Value.NearDensity;
FFarPlane := Value.FarPlane;
FFarDensity := Value.FarDensity;
end;
constructor TGLD3dsLayerFog.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FUse := False;
FCol := TGLDColor4fClass.Create(Self);
end;
destructor TGLD3dsLayerFog.Destroy;
begin
FCol.Free;
inherited Destroy;
end;
procedure TGLD3dsLayerFog.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLD3dsLayerFog) then Exit;
SetParams(TGLD3dsLayerFog(Source).GetParams);
end;
class function TGLD3dsLayerFog.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_3DS_LAYERFOG;
end;
procedure TGLD3dsLayerFog.LoadFromStream(Stream: TStream);
begin
Stream.Read(FUse, SizeOf(GLboolean));
Stream.Read(FFlags, SizeOf(GLuint));
Stream.Read(FCol.GetPointer^, SizeOf(TGLDVector3f));
Stream.Read(FNearY, SizeOf(GLfloat));
Stream.Read(FFarY, SizeOf(GLfloat));
Stream.Read(FDensity, SizeOf(GLfloat));
end;
procedure TGLD3dsLayerFog.SaveToStream(Stream: TStream);
begin
Stream.Write(FUse, SizeOf(GLboolean));
Stream.Write(FFlags, SizeOf(GLuint));
Stream.Write(FCol.GetPointer^, SizeOf(TGLDVector3f));
Stream.Write(FNearY, SizeOf(GLfloat));
Stream.Write(FFarY, SizeOf(GLfloat));
Stream.Write(FDensity, SizeOf(GLfloat));
end;
function TGLD3dsLayerFog.Read(Stream: TStream): GLboolean;
var
C: TGLD3dsChunk;
HaveLin: GLboolean;
begin
HaveLin := False;
Result := False;
if not GLD3dsChunkReadStart(C, GLD3DS_LAYER_FOG, Stream) then Exit;
Stream.Read(FNearY, SizeOf(GLfloat));
Stream.Read(FFarY, SizeOf(GLfloat));
Stream.Read(FDensity, SizeOf(GLfloat));
Stream.Read(FFlags, SizeOf(GLfloat));
repeat
GLD3dsChunkRead(C, Stream);
case C.Chunk of
GLD3DS_LIN_COLOR_F:
begin
Stream.Read(FCol.GetPointer^, SizeOf(TGLDVector3f));
HaveLin := True;
end;
GLD3DS_COLOR_F:
begin
Stream.Read(FCol.GetPointer^, SizeOf(TGLDVector3f));
end;
else
begin
GLD3dsChunkReadReset(Stream);
C.Chunk := 0;
end;
end;
until C.Chunk = 0;
Result := True;
end;
procedure TGLD3dsLayerFog.SetOnChange(Value: TNotifyEvent);
begin
inherited SetOnChange(Value);
FCol.OnChange := FOnChange;
end;
procedure TGLD3dsLayerFog.SetUse(Value: GLboolean);
begin
if FUse = Value then Exit;
FUse := Value;
Change;
end;
procedure TGLD3dsLayerFog.SetFlags(Value: GLuint);
begin
if FFlags = Value then Exit;
FFLags := Value;
Change;
end;
procedure TGLD3dsLayerFog.SetCol(Value: TGLDColor4fClass);
begin
FCol.Assign(Value);
end;
procedure TGLD3dsLayerFog.SetNearY(Value: GLfloat);
begin
if FNearY = Value then Exit;
FNearY := Value;
Change;
end;
procedure TGLD3dsLayerFog.SetFarY(Value: GLfloat);
begin
if FFarY = Value then Exit;
FFarY := Value;
Change;
end;
procedure TGLD3dsLayerFog.SetDensity(Value: GLfloat);
begin
if FDensity = Value then Exit;
FDensity := Value;
Change;
end;
function TGLD3dsLayerFog.GetParams: TGLD3dsLayerFogParams;
begin
Result := GLDX3DSLayerFogParams(FUse, FFlags, FCol.Color3f,
FNearY, FFarY, FDensity);
end;
procedure TGLD3dsLayerFog.SetParams(Value: TGLD3dsLayerFogParams);
begin
if GLDX3DSLayerFogParamsEqual(GetParams, Value) then Exit;
FUse := Value.Use;
FFlags := Value.Flags;
PGLDColor3f(FCol.GetPointer)^ := Value.Col;
FNearY := Value.NearY;
FFarY := Value.FarY;
FDensity := Value.Density;
Change;
end;
constructor TGLD3dsDistanceCue.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FUse := False;
FCueBackground := False;
end;
destructor TGLD3dsDistanceCue.Destroy;
begin
inherited Destroy;
end;
procedure TGLD3dsDistanceCue.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLD3dsDistanceCue) then Exit;
SetParams(TGLD3dsDistanceCue(Source).GetParams);
end;
class function TGLD3dsDistanceCue.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_3DS_DISTANCECUE;
end;
procedure TGLD3dsDistanceCue.LoadFromStream(Stream: TStream);
begin
Stream.Read(FUse, SizeOf(GLboolean));
Stream.Read(FCueBackground, SizeOf(GLboolean));
Stream.Read(FNearPlane, SizeOf(GLfloat));
Stream.Read(FNearDimming, SizeOf(GLfloat));
Stream.Read(FFarPlane, SizeOf(GLfloat));
Stream.Read(FFarDimming, SizeOf(GLfloat));
end;
procedure TGLD3dsDistanceCue.SaveToStream(Stream: TStream);
begin
Stream.Write(FUse, SizeOf(GLboolean));
Stream.Write(FCueBackground, SizeOf(GLboolean));
Stream.Write(FNearPlane, SizeOf(GLfloat));
Stream.Write(FNearDimming, SizeOf(GLfloat));
Stream.Write(FFarPlane, SizeOf(GLfloat));
Stream.Write(FFarDimming, SizeOf(GLfloat));
end;
function TGLD3dsDistanceCue.Read(Stream: TStream): GLboolean;
var
C: TGLD3dsChunk;
begin
Result := False;
if not GLD3dsChunkReadStart(C, GLD3DS_DISTANCE_CUE, Stream) then Exit;
Stream.Read(FNearPlane, SizeOf(GLfloat));
Stream.Read(FNearDimming, SizeOf(GLfloat));
Stream.Read(FFarPlane, SizeOf(GLfloat));
Stream.Read(FFarDimming, SizeOf(GLfloat));
repeat
GLD3dsChunkRead(C, Stream);
case C.Chunk of
GLD3DS_DCUE_BGND:
begin
FCueBackground := True;
end;
else
begin
GLD3dsChunkReadReset(Stream);
C.Chunk := 0;
end;
end;
until C.Chunk = 0;
Result := True;
end;
procedure TGLD3dsDistanceCue.SetUse(Value: GLboolean);
begin
if FUse = Value then Exit;
FUse := Value;
Change;
end;
procedure TGLD3dsDistanceCue.SetCueBackground(Value: GLboolean);
begin
if FCueBackground = Value then Exit;
FCueBackground := Value;
Change;
end;
procedure TGLD3dsDistanceCue.SetNearPlane(Value: GLfloat);
begin
if FNearPlane = Value then Exit;
FNearPlane := Value;
Change;
end;
procedure TGLD3dsDistanceCue.SetNearDimming(Value: GLfloat);
begin
if FNearDimming = Value then Exit;
FNearDimming := Value;
Change;
end;
procedure TGLD3dsDistanceCue.SetFarPlane(Value: GLfloat);
begin
if FFarPlane = Value then Exit;
FFarPlane := Value;
Change;
end;
procedure TGLD3dsDistanceCue.SetFarDimming(Value: GLfloat);
begin
if FFarDimming = Value then Exit;
FFarDimming := Value;
Change;
end;
function TGLD3dsDistanceCue.GetParams: TGLD3dsDistanceCueParams;
begin
Result := GLDX3DSDistanceCueParams(FUse, FCueBackground,
FNearPlane, FNearDimming, FFarPlane, FFarDimming);
end;
procedure TGLD3dsDistanceCue.SetParams(Value: TGLD3dsDistanceCueParams);
begin
if GLDX3DSDistanceCueParamsEqual(GetParams, Value) then Exit;
FUse := Value.Use;
FCueBackground := Value.CueBackground;
FNearPlane := Value.NearPlane;
FNearDimming := Value.NearDimming;
FFarPlane := Value.FarPlane;
FFarDimming := Value.FarDimming;
Change;
end;
end.
|
(* NO ERRORS, SHOULD PARSE CORRECTLY *)
program p1;
VAR I, J : INTEGER;
var P,Q : real;
var s : string;
begin
I := 6 * 2 + 4;
J := I / 3 - 1;
P := 3.5 * 2.0 + 4.0;
Q := P / 3.0 - 1.0;
S := 'Hello world'
end.
|
unit tesseractocr.leptonica;
{ The MIT License (MIT)
TTesseractOCR4
Copyright (c) 2018 Damian Woroch, http://rime.ddns.net/
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. }
interface
uses
tesseractocr.consts;
type
l_uint8 = Byte;
pl_uint8 = ^l_uint8;
l_uint32 = Cardinal;
pl_uint32 = ^l_uint32;
l_int32 = Integer;
l_float32 = Single;
size_t = NativeInt;
TPixColormap = record
arr: Pointer;
depth: l_int32;
nalloc: l_int32;
n: l_int32;
end;
PPixColormap = ^TPixColormap;
TPix = record
w: l_uint32;
h: l_uint32;
d: l_uint32;
spp: l_uint32; //*!< number of samples per pixel */
wpl: l_uint32;
refcount: l_uint32;
xres: l_int32;
yres: l_int32;
informat: l_int32;
special: l_int32; //*!< special instructions for I/O, etc */
text: PUTF8Char;
colormap: PPixColormap;
data: pl_uint32;
end;
PPix = ^TPix;
PPPix = ^PPix;
TBox = record
x: l_int32;
y: l_int32;
w: l_int32;
h: l_int32;
refcount: l_uint32;
end;
PBox = ^TBox;
PPBox = ^PBox;
TBoxa = record
n: l_int32;
nalloc: l_int32;
refcount: l_uint32;
box: PPBox;
end;
PBoxa = ^TBoxa;
TPixa = record
n: l_int32;
nalloc: l_int32;
refcount: l_uint32;
pix: PPPix;
boxa: PBoxa;
end;
PPixa = ^TPixa;
const
L_INSERT = 0;
L_COPY = 1;
L_CLONE = 2;
type
TfnpixRead = function(const filename: PUTF8Char): PPix; cdecl;
TfnpixDestroy = procedure(var pix: PPix); cdecl;
TfnboxaGetBox = function(boxa: PBoxa; index: l_int32; accessflag: l_int32): Pbox; cdecl;
TfnboxaGetCount = function(boxa: PBoxa): l_int32; cdecl;
TfnboxDestroy = procedure(var box: PBox); cdecl;
TfnboxaDestroy = procedure(var boxa: PBoxa); cdecl;
TfnpixReadMem = function(const pdata: pl_uint8; size: size_t): PPix; cdecl;
TfnpixWriteMemPng = function(pdata: pl_uint8; out psize: size_t; pix: PPix; gamma: l_float32): l_int32; cdecl;
TfnpixWriteMemBmp = function(pdata: pl_uint8; out psize: size_t; pix: PPix): l_int32; cdecl;
TfnpixDeskew = function(pixs: PPix; redsearch: l_int32): PPix; cdecl;
Tfnlept_free = procedure(ptr: Pointer); cdecl;
var
pixRead: TfnpixRead;
pixDestroy: TfnpixDestroy;
boxaGetBox: TfnboxaGetBox;
boxaGetCount: TfnboxaGetCount;
boxDestroy: TfnboxDestroy;
boxaDestroy: TfnboxaDestroy;
pixReadMem: TfnpixReadMem;
pixWriteMemPng: TfnpixWriteMemPng;
pixWriteMemBmp: TfnpixWriteMemBmp;
pixDeskew: TfnpixDeskew;
lept_free: Tfnlept_free;
implementation
uses
{$IFNDEF FPC}Winapi.Windows, System.SysUtils{$ELSE}dynlibs, SysUtils{$ENDIF};
var
hLeptonicaLib: THandle;
procedure FreeLeptonicaLib;
begin
if (hLeptonicaLib <> 0) then
begin
FreeLibrary(hLeptonicaLib);
hLeptonicaLib := 0;
end;
end;
function InitLeptonicaLib: Boolean;
function GetLeptonicaProcAddress(var AProcPtr: Pointer; AProcName: AnsiString): Boolean;
begin
AProcPtr := GetProcAddress(hLeptonicaLib, {$IFDEF FPC}AProcName{$ELSE}PAnsiChar(AProcName){$ENDIF});
Result := Assigned(AProcPtr);
if not Result then
raise Exception.Create('Error while loading Leptonica function: ' + String(AProcName));
end;
begin
Result := False;
if (hLeptonicaLib = 0) then
begin
hLeptonicaLib := LoadLibrary({$IFDEF FPC}libleptonica{$ELSE}PChar(libleptonica){$ENDIF});
if (hLeptonicaLib <> 0) then
begin
GetLeptonicaProcAddress({$IFNDEF FPC}@{$ELSE}Pointer({$ENDIF}pixRead{$IFDEF FPC}){$ENDIF}, 'pixRead');
GetLeptonicaProcAddress({$IFNDEF FPC}@{$ELSE}Pointer({$ENDIF}pixDestroy{$IFDEF FPC}){$ENDIF}, 'pixDestroy');
GetLeptonicaProcAddress({$IFNDEF FPC}@{$ELSE}Pointer({$ENDIF}boxaGetBox{$IFDEF FPC}){$ENDIF}, 'boxaGetBox');
GetLeptonicaProcAddress({$IFNDEF FPC}@{$ELSE}Pointer({$ENDIF}boxaGetCount{$IFDEF FPC}){$ENDIF}, 'boxaGetCount');
GetLeptonicaProcAddress({$IFNDEF FPC}@{$ELSE}Pointer({$ENDIF}boxDestroy{$IFDEF FPC}){$ENDIF}, 'boxDestroy');
GetLeptonicaProcAddress({$IFNDEF FPC}@{$ELSE}Pointer({$ENDIF}boxaDestroy{$IFDEF FPC}){$ENDIF}, 'boxaDestroy');
GetLeptonicaProcAddress({$IFNDEF FPC}@{$ELSE}Pointer({$ENDIF}pixReadMem{$IFDEF FPC}){$ENDIF}, 'pixReadMem');
GetLeptonicaProcAddress({$IFNDEF FPC}@{$ELSE}Pointer({$ENDIF}pixWriteMemPng{$IFDEF FPC}){$ENDIF}, 'pixWriteMemPng');
GetLeptonicaProcAddress({$IFNDEF FPC}@{$ELSE}Pointer({$ENDIF}pixWriteMemBmp{$IFDEF FPC}){$ENDIF}, 'pixWriteMemBmp');
GetLeptonicaProcAddress({$IFNDEF FPC}@{$ELSE}Pointer({$ENDIF}pixDeskew{$IFDEF FPC}){$ENDIF}, 'pixDeskew');
GetLeptonicaProcAddress({$IFNDEF FPC}@{$ELSE}Pointer({$ENDIF}lept_free{$IFDEF FPC}){$ENDIF}, 'lept_free');
Result := True;
end;
end;
end;
initialization
InitLeptonicaLib;
finalization
FreeLeptonicaLib;
end.
|
{
//aangepast door Henkie (BEGIN)
dit betekend dat ik een deel van de code aangepast heb
tot aan de regel:
//aangepast door Henkie (END)
//toegevoegd door Henkie (BEGIN)
dit betekend dat ik een procedure ofzo bijgevoegd heb
tot aan de regel:
//toegevoegd door Henkie (END)
}
unit NLDCalendar;
interface
uses Classes, Controls, Messages, Windows, Forms, Graphics, StdCtrls,
Grids, SysUtils;
type
//toegevoegd door Henkie (BEGIN)
//array die de hints bijhoudt
THintGrid = array[0..6,1..6] of string;
//array of de achtergrondkleur van de cellen bij te houden
//record om de kleuren van achtergrond en tekst van een bepaalde cell bij te houden
//BG = BackGround
//FG = Foreground
TBGFGColor = record
BackColor:TColor;
TextColor:TColor;
end;
//toegevoegd door Henkie (END)
TDayOfWeek = 0..6;
//aangepast door Henkie (BEGIN)
//was TColor, nu TBGFGColor
TColorGrid = array[0..6, 1..6] of TBGFGColor;
{Array that holds the assigned color for each square on the calendar}
//aangepast door Henkie (END)
TNLDCalendar = class(TCustomGrid)
private
ColorGrid: TColorGrid;
//toegevoegd door Henkie (BEGIN)
HintGrid:THintGrid;
//toegevoegd door Henkie (END)
FDate: TDateTime;
FMonthOffset: Integer;
FOnChange: TNotifyEvent;
FReadOnly: Boolean;
FStartOfWeek: TDayOfWeek;
FUpdating: Boolean;
FUseCurrentDate: Boolean;
function GetCellText(ACol, ARow: Integer): string;
function GetDateElement(Index: Integer): Integer;
procedure SetCalendarDate(Value: TDateTime);
procedure SetDateElement(Index: Integer; Value: Integer);
procedure SetStartOfWeek(Value: TDayOfWeek);
procedure SetUseCurrentDate(Value: Boolean);
function StoreCalendarDate: Boolean;
protected
procedure Change; dynamic;
procedure ChangeMonth(Delta: Integer);
procedure Click; override;
function DaysPerMonth(AYear, AMonth: Integer): Integer; virtual;
function DaysThisMonth: Integer; virtual;
procedure DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); override;
function IsLeapYear(AYear: Integer): Boolean; virtual;
function SelectCell(ACol, ARow: Longint): Boolean; override;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
//toegevoegd door Henkie (BEGIN)
procedure CMHintShow(var Msg:TCMHintShow);message CM_HINTSHOW;
procedure CMDesignHitTest(var Msg: TCMDesignHitTest); message CM_DESIGNHITTEST;
//toegevoegd door Henkie (END)
public
constructor Create(AOwner: TComponent); override;
function BGFGColor(cback, cText: TColor): TBGFGColor;
property CalendarDate: TDateTime read FDate write SetCalendarDate stored StoreCalendarDate;
property CellText[ACol, ARow: Integer]: string read GetCellText;
procedure NextMonth;
procedure NextYear;
procedure PrevMonth;
procedure PrevYear;
procedure UpdateCalendar; virtual;
//aangepast door Henkie (BEGIN)
//paramter aHint toegevoegd om tegemoet te komen aan de optie om hints in te stellen
procedure SetDateColor(Adate: TDateTime; aColor: TBGFGColor;aHint:string ='');
//naamsverandering (was ResetColors) om tegemoet te komen aan de optie om hints in te stellen
procedure ResetColorsAndHints;
//aangepast door Henkie (END)
published
property Align;
property Anchors;
property BorderStyle;
property Color;
property Constraints;
property Ctl3D;
property Day: Integer index 3 read GetDateElement write SetDateElement stored True;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property GridLineWidth;
property Month: Integer index 2 read GetDateElement write SetDateElement stored True;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ReadOnly: Boolean read FReadOnly write FReadOnly default False;
property ShowHint;
property StartOfWeek: TDayOfWeek read FStartOfWeek write SetStartOfWeek;
property TabOrder;
property TabStop;
property UseCurrentDate: Boolean read FUseCurrentDate write SetUseCurrentDate default True;
property Visible;
property Year: Integer index 1 read GetDateElement write SetDateElement stored True;
property OnClick;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
//toegevoegd door Henkie (BEGIN)
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
//toegevoegd door Henkie (END)
property OnStartDock;
property OnStartDrag;
end;
//toegevoegd door Henkie (BEGIN)
const
sInvalidDate = 'The supplied date is not covered by this calendar';
//toegevoegd door Henkie (END)
procedure Register;
implementation
//toegevoegd door Henkie (BEGIN)
function TNLDCalendar.BGFGColor(cback, cText:TColor):TBGFGColor;
begin
result.BackColor:=cback;
result.TextColor:=ctext;
end;
//toegevoegd door Henkie (END)
{$R *.DCR}
type
EDateRangeError = class(Exception);
{Exception that is raised if the date passed to SetDateColor is }
{Not within the dates displayed by this calendar}
procedure Register;
begin
RegisterComponents('NLDelphi', [TNLDCalendar]);
end;
constructor TNLDCalendar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
//toegevoegd door Henkie (BEGIN)
DefaultDrawing:=false;
//nodig bij DrawCell()
DoubleBuffered:=true;
//Width en Height stonden er nog niet in
Height:=115;
Width:=318;
//toegevoegd door Henkie (END)
{ defaults }
FUseCurrentDate := True;
FixedCols := 0;
//aangepast door Henkie (BEGIN)
//was 1, nu 0. We tekenen de header zelf
FixedRows := 0;
//aangepast door Henkie (END)
ColCount := 7;
RowCount := 7;
ScrollBars := ssNone;
//aangepast door Henkie (BEGIN)
//goVertLine en goHorzLine weggelaten
//teken alle lijnen zelf in DrawCell
Options := Options - [goRangeSelect, goVertLine, goHorzLine] + [goDrawFocusSelected];
//aangepast door Henkie (END)
If UseCurrentDate = True then
begin
FDate := Now;
SetCalendarDate(Date)
end else
SetCalendarDate(EncodeDate(Year, Month, Day));
UpdateCalendar;
//aangepast door Henkie (BEGIN)
ResetColorsAndHints;
//aangepast door Henkie (END)
end;
procedure TNLDCalendar.ResetColorsAndHints;
{This procedure put's 0's in the entire Color Grid Array}
//toegevoegd door Henkie
{And put's '' (empty strings) in the entire HintGrid array}
//toegevoegd door Henkie
{then it calls the parents Update Calendar Procedure}
{The UpdateCalendar Procedure does some other work then}
{It calls DrawCell for each cell in the calendar}
var
row, col: integer;
begin
for col := 0 to 6 do
for row := 1 to 6 do
begin
//aangapast door Henkie (BEGIN)
//maakt nu gebruik van TBGFGColor
ColorGrid[col, row] := bgfgcolor(clWindow,clWindowText);
//aangepast door Henkie (END)
//toegevoegd door Henkie (BEGIN)
//de hints "resetten"
HintGrid[col,row]:='';
//toegevoegd door Henkie (END)
end;
UpdateCalendar;
end;
procedure TNLDCalendar.SetDateColor(Adate: TDateTime; aColor: TBGFGColor;aHint:string ='');
var
col, row: Integer;
found: Boolean;
theText, dayText: string;
aYear, aMonth, aDay: Word;
begin
DecodeDate(Adate, AYear, AMonth, ADay);
{Turn the date into month,day, and year integers}
if (aYear <> Year) or (aMonth <> Month) then
//aangepast door Henkie (BEGIN)
//de string is nu een constante
raise EDateRangeError.Create(sInvalidDate);
//aangepast door Henkie (END)
{If the Month or year passed is different from the current month or year of the}
{calendar, the EDateRangeError is raised. You must check for this}
{Exception in the calling code}
dayText := IntToStr(aDay);
{search for the cell that contains the same day as the day passed}
{ to this procedure}
found := False;
row := 1;
{again, we don't have to search the first row because the names}
{of the days are there}
while not (found) and (row < 7) do
{Found is a boolean variable that is set to true when the correct day}
{has been found. This improves loop performance by allowing for }
{early exit from the loop}
begin
col := 0;
while not (found) and (col < 7) do
begin
theText := CellText[col, row];
if theText = dayText then
begin
found := True;
{write the color of this cell to the color grid array}
ColorGrid[col, row] := aColor;
//toegevoegd door Henkie (BEGIN)
if length(hintgrid[col,row]) > 0 then
hintgrid[col,row]:=hintgrid[col,row]+#13#10+ahint
else
hintgrid[col,row]:=aHint;
//toegevoegd door Henkie (END)
UpdateCalendar; (*** remove the // to test and use RL. ***)
end;
Inc(col);
end;
Inc(row);
end;
end;
procedure TNLDCalendar.Change;
begin
if Assigned(FOnChange) then FOnChange(Self);
end;
procedure TNLDCalendar.Click;
var
TheCellText: string;
begin
inherited Click;
TheCellText := CellText[Col, Row];
if TheCellText <> '' then
Day := StrToInt(TheCellText);
end;
function TNLDCalendar.IsLeapYear(AYear: Integer): Boolean;
begin
Result := (AYear mod 4 = 0) and ((AYear mod 100 <> 0) or (AYear mod 400 = 0));
end;
function TNLDCalendar.DaysPerMonth(AYear, AMonth: Integer): Integer;
const
DaysInMonth: array[1..12] of Integer = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
begin
Result := DaysInMonth[AMonth];
if (AMonth = 2) and IsLeapYear(AYear) then
Inc(Result); { leap-year Feb is special }
end;
function TNLDCalendar.DaysThisMonth: Integer;
begin
Result := DaysPerMonth(Year, Month);
end;
procedure TNLDCalendar.DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState);
//toegevoegd door Henkie (BEGIN)
const
//alle kleuren worden op 1 plaats gehouden, makkelijker onderhoud en minder kans op fouten
SelectieKleur:TColor = clHighLight;
SelectieTekstKleur :TColor = clHighlightText;
RandKleur:TColor = clBtnShadow;
HeaderKleur:TColor = clbtnface;
// Vulkleur:TColor = clWindow;
AndereMaandKleur:TColor = clbtnFace;
//toegevoegd door Henkie (END)
var
theText: string;
{Used by the CellText procedure to get the text from the grid}
{that is pointed to by ACol and ARow}
begin
theText := CellText[ACol, ARow];
{Get the date text from the current cell}
//aangepast door Henkie (BEGIN)
//pen.Width op 2 gezet, is nodig om de border rond de cellen te tekenen
canvas.Pen.Width:=2;
//teken zelf de headers
if aRow = 0 then
begin
canvas.brush.color:=HeaderKleur;
DrawFrameControl(canvas.Handle,arect,DFC_BUTTON,DFCS_ADJUSTRECT or DFCS_BUTTONPUSH);
canvas.TextRect(arect,arect.left+((arect.right-arect.Left-canvas.TextWidth(TheText)) div 2),
arect.top+((arect.bottom-arect.top-canvas.TextHeight(TheText)) div 2),TheText);
exit;
end;
//aangepast door Henkie (END)
if theText <> '' then
{Can only set the color on grid cells that contain a date}
begin
{the current box is selected, overwrite the selected box hilight}
//aangepast door Henkie (BEGIN)
//anders zie je niet welke cell geselecteerd is ;)
if gdSelected in AState then
Canvas.Brush.Color := SelectieKleur
else
begin
canvas.Brush.color:=colorgrid[acol,arow].BackColor;
canvas.pen.color:=Randkleur;
canvas.Rectangle(arect);
end;
//aangepast door Henkie (END)
end {If Thetext <> ''}else
//toegevoegd door Henkie (BEGIN)
begin
//de cellen zonder tekst (die dus tot de volgende of vorige maand behoren
//worden ingekleurd met AndereMaandKleur --> clBtnFace
canvas.brush.color:=AndereMaandKleur;
canvas.pen.color:=AndereMaandKleur;
canvas.Rectangle(arect);
end;
//toegevoegd door Henkie (END)
//aangepast door Henkie (BEGIN)
//nam de systeeminstellingen voor de geslecteerde tekstkleur niet over
if (gdSelected in aState) then
canvas.Font.Color:=SelectieTekstKleur
else
//aangepast door Henkie (END)
Canvas.Font.Color := colorgrid[aCol,aRow].TextColor;
with ARect, Canvas do
TextRect(ARect, Left + (Right - Left - TextWidth(theText)) div 2,
Top + (Bottom - Top - TextHeight(theText)) div 2, theText);
{This procedure was copied from the parent class}
end;
function TNLDCalendar.GetCellText(ACol, ARow: Integer): string;
var
DayNum: Integer;
begin
if ARow = 0 then { day names at tops of columns }
Result := ShortDayNames[(StartOfWeek + ACol) mod 7 + 1]
else
begin
DayNum := FMonthOffset + ACol + (ARow - 1) * 7;
if (DayNum < 1) or (DayNum > DaysThisMonth) then
Result := ''
else
Result := IntToStr(DayNum);
end;
end;
function TNLDCalendar.SelectCell(ACol, ARow: Longint): Boolean;
begin
//aangepast door Henkie (BEGIN)
//or (aRow =0) toegevoegd, dit omdat je anders een header kon selecteren
if ((not FUpdating) and FReadOnly) or (CellText[ACol, ARow] = '') or (aRow = 0) then
//aangepast door Henkie (END)
Result := False
else
Result := inherited SelectCell(ACol, ARow);
//toegevoegd door Henkie (BEGIN)
//Invalidate is hier nodig om de cellen te hertekenen wanneer je een range probeert te selecteren
invalidate;
//toegevoegd door Henkie (END)
end;
procedure TNLDCalendar.SetCalendarDate(Value: TDateTime);
begin
FDate := Value;
UpdateCalendar;
Change;
end;
function TNLDCalendar.StoreCalendarDate: Boolean;
begin
Result := not FUseCurrentDate;
end;
function TNLDCalendar.GetDateElement(Index: Integer): Integer;
var
AYear, AMonth, ADay: Word;
begin
DecodeDate(FDate, AYear, AMonth, ADay);
case Index of
1: Result := AYear;
2: Result := AMonth;
3: Result := ADay;
else Result := -1;
end;
end;
procedure TNLDCalendar.SetDateElement(Index: Integer; Value: Integer);
var
AYear, AMonth, ADay: Word;
begin
if Value > 0 then
begin
DecodeDate(FDate, AYear, AMonth, ADay);
case Index of
1: if AYear <> Value then AYear := Value else Exit;
2: if (Value <= 12) and (Value <> AMonth) then AMonth := Value else Exit;
3: if (Value <= DaysThisMonth) and (Value <> ADay) then ADay := Value else Exit;
else Exit;
end;
FDate := EncodeDate(AYear, AMonth, ADay);
FUseCurrentDate := False;
UpdateCalendar;
Change;
end;
end;
procedure TNLDCalendar.SetStartOfWeek(Value: TDayOfWeek);
begin
if Value <> FStartOfWeek then
begin
FStartOfWeek := Value;
UpdateCalendar;
end;
end;
procedure TNLDCalendar.SetUseCurrentDate(Value: Boolean);
begin
if Value <> FUseCurrentDate then
begin
FUseCurrentDate := Value;
if Value then
begin
FDate := Date; { use the current date, then }
UpdateCalendar;
end;
end;
end;
{ Given a value of 1 or -1, moves to Next or Prev month accordingly }
procedure TNLDCalendar.ChangeMonth(Delta: Integer);
var
AYear, AMonth, ADay: Word;
NewDate: TDateTime;
CurDay: Integer;
begin
DecodeDate(FDate, AYear, AMonth, ADay);
CurDay := ADay;
if Delta > 0 then
ADay := DaysPerMonth(AYear, AMonth)
else
ADay := 1;
NewDate := EncodeDate(AYear, AMonth, ADay);
NewDate := NewDate + Delta;
DecodeDate(NewDate, AYear, AMonth, ADay);
if DaysPerMonth(AYear, AMonth) > CurDay then
ADay := CurDay
else
ADay := DaysPerMonth(AYear, AMonth);
CalendarDate := EncodeDate(AYear, AMonth, ADay);
end;
procedure TNLDCalendar.PrevMonth;
begin
ChangeMonth(-1);
end;
procedure TNLDCalendar.NextMonth;
begin
ChangeMonth(1);
end;
procedure TNLDCalendar.NextYear;
begin
if IsLeapYear(Year) and (Month = 2) and (Day = 29) then
Day := 28;
Year := Year + 1;
end;
procedure TNLDCalendar.PrevYear;
begin
if IsLeapYear(Year) and (Month = 2) and (Day = 29) then
Day := 28;
Year := Year - 1;
end;
procedure TNLDCalendar.UpdateCalendar;
var
AYear, AMonth, ADay: Word;
FirstDate: TDateTime;
begin
FUpdating := True;
try
DecodeDate(FDate, AYear, AMonth, ADay);
FirstDate := EncodeDate(AYear, AMonth, 1);
FMonthOffset := 2 - ((DayOfWeek(FirstDate) - StartOfWeek + 7) mod 7); { day of week for 1st of month }
if FMonthOffset = 2 then
FMonthOffset := -5;
MoveColRow((ADay - FMonthOffset) mod 7, (ADay - FMonthOffset) div 7 + 1,False, False);
Invalidate;
finally
FUpdating := False;
end;
end;
procedure TNLDCalendar.WMSize(var Message: TWMSize);
var
GridLines: Integer;
begin
GridLines := 6 * GridLineWidth;
DefaultColWidth := (Message.Width - GridLines) div 7;
DefaultRowHeight := (Message.Height - GridLines) div 7;
end;
//toegevoegd door Henkie (BEGIN)
procedure TNLDCalendar.CMHintShow(var Msg: TCMHintShow);
//nodig om de hints per cell te tonen
var
gc:TGridCoord;
pt:tpoint;
aCellRect:trect;
aHint:string;
begin
with msg do
begin
result:=1;
//cursorpos omzeten naar row en col
pt:=point(hintinfo.CursorPos.X,hintinfo.CursorPos.Y);
gc:=mousecoord(pt.x,pt.y);
if ((gc.x < 0) or (gc.x > 6)) or ((gc.y < 1) or (gc.y > 6)) then
exit;
acellrect:=self.CellRect(gc.x,gc.y);
//hint ophalen
aHint:=self.HintGrid[gc.x,gc.y];
end;
with msg.HintInfo^ do
begin
//hint tonen
CursorRect := aCellrect;
HintStr := aHint;
Msg.Result := 0;
end;
end;
procedure TNLDCalendar.CMDesignHitTest(var Msg: TCMDesignHitTest);
//maakt het selecteren van een cell @designtime mogelijk
var
gc:TgridCoord;
pt:tpoint;
begin
pt:=point(msg.XPos,msg.YPos);
gc:=mousecoord(pt.X,pt.y);
msg.result:=ord(SelectCell(gc.x,gc.y));
end;
//toegevoegd door Henkie (END)
end.
|
unit UFlow;
interface
uses UConst, URegularFunctions;
type
Flow = class
mass_fractions: array of real;
volume_fractions: array of real;
mole_fractions: array of real;
mass_flow_rate: real;
volume_flow_rate: real;
mole_flow_rate: real;
temperature: real;
cp: real;
density: real;
average_mol_mass: real;
constructor(mass_fractions: array of real;
mass_flow_rate: real;
temperature: real);
end;
implementation
constructor Flow.Create(mass_fractions: array of real;
mass_flow_rate: real;
temperature: real);
begin
self.mass_fractions := normalize(mass_fractions);
self.mass_flow_rate := mass_flow_rate;
self.temperature := temperature;
self.volume_fractions := convert_mass_to_volume_fractions(
self.mass_fractions, UConst.DENSITIES);
self.mole_fractions := convert_mass_to_mole_fractions(
self.mass_fractions, UConst.MR);
self.cp := get_flow_cp(self.mass_fractions, self.temperature,
UConst.HEATCAPACITYCOEFFS);
self.density := get_flow_density(self.mass_fractions,
UConst.DENSITIES);
self.average_mol_mass := get_average_mol_mass(
self.mass_fractions, UConst.MR);
self.mole_flow_rate := self.mass_flow_rate / self.average_mol_mass;
self.volume_flow_rate := self.mass_flow_rate / self.density
end;
end. |
{
@abstract Implements class that formats filter string for TOpenDialog and TSaveDialog.
If you set the whole filter string into one single resource string the format of string
is quite complicated. For example.
@longCode(#
All supported files (*.xml;*.ini)|*.xml;*.ini|XML files (*.xml)|*.xml|Ini files (*.ini)|*.ini
#)
It is likely that translator will break the above format and your localized application
will crash when the incorrect filter string is assigned to dialog's Filter property.
Use this class to break the complicated string into plain string that are easy and safe
to translate. Instead of one complex string we will have three simple strings to be translated.
@longCode(#
All supported files
XML files
Ini files
#)
There is no possibility to break the filter format my entering invalid translations.
See the following code about how ti use the class.
@longCode(#
resourcestring
SAllSupportedFiles = 'All supported files';
SXmlFiles = 'XML files';
SIniFiles = 'Ini files';
var
dialog: TOpenDialog;
filter: TNtDialogFilter;
begin
dialog := TOpenDialog.Create(nil);
try
dialog.Title := SOpenTitle;
filter := TNtDialogFilter.Create;
try
filter.Supported(SAllSupportedFiles);
filter.Add(SXmlFiles, 'xml');
filter.Add(SIniFiles, 'ini');
filter.All(SAllFiles);
dialog.Filter := filter.Value;
finally
filter.Free;
end;
if dialog.Execute then
ShowMessage(dialog.FileName);
finally
dialog.Free;
end;
#)
When you create @link(TNtDialogFilter) you have to call @link(TNtDialogFilter.Add)
method as least once. @link(TNtDialogFilter.Supported) and @link(TNtDialogFilter.All)
are optional.
See @italic(Samples\Delphi\VCL\FileDialog) sample to see how to use the unit.
}
unit NtDialog;
interface
uses
Classes;
type
TNtDialogFilterPosition = (fpNone, fpFirst, fpLast);
{ @abstract Dialog filter formatter class. }
TNtDialogFilter = class(TObject)
private
FAllSupportedPosition: TNtDialogFilterPosition;
FFirstPart: String;
FSecondPart: String;
FAllSupportedPattern: String;
FMasks: TStringList;
function GetValue: String;
procedure DoAdd(const value: String);
public
constructor Create;
destructor Destroy; override;
{ Add All files part to the filter.
@param pattern All files pattern. It can contain an optional %s placeholder where mask is injected. }
procedure All(const pattern: String);
{ Add All supported files part to the filter.
@param pattern All supported files pattern. It can contain an optional %s placeholder where mask is injected. }
procedure Supported(const pattern: String);
{ Add one file format.
@param pattern File type description. It can contain an optional %s placeholder where mask is injected.
@param mask Mask or extension of the file type. }
procedure Add(const pattern: String; mask: String);
class function AddOne(
const pattern: String;
mask: String;
const allPattern: String = ''): String;
property Value: String read GetValue;
end;
implementation
uses
SysUtils;
function AppendSeparator(const filter: String): String;
begin
// Append separator character, |, if needed.
Result := filter;
if Result <> '' then
Result := Result + '|';
end;
function GetFilter(const pattern, mask: String): String;
begin
Result := pattern;
if Pos('%s', Result) = 0 then
Result := Result + ' (%s)';
Result := Format(Result, [mask]) + '|' + mask;
end;
constructor TNtDialogFilter.Create;
begin
inherited;
FMasks := TStringList.Create;
end;
destructor TNtDialogFilter.Destroy;
begin
FMasks.Free;
inherited;
end;
procedure TNtDialogFilter.DoAdd(const value: String);
begin
if FAllSupportedPosition = fpLast then
FSecondPart := AppendSeparator(FSecondPart) + value
else
FFirstPart := AppendSeparator(FFirstPart) + value;
end;
procedure TNtDialogFilter.All(const pattern: String);
begin
DoAdd(GetFilter(pattern, '*.*'));
end;
procedure TNtDialogFilter.Supported(const pattern: String);
begin
if FFirstPart = '' then
FAllSupportedPosition := fpFirst
else
FAllSupportedPosition := fpLast;
FAllSupportedPattern := pattern;
end;
procedure TNtDialogFilter.Add(const pattern: String; mask: String);
begin
// "" -> *.*
// ext -> *.ext
// .ext -> *.ext
if mask = '' then
mask := '*.*'
else if mask[1] = '.' then
mask := '*' + mask
else if mask[1] <> '*' then
mask := '*.' + mask;
FMasks.Add(mask);
DoAdd(GetFilter(pattern, mask));
end;
function TNtDialogFilter.GetValue: String;
var
i: Integer;
mask, masksStr: String;
begin
masksStr := '';
if FAllSupportedPosition <> fpNone then
begin
for i := 0 to FMasks.Count - 1 do
begin
mask := FMasks[i];
if masksStr <> '' then
masksStr := masksStr + ';';
masksStr := masksStr + mask;
end;
end;
Result := '';
if (FAllSupportedPosition = fpFirst) and (masksStr <> '') then
Result := AppendSeparator(Result) + GetFilter(FAllSupportedPattern, masksStr);
Result := AppendSeparator(Result) + FFirstPart;
if (FAllSupportedPosition = fpLast) and (masksStr <> '') then
Result := AppendSeparator(result) + GetFilter(FAllSupportedPattern, masksStr);
if FSecondPart <> '' then
Result := AppendSeparator(Result) + FSecondPart;
end;
class function TNtDialogFilter.AddOne(
const pattern: String;
mask: String;
const allPattern: String = ''): String;
var
filter: TNtDialogFilter;
begin
filter := TNtDialogFilter.Create;
try
filter.Add(pattern, mask);
if allPattern <> '' then
filter.All(allPattern);
Result := filter.Value;
finally
filter.Free;
end;
end;
end.
|
{-------------------------------------------------------------------------------
Copyright 2012 Ethea S.r.l.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-------------------------------------------------------------------------------}
unit Kitto.Ext.BorderPanel;
{$I Kitto.Defines.inc}
interface
uses
SysUtils,
Ext,
EF.Tree,
Kitto.Ext.Base, Kitto.Ext.Controller;
type
TKExtBorderPanelController = class;
TKExtBorderPanelControllerClass = class of TKExtBorderPanelController;
TKExtBorderPanelController = class(TKExtPanelControllerBase)
strict private
FControllers: array[TExtBoxComponentRegion] of TObject;
procedure CreateController(const ARegion: TExtBoxComponentRegion);
strict protected
function FindRegionControllerConfig(const ARegion: TExtBoxComponentRegion): TEFNode; virtual;
protected
procedure DoDisplay; override;
function GetRegionDefaultControllerClass(const ARegion: TExtBoxComponentRegion): string; virtual;
function GetRegionName(const ARegion: TExtBoxComponentRegion): string; virtual;
function GetRegionViewNodeName(const ARegion: TExtBoxComponentRegion): string;
function GetRegionControllerNodeName(const ARegion: TExtBoxComponentRegion): string;
public
end;
implementation
uses
TypInfo,
EF.Intf, EF.StrUtils,
Kitto.Ext.Session, Kitto.Metadata.Views;
{ TKExtBorderPanelController }
function TKExtBorderPanelController.GetRegionName(const ARegion: TExtBoxComponentRegion): string;
begin
Result := StripPrefix(GetEnumName(TypeInfo(TExtBoxComponentRegion), Ord(ARegion)), 'rg');
end;
function TKExtBorderPanelController.GetRegionViewNodeName(const ARegion: TExtBoxComponentRegion): string;
begin
Result := GetRegionName(ARegion) + 'View';
end;
function TKExtBorderPanelController.GetRegionControllerNodeName(const ARegion: TExtBoxComponentRegion): string;
begin
Result := GetRegionName(ARegion) + 'Controller';
end;
function TKExtBorderPanelController.GetRegionDefaultControllerClass(const ARegion: TExtBoxComponentRegion): string;
begin
Result := '';
end;
function TKExtBorderPanelController.FindRegionControllerConfig(
const ARegion: TExtBoxComponentRegion): TEFNode;
var
LRegionControllerNodeName: string;
LRegionDefaultControllerClass: string;
begin
LRegionControllerNodeName := GetRegionControllerNodeName(ARegion);
Assert(LRegionControllerNodeName <> '');
LRegionDefaultControllerClass := GetRegionDefaultControllerClass(ARegion);
Result := Config.FindNode(LRegionControllerNodeName);
if not Assigned(Result) then
begin
if LRegionDefaultControllerClass <> '' then
Result := TEFNode.Create(LRegionControllerNodeName, LRegionDefaultControllerClass);
end
else
begin
if Result.Value = '' then
Result.Value := LRegionDefaultControllerClass;
end;
end;
procedure TKExtBorderPanelController.CreateController(const ARegion: TExtBoxComponentRegion);
var
LSubView: TKView;
LControllerConfig: TEFNode;
LIntf: IKExtController;
begin
Assert(Assigned(View));
// If subcontrollers are specified, they inherit this controller's view.
// If no subcontroller is configured for a given region, look for a subview.
LControllerConfig := FindRegionControllerConfig(ARegion);
if Assigned(LControllerConfig) then
begin
LSubView := View;
end
else
LSubView := Session.Config.Views.FindViewByNode(Config.FindNode(GetRegionViewNodeName(ARegion)));
if LSubView <> nil then
begin
FControllers[ARegion] := TKExtControllerFactory.Instance.CreateController(Self, LSubView, Self, LControllerConfig).AsObject;
Assert(FControllers[ARegion] is TExtBoxComponent);
TExtBoxComponent(FControllers[ARegion]).Region := ARegion;
if Supports(FControllers[ARegion], IKExtController, LIntf) then
InitSubController(LIntf);
LIntf.Display;
end;
end;
procedure TKExtBorderPanelController.DoDisplay;
var
I: TExtBoxComponentRegion;
begin
inherited;
Layout := lyBorder;
for I := Low(FControllers) to High(FControllers) do
CreateController(I);
end;
initialization
TKExtControllerRegistry.Instance.RegisterClass('BorderPanel', TKExtBorderPanelController);
finalization
TKExtControllerRegistry.Instance.UnregisterClass('BorderPanel');
end.
|
unit GameObject;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
Types,
ParameterList,
Map;
type
TGameObject = class;
TBeingZoneStatus = (
isOffline,
isOnline
);
{[2007/03/28] CR - No X,Y parameters needed -- reduced and eliminated. }
TLoopCall = procedure(
const ACurrentObject : TGameObject;
const AObject : TGameObject;
const AObjectID : LongWord;
const AParameters : TParameterList = nil
);
TGameObject = class
protected
fName : String;
fPosition : TPoint;
fMap : String;
procedure SetPosition(Value : TPoint); virtual;
procedure SetMap(Value : string); virtual;
procedure SetName(const Value : String); virtual;
public
ID : LongWord;
ZoneStatus : TBeingZoneStatus; //Is the being online in the Zone or not?
MapInfo : TMap;
property Name : string read fName write SetName;
property Position : TPoint read fPosition write SetPosition;
property Map : string read fMap write SetMap;
procedure AreaLoop(ALoopCall:TLoopCall; AIgnoreCurrentBeing:Boolean=True;AParameter : TParameterList = nil);
function Distance(const APoint:TPoint):Word;
end;
implementation
uses
Math,
Main,
Being,
Character
;
procedure TGameObject.SetPosition(Value : TPoint);
var
OldPt : TPoint;
Index : Integer;
begin
OldPt := Position;
fPosition := Value;
//check if we're online before we add/remove ourselves from the map...
if (NOT(Self is TCharacter)AND Assigned(MapInfo)) OR (ZoneStatus = isOnline) then
begin
//Position is initialized to -1, -1 on create, so if we're not on the map
//yet, don't remove us!
if MapInfo.PointInRange(OldPt) then
begin
Index := MapInfo.Cell[OldPt.X][OldPt.Y].Beings.IndexOf(ID);
if Index > -1 then
begin
MapInfo.Cell[OldPt.X][OldPt.Y].Beings.Delete(
Index
);
end;
end;
//same as above, if we've set position to -1, -1, then don't add us to a
//non-existant cell!
if MapInfo.PointInRange(Position) then
begin
MapInfo.Cell[Position.X][Position.Y].Beings.AddObject(ID, self);
end;
end;
end;{SetPosition}
//------------------------------------------------------------------------------
procedure TGameObject.SetMap(Value : string); begin fMap := Value; end;
//------------------------------------------------------------------------------
//ViewAreaLoop PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// master procedure for Area loop, and call Dynamic Sub Procedure.
//
// Changes -
// March 20th, 2007 - Aeomin - Created
//------------------------------------------------------------------------------
procedure TGameObject.AreaLoop(ALoopCall:TLoopCall; AIgnoreCurrentBeing:Boolean=True;AParameter : TParameterList = nil);
var
idxY : integer;
idxX : integer;
ObjectIdx : integer;
AObject : TGameObject;
begin
for idxY := Max(0,Position.Y-MainProc.ZoneServer.Options.CharShowArea) to Min(Position.Y+MainProc.ZoneServer.Options.CharShowArea, MapInfo.Size.Y-1) do
begin
for idxX := Max(0,Position.X-MainProc.ZoneServer.Options.CharShowArea) to Min(Position.X+MainProc.ZoneServer.Options.CharShowArea, MapInfo.Size.X-1) do
begin
for ObjectIdx := MapInfo.Cell[idxX][idxY].Beings.Count -1 downto 0 do
begin
if MapInfo.Cell[idxX][idxY].Beings.Objects[ObjectIdx] is TBeing then
begin
AObject := MapInfo.Cell[idxX][idxY].Beings.Objects[ObjectIdx] as TGameObject;
if (Self = AObject) and AIgnoreCurrentBeing then Continue;
{if not (ABeing is TCharacter) then Continue;} //Target MUST be a TCharacter
//Even though it's good idea to prevent packet send to non players
//But the problem is that.. NPC is invisible now
if (AObject is TCharacter) AND (Self = AObject) then
ALoopCall(Self, AObject, TCharacter(Self).AccountID, AParameter)
else
ALoopCall(Self, AObject, TBeing(Self).ID, AParameter);
end;
end;
if MapInfo.Cell[idxX][idxY].Items.Count > 0 then
begin
for ObjectIdx := MapInfo.Cell[idxX][idxY].Items.Count -1 downto 0 do
begin
AObject := MapInfo.Cell[idxX][idxY].Items.Objects[ObjectIdx] as TGameObject;
ALoopCall(Self, AObject, TGameObject(AObject).ID, AParameter);
end;
end;
end;
end;
end;
//------------------------------------------------------------------------------
(*- Procedure -----------------------------------------------------------------*
TBeing.SetName
--------------------------------------------------------------------------------
Overview:
--
Property method for Name.
--
Revisions:
--
(Format: [yyyy/mm/dd] <Author> - <Comment>)
[2007/04/24] CR - Added Comment Header, made Value parameter const.
*-----------------------------------------------------------------------------*)
Procedure TGameObject.SetName(
const
Value : String
);
Begin
fName := Value;
End; (* Proc TBeing.SetName
*-----------------------------------------------------------------------------*)
//------------------------------------------------------------------------------
//Distance FUNCTION
//------------------------------------------------------------------------------
// What it does-
// Calculate distance between 2 TPoint.
// Note that this routine only get either distance of X or Y.
// Because visible range was in square...
//
// Changes-
// [2008/12/14] Aeomin - Create.
//------------------------------------------------------------------------------
function TGameObject.Distance(const APoint:TPoint):Word;
var
DistanceX, DistanceY : Word;
begin
DistanceX := Abs(APoint.X - fPosition.X);
DistanceY := Abs(APoint.Y - fPosition.Y);
if DistanceX > DistanceY then
Result := DistanceX
else
Result := DistanceY;
end;{Distance}
//------------------------------------------------------------------------------
end.
|
unit uFreeImageImage;
interface
uses
Windows,
SysUtils,
Graphics,
Classes,
uMemory,
Dmitry.Graphics.Types,
uTime,
FreeBitmap,
FreeImage,
uFreeImageIO,
CCR.Exif,
uBitmapUtils;
type
TFreeImageImage = class(TBitmap)
private
procedure LoadFromFreeImage(Image: TFreeBitmap);
protected
function Flags: Integer;
public
constructor Create; override;
procedure LoadFromStream(Stream: TStream); override;
procedure LoadFromFile(const Filename: string); override;
end;
implementation
{ TFreeImageImage }
constructor TFreeImageImage.Create;
begin
inherited;
FreeImageInit;
end;
function TFreeImageImage.Flags: Integer;
begin
Result := 0;
end;
procedure TFreeImageImage.LoadFromFile(const FileName: string);
var
RawBitmap: TFreeWinBitmap;
IsValidImage: Boolean;
begin
RawBitmap := TFreeWinBitmap.Create;
try
IsValidImage := RawBitmap.LoadU(FileName, Flags);
if not IsValidImage then
raise Exception.Create('Invalid Free Image File format!');
LoadFromFreeImage(RawBitmap);
finally
F(RawBitmap);
end;
end;
procedure TFreeImageImage.LoadFromStream(Stream: TStream);
var
RawBitmap: TFreeWinBitmap;
IO: FreeImageIO;
begin
RawBitmap := TFreeWinBitmap.Create;
try
SetStreamFreeImageIO(IO);
if RawBitmap.LoadFromHandle(@IO, Stream, Flags) then
LoadFromFreeImage(RawBitmap);
finally
F(RawBitmap);
end;
end;
procedure TFreeImageImage.LoadFromFreeImage(Image: TFreeBitmap);
var
I, J: Integer;
PS, PD: PARGB;
PS32, PD32: PARGB32;
W, H: Integer;
FreeImage: PFIBITMAP;
begin
if not (Image.GetBitsPerPixel in [24, 32, 96, 128]) then
Image.ConvertTo24Bits;
if Image.GetBitsPerPixel = 96 then
Image.ToneMapping(FITMO_DRAGO03, 0, 0);
if Image.GetBitsPerPixel = 128 then
Image.ToneMapping(FITMO_DRAGO03, 0, 0);
if Image.GetBitsPerPixel = 32 then
PixelFormat := pf32Bit;
if Image.GetBitsPerPixel = 24 then
PixelFormat := pf24Bit;
W := Image.GetWidth;
H := Image.GetHeight;
SetSize(W, H);
FreeImage := Image.Dib;
if Image.GetBitsPerPixel = 24 then
for I := 0 to H - 1 do
begin
PS := PARGB(FreeImage_GetScanLine(FreeImage, H - I - 1));
PD := ScanLine[I];
for J := 0 to W - 1 do
PD[J] := PS[J];
end;
if Image.GetBitsPerPixel = 32 then
for I := 0 to H - 1 do
begin
PS32 := PARGB32(FreeImage_GetScanLine(FreeImage, H - I - 1));
PD32 := ScanLine[I];
for J := 0 to W - 1 do
PD32[J] := PS32[J];
end;
end;
initialization
TPicture.RegisterFileFormat('jp2', 'JPEG 2000 Images', TFreeImageImage);
TPicture.RegisterFileFormat('j2k', 'JPEG 2000 Images', TFreeImageImage);
TPicture.RegisterFileFormat('jpf', 'JPEG 2000 Images', TFreeImageImage);
TPicture.RegisterFileFormat('jpx', 'JPEG 2000 Images', TFreeImageImage);
TPicture.RegisterFileFormat('jpm', 'JPEG 2000 Images', TFreeImageImage);
TPicture.RegisterFileFormat('mj2', 'JPEG 2000 Images', TFreeImageImage);
TPicture.RegisterFileFormat('dds', 'DirectDraw Surface graphics', TFreeImageImage);
TPicture.RegisterFileFormat('hdr', 'DirectDraw Surface graphics', TFreeImageImage);
TPicture.RegisterFileFormat('exr', 'DirectDraw Surface graphics', TFreeImageImage);
TPicture.RegisterFileFormat('iff', 'Amiga IFF Graphic', TFreeImageImage);
TPicture.RegisterFileFormat('jng', 'JPEG Network Graphic', TFreeImageImage);
//TPicture.RegisterFileFormat('xbm', 'X11 Bitmap Graphic', TFreeImageImage);
//TPicture.RegisterFileFormat('xpm', 'X11 Bitmap Graphic', TFreeImageImage);
//TPicture.RegisterFileFormat('mng', 'Multiple Network Graphic', TFreeImageImage);
finalization
TPicture.UnregisterGraphicClass(TFreeImageImage);
end.
|
{----------------------------------------------------------------
Nome: UntCanal
Descrição: Unit do Form do tipo TFrmCanal. Este form contém várias
procedures para manipulação de todos as Janelas-Canais.
Métodos:
-procedure AdNick(Nick: string);
-procedure RmNick(Nick: string);
-procedure AdLinha(Texto: string);
----------------------------------------------------------------}
unit UntCanal;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, IRCUtils;
type
TFrmCanal = class(TForm)
CmbMenssagem: TComboBox;
LsbNicks: TListBox;
MemCanal: TMemo;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure MemCanalMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure CmbMenssagemKeyPress(Sender: TObject; var Key: Char);
procedure FormResize(Sender: TObject);
private
public
Canal: string;
Topico: string;
procedure AdNick(Nick: string);
procedure RmNick(Nick: string);
procedure AdLinha(Texto: string);
end;
var
FrmCanal: TFrmCanal;
implementation
uses UntPrincipal, UntComandos, UntStatus;
{$R *.DFM}
{ TFrmCanal }
{Procedures}
procedure TFrmCanal.AdLinha(Texto: string);
begin
MemCanal.Lines.Add(Texto);
FrmPrincipal.RolarTexto(MemCanal);
end;
procedure TFrmCanal.AdNick(Nick: string);
var
IndiceA, IndiceB: integer;
begin
{Só adiciona o nick se ele nãi estiver adicionado}
IndiceA:=LsbNicks.Items.IndexOf(Nick);
IndiceB:=LsbNicks.Items.IndexOf(NickReal(Nick)); {Testa sem os atributos}
if ((IndiceA < 0) or (IndiceB < 0)) then
LsbNicks.Items.Add(Nick);
end;
procedure TFrmCanal.RmNick(Nick: string);
var
Contador: integer;
begin
for Contador:=0 to LsbNicks.Items.Count - 1 do
if (NickReal(LsbNicks.Items.Strings[Contador]) = NickReal(Nick)) then
LsbNicks.Items.Delete(Contador);
end;
{Fim}
procedure TFrmCanal.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=caFree;
PartCha(Canal);
end;
procedure TFrmCanal.MemCanalMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
MemCanal.CopyToClipboard;
MemCanal.SelLength:=0;
CmbMenssagem.SetFocus;
end;
procedure TFrmCanal.CmbMenssagemKeyPress(Sender: TObject; var Key: Char);
var
Texto: string;
begin
if (Key = #13) then
begin
if (FrmPrincipal.EstIRC = eiDesconectado) then
begin
AdLinha('Não conectado!');
CmbMenssagem.Text:='';
end
else
if (Length(CmbMenssagem.Text) > 0) then
begin
Texto:=CmbMenssagem.Text;
AdLinha('[MeuNick] ' + Texto);
CmbMenssagem.Items.Insert(0, CmbMenssagem.Text);
PvtMsg(Canal, Texto);
CmbMenssagem.Text:='';
end;
FrmPrincipal.RolarTexto(Self.MemCanal);
Abort;
end;
end;
procedure TFrmCanal.FormResize(Sender: TObject);
begin
LsbNicks.Left:=ClientWidth - LsbNicks.Width;
CmbMenssagem.Top:=ClientHeight - 23;
CmbMenssagem.Width:=ClientWidth;
MemCanal.Width:=ClientWidth - LsbNicks.Width;
MemCanal.Height:=(ClientHeight - CmbMenssagem.Height) - 1;
LsbNicks.Height:=(ClientHeight - CmbMenssagem.Height) - 1;
end;
end.
|
unit uDM;
interface
uses
SysUtils, Classes, DB, ADODB, Registry, Windows, IniFiles, Forms,
ufrmServerInfo, Dialogs;
const
KEY_CUSTOMER_COLUMN = 'ImportCustomerColumn';
MR_INI_FILE = 'MRIntegrator.ini';
ACC_SOFTWARE_MAS90 = 'Mas90_';
ORIGINAL_CUSTOMER_WHERE = 'Path LIKE ''.001%'' AND P.Desativado = 0 AND P.Hidden = 0';
ORIGINAL_WHERE = 'P.Desativado = 0 AND P.Hidden = 0';
SOFTWARE_QUICKEN = 0;
SOFTWARE_QUICKBOOKS = 1;
SOFTWARE_PEACHTREE = 2;
SOFTWARE_MAS90 = 3;
ENTITY_CUSTOMER = 0;
ENTITY_PAYMENT = 1;
ENTITY_SALE_INVOICE = 2;
COLUMN_ID = 0;
COLUMN_OTHER_ACC = 1;
COLUMN_OFFICEM = 2;
type
TMRDatabase = class
private
fDatabaseName : String;
fServer : String;
fUser : String;
fPW : String;
public
property DatabaseName : String read fDatabaseName write fDatabaseName;
property Server : String read fServer write fServer;
property User : String read fUser write fUser;
property PW : String read fPW write fPW;
end;
TDM = class(TDataModule)
MRDBConnection: TADOConnection;
quCustomer: TADODataSet;
quPaymentTotal: TADODataSet;
quPaymentDetail: TADODataSet;
quPaymentTotalIDPaymentType: TIntegerField;
quPaymentTotalType: TIntegerField;
quPaymentTotalPaymentType: TStringField;
quPaymentTotalTotalType: TBCDField;
quSaleInvoice: TADODataSet;
quStoreList: TADODataSet;
quCategoryList: TADODataSet;
quStoreListIDStore: TIntegerField;
quTaxScheduleList: TADODataSet;
quTaxScheduleListIDTaxCategory: TIntegerField;
quTaxScheduleListTaxCategory: TStringField;
quCategoryListIDGroup: TIntegerField;
quCategoryListName: TStringField;
quStoreListStore: TStringField;
quSaleInvoiceInvoiceNumber: TStringField;
quSaleInvoiceInvoiceDate: TDateTimeField;
quSaleInvoiceCustomer_No: TIntegerField;
quSaleInvoiceDiscount: TStringField;
quSaleInvoiceProductLine: TIntegerField;
quSaleInvoiceUnitPrice: TBCDField;
quSaleInvoicePriceExtension: TBCDField;
quSaleInvoiceTaxableAmount: TBCDField;
quSaleInvoiceNonTaxableAmount: TBCDField;
quSaleInvoiceSalesTax: TBCDField;
quSaleInvoiceLineDiscountPercent: TBCDField;
quSaleInvoiceUnitCost: TBCDField;
quSaleInvoiceItemDescription: TStringField;
quSaleInvoiceShippingDate: TDateTimeField;
quSaleInvoiceOrderDate: TDateTimeField;
quSaleInvoiceInvoiceDueDate: TDateTimeField;
quSaleInvoiceDiscountDueDate: TDateTimeField;
quSaleInvoiceCustomerName: TStringField;
quSaleInvoiceCustomerAddress: TStringField;
quSaleInvoiceCustomerCity: TStringField;
quSaleInvoiceCustomerZip: TStringField;
quSaleInvoiceCustomerStateCode: TStringField;
quSaleInvoiceCustomerState: TStringField;
quSaleInvoiceShipToAddress: TStringField;
quSaleInvoiceDiscountValue: TBCDField;
quSaleInvoiceExtTotalSale: TBCDField;
quSaleInvoiceStoreName: TStringField;
quSaleInvoiceCategoryName: TStringField;
quSaleInvoiceTaxCategory: TStringField;
quSaleInvoiceTaxClass: TStringField;
quSaleInvoiceSerialNumber: TStringField;
quSaleInvoiceCommentLine: TStringField;
quSaleInvoiceFreight: TBCDField;
quSaleInvoiceItemNumber: TStringField;
quSaleInvoiceUserCode: TStringField;
quPaymentDetailInvoiceNumber: TStringField;
quPaymentDetailRecordDate: TStringField;
quPaymentDetailCustomerFullName: TStringField;
quPaymentDetailCustomer_No: TIntegerField;
quPaymentDetailUserCode: TStringField;
quPaymentDetailIDPaymentType: TIntegerField;
quPaymentDetailType: TIntegerField;
quPaymentDetailPaymentType: TStringField;
quPaymentDetailTotalAmount: TBCDField;
quCustomerStoreNumber: TIntegerField;
quCustomerCustomer_No: TIntegerField;
quCustomerUserCode: TStringField;
quCustomerEntityFullName: TStringField;
quCustomerAddress: TStringField;
quCustomerDBA: TStringField;
quCustomerCity: TStringField;
quCustomerZip: TStringField;
quCustomerCountry: TStringField;
quCustomerPhone: TStringField;
quCustomerCellPhone: TStringField;
quCustomerFax: TStringField;
quCustomerContact: TStringField;
quCustomerType: TBooleanField;
quCustomerBirthDay: TDateTimeField;
quCustomerSocialSecurity: TStringField;
quCustomerFederalID: TStringField;
quCustomerSalesTax: TStringField;
quCustomerCompanyContact: TStringField;
quCustomerDriveLicence: TStringField;
quCustomerLastName: TStringField;
quCustomerFirstName: TStringField;
quCustomerHorsPerWeek: TIntegerField;
quCustomerHourValue: TBCDField;
quCustomerOverHourValue: TBCDField;
quCustomerDoubleHourValue: TBCDField;
quCustomerCustomerCard: TStringField;
quCustomerCode: TIntegerField;
quCustomerHomePage: TStringField;
quCustomerEmail: TStringField;
quCustomerOBS: TStringField;
quCustomerStateCode: TStringField;
quCustomerState: TStringField;
quSaleInvoiceMiscItemFlag: TStringField;
quSaleInvoiceMiscItemCode: TStringField;
quSaleInvoiceQty: TFloatField;
quSaleInvoiceLineType: TStringField;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
procedure quSaleInvoiceCalcFields(DataSet: TDataSet);
private
fMRIntegrator : TIniFile;
fSoftDefault :String;
procedure SetSoftDefault(aSoftDefault: String);
public
fMRDatabase : TMRDatabase;
iSoftware :Integer;
iEntityType :Integer;
fLocalPath :String;
property SoftDefault : String read fSoftDefault write SetSoftDefault;
procedure OpenCustomer;
procedure OpenSaleInvoiceCustomer(Cod :String);
procedure CloseSaleInvoiceCustomer;
procedure CloseCustomer;
procedure OpenSaleInvoice(BeginDate, EndDate: String);
procedure CloseSaleInvoice;
procedure OpenPaymentTotal(BeginDate, EndDate: String);
procedure ClosePaymentTotal;
procedure OpenPaymentDetail(IDMeioPag: Integer; BeginDate, EndDate: String);
procedure ClosePaymentDetail;
procedure CloseQuerys;
procedure CloseQuerysMas90List;
procedure OpenStoreList;
procedure OpenCategoryList;
procedure OpenTaxScheduleList;
procedure CloseStoreList;
procedure CloseCategoryList;
procedure CloseTaxScheduleList;
function GetIniFile(sSection, sKey : String):String;
procedure SetIniFileString(sSection, sKey : String; Text : String);
procedure SetConnection(sServer, sDB, sUser, sPW : String);
function OpenDatabase:Boolean;
procedure BuildConnection;
function GetConnection: String;
function CloseDatabase:Boolean;
end;
var
DM: TDM;
implementation
uses uSqlFunctions, uParamFunctions, uEncryptFunctions;
{$R *.dfm}
procedure TDM.ClosePaymentDetail;
begin
with quPaymentDetail do
if Active then
Close;
end;
procedure TDM.ClosePaymentTotal;
begin
with quPaymentTotal do
if Active then
Close;
end;
procedure TDM.CloseCustomer;
begin
with quCustomer do
if Active then
Close;
end;
procedure TDM.DataModuleCreate(Sender: TObject);
begin
fMRDatabase := TMRDatabase.Create;
fMRIntegrator := TIniFile.Create(ExtractFilePath(Application.ExeName)+MR_INI_FILE);
fMRDatabase.DatabaseName := fMRIntegrator.ReadString('MRSetting','Database','');
fSoftDefault := fMRIntegrator.ReadString('Setup','SoftwareDefault','');
fLocalPath := fMRIntegrator.ReadString('Setup',fSoftDefault+'_FilePath','');
if fLocalPath='' then
fLocalPath := ExtractFilePath(Application.ExeName);
BuildConnection;
OpenDatabase;
end;
procedure TDM.DataModuleDestroy(Sender: TObject);
begin
CloseDatabase;
FreeAndNil(fMRIntegrator);
FreeAndNil(fMRDatabase);
end;
function TDM.GetIniFile(sSection, sKey : String): String;
begin
Result := fMRIntegrator.ReadString(sSection, sKey, '');
end;
procedure TDM.OpenCustomer;
begin
with quCustomer do
begin
if Active then
Close;
Open;
end;
end;
procedure TDM.OpenPaymentDetail(IDMeioPag: Integer; BeginDate, EndDate: String);
begin
with quPaymentDetail do
begin
if Active then
Close;
Parameters.ParamByName('IDMeioPag').Value := IDMeioPag;
Parameters.ParamByName('BeginDate').Value := BeginDate;
Parameters.ParamByName('EndDate').Value := EndDate;
Open;
end;
end;
procedure TDM.OpenPaymentTotal(BeginDate, EndDate: String);
begin
with quPaymentTotal do
begin
if Active then
Close;
Parameters.ParamByName('BeginDate').Value := BeginDate;
Parameters.ParamByName('EndDate').Value := EndDate;
Open;
end;
end;
procedure TDM.SetIniFileString(sSection, sKey : String; Text : String);
begin
fMRIntegrator.WriteString(sSection, sKey, Text);
end;
procedure TDM.CloseSaleInvoice;
begin
with quSaleInvoice do
if Active then
Close;
end;
procedure TDM.OpenSaleInvoice(BeginDate, EndDate: String);
begin
with quSaleInvoice do
begin
if Active then
Close;
Parameters.ParamByName('BeginDate').Value := BeginDate;
Parameters.ParamByName('EndDate').Value := EndDate;
Open;
end;
end;
procedure TDM.CloseQuerys;
begin
case iEntityType of
ENTITY_CUSTOMER : CloseCustomer;
ENTITY_PAYMENT :
begin
ClosePaymentTotal;
ClosePaymentDetail;
end;
ENTITY_SALE_INVOICE : CloseSaleInvoice;
end;
end;
procedure TDM.quSaleInvoiceCalcFields(DataSet: TDataSet);
begin
if quSaleInvoice.FieldByName('DiscountValue').Value <> 0 then
quSaleInvoice.FieldByName('Discount').Value := 'Y'
else
quSaleInvoice.FieldByName('Discount').Value := 'N';
if quSaleInvoice.FieldByName('TaxIsent').Value = 1 then
begin
quSaleInvoice.FieldByName('TaxableAmount').Value := 0;
quSaleInvoice.FieldByName('non_TaxableAmount').Value := quSaleInvoice.FieldByName('TotalSale').Value;
end
else
begin
quSaleInvoice.FieldByName('TaxableAmount').Value := quSaleInvoice.FieldByName('ExtTotalSale').Value;
quSaleInvoice.FieldByName('non_TaxableAmount').Value := 0;
end;
end;
procedure TDM.OpenSaleInvoiceCustomer(Cod :string);
var
sWhere :string;
begin
if quCustomer.Active then
quCustomer.Close;
sWhere := ORIGINAL_CUSTOMER_WHERE + ' AND IDPessoa IN ('+Cod+')';
quCustomer.Commandtext := ChangeWhereClause(quCustomer.CommandText,sWhere,True);
quCustomer.Open;
end;
procedure TDM.CloseSaleInvoiceCustomer;
begin
if quCustomer.Active then
begin
quCustomer.Close;
quCustomer.Commandtext := ChangeWhereClause(quCustomer.CommandText,ORIGINAL_CUSTOMER_WHERE,True);
end;
end;
procedure TDM.SetSoftDefault(aSoftDefault: String);
begin
fSoftDefault := aSoftDefault;
fMRIntegrator.WriteString('Setup','SoftwareDefault',aSoftDefault);
end;
function TDM.CloseDatabase;
begin
with MRDBConnection do
if Connected then
try
Close;
Result := True;
except
on E: Exception do
begin
Result := False;
ShowMessage(E.Message);
end;
end;
end;
function TDM.OpenDatabase: Boolean;
begin
with MRDBConnection do
try
ConnectionString := GetConnection;
Open;
Result := True;
except
on E: Exception do
begin
Result := False;
ShowMessage(E.Message);
end;
end;
end;
procedure TDM.OpenCategoryList;
begin
with quCategoryList do
begin
if Active then
Close;
Open;
end;
end;
procedure TDM.OpenStoreList;
begin
with quStoreList do
begin
if Active then
Close;
Open;
end;
end;
procedure TDM.CloseCategoryList;
begin
with quCategoryList do
if Active then
Close;
end;
procedure TDM.CloseStoreList;
begin
with quStoreList do
if Active then
Close;
end;
procedure TDM.CloseTaxScheduleList;
begin
with quTaxScheduleList do
if Active then
Close;
end;
procedure TDM.OpenTaxScheduleList;
begin
with quTaxScheduleList do
begin
if Active then
Close;
Open;
end;
end;
procedure TDM.CloseQuerysMas90List;
begin
CloseStoreList;
CloseCategoryList;
CloseTaxScheduleList;
end;
procedure TDM.BuildConnection;
begin
fMRDatabase.DatabaseName := DecodeServerInfo(GetIniFile('MRSetting','Database'), 'Database', CIPHER_TEXT_STEALING, FMT_UU);
fMRDatabase.Server := DecodeServerInfo(GetIniFile('MRSetting','Server'), 'Server', CIPHER_TEXT_STEALING, FMT_UU);
fMRDatabase.User := DecodeServerInfo(GetIniFile('MRSetting','User'), 'User', CIPHER_TEXT_STEALING, FMT_UU);
fMRDatabase.PW := DecodeServerInfo(GetIniFile('MRSetting','PW'), 'PW', CIPHER_TEXT_STEALING, FMT_UU);
end;
function TDM.GetConnection: String;
begin
Result := 'Provider=SQLOLEDB.1;Password='+fMRDatabase.PW+';Persist Security Info=True;'+
'User ID='+fMRDatabase.User+';Initial Catalog='+fMRDatabase.DatabaseName+
';Data Source='+fMRDatabase.Server+';Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=DESENV003;Use Encryption for Data=False;Tag with column collation when possible=False';
end;
procedure TDM.SetConnection(sServer, sDB, sUser, sPW: String);
begin
sDB := EncodeServerInfo(sDB, 'Database', CIPHER_TEXT_STEALING, FMT_UU);
sServer := EncodeServerInfo(sServer, 'Server', CIPHER_TEXT_STEALING, FMT_UU);
sUser := EncodeServerInfo(sUser, 'User', CIPHER_TEXT_STEALING, FMT_UU);
sPW := EncodeServerInfo(sPW, 'PW', CIPHER_TEXT_STEALING, FMT_UU);
SetIniFileString('MRSetting','Database', sDB);
SetIniFileString('MRSetting','Server', sServer);
SetIniFileString('MRSetting','User', sUser);
SetIniFileString('MRSetting','PW', sPW);
BuildConnection;
end;
end.
|
(*
Category: SWAG Title: ANYTHING NOT OTHERWISE CLASSIFIED
Original name: 0080.PAS
Description: English Number Strings
Author: GAYLE DAVIS
Date: 01-27-94 17:33
*)
{
Converts REAL number to ENGLISH strings
GAYLE DAVIS 1/21/94
Amounts up to and including $19,999,999.99 are supported.
If you write amounts larger than that, you don't need a computer !!
======================================================================
Dedicated to the PUBLIC DOMAIN, this software code has been tested and
used under BP 7.0/DOS and MS-DOS 6.2.
}
USES CRT;
{CONST
Dot : CHAR = #42;
VAR
SS : STRING;
AA : REAL;}
FUNCTION EnglishNumber (Amt : REAL) : STRING;
TYPE
Mword = STRING [10];
Amstw = STRING [80]; {for function TenUnitToWord output}
CONST
NumStr : ARRAY [0..27] OF Mword =
('', 'ONE ', 'TWO ', 'THREE ', 'FOUR ', 'FIVE ', 'SIX ', 'SEVEN ',
'EIGHT ','NINE ', 'TEN ', 'ELEVEN ', 'TWELVE ', 'THIRTEEN ',
'FOURTEEN ', 'FIFTEEN ', 'SIXTEEN ', 'SEVENTEEN ', 'EIGHTEEN ',
'NINETEEN ', 'TWENTY ', 'THIRTY ', 'FORTY ', 'FIFTY ', 'SIXTY ',
'SEVENTY ', 'EIGHTY ', 'NINETY ');
VAR
{S : STRING;}
Temp : REAL;
DigitA, DigitB : INTEGER;
Ams : STRING;
Ac : STRING [2];
FUNCTION TenUnitToWord (TeUn : INTEGER) : Amstw;
{ convert tens and units to words }
BEGIN
IF TeUn < 21 THEN TenUnitToWord := NumStr [TeUn]
ELSE TenUnitToWord := NumStr [TeUn DIV 10 + 18] + NumStr [TeUn MOD 10];
END; {function TenUnitToWord}
BEGIN
{ Nothing bigger than 20 million }
IF (Amt > 20000000.0) OR (Amt <= 0.0) THEN
BEGIN
EnglishNumber := ''; {null string if out of range}
EXIT;
END;
{ Convert 1,000,000 decade }
Ams := '';
DigitA := TRUNC (Amt / 1E6);
IF DigitA > 0 THEN Ams := Ams + NumStr [DigitA] + 'MILLION ';
Temp := Amt - DigitA * 1E6;
{ Convert 100,000, 10,000, 1,000 decades }
DigitA := TRUNC (Temp / 1E5); {extract 100,000 decade}
IF DigitA > 0 THEN Ams := Ams + NumStr [DigitA] + 'HUNDRED ';
Temp := Temp - DigitA * 1E5;
DigitB := TRUNC (Temp / 1000); {extract sum of 10,000 and 1,000 decades}
Ams := Ams + TenUnitToWord (DigitB);
IF ( (DigitA > 0) OR (DigitB > 0) ) THEN Ams := Ams + 'THOUSAND ';
{Convert 100, 10, unit decades}
Temp := Temp - DigitB * 1000.0;
DigitA := TRUNC (Temp / 100); {extract 100 decade}
IF DigitA > 0 THEN Ams := Ams + NumStr [DigitA] + 'HUNDRED ';
DigitB := TRUNC (Temp - DigitA * 100.0); {extract sum of 10 and unit decades}
Ams := Ams + TenUnitToWord (DigitB);
{Convert cents to form XX/100}
IF INT (Amt) > 0.0 THEN Ams := Ams + 'AND ';
DigitA := ROUND ( (FRAC (Amt) * 100) );
IF DigitA > 0 THEN
BEGIN
STR (DigitA : 2, Ac);
IF Ac [1] = ' ' THEN Ac [1] := '0';
Ams := Ams + Ac + '/100'
END
ELSE Ams := Ams + 'NO/100';
EnglishNumber := Ams + ' Dollars';
END;
BEGIN
ClrScr;
WriteLn(EnglishNumber (1234.55));
WriteLn(EnglishNumber (991234.55));
WriteLn(EnglishNumber (19891234.55));
Readkey;
END.
|
{ *********************************************************************** }
{ }
{ The Bantung Software Runtime Library }
{ Bantung - Common Library }
{ }
{ Copyright (c) 2012 Bantung Software Co., Ltd. }
{ }
{ *********************************************************************** }
unit CommonLIB;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,Provider, DBClient,SqlExpr,MyAccess,
Dialogs, cxCurrencyEdit, cxControls, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, cxDropDownEdit, StdCtrls, ExtCtrls, cxLookAndFeelPainters,
cxButtons, RzPanel, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
ComCtrls, RzButton, Mask, RzEdit,RzDBEdit,RzCmboBx,uCiaXml,RzDBCmbo,DBCtrls
,ImgList,buttons;
const
_focusColor=$00FFD7FF;
_disableColor=$00EAEAEA;
_enableColor=clWhite;
_config_file='config.xml';
_sample_db='fddb_temp';
_frameVisivle=true;
GridBgColor=$00D9C1BB;
GridBgColor2=$00D2A4A4;
// Sets UnixStartDate to TDateTime of 01/01/1970
UnixStartDate: TDateTime = 25569.0;
type
THackDBNavigator = class(TDBNavigator);
TDLLParameter = record
UserID : String;
WorkStation:String;
Company:string;
Branch:String;
Password : String;
connUser:string;
connPasswd:string;
connDatabase:string;
connServer:string;
CompanyName : string;
CompanyAddr1: string;
CompanyAddr2: string;
CompanyTel :string;
CompanyFax :string;
Parameters : string;
SelectCode : string;
SelectName : string;
ParametersBool1 : boolean;
ParametersBool2 : boolean;
ParametersBool3 : boolean;
ParametersBool4 : boolean;
ParametersBool5 : boolean;
SearchText1 : string;
SearchText2 : string;
SearchText3 : string;
SearchText4 : string;
SearchText5 : string;
ReportCode : string;
ParameterString1:string;
ParameterString2:string;
ParameterString3:string;
ParameterString4:string;
ParameterString5:string;
ParameterString6:string;
ParameterString7:string;
ParameterString8:string;
ParameterString9:string;
ParameterString10:string;
ParameterCurrency1:string;
ParameterCurrency2:string;
ParameterCurrency3:string;
ParameterCurrency4:string;
ParameterCurrency5:string;
ParameterCurrency6:string;
ParameterCurrency7:string;
ParameterCurrency8:string;
ParameterCurrency9:string;
ParameterCurrency10:string;
ParameterNum1:string;
ParameterNum2:string;
ParameterNum3:string;
ParameterNum4:string;
ParameterNum5:string;
ParameterNum6:string;
ParameterNum7:string;
ParameterNum8:string;
ParameterNum9:string;
ParameterNum10:string;
end;
TString = class(TObject)
private
fStr: String;
public
constructor Create(const AStr: String) ;
property Str: String read FStr write FStr;
end;
TStringValue = class(TObject)
private
FValue: string;
FCode: string;
procedure SetCode(const Value: string);
procedure SetValue(const Value: string);
public
constructor Create(const ACode , AValue :string);
property Code : string read FCode write SetCode;
property Value : string read FValue write SetValue;
end;
TRecStampData= array[0..7] of byte;
// App must instantiate own copy of this object for use
TRecStamp= class(TObject)
private
FData: TRecStampData;
public
constructor Create;
procedure Free;
function SetStamp(aField: TField): boolean; // Set the object's
function GetStamp: TRecStampData; // Return the stamp data
function IsBlank: boolean; // Has the stamp data been assigned?
function IsSameStamp(otherData: TRecStampData): boolean; // Compare
end;
var
InnerProv:TDataSetProvider;
SQ:TMyQuery;
xmlConn:TXMLConfig;
_app_address,_app_hostname,
_app_port,_system_code,
_app_ipusing,_app_serverName,_version,
_app_user,_app_password ,_app_database
:string;
function AddProv(frm:TForm;Conn:TMyConnection;ProvName: string): boolean;
procedure initCDS(proveName:string;_cds:TClientDataSet);
function initSqlConnection(sqlconn:TSQLConnection):boolean;
function initMyConnection(sqlconn:TMyConnection):boolean;
Procedure SetChildTaborders(const Parent: TWinControl) ;
Procedure SetControl(const Parent: TWinControl;_enable:boolean) ;
// foundation code
function getFoundNo(cds:TClientDataSet;objCode,CodeType:string):string;
procedure setFoundNo(cds:TClientDataSet;objCode:string;maxcode:integer);
// dis
function getRunning(cds:TClientDataSet;abr,grp,cde,value_fieldname:string):integer;
function setRunning(cds:TClientDataSet;abr,grp,cde,value_fieldname:string):integer;
// billno
function getBillNo(cds:TClientDataSet;abr,grp,cde,value_fieldname:string):integer;
procedure setBillNo(cds:TClientDataSet;abr,grp,cde,value_fieldname:string);
// peroid
function ckPeroidNo(cds:TClientDataSet;Branch:string;periodNo:integer):boolean;
function getPeroidNo(cds:TClientDataSet;abr,cde,value_fieldname:string):integer;
procedure setPeroidNo(cds:TClientDataSet;abr,cde,value_fieldname:string);
// get new donator id
function getNewDonatorId(cds:TClientDataSet):integer;
function getServerDate(_cds:TClientDataSet):TDateTime;
function DateTimeToUnix(ConvDate: TDateTime): Longint;
function UnixToDateTime(USec: Longint): TDateTime;
function getBookBankID(_cds:TClientDataSet;objcode:string):String;
function getUserFullName(_cds:TClientDataSet;UID:string):String;
function getDonationsPointName(_cds:TClientDataSet;cde:string):String;
procedure initDataset(frm:TForm;_conn:TMyConnection);
procedure initDatasetA(frm:TForm;_conn:TMyConnection;_cds:TClientDataSet);
function copyCdsA(cdsSource:TClientDataSet;cdsTarget:TClientDataSet):boolean;
procedure SetupHackedNavigator(const Navigator : TDBNavigator;const Glyphs : TImageList);
procedure HackNavMouseUp(Sender:TObject; Button: TMouseButton;Shift: TShiftState; X, Y: Integer);
function isDate ( const DateString: string ): boolean;
procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings) ;
function IsFloat(S: string): boolean;
function IsInteger(S: string): boolean;
procedure loadCmbList(cmb:TRzComboBox;cds:TClientDataset;strSQL,fCode,fName,defaultCode:string);
function loadCmbItems(CmbITem:TStrings;cds:TClientDataset;strSQL,fCode,fName,defaultCode:string):integer;
implementation
function loadCmbItems(CmbITem:TStrings;cds:TClientDataset;strSQL,fCode,fName,defaultCode:string):integer;
var i,defaultIndex: integer;
begin
cds.close;
cds.CommandText:=strsql;
cds.open;
defaultIndex:=0;
CmbITem.Clear;
if cds.RecordCount>0 then
begin
cds.first;
for i := 0 to cds.RecordCount-1 do
begin
CmbITem.AddObject(trim(cds.fieldbyname(fName).AsString),TString.Create(trim(cds.fieldbyname(fCode).AsString)));
if trim(cds.fieldbyname(fCode).AsString)=defaultCode then defaultIndex:=i;
if not cds.Eof then cds.next;
end;
end;
result:=defaultIndex;
end;
procedure loadCmbList(cmb:TRzComboBox;cds:TclientDataset;strSQL,fCode,fName,defaultCode:string);
var i,defaultIndex : integer;
begin
cds.close;
cds.CommandText:=strsql;
cds.open;
defaultIndex:=0;
cmb.Items.Clear;
if cds.RecordCount>0 then
begin
cds.first;
for i := 0 to cds.RecordCount-1 do
begin
cmb.Items.AddObject(trim(cds.fieldbyname(fName).AsString),TString.Create(trim(cds.fieldbyname(fCode).AsString)));
if trim(cds.fieldbyname(fCode).AsString)=defaultCode then defaultIndex:=i;
if not cds.Eof then cds.next;
end;
cmb.ItemIndex:=defaultIndex;
end;
end;
function IsInteger(S: string): boolean;
begin
try
StrToInt(S);
Result := true;
except
Result := false;
end;
end;
function IsFloat(S: string): boolean;
begin
try
StrToFloat(S);
Result := true;
except
Result := false;
end;
end;
procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings) ;
begin
ListOfStrings.Clear;
ListOfStrings.Delimiter := Delimiter;
ListOfStrings.DelimitedText := Str;
end;
function isDate ( const DateString: string ): boolean;
begin
try
StrToDate ( DateString );
result := true;
except
result := false;
end;
end;
procedure HackNavMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
const MoveBy : integer = 5;
begin
if NOT (Sender is TNavButton) then Exit;
case TNavButton(Sender).Index of
nbPrior:
if (ssCtrl in Shift) then
TDBNavigator(TNavButton(Sender).Parent).
DataSource.DataSet.MoveBy(-MoveBy);
nbNext:
if (ssCtrl in Shift) then
TDBNavigator(TNavButton(Sender).Parent).
DataSource.DataSet.MoveBy(MoveBy);
end;
end;
procedure SetupHackedNavigator(
const Navigator: TDBNavigator; const Glyphs: TImageList);
const
Captions : array[TNavigateBtn] of string = ('First', 'Previous', 'Next', 'Last', 'Add','Erase', 'Edit', 'Save', 'Cancel', 'Revive');
(*
Captions : array[TNavigateBtn] of string =
('First', 'Prior', 'Next', 'Last', 'Insert',
'Delete', 'Edit', 'Post', 'Cancel', 'Refresh');
in Croatia (localized):
Captions : array[TNavigateBtn] of string =
('Prvi', 'Prethodni', 'Slijedeci', 'Zadnji', 'Dodaj',
'Obrisi', 'Promjeni', 'Spremi', 'Odustani', 'Osvjezi');
*)
var
btn : TNavigateBtn;
begin
for btn := Low(TNavigateBtn) to High(TNavigateBtn) do
with THackDBNavigator(Navigator).Buttons[btn] do
begin
//from the Captions const array
Caption := Captions[btn];
Transparent:=true;
//the number of images in the Glyph property
NumGlyphs := 1;
// Remove the old glyph.
Glyph := nil;
// Assign the custom one
case Integer(btn) of
0:Glyphs.GetBitmap(63,Glyph);
1:Glyphs.GetBitmap(5,Glyph);
2:Glyphs.GetBitmap(26,Glyph);
3:Glyphs.GetBitmap(64,Glyph);
4:Glyphs.GetBitmap(1,Glyph);
5:Glyphs.GetBitmap(16,Glyph);
6:Glyphs.GetBitmap(19,Glyph);
7:Glyphs.GetBitmap(61,Glyph);
8:Glyphs.GetBitmap(8,Glyph);
9:Glyphs.GetBitmap(57,Glyph);
end;
//Glyphs.GetBitmap(Integer(btn),Glyph);
Layout:=blGlyphTop;
Flat:=true;
//OnMouseUp := HackNavMouseUp;
end;
end;
function copyCdsA(cdsSource:TClientDataSet;cdsTarget:TClientDataSet):boolean; // for targer field
var i,k:integer;
str:string;
begin
try
Result := False;
cdsSource.First();
while (not cdsSource.Eof) do
begin
cdsTarget.Append();
for i := 0 to (cdsTarget.FieldCount - 1) do
begin
for k := 0 to (cdsSource.FieldCount - 1) do
if cdsTarget.Fields[i].FieldName=cdsSource.Fields[k].FieldName then
begin
// str:=str+cdsTarget.Fields[i].FieldName+ '='+cdsSource.FieldByName(cdsSource.Fields[k].FieldName).AsString+#10#13;
cdsTarget.FieldByName(cdsTarget.Fields[i].FieldName).Value :=
cdsSource.FieldByName(cdsSource.Fields[k].FieldName).Value;
end;
end;
try
cdsTarget.Post();
except
end;
cdsSource.Next();
end;
finally
result := True;
end;
end;
procedure initDataset(frm:TForm;_conn:TMyConnection);
var provName:string;
i:integer;
begin
with frm do
begin
for I := 0 to frm.ComponentCount - 1 do
begin
if ((Components[I] is TClientDataset) and (Components[I].Tag <> 99))
then
begin
AddProv(frm,_conn,TClientDataSet(Components[I]).Name);
initCDS(TClientDataSet(Components[I]).Name,TClientDataSet(Components[I]));
end;
end;
end;
end;
procedure initDatasetA(frm:TForm;_conn:TMyConnection;_cds:TClientDataSet);
var provName:string;
i:integer;
begin
AddProv(frm,_conn,_cds.Name);
initCDS(_cds.Name,_cds);
end;
function DateTimeToUnix(ConvDate: TDateTime): Longint;
begin
Result := Round((ConvDate - UnixStartDate) * 86400);
end;
function UnixToDateTime(USec: Longint): TDateTime;
begin
Result := (Usec / 86400) + UnixStartDate;
end;
function getServerDate(_cds:TClientDataSet):TDateTime;
var
curr_date:TDateTime;
begin
with _cds do
begin
close;
CommandText:='SELECT CONVERT(DATETIME, {fn CURDATE()}) curr_date';
open;
if recordcount>0 then
begin
curr_date:=FieldByName('curr_date').AsDateTime;
end;
Result:=curr_date;
end;
end;
function getBookBankID(_cds:TClientDataSet;objcode:string):String;
var
rep:string;
begin
with _cds do
begin
close;
CommandText:='select a.*,b.* from object_code a left join san$BANKBOOK b on a.o_acccode=b.accid where a.o_code='''+objcode+'''';
open;
if recordcount>0 then
begin
rep:=trim(FieldByName('o_bookbank').AsString);
end;
Result:=rep;
end;
end;
function getUserFullName(_cds:TClientDataSet;UID:string):String;
var
rep:string;
begin
with _cds do
begin
close;
CommandText:='select us_name from user_account where us_code='''+UID+'''';
open;
if recordcount>0 then
begin
rep:=trim(FieldByName('us_name').AsString);
end;
Result:=rep;
end;
end;
function getDonationsPointName(_cds:TClientDataSet;cde:string):String;
var
rep:string;
begin
with _cds do
begin
close;
CommandText:='select MTTCDE,MTTDES from MTTCDE where MTTGRP=''FRONT'' and MTTACT=''A'' and MTTCDE='''+cde+'''';
open;
if recordcount>0 then
begin
rep:=trim(FieldByName('MTTDES').AsString);
end;
Result:=rep;
end;
end;
// foundation code
function getFoundNo(cds:TClientDataSet;objCode,CodeType:string):string;
var rep,olen,i,maxno,lencode:integer;
fstr,repstr:string;
begin
fstr:='';
rep:=0;
with cds do
begin
close;
CommandText:='select MAX(fd_code) maxcode,LEN(MAX(fd_code)) lencode from found_code where fd_codetype='''+CodeType+''' ';
// inputbox('','',CommandText);
open;
if recordcount>0 then
begin
if not FieldByName('maxcode').IsNull then
maxno:= FieldByName('maxcode').AsInteger;
if not FieldByName('lencode').IsNull then
lencode:= FieldByName('lencode').AsInteger;
end;
close;
CommandText:='select o_running,o_running_len from object_code where o_code='''+objCode+'''';
open;
if recordcount>0 then
begin
if FieldByName('o_running').IsNull then
rep :=maxno
else
rep:=FieldByName('o_running').AsInteger+1;
if FieldByName('o_running_len').IsNull then
olen :=lencode
else
olen := FieldByName('o_running_len').AsInteger;
end else
rep :=1;
for I := 0 to olen-1 do
fstr:=fstr+'0';
repstr := FormatCurr(fstr,rep+1);
end;
result:=repstr;
end;
procedure setFoundNo(cds:TClientDataSet;objCode:string;maxcode:integer);
var rep:integer;
begin
rep:=0;
with cds do
begin
close;
CommandText:='select o_running,o_running_len from object_code where o_code='''+objCode+'''';
open;
if recordcount>0 then
begin
if FieldByName('o_running').IsNull then rep :=maxcode
else
rep:=FieldByName('o_running').AsInteger+1;
end;
if rep>0 then
begin
close;
CommandText:='update object_code set o_running='+inttostr(rep)+' where o_code='''+objCode+''' ';
Execute;
end;
end;
end;
// DIS
function getRunning(cds:TClientDataSet;abr,grp,cde,value_fieldname:string):integer;
var rep:integer;
begin
rep:=0;
with cds do
begin
close;
CommandText:='select * from MTTCDE where MTTABR='''+abr+''' and MTTGRP='''+grp+''' and MTTCDE='''+cde+''' ';
open;
if recordcount>0 then
begin
rep:=FieldByName(value_fieldname).AsInteger;
end;
end;
result:=rep;
end;
// DIS
function setRunning(cds:TClientDataSet;abr,grp,cde,value_fieldname:string):integer;
var rep:integer;
begin
rep:=0;
with cds do
begin
close;
CommandText:='select * from MTTCDE where MTTABR='''+abr+''' and MTTGRP='''+grp+''' and MTTCDE='''+cde+''' ';
open;
if recordcount>0 then
begin
rep:=FieldByName(value_fieldname).AsInteger;
end;
if rep>0 then
begin
close;
CommandText:='update MTTCDE set MTTNM1='+inttostr(rep+1)+' where MTTABR='''+abr+''' and MTTGRP='''+grp+''' and MTTCDE='''+cde+'''';
Execute;
end;
end;
end;
// BILL
function getBillNo(cds:TClientDataSet;abr,grp,cde,value_fieldname:string):integer;
var rep:integer;
begin
rep:=0;
with cds do
begin
close;
//CommandText:='select * from MTTCDE where MTTABR='''+abr+''' and MTTGRP='''+grp+''' and MTTCDE='''+cde+''' ';
CommandText:='select * from MTTCDE where MTTGRP='''+grp+''' and MTTCDE='''+cde+''' ';
open;
if recordcount>0 then
begin
rep:=FieldByName(value_fieldname).AsInteger;
end;
end;
result:=rep;
end;
procedure setBillNo(cds:TClientDataSet;abr,grp,cde,value_fieldname:string);
var rep:integer;
begin
rep:=0;
with cds do
begin
close;
//CommandText:='select * from MTTCDE where MTTABR='''+abr+''' and MTTGRP='''+grp+''' and MTTCDE='''+cde+''' ';
CommandText:='select * from MTTCDE where MTTGRP='''+grp+''' and MTTCDE='''+cde+''' ';
open;
if recordcount>0 then
begin
rep:=FieldByName(value_fieldname).AsInteger;
end;
if rep>0 then
begin
close;
// CommandText:='update MTTCDE set MTTNM1='+inttostr(rep+1)+' where MTTABR='''+abr+''' and MTTGRP='''+grp+''' and MTTCDE='''+cde+'''';
CommandText:='update MTTCDE set MTTNM1='+inttostr(rep+1)+' where MTTGRP='''+grp+''' and MTTCDE='''+cde+'''';
Execute;
end;
end;
end;
// Peroid
// BILL
function getPeroidNo(cds:TClientDataSet;abr,cde,value_fieldname:string):integer;
var rep:integer;
begin
rep:=0;
with cds do
begin
close;
//CommandText:='select * from MTTCDE where MTTABR='''+abr+''' and MTTGRP=''PEROID'' and MTTCDE='''+cde+''' ';
CommandText:='select * from MTTCDE where MTTGRP=''PEROID'' and MTTCDE='''+cde+''' ';
open;
if recordcount>0 then
begin
rep:=FieldByName(value_fieldname).AsInteger;
end;
end;
result:=rep;
end;
function ckPeroidNo(cds:TClientDataSet;Branch:string;periodNo:integer):boolean;
var rep:boolean;
begin
rep:=false;
with cds do
begin
close;
CommandText:='select * from period_data where pe_branch='''+Branch+''' and pe_id='''+inttostr(periodNo)+''' and pe_status=''A''';
open;
if Active then rep:= recordcount>0 ;
end;
result:=rep;
end;
function getNewDonatorId(cds:TClientDataSet):integer;
var rep:integer;
begin
rep:=0;
with cds do
begin
close;
CommandText:='select (MAX(do_id)+1) as newdoid from donator';
open;
if recordcount>0 then
begin
rep:=FieldByName('newdoid').AsInteger;
end;
end;
result:=rep;
end;
procedure setPeroidNo(cds:TClientDataSet;abr,cde,value_fieldname:string);
var rep:integer;
begin
rep:=0;
with cds do
begin
close;
//CommandText:='select * from MTTCDE where MTTABR='''+abr+''' and MTTGRP=''PEROID'' and MTTCDE='''+cde+''' ';
CommandText:='select * from MTTCDE where MTTGRP=''PEROID'' and MTTCDE='''+cde+''' ';
open;
if recordcount>0 then
begin
rep:=FieldByName(value_fieldname).AsInteger;
end;
if rep>0 then
begin
close;
//CommandText:='update MTTCDE set MTTNM1='+inttostr(rep+1)+' where MTTABR='''+abr+''' and MTTGRP=''PEROID'' and MTTCDE='''+cde+'''';
CommandText:='update MTTCDE set MTTNM1='+inttostr(rep+1)+' where MTTGRP=''PEROID'' and MTTCDE='''+cde+'''';
Execute;
end;
end;
end;
function initMyConnection(sqlconn:TMyConnection):boolean;
var rep:boolean;
begin
try
rep:=false;
xmlConn:=TXMLConfig.Create(ExtractFilePath(Application.ExeName)+_config_file);
//xmlConn:=TXMLConfig.Create(_config_file);
if (xmlConn.ReadString('AppConfig','ADDRESS','')='') then
begin
// mssql connection
xmlConn.WriteString('AppConfig','ADDRESS','127.0.0.1');
xmlConn.WriteString('AppConfig','HOSTNAME','dev.siamdev.org');
xmlConn.WriteString('AppConfig','USER','sa');
xmlConn.WriteString('AppConfig','PASSWORD','123456');
xmlConn.WriteString('AppConfig','DATABASE',_sample_db);
xmlConn.Save;
end;
_app_address:= xmlConn.ReadString('AppConfig','ADDRESS','');
_app_hostname:= xmlConn.ReadString('AppConfig','HOSTNAME','');
_app_database:=xmlConn.ReadString('AppConfig','DATABASE','');
_app_user:=xmlConn.ReadString('AppConfig','USER','sa');
_app_password:=xmlConn.ReadString('AppConfig','PASSWORD','123456');
with sqlconn do
begin
Connected:=false;
server:=_app_address;
database:=_app_database;
username:=_app_user;
password:=_app_password;
Options.Charset:='tis620';
Connected:=true;
rep:=true;
end;
xmlConn.Free;
except
on err:Exception do
begin
rep:=false;
MessageDlg(err.Message,mtError,[mbOK],0);
ShowMessage(_app_address+'-'+_app_database+'-'+_app_user+'-'+_app_password);
end;
end;
result:=rep;
end;
function initSqlConnection(sqlconn:TSQLConnection):boolean;
var rep:boolean;
begin
try
rep:=false;
xmlConn:=TXMLConfig.Create(ExtractFilePath(Application.ExeName)+_config_file);
//xmlConn:=TXMLConfig.Create(_config_file);
if (xmlConn.ReadString('AppConfig','ADDRESS','')='') then
begin
// mssql connection
xmlConn.WriteString('AppConfig','ADDRESS','127.0.0.1');
xmlConn.WriteString('AppConfig','HOSTNAME','dev.siamdev.org');
xmlConn.WriteString('AppConfig','USER','sa');
xmlConn.WriteString('AppConfig','PASSWORD','123456');
xmlConn.WriteString('AppConfig','DATABASE',_sample_db);
xmlConn.Save;
end;
_app_address:= xmlConn.ReadString('AppConfig','ADDRESS','');
_app_hostname:= xmlConn.ReadString('AppConfig','HOSTNAME','');
_app_database:=xmlConn.ReadString('AppConfig','DATABASE','');
_app_user:=xmlConn.ReadString('AppConfig','USER','sa');
_app_password:=xmlConn.ReadString('AppConfig','PASSWORD','123456');
with sqlconn do
begin
Connected:=false;
{
Params.Values['HostName']:='192.168.41.45\SQLExpress';//app_address;
Params.Values['DataBase']:='fddb_temp2';//_app_database;
Params.Values['User_Name']:='sa';//_app_user;
Params.Values['Password']:='sqlserver2008';//_app_password;
}
Params.Values['HostName']:=_app_address;
Params.Values['DataBase']:=_app_database;
Params.Values['User_Name']:=_app_user;
Params.Values['Password']:=_app_password;
Connected:=true;
rep:=true;
end;
except
on err:Exception do
begin
rep:=false;
MessageDlg(err.Message,mtError,[mbOK],0);
ShowMessage(_app_address+'-'+_app_database+'-'+_app_user+'-'+_app_password);
end;
end;
result:=rep;
end;
function AddProv(frm:TForm;Conn:TMyConnection;ProvName: string): boolean;
begin
//if frm.FindComponent(ProvName) <> nil then
// begin
InnerProv := TDataSetProvider.Create(frm);
InnerProv.Name := 'dsp_'+ProvName;
InnerProv.UpdateMode := UpWhereAll;
InnerProv.Options := [poAllowCommandText, poRetainServerOrder, poAllowMultiRecordUpdates];
SQ := TMyQuery.Create(frm);
SQ.Name := 'SQL'+ProvName;
SQ.Connection := Conn;
InnerProv.DataSet := SQ;
//ShowMessage('ADD Provider :'+InnerProv.Name);
// TServerMethods1(self).RegisterProvider(InnerProv); //fuck it did not help
//end;
end;
procedure initCDS(proveName:string;_cds:TClientDataSet);
begin
if _cds=nil then _cds:=TClientDataSet.Create(Application);
proveName:='dsp_'+_cds.Name;
_cds.Close;
_cds.ProviderName:=proveName;//_ProviderName;
//ShowMessage('ADD Provider To DataSet '+_cds.Name+' ==>'+_cds.ProviderName);
end;
Procedure SetChildTaborders(const Parent: TWinControl) ;
procedure FixTabOrder(const Parent: TWinControl) ;
var
ctl, L: Integer;
List: TList;
begin
List := TList.Create;
try
for ctl := 0 to Parent.ControlCount - 1 do
begin
if Parent.Controls[ctl] is TWinControl then
begin
if List.Count = 0 then
L := 0
else
begin
with Parent.Controls[ctl] do
for L := 0 to List.Count - 1 do
if (Top < TControl(List[L]).Top) or ((Top = TControl(List[L]).Top) and (Left < TControl(List[L]).Left)) then Break;
end;
List.Insert(L, Parent.Controls[ctl]) ;
if Parent.Controls[ctl].Tag<>99 then
begin
//TRzEdit
if Parent.Controls[ctl] is TRzEdit then
begin
TRzEdit(Parent.Controls[ctl]).FocusColor:=_focusColor;
TRzEdit(Parent.Controls[ctl]).FrameVisible:=_frameVisivle;
end;
//TRzDBEdit
if Parent.Controls[ctl] is TRzDBEdit then
begin
TRzDBEdit(Parent.Controls[ctl]).FocusColor:=_focusColor;
TRzDBEdit(Parent.Controls[ctl]).FrameVisible:=_frameVisivle;
end;
//TRzComboBox
if Parent.Controls[ctl] is TRzComboBox then
begin
TRzComboBox(Parent.Controls[ctl]).FocusColor:=_focusColor;
TRzComboBox(Parent.Controls[ctl]).FrameVisible:=_frameVisivle;
end;
//TRzDBDateTimeEdit
if Parent.Controls[ctl] is TRzDBDateTimeEdit then
begin
TRzDBDateTimeEdit(Parent.Controls[ctl]).FocusColor:=_focusColor;
TRzDBDateTimeEdit(Parent.Controls[ctl]).FrameVisible:=_frameVisivle;
end;
//TRzDBNumericEdit
if Parent.Controls[ctl] is TRzDBNumericEdit then
begin
TRzDBNumericEdit(Parent.Controls[ctl]).FocusColor:=_focusColor;
TRzDBNumericEdit(Parent.Controls[ctl]).FrameVisible:=_frameVisivle;
end;
end;
FixTabOrder(TWinControl(Parent.Controls[ctl])) ;
end;
end;
for ctl := 0 to List.Count - 1 do
TWinControl(List[ctl]).TabOrder := ctl;
finally
List.Free;
end;
end;
begin
FixTabOrder(Parent) ;
end;
Procedure SetControl(const Parent: TWinControl;_enable:boolean) ;
procedure FixTabOrder(const Parent: TWinControl) ;
var
ctl, L: Integer;
List: TList;
begin
List := TList.Create;
try
for ctl := 0 to Parent.ControlCount - 1 do
begin
if Parent.Controls[ctl] is TWinControl then
begin
if List.Count = 0 then
L := 0
else
begin
with Parent.Controls[ctl] do
for L := 0 to List.Count - 1 do
if (Top < TControl(List[L]).Top) or ((Top = TControl(List[L]).Top) and (Left < TControl(List[L]).Left)) then Break;
end;
List.Insert(L, Parent.Controls[ctl]) ;
//TRzEdit
if Parent.Controls[ctl] is TRzEdit then
begin
TRzEdit(Parent.Controls[ctl]).Enabled:=_enable;
if _enable then
TRzEdit(Parent.Controls[ctl]).Color:=_enableColor
else
TRzEdit(Parent.Controls[ctl]).Color:=_disableColor;
end;
//TRzDBEdit
if Parent.Controls[ctl] is TRzDBEdit then
begin
TRzDBEdit(Parent.Controls[ctl]).Enabled:=_enable;
if _enable then
TRzDBEdit(Parent.Controls[ctl]).Color:=_enableColor
else
TRzDBEdit(Parent.Controls[ctl]).Color:=_disableColor;
end;
//TRzComboBox
if Parent.Controls[ctl] is TRzComboBox then
begin
TRzComboBox(Parent.Controls[ctl]).Enabled:=_enable;
if _enable then
TRzComboBox(Parent.Controls[ctl]).Color:=_enableColor
else
TRzComboBox(Parent.Controls[ctl]).Color:=_disableColor;
end;
//TRzDBComboBox
if Parent.Controls[ctl] is TRzDBComboBox then
begin
TRzDBComboBox(Parent.Controls[ctl]).Enabled:=_enable;
if _enable then
TRzDBComboBox(Parent.Controls[ctl]).Color:=_enableColor
else
TRzDBComboBox(Parent.Controls[ctl]).Color:=_disableColor;
end;
//TRzDBDateTimeEdit
if Parent.Controls[ctl] is TRzDBDateTimeEdit then
begin
TRzDBDateTimeEdit(Parent.Controls[ctl]).Enabled:=_enable;
if _enable then
TRzDBDateTimeEdit(Parent.Controls[ctl]).Color:=_enableColor
else
TRzDBDateTimeEdit(Parent.Controls[ctl]).Color:=_disableColor;
end;
//TRzDBNumericEdit
if Parent.Controls[ctl] is TRzDBNumericEdit then
begin
TRzDBNumericEdit(Parent.Controls[ctl]).Enabled:=_enable;
if _enable then
TRzDBNumericEdit(Parent.Controls[ctl]).Color:=_enableColor
else
TRzDBNumericEdit(Parent.Controls[ctl]).Color:=_disableColor;
end;
//TSpeedButton
if Parent.Controls[ctl] is TSpeedButton then
begin
TSpeedButton(Parent.Controls[ctl]).Enabled:=_enable;
end;
FixTabOrder(TWinControl(Parent.Controls[ctl])) ;
end;
end;
for ctl := 0 to List.Count - 1 do
TWinControl(List[ctl]).TabOrder := ctl;
finally
List.Free;
end;
end;
begin
FixTabOrder(Parent) ;
end;
{ TString }
constructor TString.Create(const AStr: String);
begin
inherited Create;
FStr := AStr;
end;
{ TRecStamp }
constructor TRecStamp.Create;
var i: integer;
begin
inherited;
for i:=0 to 7 do FData[i]:=0;
end;
procedure TRecStamp.Free;
begin
Destroy;
end;
function TRecStamp.GetStamp: TRecStampData;
begin
Result:=FData;
end;
function TRecStamp.IsBlank: boolean;
var i: integer;
begin
for i:=0 to High(FData) do
if FData[i]<>0
then begin
Result:=false;
break;
end
else Result:=true;
end;
function TRecStamp.IsSameStamp(otherData: TRecStampData): boolean;
var i: integer;
begin
if SizeOf(FData)<>SizeOf(otherData) then exit;
for i:=0 to High(FData) do
if FData[i]<>otherData[i]
then begin
Result:=false;
break;
end
else Result:=true;
end;
function TRecStamp.SetStamp(aField: TField): boolean;
type pTRecStampData= ^TRecStampData;
var Buf: pointer;
BufSize: word;
pData: pTRecStampData;
begin
Result:=false;
if not Assigned(aField) then exit;
BufSize:=aField.DataSize;
if BufSize<>SizeOf(TRecStampData) then exit;
try
GetMem(Buf,BufSize);
aField.GetData(Buf);
pData:= pTRecStampData(Buf);
FData:=pData^;
finally
FreeMem(Buf,BufSize);
end;
end;
{ TStringValue }
constructor TStringValue.Create(const ACode, AValue: string);
begin
self.Code := ACode;
self.Value := AValue;
end;
procedure TStringValue.SetCode(const Value: string);
begin
FCode := Value;
end;
procedure TStringValue.SetValue(const Value: string);
begin
FValue := Value;
end;
end.
|
unit Resources;
////////////////////////////////////////////////////////////////////////////////
//
// Unit : Resources
// Author : rllibby
// Date : 02.07.2008
// Description : Source code for PE resource enumeration and misc handling
//
////////////////////////////////////////////////////////////////////////////////
interface
{ Example usage:
var lpResources: TPEResources;
dwIndex: Integer;
begin
// Testing code
if (CopyFile('c:\windows\system32\calc.exe', 'c:\calc.exe', False)) then
begin
// Create resource object list
lpResources:=TPEResources.Create('c:\calc.exe');
try
// Remove the resource
lpResources.Remove(RT_MANIFEST, MakeIntResource(1));
lpResources.Remove(RT_VERSION, MakeIntResource(1));
lpResources.Remove(RT_GROUP_ICON, 'SC');
for dwIndex:=1 to 6 do
begin
lpResources.Remove(RT_STRING, MakeIntResource(dwIndex));
end;
finally
// Free object
lpResources.Free;
end;
end;
end;
}
////////////////////////////////////////////////////////////////////////////////
// Include units
////////////////////////////////////////////////////////////////////////////////
uses
Windows, SysUtils, Classes;
////////////////////////////////////////////////////////////////////////////////
// Data types
////////////////////////////////////////////////////////////////////////////////
type
TResNameID = packed record
Name: PChar;
ID: PChar;
end;
////////////////////////////////////////////////////////////////////////////////
// Updated list of predefined resource types
////////////////////////////////////////////////////////////////////////////////
const
// Missing predefined types
RT_HTML = MakeIntResource(23);
RT_MANIFEST = MakeIntResource(24);
// Maximum predefined value
RT_MAX_PREDEFINE = 24;
// List of predefined types with associated name
RT_PREDEFINED: Array [0..RT_MAX_PREDEFINE] of TResNameID =
(
(Name: '#0'; ID: MakeIntResource(0)),
(Name: 'Cursor'; ID: RT_CURSOR),
(Name: 'Bitmap'; ID: RT_BITMAP),
(Name: 'Icon'; ID: RT_ICON),
(Name: 'Menu'; ID: RT_MENU),
(Name: 'Dialog'; ID: RT_DIALOG),
(Name: 'String'; ID: RT_STRING),
(Name: 'Fonts'; ID: RT_FONTDIR),
(Name: 'Font'; ID: RT_FONT),
(Name: 'Accelerator'; ID: RT_ACCELERATOR),
(Name: 'Data'; ID: RT_RCDATA),
(Name: 'Message Table'; ID: RT_MESSAGETABLE),
(Name: 'Group Cursor'; ID: RT_GROUP_CURSOR),
(Name: '#13'; ID: MakeIntResource(13)),
(Name: 'Group Icon'; ID: RT_GROUP_ICON),
(Name: '#15'; ID: MakeIntResource(15)),
(Name: 'Version'; ID: RT_VERSION),
(Name: 'Dialog'; ID: RT_DLGINCLUDE),
(Name: '#18'; ID: MakeIntResource(18)),
(Name: 'Plug And Play'; ID: RT_PLUGPLAY),
(Name: 'VXD'; ID: RT_VXD),
(Name: 'Animated Cursor'; ID: RT_ANICURSOR),
(Name: 'Animated Icon'; ID: RT_ANIICON),
(Name: 'Html'; ID: RT_HTML),
(Name: 'Manifest'; ID: RT_MANIFEST)
);
////////////////////////////////////////////////////////////////////////////////
// PE Resource objects
////////////////////////////////////////////////////////////////////////////////
type
// Resource object
TPEResource = class(TObject)
private
// Private declarations
FName: PChar;
FType: PChar;
FLanguages: TList;
protected
// Protected declarations
procedure Load(Module: HMODULE);
function GetLanguages(Index: Integer): Word;
function GetLanguageCount: Integer;
public
// Public declarations
constructor Create(AModule: HMODULE; AName, AType: PChar);
destructor Destroy; override;
property Languages[Index: Integer]: Word read GetLanguages;
property LanguageCount: Integer read GetLanguageCount;
property ResName: PChar read FName;
property ResType: PChar read FType;
end;
// Resource group object
TPEResourceGroup = class(TObject)
private
// Private declarations
FType: PChar;
FResources: TList;
protected
// Protected declarations
procedure Clear;
procedure Load(Module: HMODULE);
procedure Remove(Obj: TObject);
function GetResources(Index: Integer): TPEResource;
function GetResourceCount: Integer;
function GetResTypeName: String;
public
// Public declarations
constructor Create(AModule: HMODULE; AType: PChar);
destructor Destroy; override;
function Find(ResourceName: PChar): TPEResource;
property ResType: PChar read FType;
property ResTypeName: String read GetResTypeName;
property Resources[Index: Integer]: TPEResource read GetResources;
property ResourceCount: Integer read GetResourceCount;
end;
// Resource container
TPEResources = class(TObject)
private
// Private declarations
FLibFileName: String;
FGroups: TList;
protected
// Protected declarations
procedure Clear;
procedure Load(LibFileName: String);
function GetGroupCount: Integer;
function GetGroups(Index: Integer): TPEResourceGroup;
public
// Public declarations
constructor Create(LibFileName: String);
destructor Destroy; override;
function Find(ResourceType, ResourceName: PChar): TPEResource;
function GroupByType(ResourceType: PChar): TPEResourceGroup;
procedure Remove(ResourceType, ResourceName: PChar);
property Groups[Index: Integer]: TPEResourceGroup read GetGroups;
property GroupCount: Integer read GetGroupCount;
end;
////////////////////////////////////////////////////////////////////////////////
// Utility functions
////////////////////////////////////////////////////////////////////////////////
function GetResourceTypeName(ResourceType: PChar): String;
function GetResourceName(ResourceName: PChar): String;
function IsIntResource(ResourceTypeOrName: PChar): Boolean;
procedure KillResource(ExeFile: String; ResType, ResName: PChar; LangID: Word = 0);
function ResAlloc(ResourceTypeOrName: PChar): PChar;
procedure ResFree(ResourceTypeOrName: PChar);
function ResCompare(ResourceTypeOrName1, ResourceTypeOrName2: PChar): Boolean;
implementation
//// Callback functions ////////////////////////////////////////////////////////
function EnumResLangProc(Module: HMODULE; lpszType, lpszName: PChar; wIDLanguage: Word; lParam: Pointer): BOOL; stdcall;
begin
// Resource protection
try
// Cast lParam as resource object and add language
TPEResource(lParam).FLanguages.Add(Pointer(wIDLanguage));
finally
// Keep enumerating
result:=True;
end;
end;
function EnumResNameProc(Module: HMODULE; lpszType, lpszName: PChar; lParam: Pointer): BOOL; stdcall;
begin
// Resource protection
try
// Create new resource and add to list
TPEResourceGroup(lParam).FResources.Add(TPEResource.Create(Module, lpszName, lpszType));
finally
// Keep enumerating
result:=True;
end;
end;
function EnumResTypeProc(Module: HMODULE; lpszType: PChar; lParam: Pointer): BOOL; stdcall;
begin
// Resource protection
try
// Create new resource group and add to list
TPEResources(lParam).FGroups.Add(TPEResourceGroup.Create(Module, lpszType));
finally
// Keep enumerating
result:=True;
end;
end;
//// TPEResource ///////////////////////////////////////////////////////////////
procedure TPEResource.Load(Module: HMODULE);
begin
// Enumerate the languages
EnumResourceLanguages(Module, FType, FName, @EnumResLangProc, Integer(Self));
end;
function TPEResource.GetLanguageCount: Integer;
begin
// Return count of languages
result:=FLanguages.Count;
end;
function TPEResource.GetLanguages(Index: Integer): Word;
begin
// Return the langauge at the specified index
result:=Word(FLanguages[Index]);
end;
constructor TPEResource.Create(AModule: HMODULE; AName, AType: PChar);
begin
// Perform inherited
inherited Create;
// Set defaults
FLanguages:=TList.Create;
FName:=ResAlloc(AName);
FType:=ResAlloc(AType);
// Load
Load(AModule);
end;
destructor TPEResource.Destroy;
begin
// Resource protection
try
// Free the list
FLanguages.Free;
// Free allocated memory
ResFree(FName);
ResFree(FType);
finally
// Perform inherited
inherited Destroy;
end;
end;
//// TPEResourceGroup //////////////////////////////////////////////////////////
function TPEResourceGroup.Find(ResourceName: PChar): TPEResource;
var lpResource: TPEResource;
dwIndex: Integer;
begin
// Set default result
result:=nil;
// Find the desired resource
for dwIndex:=0 to Pred(FResources.Count) do
begin
// Access the resource
lpResource:=GetResources(dwIndex);
// Check the resource name
if ResCompare(ResourceName, lpResource.ResName) then
begin
// Match was found, return resource
result:=lpResource;
// Done processing
break;
end;
end;
end;
procedure TPEResourceGroup.Remove(Obj: TObject);
begin
// Check assignment
if Assigned(Obj) and (FResources.IndexOf(Obj) >= 0) then
begin
// Resource protection
try
// Remove from list
FResources.Remove(Obj);
finally
// Free the object
Obj.Free;
end;
end;
end;
procedure TPEResourceGroup.Load(Module: HMODULE);
begin
// Enumerate the resources for this type
EnumResourceNames(Module, FType, @EnumResNameProc, LongInt(Self));
end;
procedure TPEResourceGroup.Clear;
var dwIndex: Integer;
begin
// Resource protection
try
// Walk the resource list
for dwIndex:=0 to Pred(FResources.Count) do
begin
// Free the resource
TPEResource(FResources[dwIndex]).Free;
end;
finally
// Clear the list
FResources.Clear;
end;
end;
function TPEResourceGroup.GetResources(Index: Integer): TPEResource;
begin
// Return the resource at the specified index
result:=TPEResource(FResources[Index]);
end;
function TPEResourceGroup.GetResourceCount: Integer;
begin
// Return the count of resources
result:=FResources.Count;
end;
function TPEResourceGroup.GetResTypeName: String;
begin
// Return the stringifed name
result:=GetResourceTypeName(FType);
end;
constructor TPEResourceGroup.Create(AModule: HMODULE; AType: PChar);
begin
// Perform inherited
inherited Create;
// Set defaults
FResources:=TList.Create;
FType:=ResAlloc(AType);
// Load
Load(AModule);
end;
destructor TPEResourceGroup.Destroy;
begin
// Resource protection
try
// Clear
Clear;
// Free the list
FResources.Free;
// Free allocated memory
ResFree(FType);
finally
// Perform inherited
inherited Destroy;
end;
end;
//// TPEResources //////////////////////////////////////////////////////////////
procedure TPEResources.Remove(ResourceType, ResourceName: PChar);
var lpGroup: TPEResourceGroup;
lpResource: TPEResource;
dwIndex: Integer;
begin
// Try to get the group
lpGroup:=GroupByType(ResourceType);
// Check result
if Assigned(lpGroup) then
begin
// Have the group lookup the resource name
lpResource:=lpGroup.Find(ResourceName);
// Check result
if Assigned(lpResource) then
begin
// Resource protection
try
// Remove all resources using the language values
if (lpResource.LanguageCount = 0) then
// No language, kill resource
KillResource(FLibFileName, lpResource.ResType, lpResource.ResName, 0)
else
begin
// Walk the languages
for dwIndex:=0 to Pred(lpResource.LanguageCount) do
begin
// Kill the resource based on language id
KillResource(FLibFileName, lpResource.ResType, lpResource.ResName, lpResource.Languages[dwIndex]);
end;
end;
finally
// Have the group free the resource object
lpGroup.Remove(lpResource);
end;
end;
end;
end;
function TPEResources.GroupByType(ResourceType: PChar): TPEResourceGroup;
var lpGroup: TPEResourceGroup;
dwIndex: Integer;
begin
// Set default result
result:=nil;
// Find the desired group
for dwIndex:=0 to Pred(FGroups.Count) do
begin
// Access the group
lpGroup:=GetGroups(dwIndex);
// Check the group
if ResCompare(lpGroup.ResType, ResourceType) then
begin
// Set group result
result:=lpGroup;
// Done processing
break;
end;
end;
end;
function TPEResources.Find(ResourceType, ResourceName: PChar): TPEResource;
var lpGroup: TPEResourceGroup;
dwIndex: Integer;
begin
// Try to get the group
lpGroup:=GroupByType(ResourceType);
// Check result
if Assigned(lpGroup) then
// Have the group lookup the resource name
result:=lpGroup.Find(ResourceName)
else
// Set default result
result:=nil;
end;
procedure TPEResources.Clear;
var dwIndex: Integer;
begin
// Resource protection
try
// Walk the groups list
for dwIndex:=0 to Pred(FGroups.Count) do
begin
// Free the group
TPEResourceGroup(FGroups[dwIndex]).Free;
end;
finally
// Clear the list
FGroups.Clear;
end;
end;
procedure TPEResources.Load(LibFileName: String);
var hMod: HMODULE;
begin
// Attempt to load the library
hMod:=LoadLibraryEx(PChar(LibFileName), 0, LOAD_LIBRARY_AS_DATAFILE);
// Check module handle
if (hMod = 0) then
// Failed to load
RaiseLastWin32Error
else
begin
// Resource protection
try
// Enumerate the resource types
EnumResourceTypes(hMod, @EnumResTypeProc, LongInt(Self));
finally
// Free the library
FreeLibrary(hMod);
end;
end;
end;
function TPEResources.GetGroupCount: Integer;
begin
// Return the count of groups
result:=FGroups.Count;
end;
function TPEResources.GetGroups(Index: Integer): TPEResourceGroup;
begin
// Return the group at the specified index
result:=TPEResourceGroup(FGroups[Index]);
end;
constructor TPEResources.Create(LibFileName: String);
begin
// Perform inherited
inherited Create;
// Set defaults
FGroups:=TList.Create;
FLibFileName:=LibFileName;
// Load the library / exe file
Load(LibFileName);
end;
destructor TPEResources.Destroy;
begin
// Resource protection
try
// Clear
Clear;
// Free the list
FGroups.Free;
finally
// Perform inherited
inherited Destroy;
end;
end;
//// Utility functions /////////////////////////////////////////////////////////
function ResCompare(ResourceTypeOrName1, ResourceTypeOrName2: PChar): Boolean;
begin
// Check the name for integer value
if IsIntResource(ResourceTypeOrName1) then
// Can only match if the second value is an integer as well
result:=(IsIntResource(ResourceTypeOrName2) and (ResourceTypeOrName1 = ResourceTypeOrName2))
// Check second value
else if IsIntResource(ResourceTypeOrName2) then
// Can only match if the first value is an integer as well
result:=(IsIntResource(ResourceTypeOrName1) and (ResourceTypeOrName1 = ResourceTypeOrName2))
else
// Case insensitive compare
result:=(StrIComp(ResourceTypeOrName1, ResourceTypeOrName2) = 0);
end;
function GetResourceName(ResourceName: PChar): String;
begin
// Check the resource type
if IsIntResource(ResourceName) then
// Format as #NUMBER
result:=Format('#%d', [Word(Pointer(ResourceName))])
else
// Return type name
result:=ResourceName;
end;
function ResAlloc(ResourceTypeOrName: PChar): PChar;
begin
// Check for int resource name
if IsIntResource(ResourceTypeOrName) then
// Return as is
result:=ResourceTypeOrName
else
// Allocate and copy
result:=StrCopy(AllocMem(Succ(StrLen(ResourceTypeOrName))), ResourceTypeOrName);
end;
procedure ResFree(ResourceTypeOrName: PChar);
begin
// Check for int resource name
if not(IsIntResource(ResourceTypeOrName)) then
begin
// Free allocated memory
FreeMem(ResourceTypeOrName);
end;
end;
function GetResourceTypeName(ResourceType: PChar): String;
var wType: Word;
begin
// Check the resource type
if IsIntResource(ResourceType) then
begin
// Get actual word value
wType:=Word(Pointer(ResourceType));
// Determine if predefined
if (wType <= RT_MAX_PREDEFINE) then
// Get name from static table
result:=RT_PREDEFINED[wType].Name
else
// Format as #NUMBER
result:=Format('#%d', [wType]);
end
else
// Return type name
result:=ResourceType;
end;
function IsIntResource(ResourceTypeOrName: PChar): Boolean;
begin
// Determine if the resource type / name is actually a word value
result:=((LongWord(Pointer(ResourceTypeOrName)) shr 16) = 0);
end;
procedure KillResource(ExeFile: String; ResType, ResName: PChar; LangID: Word = 0);
var hUpdate: THandle;
begin
// Open file for resource updating
hUpdate:=BeginUpdateResource(PChar(ExeFile), False);
// Check handle
if (hUpdate = 0) then
// Raise error
RaiseLastWin32Error
// Remove resource
else if UpdateResource(hUpdate, ResType, ResName, LangID, nil, 0) then
begin
// End the update
if not(EndUpdateResource(hUpdate, False)) then RaiseLastWin32Error;
end
else
// Raise error
RaiseLastWin32Error
end;
end.
|
unit utils;
{$mode objfpc}{$H+}
interface
uses
windows, SysUtils;
type // This type will be used for containing every array of disk hex data
TDynamicCharArray = array of Char;
type
TBOOT_SEQUENCE = packed record
_jmpcode : array[1..3] of Byte;
cOEMID: array[1..8] of Char;
wBytesPerSector: Word;
bSectorsPerCluster: Byte;
wSectorsReservedAtBegin: Word;
Mbz1: Byte;
Mbz2: Word;
Reserved1: Word;
bMediaDescriptor: Byte;
Mbz3: Word;
wSectorsPerTrack: Word;
wSides: Word;
dwSpecialHiddenSectors: DWord;
Reserved2: DWord;
Reserved3: DWord;
TotalSectors: Int64;
MftStartLcn: Int64;
Mft2StartLcn: Int64;
ClustersPerFileRecord: DWord;
ClustersPerIndexBlock: DWord;
VolumeSerialNumber: Int64;
_loadercode: array[1..430] of Byte;
wSignature: Word;
end;
//https://docs.microsoft.com/fr-fr/windows/desktop/DevNotes/attribute-record-header
type
TRECORD_ATTRIBUTE = packed record
AttributeType : DWord; //0-3
Length : DWord; //4-7
NonResident : Byte; //8
NameLength : Byte; //9
NameOffset : Word; //10-11
Flags : Word; //12-13
AttributeNumber : Word; //14-15
end;
type
TNONRESIDENT_ATTRIBUTE = packed record
Attribute: TRECORD_ATTRIBUTE;
LowVCN: Int64;
HighVCN: Int64;
RunArrayOffset : Word;
CompressionUnit : Byte;
Padding : array[1..5] of Byte;
AllocatedSize: Int64;
DataSize: Int64;
InitializedSize: Int64;
CompressedSize: Int64;
end;
type
TNTFS_RECORD_HEADER = packed record //or called MFT header
Identifier: array[1..4] of Char; // Here must be 'FILE'
UsaOffset : Word;
UsaCount : Word;
LSN : Int64;
end;
//https://flatcap.org/linux-ntfs/ntfs/concepts/file_record.html
type
TFILE_RECORD = packed record
Header: TNTFS_RECORD_HEADER;
SequenceNumber : Word;
ReferenceCount : Word;
AttributesOffset : Word;
Flags : Word; // $0000 = Deleted File, $0001 = InUse File,
// $0002 = Deleted Directory, $0003 = InUse Directory
BytesInUse : DWord;
BytesAllocated : DWord;
BaseFileRecord : Int64;
NextAttributeID : Word;
dummy:word;
MFT_Record_No:dword;
end;
type
TRESIDENT_ATTRIBUTE = packed record
Attribute : TRECORD_ATTRIBUTE;
ValueLength : DWord;
ValueOffset : Word;
Flags : Word;
end;
type
TFILENAME_ATTRIBUTE = packed record
Attribute: TRESIDENT_ATTRIBUTE;
DirectoryFileReferenceNumber: Int64;
CreationTime: Int64;
ChangeTime: Int64;
LastWriteTime: Int64;
LastAccessTime: Int64;
AllocatedSize: Int64;
DataSize: Int64;
FileAttributes: DWord;
AlignmentOrReserved: DWord;
NameLength: Byte;
NameType: Byte;
Name: Word;
end;
type
TSTANDARD_INFORMATION = packed record
Attribute: TRESIDENT_ATTRIBUTE;
CreationTime: Int64;
ChangeTime: Int64;
LastWriteTime: Int64;
LastAccessTime: Int64;
FileAttributes: DWord;
Alignment: array[1..3] of DWord;
QuotaID: DWord;
SecurityID: DWord;
QuotaCharge: Int64;
USN: Int64;
end;
function Int64TimeToDateTime(aFileTime: Int64): TDateTime;
implementation
//=====================================================================================================//
// Converts WinFile_Time into UTC_Time
//-----------------------------------------------------------------------------------------------------//
function Int64TimeToDateTime(aFileTime: Int64): TDateTime;
var
UTCTime, LocalTime: TSystemTime;
begin
FileTimeToSystemTime( TFileTime(aFileTime), UTCTime);
SystemTimeToTzSpecificLocalTime(nil, UTCTime, LocalTime);
result := SystemTimeToDateTime(LocalTime);
end;
end.
|
unit frmPKCS11NewSecretKey;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,
pkcs11_session,
PKCS11Lib, SDUForms;
type
TfrmPKCS11NewSecretKey = class(TSDUForm)
pbCancel: TButton;
pbOK: TButton;
cbKeyType: TComboBox;
Label1: TLabel;
edLabel: TEdit;
Label2: TLabel;
Label3: TLabel;
procedure pbOKClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure edLabelChange(Sender: TObject);
procedure cbKeyTypeChange(Sender: TObject);
private
{ Private declarations }
protected
FPKCS11Session: TPKCS11Session;
function CreateNewKey(): boolean;
function GetKeyType(): TPKCS11SecretKeyType;
public
ExistingKeys: TStringList;
property PKCS11Session: TPKCS11Session read FPKCS11Session write FPKCS11Session;
procedure PopulateKeyTypes();
procedure DefaultKeyType();
procedure EnableDisableControls();
end;
implementation
{$R *.dfm}
uses
SDUi18n,
SDUGeneral,
lcDialogs;
// Populate list of key types with all those available on the token
procedure TfrmPKCS11NewSecretKey.PopulateKeyTypes();
var
i: integer;
secretKeyTypes: TPKCS11SecretKeyTypeArr;
errMsg: string;
begin
cbKeyType.Items.clear();
if not(GetAllPKCS11SecretKeyTypes(
PKCS11Session,
secretKeyTypes,
errMsg
)) then
begin
SDUMessageDlg(_('Unable to get list of key types for Token')+SDUCRLF+SDUCRLF+errMsg, mtError);
end
else
begin
for i:=low(secretKeyTypes) to high(secretKeyTypes) do
begin
cbKeyType.items.add(PKCS11_SECRET_KEY_TYPES[secretKeyTypes[i]].Name);
end;
end;
end;
procedure TfrmPKCS11NewSecretKey.DefaultKeyType();
var
i: integer;
begin
// None selected
cbKeyType.itemindex := -1;
if (cbKeyType.items.count = 1) then
begin
cbKeyType.itemindex := 0;
end
else
begin
for i:=0 to (cbKeyType.items.count - 1) do
begin
if (cbKeyType.items[i] = PKCS11_DEFAULT_KEYTYPE) then
begin
cbKeyType.itemindex := i;
break;
end;
end;
end;
end;
procedure TfrmPKCS11NewSecretKey.edLabelChange(Sender: TObject);
begin
EnableDisableControls();
end;
procedure TfrmPKCS11NewSecretKey.FormClose(Sender: TObject; var Action: TCloseAction);
begin
ExistingKeys.Free();
end;
procedure TfrmPKCS11NewSecretKey.FormCreate(Sender: TObject);
begin
ExistingKeys := TStringList.Create();
end;
procedure TfrmPKCS11NewSecretKey.FormShow(Sender: TObject);
begin
edLabel.text := '';
PopulateKeyTypes();
DefaultKeyType();
EnableDisableControls();
end;
procedure TfrmPKCS11NewSecretKey.cbKeyTypeChange(Sender: TObject);
begin
EnableDisableControls();
end;
function TfrmPKCS11NewSecretKey.CreateNewKey(): boolean;
var
retval: boolean;
errMsg: string;
newKeyLabel: string;
csrPrev: TCursor;
begin
newKeyLabel := trim(edLabel.text);
if (ExistingKeys.Indexof(newKeyLabel) >= 0) then
begin
SDUMessageDlg(
_('A key with the name specified already exists.')+SDUCRLF+
SDUCRLF+
_('Please enter a unique key name'),
mtError);
retval := FALSE;
end
else
begin
csrPrev := screen.Cursor;
screen.Cursor := crHourglass;
try
retval := CreatePKCS11SecretKey(
PKCS11Session,
newKeyLabel,
GetKeyType(),
errMsg
);
finally
screen.Cursor := csrPrev;
end;
if not(retval) then
begin
SDUMessageDlg(_('Unable to create new key')+SDUCRLF+SDUCRLF+errMsg, mtError);
end
else
begin
SDUMessageDlg(SDUParamSubstitute(_('Key "%1" created'), [edLabel.text]), mtInformation);
end;
end;
Result := retval;
end;
procedure TfrmPKCS11NewSecretKey.pbOKClick(Sender: TObject);
begin
if CreateNewKey() then
begin
ModalResult := mrOK;
end;
end;
procedure TfrmPKCS11NewSecretKey.EnableDisableControls();
begin
SDUEnableControl(pbOK, (
(cbKeyType.itemindex >= 0) and
(edLabel.text <> '')
));
SDUEnableControl(cbKeyType, (cbKeyType.items.count > 1));
end;
function TfrmPKCS11NewSecretKey.GetKeyType(): TPKCS11SecretKeyType;
var
retval: TPKCS11SecretKeyType;
i: TPKCS11SecretKeyType;
begin
retval := low(PKCS11_SECRET_KEY_TYPES);
for i:=low(PKCS11_SECRET_KEY_TYPES) to high(PKCS11_SECRET_KEY_TYPES) do
begin
if (PKCS11_SECRET_KEY_TYPES[i].Name = cbKeyType.Items[cbKeyType.itemindex]) then
begin
retval := i;
break;
end;
end;
Result := retval;
end;
END.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Label1: TLabel;
edSerialNumber: TMemo;
edInfo: TMemo;
btTry: TButton;
btClose: TButton;
edHWID: TEdit;
Label2: TLabel;
procedure btCloseClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure edSerialNumberChange(Sender: TObject);
procedure btTryClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses VMProtectSDK;
procedure TForm1.btCloseClick(Sender: TObject);
begin
Close;
end;
procedure TForm1.FormCreate(Sender: TObject);
var buf: array [0..127] of AnsiChar;
begin
FillChar(buf, 0, sizeof(buf));
VMProtectGetCurrentHWID(buf, sizeof(buf));
edHWID.Text := buf;
end;
procedure TForm1.edSerialNumberChange(Sender: TObject);
const
BoolToStr: array [Boolean] of String = ('FALSE', 'TRUE');
var nState, nState2: Integer;
sd: TVMProtectSerialNumberData;
res: Boolean;
begin
edInfo.Lines.BeginUpdate;
// set the serial number
nState := VMProtectSetSerialNumber(PAnsiChar(AnsiString(edSerialNumber.Text)));
// parse serial number state
edInfo.Lines.Clear;
edInfo.Lines.Add(Format('VMProtectSetSerialNumber() returned: 0x%.8X', [nState]));
if nState and SERIAL_STATE_FLAG_CORRUPTED <> 0 then
edInfo.Lines.Add(#9'SERIAL_STATE_FLAG_CORRUPTED');
if nState and SERIAL_STATE_FLAG_INVALID <> 0 then
edInfo.Lines.Add(#9'SERIAL_STATE_FLAG_INVALID');
if nState and SERIAL_STATE_FLAG_BLACKLISTED <> 0 then
edInfo.Lines.Add(#9'SERIAL_STATE_FLAG_BLACKLISTED');
if nState and SERIAL_STATE_FLAG_DATE_EXPIRED <> 0 then
edInfo.Lines.Add(#9'SERIAL_STATE_FLAG_DATE_EXPIRED');
if nState and SERIAL_STATE_FLAG_RUNNING_TIME_OVER <> 0 then
edInfo.Lines.Add(#9'SERIAL_STATE_FLAG_RUNNING_TIME_OVER');
if nState and SERIAL_STATE_FLAG_BAD_HWID <> 0 then
edInfo.Lines.Add(#9'SERIAL_STATE_FLAG_BAD_HWID');
if nState and SERIAL_STATE_FLAG_MAX_BUILD_EXPIRED <> 0 then
edInfo.Lines.Add(#9'SERIAL_STATE_FLAG_MAX_BUILD_EXPIRED');
// another way to get a state
nState2 := VMProtectGetSerialNumberState();
edInfo.Lines.Add(Format(#13#10'VMProtectGetSerialNumberState() returned: 0x%.8X',[nState2]));
// try to read serial number data
FillChar(sd, 0, SizeOf(sd));
res := VMProtectGetSerialNumberData(@sd, sizeof(sd));
edInfo.Lines.Add(Format(#13#10'VMProtectGetSerialNumberData() returned: %s',[BoolToStr[res]]));
if res then
begin
edInfo.Lines.Add(Format('State = 0x%.8X', [sd.nState]));
edInfo.Lines.Add(Format('User Name = %s', [sd.wUserName]));
edInfo.Lines.Add(Format('E-Mail = %s', [sd.wEMail]));
edInfo.Lines.Add(Format('Date of expiration = %.4d-%.2d-%.2d', [sd.dtExpire.wYear, sd.dtExpire.bMonth, sd.dtExpire.bDay]));
edInfo.Lines.Add(Format('Max date of build = %.4d-%.2d-%.2d', [sd.dtMaxBuild.wYear, sd.dtMaxBuild.bMonth, sd.dtMaxBuild.bDay]));
edInfo.Lines.Add(Format('Running time limit = %d minutes', [sd.bRunningTime]));
edInfo.Lines.Add(Format('Length of user data = %d bytes', [sd.nUserDataLength]));
end;
edInfo.Lines.EndUpdate;
end;
procedure TForm1.btTryClick(Sender: TObject);
begin
Application.MessageBox('Protected code succesfully executed', PChar(ExtractFileName(Application.ExeName)), MB_OK or MB_ICONINFORMATION);
end;
end.
|
unit LangString;
interface
uses SysUtils, INIFiles;
{ var
_FILELANGUAGE_: String = 'English';
(* DIALOG *)
_OK_: String = 'Ok';
_YES_: String = 'Yes';
_NO_: String = 'No';
_APPLY_: String = 'Apply';
_CANCEL_: String = 'Cancel';
_ALL_: String = 'All';
_EXIT_: String = 'Exit';
_PREVIOUSSTEP_: String = 'Previous step';
_NEXTSTEP_: String = 'Next step';
_FINISH_: String = 'Finish';
(* ERRORS *)
_ERROR_LOGIN_: String = 'Login error for %s';
_ERROR_OCCURED_: String = 'Error occured: %s';
_NO_DIRECTORY_: String = 'Directory ''%s'' not exists';
_NO_FILE_: String = 'File ''%s'' not found';
_FILE_READ_ERROR_: String = 'Error reading file: %s';
_NO_FIELD_: String = 'Field "%s" not found';
_SYMBOL_MISSED_: String = 'Can''t found symbol "%s" for #%d "%s" in "%s"';
_OPERATOR_MISSED_: String = 'Must be an operator instead of #%d "%s" in "%s"';
_OPERAND_MISSED_: String = 'Must be an oparand instead of #%d "%s" in "%s"';
_INVALID_TYPECAST_: String = 'Invalid typecast for "%s" %s "%s" near #%d in "%s"';
_INCORRECT_SYMBOL_: String = 'Incorrect value "%s" near #%d in "%s"';
_TAB_IS_BUSY_: String = 'Tab is busy. You need to stop the work first';
_SCRIPT_READ_ERROR_: String = 'Error reading script: %s';
_SYMBOLS_IN_SECTOR_NAME_: String = 'Incorrect symbol in sector name';
_INCORRECT_DECLORATION_: String = 'Incorrect decloration near symbol %s';
_INCORRECT_FILESIZE_: String = 'Incorrect file size';
_NOUPDATES_ : String = 'Nothing to update';
_NEWUPDATES_: String = 'New updates is avalable. Do you want to download it?';
_UPDATEERROR_: String = 'Error on cheking updates';
_UNKNOWNMETHOD_: String = 'Unknown method: %s';
_BUSY_MAIN_LIST_: String = 'List is busy. You need to finish another new or editing list';
(* OTHER *)
_NEWLIST_: String = 'New list';
_LOADLIST_: String = 'Load list';
_SAVELIST_: String = 'Save list';
_MAINCONFIG_: String = 'Main configuration';
_EDITIONALCONFIG_: String ='Editionals';
_TAGSTRING_: String = 'Tag';
_INHERIT_: String = 'Inherit configuration';
_SETTINGS_: String = 'Settings';
_GENERAL_: String = 'General';
_RESNAME_: String = 'Resource';
_RESID_: String = '#';
_PICTURELABEL_: String = 'Label';
_COLUMNS_: String = 'Columns';
_FILTER_: String = 'Filter';
_ON_AIR_: String = 'ON AIR';
_WORK_: String = 'Work';
_THREAD_COUNT_: String = 'Threads count';
_USE_PER_RES_: String = 'Threads per resource';
_PER_RES_: String = 'Threads per resource';
_PIC_THREADS_: String = 'Picitures threads';
_RETRIES_: String = 'Retries count';
_DEBUGMODE_: String = 'Debug';
_PROXY_: String = 'Proxy';
_USE_PROXY_: String = 'Use proxy';
_AUTHORISATION_: String = 'Authorisation';
_SAVE_PASSWORD_: String = 'Save password';
_LOG_: String = 'Log';
_ERRORS_: String = 'Errors';
_STARTLIST_: String = 'Start getting list';
_STOPLIST_: String = 'Stop getting list';
_STARTPICS_: String = 'Start download pictures';
_STOPPICS_: String = 'Stop download pictures';
_NEWTABCAPTION_: String = 'New';
_COUNT_: String = 'Count';
_NAMEFORMAT_: String = 'Save file format';
_SAVEPATH_: String = 'save path';
_FILENAME_: String = 'File name';
_EXTENSION_: String = 'Extension';
_INFO_: String = 'Pic info';
_TAGS_: String = 'Tags';
_DOUBLES_: String = 'Doubles';
_UPDATING_: String = 'Updating';
_DOWNLOADED_: String = 'Downloaded';
_SIZE_: String = 'Size';
_PROGRESS_: String = 'Progress';
_COMMON_: String = 'Common';
_HOST_: String = 'Server';
_PORT_: String = 'Port';
_LOGIN_: String = 'Login';
_LOGINON_: String = 'Login on %s';
_PASSWORD_: String = 'Password';
_LANGUAGE_: String = 'Language';
_RESOURCES_: String = 'Resources';
_INTERFACE_: String = 'Interface';
_THREADS_: String = 'Threads';
_AUTOUPDATE_: String = 'autoupdate after application starts';
_UPDATENOW_: String = 'Check updates now'; }
// procedure LoadLang(FileName: String);
var
LangINI: TINIFile = nil;
procedure CreateLangINI(filename: string);
function lang(SName: String; cat: string = 'lang'): String;
implementation
procedure CreateLangINI(filename: string);
begin
if Assigned(LangINI) then
LangINI.Free;
LangINI := TINIFile.Create(filename);
end;
function lang(SName: String; cat: string = 'lang'): String;
begin
Result := LangINI.ReadString(cat, SName, SName);
end;
{ procedure LoadLang(FileName: String);
var
INI: TINIFile;
begin
if not FileExists(FileName) then
Exit;
INI := TINIFile.Create(FileName);
_FILELANGUAGE_ := INI.ReadString('lang','_FILELANGUAGE_',_FILELANGUAGE_);
(* DIALOG *)
_OK_ := INI.ReadString('lang','_OK_',_OK_);
_YES_ := INI.ReadString('lang','_YES_',_YES_);
_NO_ := INI.ReadString('lang','_NO_',_NO_);
_APPLY_ := INI.ReadString('lang','_APPLY_',_APPLY_);
_CANCEL_ := INI.ReadString('lang','_CANCEL_',_CANCEL_);
_ALL_ := INI.ReadString('lang','_ALL_',_ALL_);
_EXIT_ := INI.ReadString('lang','_EXIT_',_EXIT_);
_PREVIOUSSTEP_ := INI.ReadString('lang','_PREVIOUSSTEP_',_PREVIOUSSTEP_);
_NEXTSTEP_ := INI.ReadString('lang','_NEXTSTEP_',_NEXTSTEP_);
_FINISH_ := INI.ReadString('lang','_FINISH_',_FINISH_);
(* ERRORS *)
_ERROR_OCCURED_ := INI.ReadString('lang','_ERROR_OCCURED_',_ERROR_OCCURED_);
_NO_DIRECTORY_ := INI.ReadString('lang','_NO_DIRECTORY_',_NO_DIRECTORY_);
_NO_FILE_ := INI.ReadString('lang','_NO_FILE_',_NO_FILE_);
_FILE_READ_ERROR_ := INI.ReadString('lang','_FILE_READ_ERROR_',_FILE_READ_ERROR_);
_NO_FIELD_ := INI.ReadString('lang','_NO_FIELD_',_NO_FIELD_);
_SYMBOL_MISSED_ := INI.ReadString('lang','_SYMBOL_MISSED_',_SYMBOL_MISSED_);
_OPERATOR_MISSED_ := INI.ReadString('lang','_OPERATOR_MISSED_',_OPERATOR_MISSED_);
_OPERAND_MISSED_ := INI.ReadString('lang','_OPERAND_MISSED_',_OPERAND_MISSED_);
_INVALID_TYPECAST_ := INI.ReadString('lang','_INVALID_TYPECAST_',_INVALID_TYPECAST_);
_INCORRECT_SYMBOL_ := INI.ReadString('lang','_INCORRECT_SYMBOL_',_INCORRECT_SYMBOL_);
_TAB_IS_BUSY_ := INI.ReadString('lang','_TAB_IS_BUSY_',_TAB_IS_BUSY_);
_SCRIPT_READ_ERROR_ := INI.ReadString('lang','_SCRIPT_READ_ERROR_',_SCRIPT_READ_ERROR_);
_SYMBOLS_IN_SECTOR_NAME_ := INI.ReadString('lang','_SYMBOLS_IN_SECTOR_NAME_',_SYMBOLS_IN_SECTOR_NAME_);
_INCORRECT_DECLORATION_ := INI.ReadString('lang','_INCORRECT_DECLORATION_',_INCORRECT_DECLORATION_);
_UNKNOWNMETHOD_ := INI.ReadString('lang','_UNKNOWNMETHOD_',_UNKNOWNMETHOD_);
_BUSY_MAIN_LIST_ := INI.ReadString('lang','_BUSY_MAIN_LIST_',_BUSY_MAIN_LIST_);
(* OTHER *)
_NEWLIST_ := INI.ReadString('lang','_NEWLIST_',_NEWLIST_);
_LOADLIST_ := INI.ReadString('lang','_LOADLIST_',_LOADLIST_);
_SAVELIST_ := INI.ReadString('lang','_SAVELIST_',_SAVELIST_);
_MAINCONFIG_ := INI.ReadString('lang','_MAINCONFIG_',_MAINCONFIG_);
_EDITIONALCONFIG_ := INI.ReadString('lang','_EDITIONALCONFIG_',_EDITIONALCONFIG_);
_TAGSTRING_ := INI.ReadString('lang','_TAGSTRING_',_TAGSTRING_);
_INHERIT_ := INI.ReadString('lang','_INHERIT_',_INHERIT_);
_SETTINGS_ := INI.ReadString('lang','_SETTINGS_',_SETTINGS_);
_GENERAL_ := INI.ReadString('lang','_GENERAL_',_GENERAL_);
_RESNAME_ := INI.ReadString('lang','_RESNAME_',_RESNAME_);
_RESID_ := INI.ReadString('lang','_RESID_',_RESID_);
_PICTURELABEL_ := INI.ReadString('lang','_PICTURELABEL_',_PICTURELABEL_);
_COLUMNS_ := INI.ReadString('lang','_COLUMNS_',_COLUMNS_);
_FILTER_ := INI.ReadString('lang','_FILTER_',_FILTER_);
_ON_AIR_ := INI.ReadString('lang','_ON_AIR_',_ON_AIR_);
_WORK_ := INI.ReadString('lang','_WORK_',_WORK_);
_THREAD_COUNT_ := INI.ReadString('lang','_THREAD_COUNT_',_THREAD_COUNT_);
_USE_PER_RES_ := INI.ReadString('lang','_USE_PER_RES_',_USE_PER_RES_);
_PER_RES_ := INI.ReadString('lang','_PER_RES_',_PER_RES_);
_PIC_THREADS_ := INI.ReadString('lang','_PIC_THREADS_',_PIC_THREADS_);
_RETRIES_ := INI.ReadString('lang','_RETRIES_',_RETRIES_);
_DEBUGMODE_ := INI.ReadString('lang','_DEBUGMODE_',_DEBUGMODE_);
_PROXY_ := INI.ReadString('lang','_PROXY_',_PROXY_);
_USE_PROXY_ := INI.ReadString('lang','_USE_PROXY_',_USE_PROXY_);
_AUTHORISATION_ := INI.ReadString('lang','_AUTHORISATION_',_AUTHORISATION_);
_SAVE_PASSWORD_ := INI.ReadString('lang','_SAVE_PASSWORD_',_SAVE_PASSWORD_);
_LOG_ := INI.ReadString('lang','_LOG_',_LOG_);
_ERRORS_ := INI.ReadString('lang','_ERRORS_',_ERRORS_);
_STARTLIST_ := INI.ReadString('lang','_STARTLIST_',_STARTLIST_);
_STOPLIST_ := INI.ReadString('lang','_STOPLIST_',_STOPLIST_);
_STARTPICS_ := INI.ReadString('lang','_STARTPICS_',_STARTPICS_);
_STOPPICS_ := INI.ReadString('lang','_STOPPICS_',_STOPPICS_);
_NEWTABCAPTION_ := INI.ReadString('lang','_NEWTABCAPTION_',_NEWTABCAPTION_);
_COUNT_ := INI.ReadString('lang','_COUNT_',_COUNT_);
_NAMEFORMAT_ := INI.ReadString('lang','_NAMEFORMAT_',_NAMEFORMAT_);
_SAVEPATH_ := INI.ReadString('lang','_SAVEPATH_',_SAVEPATH_);
_FILENAME_ := INI.ReadString('lang','_FILENAME_',_FILENAME_);
_EXTENSION_ := INI.ReadString('lang','_EXTENSION_',_EXTENSION_);
_INFO_ := INI.ReadString('lang','_INFO_',_INFO_);
_TAGS_ := INI.ReadString('lang','_TAGS_',_TAGS_);
_DOUBLES_ := INI.ReadString('lang','_DOUBLES_',_DOUBLES_);
_UPDATING_ := INI.ReadString('lang','_UPDATING_',_UPDATING_);
_NEWUPDATES_ := INI.ReadString('lang','_NEWUPDATES_',_NEWUPDATES_);
_DOWNLOADED_ := INI.ReadString('lang','_DOWNLOADED_',_DOWNLOADED_);
_SIZE_ := INI.ReadString('lang','_SIZE_',_SIZE_);
_PROGRESS_ := INI.ReadString('lang','_PROGRESS_',_PROGRESS_);
_COMMON_ := INI.ReadString('lang','_COMMON_',_COMMON_);
_HOST_ := INI.ReadString('lang','_HOST_',_HOST_);
_PORT_ := INI.ReadString('lang','_PORT_',_PORT_);
_LOGIN_ := INI.ReadString('lang','_LOGIN_',_LOGIN_);
_PASSWORD_ := INI.ReadString('lang','_PASSWORD_',_PASSWORD_);
_LANGUAGE_ := INI.ReadString('lang','_LANGUAGE_',_LANGUAGE_);
_THREADS_ := INI.ReadString('lang','_THREADS_',_THREADS_);
_INTERFACE_ := INI.ReadString('lang','_INTERFACE_',_INTERFACE_);
_RESOURCES_ := INI.ReadString('lang','_RESOURCES_',_RESOURCES_);
_AUTOUPDATE_ := INI.ReadString('lang','_AUTOUPDATE_',_AUTOUPDATE_);
_UPDATENOW_ := INI.ReadString('lang','_AUTOUPDATE_',_AUTOUPDATE_);
INI.Free;
end; }
initialization
finalization
if Assigned(LangINI) then
LangINI.Free;
end.
|
unit uActivation;
interface
uses
System.SysUtils,
System.Classes,
Winapi.Windows,
Winapi.Messages,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Vcl.Imaging.jpeg,
Vcl.Imaging.pngimage,
Dmitry.Controls.Base,
Dmitry.Controls.LoadingSign,
uRuntime,
uDBForm,
uMemory,
uWizards,
uResources,
uThemesUtils,
uVCLHelpers,
uFormInterfaces;
type
TActivateForm = class(TDBForm, IActivationForm)
Bevel1: TBevel;
BtnNext: TButton;
BtnCancel: TButton;
BtnFinish: TButton;
BtnPrevious: TButton;
ImActivationImage: TImage;
LbInfo: TLabel;
LsLoading: TLoadingSign;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure Execute;
procedure Button1Click(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure BtnCancelClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure BtnFinishClick(Sender: TObject);
procedure BtnNextClick(Sender: TObject);
procedure BtnPreviousClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
{ Private declarations }
FWizard: TWizardManager;
procedure LoadLanguage;
procedure UpdateLayout;
procedure StepChanged(Sender: TObject);
procedure WMMouseDown(var Message: TMessage); message WM_LBUTTONDOWN;
protected
function GetFormID: string; override;
public
{ Public declarations }
end;
implementation
uses
FormManegerUnit,
uFrameActivationLanding;
var
IsActivationActive: Boolean = False;
{$R *.dfm}
procedure TActivateForm.FormCreate(Sender: TObject);
var
Activation: TPngImage;
begin
LoadLanguage;
FWizard := TWizardManager.Create(Self);
FWizard.OnChange := StepChanged;
FWizard.AddStep(TFrameActivationLanding);
FWizard.Start(Self, ImActivationImage.Left + ImActivationImage.Width + 5, 8);
LsLoading.Color := Theme.WizardColor;
Activation := GetActivationImage;
try
ImActivationImage.Picture.Graphic := Activation;
finally
F(Activation);
end;
UpdateLayout;
end;
procedure TActivateForm.FormDestroy(Sender: TObject);
begin
F(FWizard);
end;
procedure TActivateForm.Execute;
begin
if IsActivationActive then
Exit;
IsActivationActive := True;
try
ShowModal;
finally
IsActivationActive := False;
end;
end;
procedure TActivateForm.BtnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TActivateForm.BtnFinishClick(Sender: TObject);
begin
FWizard.Execute;
end;
procedure TActivateForm.BtnNextClick(Sender: TObject);
begin
if FWizard.CanGoNext then
FWizard.NextStep;
end;
procedure TActivateForm.BtnPreviousClick(Sender: TObject);
begin
if FWizard.CanGoBack then
FWizard.PrevStep;
end;
procedure TActivateForm.Button1Click(Sender: TObject);
begin
Close;
end;
procedure TActivateForm.WMMouseDown(var Message: TMessage);
begin
Perform(WM_NCLBUTTONDOWN, HTCaption, Message.lparam);
end;
procedure TActivateForm.LoadLanguage;
begin
BeginTranslate;
try
Caption := L('Activation');
LbInfo.Caption := L('This wizard helps you to activate this copy of application. Please fill all required fields and follow the instructions.');
BtnCancel.Caption := L('Close');
BtnPrevious.Caption := L('Previous');
BtnNext.Caption := L('Next');
BtnFinish.Caption := L('Finish');
finally
EndTranslate;
end;
end;
procedure TActivateForm.StepChanged(Sender: TObject);
begin
LsLoading.Visible := FWizard.IsBusy;
BtnCancel.SetEnabledEx(not FWizard.IsBusy);
BtnNext.SetEnabledEx(FWizard.CanGoNext and not FWizard.IsBusy);
BtnPrevious.SetEnabledEx(FWizard.CanGoBack);
BtnFinish.SetEnabledEx(FWizard.IsFinalStep and not FWizard.IsBusy);
BtnFinish.Visible := FWizard.IsFinalStep;
BtnNext.Visible := not FWizard.IsFinalStep;
if FWizard.WizardDone then
Close;
end;
procedure TActivateForm.UpdateLayout;
var
CW: Integer;
begin
CW := ClientWidth;
BtnFinish.Left := CW - BtnFinish.Width - 5;
BtnNext.Left := CW - BtnFinish.Width - 5;
BtnPrevious.Left := BtnFinish.Left - BtnPrevious.Width - 5;
BtnCancel.Left := BtnPrevious.Left - BtnCancel.Width - 5;
Bevel1.Width := ClientWidth - 10;
end;
procedure TActivateForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
UnRegisterMainForm(Self);
Action := caFree;
end;
procedure TActivateForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := not FWizard.IsBusy;
end;
procedure TActivateForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then
Close;
end;
function TActivateForm.GetFormID: string;
begin
Result := 'Activation';
end;
initialization
FormInterfaces.RegisterFormInterface(IActivationForm, TActivateForm);
end.
|
unit frmSelectVolumeAndOffset;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, Spin64,
OTFEFreeOTFE_U,
OTFEFreeOTFEBase_U,
SDUForms, SDUFrames, SDUSpin64Units, SDUDialogs,
fmeVolumeSelect;
type
TfrmSelectVolumeFileAndOffset = class(TSDUForm)
lblFileDescSrc: TLabel;
lblOffsetSrc: TLabel;
pbOK: TButton;
pbCancel: TButton;
lblInstructions: TLabel;
se64UnitOffset: TSDUSpin64Unit_Storage;
OTFEFreeOTFEVolumeSelect1: TfmeVolumeSelect;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure OTFEFreeOTFEVolumeSelect1Change(Sender: TObject);
protected
procedure EnableDisableControls();
public
// OTFEFreeOTFE: TOTFEFreeOTFEBase;
procedure SetDlgPurpose(encryptNotDecrypt: boolean);
function Volume(): string;
function Offset(): int64;
end;
implementation
{$R *.dfm}
uses
SDUi18n,
SDUGeneral;
procedure TfrmSelectVolumeFileAndOffset.SetDlgPurpose(encryptNotDecrypt: boolean);
begin
if encryptNotDecrypt then
begin
self.Caption := _('Secure with PKCS#11 Secret Key');
lblInstructions.caption := _('Please enter the container/keyfile you wish to encrypt using the selected PKCS#11 secret key.');
end
else
begin
self.Caption := _('Remove PKCS#11 Secret Key Security');
lblInstructions.caption := _('Please enter the container/keyfile you wish to decrypt using the selected PKCS#11 secret key.');
end;
end;
function TfrmSelectVolumeFileAndOffset.Volume(): string;
begin
Result := OTFEFreeOTFEVolumeSelect1.Filename;
end;
function TfrmSelectVolumeFileAndOffset.Offset(): int64;
begin
Result := se64UnitOffset.Value;
end;
procedure TfrmSelectVolumeFileAndOffset.OTFEFreeOTFEVolumeSelect1Change(
Sender: TObject);
begin
EnableDisableControls();
end;
procedure TfrmSelectVolumeFileAndOffset.FormCreate(Sender: TObject);
begin
// Note: This must be in the FormCreate(...) event, and not FormShow(...)
// since the width must be set *before* the caption is in order for the
// label's autosize to work correctly, and not adjust the label so that it's
// height is to great as to obscure the "Container/keyfile" label below it
lblInstructions.Width := (Self.Width - (lblInstructions.left * 2));
OTFEFreeOTFEVolumeSelect1.OnChange := OTFEFreeOTFEVolumeSelect1Change;
OTFEFreeOTFEVolumeSelect1.SelectFor := fndOpen;
OTFEFreeOTFEVolumeSelect1.AllowPartitionSelect := True;
end;
procedure TfrmSelectVolumeFileAndOffset.FormShow(Sender: TObject);
begin
OTFEFreeOTFEVolumeSelect1.Filename := '';
// OTFEFreeOTFEVolumeSelect1.OTFEFreeOTFE := OTFEFreeOTFE;
OTFEFreeOTFEVolumeSelect1.SelectFor := fndOpen;
OTFEFreeOTFEVolumeSelect1.FileSelectFilter := FILE_FILTER_FLT_VOLUMESANDKEYFILES;
OTFEFreeOTFEVolumeSelect1.FileSelectDefaultExt := FILE_FILTER_DFLT_VOLUMESANDKEYFILES;
se64UnitOffset.Value := 0;
EnableDisableControls();
end;
procedure TfrmSelectVolumeFileAndOffset.EnableDisableControls();
begin
SDUEnableControl(pbOK, (trim(OTFEFreeOTFEVolumeSelect1.Filename) <> ''));
end;
END.
|
unit UDExportSepVal;
interface
uses
Windows, Forms, StdCtrls, Buttons, Controls, Classes, ExtCtrls,
UCrpe32;
type
TCrpeSepValDlg = class(TForm)
pnlSepVal: TPanel;
editStringDelimiter: TEdit;
editFieldSeparator: TEdit;
lblStringDelimiter: TLabel;
lblFieldSeparator: TLabel;
sb1: TSpeedButton;
sb2: TSpeedButton;
sb4: TSpeedButton;
sb3: TSpeedButton;
sb5: TSpeedButton;
sb13: TSpeedButton;
sb6: TSpeedButton;
sb14: TSpeedButton;
sb15: TSpeedButton;
sb16: TSpeedButton;
sb17: TSpeedButton;
sb7: TSpeedButton;
sb8: TSpeedButton;
sb9: TSpeedButton;
sb10: TSpeedButton;
sb11: TSpeedButton;
sb12: TSpeedButton;
sb18: TSpeedButton;
sb19: TSpeedButton;
sb20: TSpeedButton;
sb22: TSpeedButton;
sb23: TSpeedButton;
sb21: TSpeedButton;
sb24: TSpeedButton;
btnOk: TButton;
btnCancel: TButton;
sbTab: TSpeedButton;
sbComma: TSpeedButton;
cbUseRptNumberFmt: TCheckBox;
cbUseRptDateFmt: TCheckBox;
procedure BtnCharClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnOKClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure editStringDelimiterKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure sb1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormCreate(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure sbTabClick(Sender: TObject);
procedure sbCommaClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
end;
var
CrpeSepValDlg: TCrpeSepValDlg;
implementation
{$R *.DFM}
uses UDExportOptions, UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSepValDlg.FormCreate(Sender: TObject);
begin
LoadFormPos(Self);
end;
{------------------------------------------------------------------------------}
{ FormShow procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSepValDlg.FormShow(Sender: TObject);
begin
editStringDelimiter.Text := Cr.ExportOptions.Text.StringDelimiter;
editFieldSeparator.Text := Cr.ExportOptions.Text.FieldSeparator;
cbUseRptNumberFmt.Checked := Cr.ExportOptions.Text.UseRptNumberFmt;
cbUseRptDateFmt.Checked := Cr.ExportOptions.Text.UseRptDateFmt;
end;
{------------------------------------------------------------------------------}
{ editStringDelimiterKeyDown procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSepValDlg.editStringDelimiterKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
editStringDelimiter.Text := '';
end;
{------------------------------------------------------------------------------}
{ BtnCharClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSepValDlg.BtnCharClick(Sender: TObject);
begin
if editFieldSeparator.Focused then
editFieldSeparator.SelText := TSpeedButton(Sender).Caption
else
editStringDelimiter.Text := TSpeedButton(Sender).Caption;
end;
{------------------------------------------------------------------------------}
{ sbTabClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSepValDlg.sbTabClick(Sender: TObject);
begin
editFieldSeparator.SelText := Chr(9);
end;
{------------------------------------------------------------------------------}
{ sbCommaClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSepValDlg.sbCommaClick(Sender: TObject);
begin
editFieldSeparator.SelText := ',';
end;
{------------------------------------------------------------------------------}
{ sb1MouseDown procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSepValDlg.sb1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if editStringDelimiter.Focused then
editStringDelimiter.Text := '';
end;
{------------------------------------------------------------------------------}
{ btnOKClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSepValDlg.btnOKClick(Sender: TObject);
begin
SaveFormPos(Self);
if Length(editStringDelimiter.Text) > 0 then
Cr.ExportOptions.Text.StringDelimiter := editStringDelimiter.Text[1]
else
Cr.ExportOptions.Text.StringDelimiter := #0;
Cr.ExportOptions.Text.FieldSeparator := editFieldSeparator.Text;
Cr.ExportOptions.Text.UseRptNumberFmt := cbUseRptNumberFmt.Checked;
Cr.ExportOptions.Text.UseRptDateFmt := cbUseRptDateFmt.Checked;
end;
{------------------------------------------------------------------------------}
{ btnCancelClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSepValDlg.btnCancelClick(Sender: TObject);
begin
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSepValDlg.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Release;
end;
end.
|
{
used code from Bauglir Internet Library as framework to easily upgrade any
TCP Socket class to a WebSocket implementation including streaming deflate that can
maintain current zlib context and state
v0.14, 2021-03-28, set aFinal to false if insufficient data for complete packet
v0.13, 2019-06-06, added aFinal return value to WebSocketReadData()
to allow for better handling of split packets
v0.12, 2017-10-14, fixed minor issues, client_no_context_takeover wasn't set for client,
fncProtocol and fncResourceName weren't properly set
v0.11, 2015-09-01, fixed small issue, ignore deprecated 'x-webkit-deflate-frame' (ios)
v0.10, 2015-07-31, by Alexander Paul Morris
See interface functions for usage details
Requirements: SynAUtil, SynACode (from Synapse), DelphiZlib
References:
http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17
http://tools.ietf.org/html/rfc6455
http://dev.w3.org/html5/websockets/#refsFILEAPI
https://www.igvita.com/2013/11/27/configuring-and-optimizing-websocket-compression/
http://stackoverflow.com/questions/22169036/websocket-permessage-deflate-in-chrome-with-no-context-takeover
}
{==============================================================================|
| Project : Bauglir Internet Library |
|==============================================================================|
| Content: Generic connection and server |
|==============================================================================|
| Copyright (c)2011-2012, Bronislav Klucka |
| All rights reserved. |
| Source code is licenced under original 4-clause BSD licence: |
| http://licence.bauglir.com/bsd4.php |
| |
| |
| Project download homepage: |
| http://code.google.com/p/bauglir-websocket/ |
| Project homepage: |
| http://www.webnt.eu/index.php |
| WebSocket RFC: |
| http://tools.ietf.org/html/rfc6455 |
| |
|==============================================================================|}
unit WebSocketUpgrade;
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$H+}
interface
uses
Classes, SysUtils, ScktComp, SynAUtil, SynACode, ZLibEx, ZLibExApi;
const
{:Constants section defining what kind of data are sent from one pont to another}
{:Continuation frame }
wsCodeContinuation = $0;
{:Text frame }
wsCodeText = $1;
{:Binary frame }
wsCodeBinary = $2;
{:Close frame }
wsCodeClose = $8;
{:Ping frame }
wsCodePing = $9;
{:Frame frame }
wsCodePong = $A;
{:Constants section defining close codes}
{:Normal valid closure, connection purpose was fulfilled}
wsCloseNormal = 1000;
{:Endpoint is going away (like server shutdown) }
wsCloseShutdown = 1001;
{:Protocol error }
wsCloseErrorProtocol = 1002;
{:Unknown frame data type or data type application cannot handle }
wsCloseErrorData = 1003;
{:Reserved }
wsCloseReserved1 = 1004;
{:Close received by peer but without any close code. This close code MUST NOT be sent by application. }
wsCloseNoStatus = 1005;
{:Abnotmal connection shutdown close code. This close code MUST NOT be sent by application. }
wsCloseErrorClose = 1006;
{:Received text data are not valid UTF-8. }
wsCloseErrorUTF8 = 1007;
{:Endpoint is terminating the connection because it has received a message that violates its policy. Generic error. }
wsCloseErrorPolicy = 1008;
{:Too large message received }
wsCloseTooLargeMessage = 1009;
{:Client is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake }
wsCloseClientExtensionError= 1010;
{:Server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request }
wsCloseErrorServerRequest = 1011;
{:Connection was closed due to a failure to perform a TLS handshake. This close code MUST NOT be sent by application. }
wsCloseErrorTLS = 1015;
type
TZlibBuffer = class
published
constructor Create(bufSize: Cardinal = 16384);
Destructor Destroy; override;
public
bufferSize: Cardinal;
readBuffer: Array of Byte;
writeBuffer: Array of Byte;
procedure SetBufferSize(bufSize: Cardinal);
end;
TWebSocketConnection = class
private
published
Constructor Create;
Destructor Destroy; override;
public
isServerConnection: boolean;
isPerMessageDeflate: boolean;
fCookie: AnsiString;
fVersion: integer;
fProtocol: AnsiString;
fResourceName: AnsiString;
fOrigin: AnsiString;
fExtension: AnsiString;
fPort: AnsiString;
fHost: AnsiString;
fHeaders: AnsiString;
fWebSocketHeaders: AnsiString;
fwsKey: AnsiString;
fHandShake: boolean;
fMasking: boolean;
fRequireMasking: boolean;
inCompWindowBits: integer;
outCompWindowBits: integer;
inFZStream: TZStreamRec;
outFZStream: TZStreamRec;
FZBuffer: TZlibBuffer;
inCompNoContext: boolean;
outCompNoContext: boolean;
end;
//creates Server TWebSocketConnection object, with socket.send() headers in fWebSocketHeaders
//to upgrade the socket if client sent a WebSocket HTTP header
//tryDeflate = 0 for false, or zlib windowBits for true (ie. default = 15)
function CreateServerWebSocketConnection(str_headers: AnsiString; tryDeflate: byte = 15): TWebSocketConnection;
//creates Client TWebSocketConnection object, with socket.send() headers in fncWebSocketHeaders
function CreateClientWebSocketConnection(wsUri: AnsiString; tryDeflate: boolean): TWebSocketConnection;
//confirms Client TWebSocketConnection handshake with server
//returns true if succesful, or false upon failure (and also frees wsConn)
function ConfirmClientWebSocketConnection(var wsConn: TWebSocketConnection; str_headers: AnsiString): boolean;
//if websocket, send data packets here to be decoded
function WebSocketReadData(var aData: AnsiString; const wsConn: TWebSocketConnection; var aCode: integer; var aFinal: boolean): AnsiString;
//if websocket, send text to this method to send encoded packet
//masking should only be used if socket is a ClientSocket and not a ServerSocket
function WebSocketSendData(aData: AnsiString; const wsConn: TWebSocketConnection; aCode: integer = 1{wsCodeText}; tryDeflate: boolean = true): AnsiString;
//streaming zlib inflate/deflate functions
//uses ZLibEx, ZLibExApi - windowBits = -1..-15 for raw deflate, or 31 for gzip
//create a buffer from stream (same can be used for compress and decompress): FZBuffer := TZlibBuffer.Create;
//create Compress Stream: ZCompressCheck(ZDeflateInit2(outFZStream, zcLevel8, -15, 9, zsDefault));
//compress: compText = ZlibStreamCompressString(outFZStream,messageText,FZBuffer);
//free Compress Stream and Buffer: try ZCompressCheck(ZDeflateEnd(outFZStream)); except end; FZBuffer.Free;
//reset Compress Stream: ZCompressCheck(ZDeflateReset(outFZStream));
function ZlibStreamCompressString(var outFZStream: TZStreamRec; const aText: AnsiString; const zBuf: TZlibBuffer): AnsiString;
//uses ZLibEx, ZLibExApi - windowBits = -1..-15 for raw deflate, or 31 for gzip
//create a buffer from stream (same can be used for compress and decompress): FZBuffer := TZlibBuffer.Create;
//create Decompress Stream: ZDecompressCheck(ZInflateInit2(inFZStream, -15));
//decompress: decompText = ZlibStreamDecompressString(inFZStream,compressedText,FZBuffer);
//free Decompress Stream and Buffer: try ZDecompressCheck(ZInflateEnd(inFZStream)); except end; FZBuffer.Free;
//reset Decompress Stream: ZDecompressCheck(ZInflateReset(inFZStream));
function ZlibStreamDecompressString(var inFZStream: TZStreamRec; const aText: AnsiString; const zBuf: TZlibBuffer; aTextPos: Cardinal = 0): AnsiString;
//zlib single-use (no context) inflate/deflate functions
function ZlibCompressString(const aText: AnsiString; const aCompressionLevel: TZCompressionLevel; const windowBits: integer; const memLevel: integer; const strategy: TZStrategy): AnsiString;
function ZlibDecompressString(const aText: AnsiString; const windowBits: integer): AnsiString;
//zlib helper functions exported
function ZCompressCheck(code: Integer): Integer;
function ZDecompressCheck(code: Integer; raiseBufferError: Boolean = True): Integer;
implementation
uses Math, Windows;
{$IFDEF Win32} {$O-} {$ENDIF Win32}
function ZCompressCheck(code: Integer): Integer;
begin
result := code;
if code < 0 then
begin
raise EZCompressionError.Create(code);
end;
end;
function ZDecompressCheck(code: Integer; raiseBufferError: Boolean = True): Integer;
begin
Result := code;
if code < 0 then
begin
if (code <> Z_BUF_ERROR) or raiseBufferError then
begin
raise EZDecompressionError.Create(code);
end;
end;
end;
constructor TWebSocketConnection.Create;
begin
fCookie := '';
fVersion := 0;
fProtocol := '-';
fResourceName := '';
fOrigin := '';
fExtension := '-';
fPort := '';
fHost := '';
fHeaders := '';
fWebSocketHeaders := '';
fMasking := false;
fRequireMasking := false;
isPerMessageDeflate := false;
inCompWindowBits := 0;
outCompWindowBits := 0;
inCompNoContext := False;
outCompNoContext := False;
FillChar(inFZStream,SizeOf(inFZStream),0);
FillChar(outFZStream,SizeOf(outFZStream),0);
FZBuffer := nil;
end;
destructor TWebSocketConnection.Destroy;
begin
if isPerMessageDeflate then begin
try ZDecompressCheck(ZInflateEnd(inFZStream)); except end;
try ZCompressCheck(ZDeflateEnd(outFZStream)); except end;
FZBuffer.Free;
end;
inherited Destroy;
end;
function ZlibStreamCompressString(var outFZStream: TZStreamRec; const aText: AnsiString; const zBuf: TZlibBuffer): AnsiString;
var
zresult: Integer;
len,i,outLen: integer;
aTextPos: Cardinal;
begin
result := '';
try
zresult := Z_OK;
aTextPos := 0;
while (aTextPos+1 < Length(aText)) do begin
len := length(aText)-aTextPos;
if (len > zBuf.bufferSize) then len := zBuf.bufferSize;
Move(aText[aTextPos+1], zBuf.readBuffer[0], len);
aTextPos := aTextPos + len;
outFZStream.next_in := @zBuf.readBuffer[0];
outFZStream.avail_in := len;
outFZStream.next_out := @zBuf.writeBuffer[0];
outFZStream.avail_out := zBuf.bufferSize;
zresult := ZCompressCheck(ZDeflate(outFZStream, zfNoFlush));
outLen := zBuf.bufferSize-outFZStream.avail_out;
if (outLen > 0) then begin
SetLength(result,length(result)+outLen);
Move(zBuf.writeBuffer[0], result[length(result)-outLen+1], outLen);
end;
end;
while (zresult = Z_OK) do begin
outFZStream.next_out := @zBuf.writeBuffer[0];
outFZStream.avail_out := zBuf.bufferSize;
try
zresult := ZCompressCheck(ZDeflate(outFZStream, zfSyncFlush));
outLen := zBuf.bufferSize-outFZStream.avail_out;
if (outLen > 0) then begin
SetLength(result,length(result)+outLen);
Move(zBuf.writeBuffer[0], result[length(result)-outLen+1], outLen);
end;
except zresult := Z_STREAM_END; end;
if (outFZStream.avail_out > 0) then zresult := Z_STREAM_END;
end;
if (Copy(Result,length(Result)-8,9) = #$00#$00#$ff#$ff#$00#$00#$00#$ff#$ff) then Delete(Result,length(Result)-8,9) else // remove 9 octets from tail, for cases of hitting buffer boundary
Delete(Result,length(Result)-3,4); //remove 4 octets from tail
except
on E: EZCompressionError do
result := '[compressionError:'+E.Message+']';
end;
end;
function ZlibStreamDecompressString(var inFZStream: TZStreamRec; const aText: AnsiString; const zBuf: TZlibBuffer; aTextPos: Cardinal = 0): AnsiString;
var
zresult: Integer;
len,i,outLen: integer;
begin
result := '';
try
zresult := Z_OK;
//aTextPos := 0; // <-- defined as parameter
inFZStream.avail_in := 0;
while (inFZStream.avail_in > 0) or (aTextPos+1 < Length(aText)) do begin
if (inFZStream.avail_in = 0) then begin
len := length(aText)-aTextPos;
if (len > zBuf.bufferSize) then len := zBuf.bufferSize;
Move(aText[aTextPos+1], zBuf.readBuffer[0], len);
inFZStream.next_in := @zBuf.readBuffer[0];
inFZStream.avail_in := len;
end else len := 0;
inFZStream.next_out := @zBuf.writeBuffer[0];
inFZStream.avail_out := zBuf.bufferSize;
zresult := ZDecompressCheck(ZInflate(inFZStream, zfNoFlush));
aTextPos := aTextPos + len;
outLen := zBuf.bufferSize-inFZStream.avail_out;
if (outLen > 0) then begin
SetLength(result,length(result)+outLen);
Move(zBuf.writeBuffer[0], result[length(result)-outLen+1], outLen);
end;
end;
//add 4 octets to tail
inFZStream.next_in := @zBuf.readBuffer[0];
inFZStream.avail_in := 4;
zBuf.readBuffer[0]:=$00; zBuf.readBuffer[1]:=$00; zBuf.readBuffer[2]:=$ff; zBuf.readBuffer[3]:=$ff;
while (zresult = Z_OK) do begin
inFZStream.next_out := @zBuf.writeBuffer[0];
inFZStream.avail_out := zBuf.bufferSize;
try
zresult := ZDecompressCheck(ZInflate(inFZStream, zfNoFlush));
outLen := zBuf.bufferSize-inFZStream.avail_out;
if (outLen > 0) then begin
SetLength(result,length(result)+outLen);
Move(zBuf.writeBuffer[0], result[length(result)-outLen+1], outLen);
end;
except
if (copy(inFZStream.msg,1,7)='invalid') then
ZDecompressCheck(ZInflateReset(inFZStream)); //try resetting context, if extra BFINAL byte added to stream
zresult := Z_STREAM_END;
end;
if (inFZStream.avail_out > 0) then zresult := Z_STREAM_END;
end;
except
on E: EZDecompressionError do
result := '[DecompressionError:'+E.Message+']';
end;
end;
function ZlibCompressString(const aText: AnsiString; const aCompressionLevel: TZCompressionLevel; const windowBits: integer; const memLevel: integer; const strategy: TZStrategy): AnsiString;
var
strInput,
strOutput: TStringStream;
Zipper: TZCompressionStream;
begin
Result := '';
strInput := TStringStream.Create(aText);
strOutput := TStringStream.Create('');
try
Zipper := TZCompressionStream.Create(strOutput, aCompressionLevel, windowBits, memLevel, strategy);
try
Zipper.CopyFrom(strInput, strInput.Size);
finally
Zipper.Free;
end;
Result := strOutput.DataString;
finally
strInput.Free;
strOutput.Free;
end;
end;
function ZlibDecompressString(const aText: AnsiString; const windowBits: integer): AnsiString;
var
strInput,
strOutput: TStringStream;
Unzipper: TZDecompressionStream;
begin
Result := '';
strInput := TStringStream.Create(aText);
strOutput := TStringStream.Create('');
try
Unzipper := TZDecompressionStream.Create(strInput, windowBits);
try
strOutput.CopyFrom(Unzipper, Unzipper.Size);
finally
Unzipper.Free;
end;
Result := strOutput.DataString;
finally
strInput.Free;
strOutput.Free;
end;
end;
function httpCode(code: integer): AnsiString;
begin
case (code) of
100: result := 'Continue';
101: result := 'Switching Protocols';
200: result := 'OK';
201: result := 'Created';
202: result := 'Accepted';
203: result := 'Non-Authoritative Information';
204: result := 'No Content';
205: result := 'Reset Content';
206: result := 'Partial Content';
300: result := 'Multiple Choices';
301: result := 'Moved Permanently';
302: result := 'Found';
303: result := 'See Other';
304: result := 'Not Modified';
305: result := 'Use Proxy';
307: result := 'Temporary Redirect';
400: result := 'Bad Request';
401: result := 'Unauthorized';
402: result := 'Payment Required';
403: result := 'Forbidden';
404: result := 'Not Found';
405: result := 'Method Not Allowed';
406: result := 'Not Acceptable';
407: result := 'Proxy Authentication Required';
408: result := 'Request Time-out';
409: result := 'Conflict';
410: result := 'Gone';
411: result := 'Length Required';
412: result := 'Precondition Failed';
413: result := 'Request Entity Too Large';
414: result := 'Request-URI Too Large';
415: result := 'Unsupported Media Type';
416: result := 'Requested range not satisfiable';
417: result := 'Expectation Failed';
500: result := 'Internal Server Error';
501: result := 'Not Implemented';
502: result := 'Bad Gateway';
503: result := 'Service Unavailable';
504: result := 'Gateway Time-out';
else result := 'unknown code: $code';
end;
end;
procedure SplitExtension(var extString,key,value: AnsiString);
var i: integer;
tmps: AnsiString;
begin
i := Pos('; ',extString);
if (i <> 0) then begin
tmps := trim(lowercase(copy(extString,1,i-1)));
delete(extString,1,i);
end else begin
tmps := trim(lowercase(extString));
extString := '';
end;
i := Pos('=',tmps);
if (i <> 0) then begin
key := trim(copy(tmps,1,i-1));
value := trim(copy(tmps,i+1,length(tmps)));
end else begin
key := trim(tmps);
value := '';
end;
end;
//tryDeflate = 0 for false, or zlib windowBits for true (ie. 15)
function CreateServerWebSocketConnection(str_headers: AnsiString; tryDeflate: Byte = 15): TWebSocketConnection;
var headers, hrs: TStringList;
get,extKey,extVal: AnsiString;
s, key, version: AnsiString;
iversion, vv: integer;
res: boolean;
r : TWebSocketConnection;
fncResourceName: AnsiString;
fncHost: AnsiString;
fncPort: AnsiString;
fncOrigin: AnsiString;
fncProtocol: AnsiString;
fncExtensions: AnsiString;
fncCookie: AnsiString;
fncHeaders: AnsiString;
fncWebSocketHeaders: AnsiString;
fncResultHttp: integer;
fncInCompWindowBits: byte;
fncOutCompWindowBits: byte;
fncinCompNoContext: boolean;
fncoutCompNoContext: boolean;
fncPerMessageDeflate: boolean;
begin
result := nil;
headers := TStringList.Create;
try
for vv:=length(str_headers)-1 downto 1 do begin
if (copy(str_headers,vv,2)=': ') then begin
str_headers[vv]:='='; delete(str_headers,vv+1,1);
end;
end;
headers.Text := str_headers;
get := '';
if (headers.count<>0) then begin
get := headers[0]; res := True;
end;
if (res) then
begin
res := false;
try
//CHECK HTTP GET
if ((Pos('GET ', Uppercase(get)) <> 0) and (Pos(' HTTP/1.1', Uppercase(get)) <> 0)) then
begin
fncResourceName := SeparateRight(get, ' ');
fncResourceName := SeparateLeft(fncResourceName, ' ');
end
else exit;
fncResourceName := trim(fncResourceName);
//CHECK HOST AND PORT
s := headers.Values['host'];
if (s <> '') then
begin
fncHost := trim(s);
fncPort := SeparateRight(fncHost, ':');
fncHost := SeparateLeft(fncHost, ':');
end;
fncHost := trim(fncHost);
fncPort := trim(fncPort);
if (fncHost = '') then exit;
//WEBSOCKET KEY
s := headers.Values['sec-websocket-key'];
if (s <> '') then
begin
if (Length(DecodeBase64(s)) = 16) then
begin
key := s;
end;
end;
if (key = '') then exit;
key := trim(key);
//WEBSOCKET VERSION
s := headers.Values['sec-websocket-version'];
if (s <> '') then
begin
vv := StrToIntDef(s, -1);
if ((vv >= 7) and (vv <= 13)) then
begin
version := s;
end;
end;
if (version = '') then exit;
version := trim(version);
iversion := StrToIntDef(version, 13);
if (LowerCase(headers.Values['upgrade']) <> LowerCase('websocket')) or (pos('upgrade', LowerCase(headers.Values['connection'])) = 0) then
exit;
//COOKIES
fncProtocol := '-';
fncExtensions := '-';
fncCookie := '-';
fncOrigin := '-';
fncPerMessageDeflate := false;
if (iversion < 13) then
begin
if (headers.IndexOfName('sec-websocket-origin') > -1) then
fncOrigin := trim(headers.Values['sec-websocket-origin']);
end
else begin
if (headers.IndexOfName('origin') > -1) then
fncOrigin := trim(headers.Values['origin']);
end;
if (headers.IndexOfName('sec-websocket-protocol') > -1) then
fncProtocol := trim(headers.Values['sec-websocket-protocol']);
if (headers.IndexOfName('sec-websocket-extensions') > -1) then begin
fncExtensions := trim(headers.Values['sec-websocket-extensions']);
// ignore deprecated 'x-webkit-deflate-frame' (ios devices)
if (Pos('permessage-deflate',fncExtensions) <> 0) then begin
try
if (tryDeflate>0) then begin
//fncExtensions := 'permessage-deflate; client_max_window_bits=12; server_max_window_bits=12';//; client_no_context_takeover';
fncInCompWindowBits := tryDeflate;
fncOutCompWindowBits := tryDeflate;
while (fncExtensions <> '') do begin
SplitExtension(fncExtensions,extKey,extVal);
if (extKey = 'client_max_window_bits') then begin
if (extVal <> '') and (extVal <> '0') then fncInCompWindowBits := StrToInt(extVal);
if (fncInCompWindowBits < 8) or (fncInCompWindowBits > tryDeflate) then fncInCompWindowBits := tryDeflate;
end;
if (extKey = 'client_no_context_takeover') then fncinCompNoContext := true;
end;
fncExtensions := 'permessage-deflate; client_max_window_bits';
if (fncInCompWindowBits > 0) then fncExtensions := fncExtensions+'='+IntToStr(fncInCompWindowBits);
fncExtensions := fncExtensions + '; server_max_window_bits';
if (fncOutCompWindowBits > 0) then fncExtensions := fncExtensions+'='+IntToStr(fncOutCompWindowBits);
fncExtensions := fncExtensions + '; ';
if fncinCompNoContext then fncExtensions := fncExtensions + 'client_no_context_takeover; ';
if fncoutCompNoContext then fncExtensions := fncExtensions + 'server_no_context_takeover; ';
delete(fncExtensions,length(fncExtensions)-1,2); //delete extra '; '
fncPerMessageDeflate := true;
end else fncExtensions := '-';
except
fncExtensions := '-';
end;
end else fncExtensions := '-';
end;
if (headers.IndexOfName('cookie') > -1) then
fncCookie := trim(headers.Values['cookie']);
fncHeaders := trim(headers.text);
res := true;
finally
if (res) then
begin
fncResultHttp := 101;
hrs := TStringList.Create;
hrs.Assign(headers);
if (1=1) then
begin
if (fncResultHttp <> 101) then //HTTP ERROR FALLBACK
begin
fncWebSocketHeaders := fncWebSocketHeaders + Format('HTTP/1.1 %d %s'+#13#10, [fncResultHttp, httpCode(fncResultHttp)]);
fncWebSocketHeaders := fncWebSocketHeaders + Format('%d %s'+#13#10#13#10, [fncResultHttp, httpCode(fncResultHttp)]);
end
else
begin
key := EncodeBase64(SHA1(key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'));
s := 'HTTP/1.1 101 Switching Protocols' + #13#10;
s := s + 'Upgrade: websocket' + #13#10;
s := s + 'Connection: Upgrade' + #13#10;
s := s + 'Sec-WebSocket-Accept: ' + key + #13#10;
if (fncProtocol <> '-') then
begin
s := s + 'Sec-WebSocket-Protocol: ' + fncProtocol + #13#10;
end;
if (fncExtensions <> '-') then
begin
s := s + 'Sec-WebSocket-Extensions: ' + fncExtensions + #13#10;
end;
s := s + #13#10;
fncWebSocketHeaders := fncWebSocketHeaders + s;
result := TWebSocketConnection.Create;
TWebSocketConnection(result).isServerConnection := true;
TWebSocketConnection(result).fCookie := fncCookie;
TWebSocketConnection(result).fVersion := StrToInt(version);
TWebSocketConnection(result).fProtocol := fncProtocol;
TWebSocketConnection(result).fResourceName := fncResourceName;
TWebSocketConnection(result).fOrigin := fncOrigin;
TWebSocketConnection(result).fExtension := fncExtensions;
TWebSocketConnection(result).fPort := fncPort;
TWebSocketConnection(result).fHost := fncHost;
TWebSocketConnection(result).fHeaders := fncHeaders;
TWebSocketConnection(result).fWebSocketHeaders := fncWebSocketHeaders;
TWebSocketConnection(result).fHandshake := true;
TWebSocketConnection(result).fMasking := false; //server must not mask frames sent to client
TWebSocketConnection(result).isPerMessageDeflate := fncPerMessageDeflate;
TWebSocketConnection(result).InCompWindowBits := fncInCompWindowBits;
TWebSocketConnection(result).OutCompWindowBits := fncOutCompWindowBits;
TWebSocketConnection(result).inCompNoContext := fncinCompNoContext;
TWebSocketConnection(result).outCompNoContext := fncoutCompNoContext;
if fncPerMessageDeflate then begin
TWebSocketConnection(result).FZBuffer := TZlibBuffer.Create;
ZCompressCheck(ZDeflateInit2(TWebSocketConnection(result).outFZStream, zcLevel8, -1*fncOutCompWindowBits, 9, zsDefault));
ZDecompressCheck(ZInflateInit2(TWebSocketConnection(result).inFZStream, -1*fncInCompWindowBits));
end;
end;
end;
hrs.Free;
end;
end;
end;
finally
headers.Free;
end;
end;
function CreateClientWebSocketConnection(wsUri: AnsiString; tryDeflate: boolean): TWebSocketConnection;
var key, s, get: AnsiString;
i: integer;
fncOrigin: AnsiString;
fncHost: AnsiString;
fncPort: AnsiString;
fncResourceName: AnsiString;
fncProtocol: AnsiString;
fncExtension: AnsiString;
fncCookie: AnsiString;
fncHeaders: AnsiString;
fncWebSocketHeaders: AnsiString;
fncResultHttp: integer;
fncVersion: integer;
wsProt,wsUser,wsPass,wsPara: AnsiString;
begin
ParseURL(wsUri,wsProt,wsUser,wsPass,fncHost,fncPort,fncResourceName,wsPara);
fncOrigin := wsProt+'://'+fncHost;
if (fncPort<>'80') then fncOrigin := fncOrigin + ':'+fncPort;
fncVersion := 13;
fncProtocol := '-';
fncCookie := '-';
fncExtension := '-';
if (wsPara <> '') then fncResourceName := fncResourceName + '?' + wsPara;
if tryDeflate then fncExtension := 'permessage-deflate; client_max_window_bits';
s := Format('GET %s HTTP/1.1' + #13#10, [fncResourceName]);
s := s + Format('Upgrade: websocket' + #13#10, []);
s := s + Format('Connection: Upgrade' + #13#10, []);
s := s + Format('Host: %s:%s' + #13#10, [fncHost, fncPort]);
for I := 1 to 16 do key := key + ansichar(Random(85) + 32);
key := EncodeBase64(key);
s := s + Format('Sec-WebSocket-Key: %s' + #13#10, [(key)]);
s := s + Format('Sec-WebSocket-Version: %d' + #13#10, [fncVersion]);
//TODO extensions
if (fncProtocol <> '-') then
s := s + Format('Sec-WebSocket-Protocol: %s' + #13#10, [fncProtocol]);
if (fncOrigin <> '-') then
begin
if (fncVersion < 13) then
s := s + Format('Sec-WebSocket-Origin: %s' + #13#10, [fncOrigin])
else
s := s + Format('Origin: %s' + #13#10, [fncOrigin]);
end;
if (fncCookie <> '-') then
s := s + Format('Cookie: %s' + #13#10, [(fncCookie)]);
if (fncExtension <> '-') then
s := s + Format('Sec-WebSocket-Extensions: %s' + #13#10, [fncExtension]);
s := s + #13#10;
fncWebSocketHeaders := s;
result := TWebSocketConnection.Create;
TWebSocketConnection(result).isServerConnection := false;
TWebSocketConnection(result).fCookie := fncCookie;
TWebSocketConnection(result).fVersion := fncVersion;
TWebSocketConnection(result).fProtocol := fncProtocol;
TWebSocketConnection(result).fResourceName := fncResourceName;
TWebSocketConnection(result).fOrigin := fncOrigin;
TWebSocketConnection(result).fExtension := '-'; //assigned upon response from server
TWebSocketConnection(result).fPort := fncPort;
TWebSocketConnection(result).fHost := fncHost;
TWebSocketConnection(result).fHeaders := fncHeaders;
TWebSocketConnection(result).fWebSocketHeaders := fncWebSocketHeaders;
TWebSocketConnection(result).fwsKey := key;
TWebSocketConnection(result).fHandshake := false;
TWebSocketConnection(result).fMasking := true; //client must mask frames sent to server
end;
function ConfirmClientWebSocketConnection(var wsConn: TWebSocketConnection; str_headers: string): boolean;
var headers: TStringList;
vv: integer;
get,fncExtensions,extKey,extVal: AnsiString;
begin
result := false;
if (wsConn = nil) then exit;
result := true;
headers := TStringList.Create;
try
for vv:=length(str_headers)-1 downto 1 do begin
if (copy(str_headers,vv,2)=': ') then begin
str_headers[vv]:='='; delete(str_headers,vv+1,1);
end;
end;
headers.Text := str_headers;
get := '';
if (headers.count<>0) then begin
get := headers[0];
end else result := false;
if (result) then result := pos(LowerCase('HTTP/1.1 101'), LowerCase(get)) = 1;
if (result) then result := (LowerCase(headers.Values['upgrade']) = LowerCase('websocket')) and (LowerCase(headers.Values['connection']) = 'upgrade');
if (result) then begin
if (headers.IndexOfName('sec-websocket-protocol') > -1) then
wsConn.fProtocol := trim(headers.Values['sec-websocket-protocol']);
if (headers.IndexOfName('sec-websocket-extensions') > -1) then
wsConn.fExtension := trim(headers.Values['sec-websocket-extensions']);
end;
if (result) then result := (headers.Values['sec-websocket-accept'] = EncodeBase64(SHA1(wsConn.fwsKey + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
except
headers.Free;
end;
if (result) then begin
wsConn.fHandshake := true;
wsConn.fHeaders := str_headers;
fncExtensions := wsConn.fExtension;
if (Pos('permessage-deflate',fncExtensions) <> 0) then begin
try
//fncExtensions := 'permessage-deflate; client_max_window_bits=12; server_max_window_bits=12';//; client_no_context_takeover';
wsConn.inCompWindowBits := 15;
wsConn.outCompWindowBits := 15;
while (fncExtensions <> '') do begin
SplitExtension(fncExtensions,extKey,extVal);
if (extKey = 'client_max_window_bits') then begin
if (extVal <> '') and (extVal <> '0') then wsConn.outCompWindowBits := StrToInt(extVal);
if (wsConn.outCompWindowBits < 8) or (wsConn.outCompWindowBits > 15) then wsConn.outCompWindowBits := 15;
end;
if (extKey = 'server_max_window_bits') then begin
if (extVal <> '') and (extVal <> '0') then wsConn.inCompWindowBits := StrToInt(extVal);
if (wsConn.inCompWindowBits < 8) or (wsConn.inCompWindowBits > 15) then wsConn.inCompWindowBits := 15;
end;
if (extKey = 'server_no_context_takeover') then wsConn.inCompNoContext := true;
if (extKey = 'client_no_context_takeover') then wsConn.outCompNoContext := true;
end;
wsConn.isPerMessageDeflate := true;
wsConn.FZBuffer := TZlibBuffer.Create;
ZCompressCheck(ZDeflateInit2(wsConn.outFZStream, zcLevel8, -1*wsConn.outCompWindowBits, 9, zsDefault));
ZDecompressCheck(ZInflateInit2(wsConn.inFZStream, -1*wsConn.inCompWindowBits));
except
end;
end;
end else begin
wsConn.Free;
wsConn := nil;
end;
end;
function hexToStr(aDec: integer; aLength: integer): AnsiString;
var tmp: AnsiString;
i: integer;
begin
tmp := IntToHex(aDec, aLength);
result := '';
for i := 1 to (Length(tmp)+1) div 2 do
begin
result := result + ansichar(StrToInt('$'+Copy(tmp, i * 2 - 1, 2)));
end;
end;
function StrToHexstr2(str: string): AnsiString;
var i: integer;
begin
result := '';
for i := 1 to Length(str) do result := result + IntToHex(ord(str[i]), 2) + ' ';
end;
function WebSocketReadData(var aData: AnsiString; const wsConn: TWebSocketConnection; var aCode: integer; var aFinal: boolean): AnsiString;
var timeout, i, j: integer;
b: byte;
mask: boolean;
len, iPos: int64;
mBytes: array[0..3] of byte;
aRes1, aRes2, aRes3: boolean;
begin
result := '';
aCode := -1;
if (aData = '') then exit;
len := 0; iPos := 1;
b := ord(aData[iPos]); iPos:=iPos+1;
try
try
// BASIC INFORMATIONS
aFinal := (b and $80) = $80;
aRes1 := (b and $40) = $40;
aRes2 := (b and $20) = $20;
aRes3 := (b and $10) = $10;
aCode := b and $F;
// MASK AND LENGTH
mask := false;
if (iPos <= length(aData)) then
begin
b := ord(aData[iPos]); iPos:=iPos+1;
mask := (b and $80) = $80;
len := (b and $7F);
if (len = 126) then
begin
if (iPos <= length(aData)) then
begin
b := ord(aData[iPos]); iPos:=iPos+1;
len := b * $100; // 00 00
if (iPos <= length(aData)) then
begin
b := ord(aData[iPos]); iPos:=iPos+1;
len := len + b;
end;
end;
end
else if (len = 127) then //00 00 00 00 00 00 00 00
begin
//TODO nesting og get byte should be different
if (iPos <= length(aData)) then
begin
b := ord(aData[iPos]); iPos:=iPos+1;
len := b * $100000000000000;
if (iPos <= length(aData)) then
begin
b := ord(aData[iPos]); iPos:=iPos+1;
len := len + b * $1000000000000;
end;
if (iPos <= length(aData)) then
begin
b := ord(aData[iPos]); iPos:=iPos+1;
len := len + b * $10000000000;
end;
if (iPos <= length(aData)) then
begin
b := ord(aData[iPos]); iPos:=iPos+1;
len := len + b * $100000000;
end;
if (iPos <= length(aData)) then
begin
b := ord(aData[iPos]); iPos:=iPos+1;
len := len + b * $1000000;
end;
if (iPos <= length(aData)) then
begin
b := ord(aData[iPos]); iPos:=iPos+1;
len := len + b * $10000;
end;
if (iPos <= length(aData)) then
begin
b := ord(aData[iPos]); iPos:=iPos+1;
len := len + b * $100;
end;
if (iPos <= length(aData)) then
begin
b := ord(aData[iPos]); iPos:=iPos+1;
len := len + b;
end;
end;
end;
end;
if (iPos <= length(aData)) and (wsConn.fRequireMasking) and (not mask) then
begin
// TODO some protocol error
raise Exception.Create('mask');
end;
// MASKING KEY
if (mask) and (iPos <= length(aData)) then
begin
if (iPos <= length(aData)) then begin
mBytes[0] := ord(aData[iPos]); iPos:=iPos+1;
end;
if (iPos <= length(aData)) then begin
mBytes[1] := ord(aData[iPos]); iPos:=iPos+1;
end;
if (iPos <= length(aData)) then begin
mBytes[2] := ord(aData[iPos]); iPos:=iPos+1;
end;
if (iPos <= length(aData)) then begin
mBytes[3] := ord(aData[iPos]); iPos:=iPos+1;
end;
end;
// READ DATA
if (iPos+len-1 <= length(aData)) then
begin
//process complete packet and remove from incoming stream
for i := 0 to len-1 do begin
if mask then begin
result := result + chr(Ord(aData[iPos+i]) xor mBytes[i mod 4]);
end else result := result + aData[iPos+i];
end;
delete(aData,1,iPos+len-1);
if aRes1 and wsConn.isPerMessageDeflate then begin {deflate}
//result := ZlibDecompressString(result,-1*wsConn.InCompWindowBits);
result := ZlibStreamDecompressString(wsConn.inFZStream,result,wsConn.FZBuffer);
if wsConn.inCompNoContext then ZDecompressCheck(ZInflateReset(wsConn.inFZStream));
end;
end else aFinal := false; //still don't have enough data from buffer for complete packet
except
result := '';
end;
finally
end;
end;
function WebSocketSendData(aData: AnsiString; const wsConn: TWebSocketConnection; aCode: integer = 1{wsCodeText}; tryDeflate: boolean = true): AnsiString;
var b: byte;
s: AnsiString;
mBytes: array[0..3] of byte;
len: int64;
aFinal, aRes1, aRes2, aRes3: boolean;
i,j: integer;
begin
result := '';
try
s := '';
aFinal := true; aRes1 := false; aRes2 := false; aRes3 := false;
if tryDeflate and wsConn.isPerMessageDeflate then begin
//http://stackoverflow.com/questions/22169036/websocket-permessage-deflate-in-chrome-with-no-context-takeover
aRes1 := true;
//aData := ZlibCompressString(aData,zcLevel8,-1*wsConn.CompWindowBits,9{memLevel},zsDefault) + #0 {#0=BFINAL, forces no-context};
aData := ZlibStreamCompressString(wsConn.outFZStream,aData,wsConn.FZBuffer);
if wsConn.outCompNoContext then ZCompressCheck(ZDeflateReset(wsConn.outFZStream));
end;
b := 0;
// BASIC INFORMATION
b := IfThen(aFinal, 1, 0) * $80;
b := b + IfThen(aRes1, 1, 0) * $40;
b := b + IfThen(aRes2, 1, 0) * $20;
b := b + IfThen(aRes3, 1, 0) * $10;
b := b + aCode;
s := s + ansichar(b);
b := 0;
// MASK AND LENGTH
b := IfThen(wsConn.fMasking, 1, 0) * $80;
if (length(aData) < 126) then
b := b + length(aData)
else if (length(aData) < 65536) then
b := b + 126
else
b := b + 127;
s := s + ansichar(b);
if (length(aData) >= 126) then
begin
if (length(aData) < 65536) then
begin
s := s + hexToStr(length(aData), 4);
end
else
begin
s := s + hexToStr(length(aData), 16);
end;
end;
// MASKING KEY
if (wsConn.fMasking) then
begin
mBytes[0] := Random(256);
mBytes[1] := Random(256);
mBytes[2] := Random(256);
mBytes[3] := Random(256);
s := s + ansichar(mBytes[0]);
s := s + ansichar(mBytes[1]);
s := s + ansichar(mBytes[2]);
s := s + ansichar(mBytes[3]);
for i := 1 to length(aData) do begin
s := s + chr(Ord(aData[i]) xor mBytes[(i-1) mod 4]);
end;
result := s;
end else result := s+aData;
except result := ''; end;
end;
//TZlibBuffer class primitives
constructor TZlibBuffer.Create(bufSize: Cardinal = 16384);
begin
SetBufferSize(bufSize);
end;
destructor TZlibBuffer.Destroy;
begin
SetBufferSize(0);
inherited Destroy;
end;
procedure TZlibBuffer.SetBufferSize(bufSize: Cardinal);
begin
bufferSize := bufSize;
SetLength(readBuffer,bufferSize);
SetLength(writeBuffer,bufferSize);
end;
initialization
Randomize;
end.
|
unit RGBAByteDataSet;
interface
uses ByteDataSet;
type
TRGBAByteDataSet = class (TByteDataSet)
private
FLength : integer;
// Gets
function GetData(_pos: integer): byte; reintroduce; overload;
function GetRed(_pos: integer): byte;
function GetGreen(_pos: integer): byte;
function GetBlue(_pos: integer): byte;
function GetAlpha(_pos: integer): byte;
// Sets
procedure SetData(_pos: integer; _data: byte); reintroduce; overload;
procedure SetRed(_pos: integer; _data: byte);
procedure SetGreen(_pos: integer; _data: byte);
procedure SetBlue(_pos: integer; _data: byte);
procedure SetAlpha(_pos: integer; _data: byte);
protected
// Gets
function GetDataLength: integer; override;
function GetLength: integer; override;
function GetLast: integer; override;
// Sets
procedure SetLength(_size: integer); override;
public
// properties
property Data[_pos: integer]:byte read GetData write SetData;
property Red[_pos: integer]:byte read GetRed write SetRed;
property Green[_pos: integer]:byte read GetGreen write SetGreen;
property Blue[_pos: integer]:byte read GetBlue write SetBlue;
property Alpha[_pos: integer]:byte read GetAlpha write SetAlpha;
end;
implementation
// Gets
function TRGBAByteDataSet.GetData(_pos: integer): byte;
begin
Result := FData[_pos];
end;
function TRGBAByteDataSet.GetRed(_pos: integer): byte;
begin
Result := FData[4*_pos];
end;
function TRGBAByteDataSet.GetGreen(_pos: integer): byte;
begin
Result := FData[(4*_pos)+1];
end;
function TRGBAByteDataSet.GetBlue(_pos: integer): byte;
begin
Result := FData[(4*_pos)+2];
end;
function TRGBAByteDataSet.GetAlpha(_pos: integer): byte;
begin
Result := FData[(4*_pos)+3];
end;
function TRGBAByteDataSet.GetLength: integer;
begin
Result := FLength;
end;
function TRGBAByteDataSet.GetDataLength: integer;
begin
Result := High(FData) + 1;
end;
function TRGBAByteDataSet.GetLast: integer;
begin
Result := FLength - 1;
end;
// Sets
procedure TRGBAByteDataSet.SetData(_pos: integer; _data: byte);
begin
FData[_pos] := _data;
end;
procedure TRGBAByteDataSet.SetRed(_pos: integer; _data: byte);
begin
FData[4*_pos] := _data;
end;
procedure TRGBAByteDataSet.SetGreen(_pos: integer; _data: byte);
begin
FData[(4*_pos)+1] := _data;
end;
procedure TRGBAByteDataSet.SetBlue(_pos: integer; _data: byte);
begin
FData[(4*_pos)+2] := _data;
end;
procedure TRGBAByteDataSet.SetAlpha(_pos: integer; _data: byte);
begin
FData[(4*_pos)+3] := _data;
end;
procedure TRGBAByteDataSet.SetLength(_size: Integer);
begin
FLength := _size;
System.SetLength(FData,_size*4);
end;
end.
|
unit CCJSO_SessionUsers;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, ComCtrls, ToolWin, StdCtrls, ExtCtrls, ActnList,
DB, ADODB;
type
TfrmCCJSO_SessionUser = class(TForm)
pnlCondition: TPanel;
lblCndDatePeriod_with: TLabel;
lblCndDatePeriod_toOn: TLabel;
lblCnd_User: TLabel;
dtCndBegin: TDateTimePicker;
dtCndEnd: TDateTimePicker;
edCnd_User: TEdit;
btnCnd_User: TButton;
pnlTool: TPanel;
pnlTool_Show: TPanel;
pnlTool_Bar: TPanel;
toolBar: TToolBar;
tbtnRefresh: TToolButton;
tbtnClearCondition: TToolButton;
pnlGrid: TPanel;
GridJA: TDBGrid;
aList: TActionList;
aCondition: TAction;
aCnd_ChooseUser: TAction;
aRefresh: TAction;
aClearCondition: TAction;
aExit: TAction;
spRegActiveUser: TADOStoredProc;
dsRegActiveUser: TDataSource;
procedure FormCreate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure aExitExecute(Sender: TObject);
procedure aRefreshExecute(Sender: TObject);
procedure aClearConditionExecute(Sender: TObject);
procedure aConditionExecute(Sender: TObject);
procedure aCnd_ChooseUserExecute(Sender: TObject);
procedure edCnd_UserDblClick(Sender: TObject);
procedure GridJADrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
private
{ Private declarations }
ISignActivate : integer;
NChooseUser : integer;
procedure ShowGets;
procedure ExecCondition;
procedure CreateCondition;
procedure GridRefresh;
function GetStateClearCondition : boolean;
public
{ Public declarations }
end;
var
frmCCJSO_SessionUser: TfrmCCJSO_SessionUser;
implementation
uses
UMain, DateUtils, Util,
UCCenterJournalNetZkz, UReference;
{$R *.dfm}
procedure TfrmCCJSO_SessionUser.FormCreate(Sender: TObject);
begin
{ Инициализация }
ISignActivate := 0;
dtCndBegin.Date := date;
dtCndEnd.Date := date;
NChooseUser := 0;
end;
procedure TfrmCCJSO_SessionUser.FormActivate(Sender: TObject);
begin
if ISignActivate = 0 then begin
{ Иконка формы }
FCCenterJournalNetZkz.imgMain.GetIcon(318,self.Icon);
{ Форма активна }
ISignActivate := 1;
ExecCondition;
ShowGets;
end;
end;
procedure TfrmCCJSO_SessionUser.ShowGets;
var
SCaption : string;
begin
if ISignActivate = 1 then begin
{ Количество записей }
SCaption := VarToStr(spRegActiveUser.RecordCount);
pnlTool_Show.Caption := SCaption; pnlTool_Show.Width := TextPixWidth(SCaption, pnlTool_Show.Font) + 20;
{ Доступ к очистке условий отбора }
if GetStateClearCondition
then aClearCondition.Enabled := false
else aClearCondition.Enabled := true;
end;
end;
procedure TfrmCCJSO_SessionUser.aExitExecute(Sender: TObject);
begin
self.Close;
end;
procedure TfrmCCJSO_SessionUser.aRefreshExecute(Sender: TObject);
begin
GridRefresh;
ShowGets;
end;
procedure TfrmCCJSO_SessionUser.aClearConditionExecute(Sender: TObject);
begin
edCnd_User.Text := '';
NChooseUser := 0;
ExecCondition;
ShowGets;
end;
procedure TfrmCCJSO_SessionUser.aConditionExecute(Sender: TObject);
begin
if ISignActivate = 1 then begin
ExecCondition;
end;
end;
procedure TfrmCCJSO_SessionUser.aCnd_ChooseUserExecute(Sender: TObject);
var
DescrSelect : string;
begin
DescrSelect := '';
try
frmReference := TfrmReference.Create(Self);
frmReference.SetMode(cFReferenceModeSelect);
frmReference.SetReferenceIndex(cFReferenceUserAva);
frmReference.SetReadOnly(cFReferenceYesReadOnly);
try
frmReference.ShowModal;
DescrSelect := frmReference.GetDescrSelect;
if length(DescrSelect) > 0 then begin
NChooseUser := frmReference.GetRowIDSelect;
edCnd_User.Text := DescrSelect;
end;
finally
frmReference.Free;
end;
except
end;
end;
procedure TfrmCCJSO_SessionUser.edCnd_UserDblClick(Sender: TObject);
begin
aCnd_ChooseUser.Execute;
end;
procedure TfrmCCJSO_SessionUser.GridJADrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
db: TDBGrid;
begin
if Sender = nil then Exit;
db := TDBGrid(Sender);
if (gdSelected in State) then begin
db.Canvas.Font.Style := [fsBold];
end;
db.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
procedure TfrmCCJSO_SessionUser.ExecCondition;
var
RN: int64;
begin
if not spRegActiveUser.IsEmpty then RN := spRegActiveUser.FieldByName('NRN').AsInteger else RN := -1;
if spRegActiveUser.Active then spRegActiveUser.Active := false;
CreateCondition;
spRegActiveUser.Active := true;
spRegActiveUser.Locate('NRN', RN, []);
ShowGets;
end;
procedure TfrmCCJSO_SessionUser.CreateCondition;
begin
spRegActiveUser.Parameters.ParamValues['@USER'] := NChooseUser;
spRegActiveUser.Parameters.ParamValues['@Begin'] := FormatDateTime('yyyy-mm-dd', dtCndBegin.Date);
spRegActiveUser.Parameters.ParamValues['@End'] := FormatDateTime('yyyy-mm-dd', IncDay(dtCndEnd.Date,1));
end;
procedure TfrmCCJSO_SessionUser.GridRefresh;
var
RN: int64;
begin
if not spRegActiveUser.IsEmpty then RN := spRegActiveUser.FieldByName('NRN').AsInteger else RN := -1;
spRegActiveUser.Requery;
spRegActiveUser.Locate('NRN', RN, []);
end;
function TfrmCCJSO_SessionUser.GetStateClearCondition : boolean;
var bResReturn : boolean;
begin
if (length(trim(edCnd_User.Text)) = 0)
and (NChooseUser = 0)
then bResReturn := true
else bResReturn := false;
result := bResReturn;
end;
end.
|
unit uFrmListPayments;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ExtCtrls, siComp, uFormasPagamento,
StdCtrls, DB, ADODB, PaiDeForms, siLangRT, PaideTodosGeral, Buttons,
cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, cxDBData,
cxGridTableView, cxGridCustomTableView, cxGridDBTableView, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, cxGrid, Provider, DBClient;
const
PAYMENT_TYPE_CASHBACK = -10;
type
TFrmListPayments = class(TFrmParentAll)
pnlOption: TPanel;
pnlPayOption: TPanel;
rbPayNow: TRadioButton;
rbPayLater: TRadioButton;
pnlKay1: TPanel;
Image1: TImage;
Label1: TLabel;
lbF2: TLabel;
Panel2: TPanel;
Image2: TImage;
Label2: TLabel;
lbF3: TLabel;
Label3: TLabel;
quPaymentType: TADODataSet;
dsPaymentType: TDataSource;
quPaymentTypeIDMeioPag: TIntegerField;
quPaymentTypeMeioPag: TStringField;
btnOK: TButton;
grdPayments: TcxGrid;
grdPaymentsDB: TcxGridDBTableView;
grdPaymentsLevel: TcxGridLevel;
grdPaymentsDBMeioPag: TcxGridDBColumn;
strepPayments: TcxStyleRepository;
GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet;
csList: TcxStyle;
dspPaymentType: TDataSetProvider;
cdsPaymentType: TClientDataSet;
quPaymentTypeTipo: TIntegerField;
procedure FormShow(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btCloseClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FIDMeioPag : Integer;
FIDMeioPagTipo: Integer;
FPreDatado : Boolean;
FResult : Boolean;
procedure OpenPayment;
procedure ClosePayment;
procedure SetCashBack;
procedure CreateCashBackPayment;
procedure PaymentTypeFilter;
function CheckOnePayment: Boolean;
public
function Start(var AIDMeioPagTipo: Integer; var AIDMeioPag: Integer;
var APreDatado: Boolean; AllowSelectPaymentType : Boolean = True): Boolean;
end;
implementation
uses uDM, uSystemConst, uMsgBox, uMsgConstant;
{$R *.dfm}
function TFrmListPayments.Start(var AIDMeioPagTipo: Integer; var AIDMeioPag: Integer;
var APreDatado: Boolean; AllowSelectPaymentType : Boolean = True): Boolean;
begin
FIDMeioPag := -1;
FIDMeioPagTipo := AIDMeioPagTipo;
PaymentTypeFilter;
// Alex 09/25/2015 - Removed arg_deviceProcess and added AllowSelectPaymentType
//FResult := AllowSelectPaymentType;
// Antonio 09/10/2016 if ( FResult ) then begin
if not CheckOnePayment then
ShowModal;
//end;
if AIDMeioPagTipo = PAYMENT_TYPE_OTHER then
SetCashBack;
FPreDatado := rbPayLater.Checked;
AIDMeioPag := FIDMeioPag;
APreDatado := FPreDatado;
AIDMeioPagTipo := FIDMeioPagTipo;
Result := FResult;
end;
procedure TFrmListPayments.FormShow(Sender: TObject);
begin
inherited;
KeyPreview := True;
grdPayments.SetFocus;
end;
procedure TFrmListPayments.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_RETURN:
begin
end;
VK_ESCAPE:
begin
btCloseClick(Self);
end;
VK_F2 : begin
if pnlPayOption.Visible then
rbPayNow.Checked := True;
end;
VK_F3 : begin
if pnlPayOption.Visible then
rbPayLater.Checked := True;
end;
end;
end;
procedure TFrmListPayments.ClosePayment;
begin
with quPaymentType do
if Active then
Close;
end;
procedure TFrmListPayments.OpenPayment;
begin
with cdsPaymentType do
if not Active then
begin
Open;
CreateCashBackPayment;
end;
end;
function TFrmListPayments.CheckOnePayment: Boolean;
begin
Result := False;
pnlOption.Visible := (DM.fSystem.SrvParam[PARAM_DISPLAY_PRE_DATADO]) and (FIDMeioPagTipo in [PAYMENT_TYPE_CHECK, PAYMENT_TYPE_CARD]);
if (cdsPaymentType.RecordCount = 1) and (not pnlOption.Visible) then
begin
FIDMeioPag := cdsPaymentType.FieldByName('IDMeioPag').AsInteger;
Result := True;
FResult := True;
end
else if cdsPaymentType.RecordCount = 0 then
begin
MsgBox(MSG_CRT_PAYMENT_NOT_EXIST, vbCritical + vbOKOnly);
Result := True;
FResult := False;
end;
end;
procedure TFrmListPayments.btCloseClick(Sender: TObject);
begin
inherited;
FResult := False;
FIDMeioPag := -1;
Close;
end;
procedure TFrmListPayments.btnOKClick(Sender: TObject);
begin
inherited;
FResult := True;
FIDMeioPag := cdsPaymentType.FieldByName('IDMeioPag').AsInteger;
end;
procedure TFrmListPayments.FormCreate(Sender: TObject);
begin
inherited;
OpenPayment;
end;
procedure TFrmListPayments.FormDestroy(Sender: TObject);
begin
inherited;
ClosePayment;
end;
procedure TFrmListPayments.PaymentTypeFilter;
begin
with cdsPaymentType do
begin
Filtered := False;
Filter := 'Tipo = ' + IntToStr(FIDMeioPagTipo);
Filtered := True;
end;
end;
procedure TFrmListPayments.SetCashBack;
begin
if cdsPaymentType.FieldByName('IDMeioPag').AsInteger = PAYMENT_TYPE_CASHBACK then
begin
FIDMeioPagTipo := PAYMENT_TYPE_CASHBACK;
FIDMeioPag := PAY_TYPE_CASH;
end;
end;
procedure TFrmListPayments.CreateCashBackPayment;
begin
with cdsPaymentType do
if Active then
begin
Append;
FieldByName('IDMeioPag').AsInteger := PAYMENT_TYPE_CASHBACK;
FieldByName('Tipo').AsInteger := PAYMENT_TYPE_OTHER;
FieldByName('MeioPag').AsString := 'Cash Back';
Post;
end;
end;
end.
|
unit Form.CopyFile;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls,
Objekt.Dateikopieren;
type
Tfrm_CopyFile = class(TForm)
Bevel1: TBevel;
lbl_Von: TLabel;
lbl_Nach: TLabel;
pg: TProgressBar;
Bevel2: TBevel;
btn_Cancel: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btn_CancelClick(Sender: TObject);
private
fDateiKopieren: TDateiKopieren;
fOnAfterCopy: TNotifyEvent;
procedure DoProgress(aFileSize, aBytesTransferred: Int64);
procedure FileSize(aFileSize: Int64);
procedure AfterCopy(Sender: TObject);
public
property OnAfterCopy: TNotifyEvent read fOnAfterCopy write fOnAfterCopy;
procedure CopyFile(aSource, aDest: String);
end;
var
frm_CopyFile: Tfrm_CopyFile;
implementation
{$R *.dfm}
procedure Tfrm_CopyFile.FormCreate(Sender: TObject);
var
HR: HRgn;
// p:array[0..3] of TPoint;
begin
fDateiKopieren := TDateiKopieren.Create;
fDateiKopieren.OnFileSize := FileSize;
fDateiKopieren.OnProgress := DoProgress;
fDateiKopieren.OnAfterCopy := AfterCopy;
{
p[0]:=Point(Width div 2,1);
p[1]:=Point(1, Height div 2);
p[2]:=Point(Width div 2,Height);
p[3]:=Point(Width, Height div 2);
}
{
p[0]:=Point(10,1);
p[1]:=Point(1, 10);
p[2]:=Point(10,Height);
p[3]:=Point(Width, 10);
}
//HR:= CreateEllipticRgn (0, 0, Width, Height);
//HR:= CreateRoundRectRgn (0, 0, clientWidth, clientHeight, 30, 30);
//SetWindowRgn(Handle, HR, True);
end;
procedure Tfrm_CopyFile.FormDestroy(Sender: TObject);
begin
FreeAndNil(fDateiKopieren);
end;
procedure Tfrm_CopyFile.AfterCopy(Sender: TObject);
begin
if Assigned(fOnAfterCopy) then
fOnAfterCopy(Self);
end;
procedure Tfrm_CopyFile.btn_CancelClick(Sender: TObject);
begin
fDateiKopieren.Cancel := true;
end;
procedure Tfrm_CopyFile.CopyFile(aSource, aDest: String);
begin
lbl_Von.Caption := 'Von: ' + aSource;
lbl_Nach.Caption := 'Nach: ' + aDest;
fDateiKopieren.CopyFile(aSource, aDest);
end;
procedure Tfrm_CopyFile.DoProgress(aFileSize, aBytesTransferred: Int64);
begin
pg.Position := aBytesTransferred;
Application.ProcessMessages;
end;
procedure Tfrm_CopyFile.FileSize(aFileSize: Int64);
begin
pg.Position := 0;
pg.Max := aFileSize;
end;
end.
|
unit uEarlyConfig;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
var
{$IFDEF DARKWIN}
gAppMode: Integer = 1;
{$ENDIF}
gSplashForm: Boolean = True;
procedure SaveEarlyConfig;
implementation
uses
DCOSUtils, DCStrUtils, DCClassesUtf8, uSysFolders;
var
AConfig: String;
function GetEarlyConfig: String;
var
Index: Integer;
begin
for Index:= 1 to ParamCount do
begin
if StrBegins(ParamStr(Index), '--config-dir=') then
begin
Result:= Copy(ParamStr(Index), 14, MaxInt);
Result:= IncludeTrailingBackslash(Result) + ApplicationName + ConfigExtension;
Exit;
end;
end;
Result:= ExtractFilePath(ParamStr(0));
if mbFileExists(Result + ApplicationName + '.inf') then
Result:= Result + ApplicationName + ConfigExtension
else begin
Result:= IncludeTrailingBackslash(GetAppConfigDir) + ApplicationName + ConfigExtension;
end;
end;
procedure Initialize;
begin
AConfig:= GetEarlyConfig;
if mbFileExists(AConfig) then
try
with TStringListEx.Create do
try
LoadFromFile(AConfig);
gSplashForm:= StrToBoolDef(Values['SplashForm'], gSplashForm);
{$IFDEF DARKWIN}
gAppMode:= StrToIntDef(Values['DarkMode'], gAppMode);
{$ENDIF}
finally
Free;
end;
except
// Skip
end;
end;
procedure SaveEarlyConfig;
begin
AConfig:= GetEarlyConfig;
ForceDirectories(ExtractFileDir(AConfig));
with TStringListEx.Create do
try
Add('SplashForm' + NameValueSeparator + BoolToStr(gSplashForm));
{$IFDEF DARKWIN}
AddPair('DarkMode', IntToStr(gAppMode));
{$ENDIF}
SaveToFile(AConfig);
finally
Free;
end;
end;
initialization
Initialize;
end.
|
{$A+,B-,D+,E+,F-,G-,I-,L+,N+,O-,P-,Q-,R-,S-,T-,V-,X+,Y+}
{$M 65384,0,655360}
{29þ Compre barato y Compre m s barato Turqu¡a 1999
ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ
El anuncio de " compre barato" es la f¢rmula del ‚xito en los
supermercados. Pero para ser considerado un gran comprador usted
tambi‚n tiene que seguir la premisa de: "Comprar barato, pero aun m s
barato".
Esto es, cada vez que usted compre un producto, este tiene que tener
un precio m s barato que la £ltima vez que usted compr¢ un producto.
Mientras m s veces usted compre a menos precio usted ser considerado
un mejor comprador.
A usted le ser n dados los precios diarios de venta de un producto por
muchos d¡as. Usted puede comprar m s de una vez un producto en varios
d¡as; recuerde que cada vez que usted compre el producto, el precio
debe ser menor que el d¡a previo que usted compr¢ el producto.
Su tarea ser escribir un programa el cual identifique cu les d¡as
usted debe comprar un producto (siguiendo la regla del p rrafo
anterior) para maximizar el n£mero de veces que usted comprar .
Por ejemplo, suponga que en d¡as sucesivos los precios de venta de un
producto son:
D¡a 1 2 3 4 5 6 7 8 9 10 11 12
Precio 68 69 54 70 68 64 70 62 67 78 98 87
En el ejemplo de arriba, el mejor puede comprar como m ximo 4 veces si
sigue la regla de que cada compra tiene un precio menor que la previa.
Los cuatro d¡as en esta secuencia son:
D¡a 4 5 6 8 ¢ D¡a 2 5 6 8
Precio 70 68 64 62 Precio 69 68 64 62
Archivo de Entrada
Contiene en la primera l¡nea el n£mero N de d¡as (1 <= N <= 5000). En
las pr¢xim s N l¡neas en cada una se escribir el precio (un entero
positivo) del producto en cada d¡a.
Archivo de Salida
Contendr en una l¡nea dos enteros positivos separados por un espacio
en blanco. El primero la longitud de la secuencia m s larga de precios
decrecientes. El segundo, el n£mero de secuencias que tienen esa
longitud. Dos soluciones son consideradas iguales si ellas repiten la
misma cadena de precios descendentes aunque sean encontradas en d¡as
diferentes.
ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿ ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
³ Ejemplo de Entrada ³ ³ Ejemplo de Salida ³
ÃÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ´ ÃÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ´
³ 12 ³ ³ 4 2 ³
³ 68 ³ ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
³ 69 ³
³ 54 ³
³ 70 ³
³ 68 ³
³ 64 ³
³ 70 ³
³ 62 ³
³ 67 ³
³ 78 ³
³ 98 ³
³ 87 ³
ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
}
var
fe,fs : text;
n,sol,max : integer;
a,res,c : array[1..5001] of integer;
procedure open;
begin
assign(fe,'tur029.in'); reset(fe);
assign(fs,'tur029.out'); rewrite(fs);
end;
procedure work;
var
i,j,p,s : integer;
begin
sol:=0; max:=0;
readln(fe,n);
for i:=n downto 1 do
begin
c[i]:=1;
readln(fe,a[i]);
for j:=i+1 to n do
if (a[i] < a[j]) then
begin
if (res[j] > res[i]) then
begin
res[i]:=res[j];
c[i]:=c[j];
p:=a[j];
end
else
if (res[i] = res[j]) and (a[j] <> p) then
begin
c[i]:=c[i] + c[j];
p:=a[j];
end;
end;
inc(res[i]);
if res[i] > sol then
begin
sol:=res[i];
max:=c[i];
s:=i;
end
else
if (res[i]=sol) and (a[s] <> a[i]) then
max:=max + c[i];
end;
close(fe);
end;
procedure closer;
begin
writeln(fs,sol,' ',max);
close(fs);
end;
begin
open;
work;
closer;
end. |
unit ufraSellingPrice;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, Math, uRetnoUnit,
ActnList, uFormProperty, System.Actions, cxGridCustomTableView,
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB,
cxDBData, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses,
cxGridCustomView, cxGrid, cxContainer, cxTextEdit, cxCurrencyEdit,
Vcl.Menus, cxButtons, cxLabel, Vcl.StdCtrls;
type
TSaveMode = (smAdd,smEdit);
TfraSellingPrice = class(TFrame)
pnl4: TPanel;
pnl1: TPanel;
lblClose: TcxLabel;
lblAdd: TcxLabel;
lblDelete: TcxLabel;
pnlAddEdit: TPanel;
lbl1: TLabel;
lbl2: TLabel;
lbl3: TLabel;
lbl4: TLabel;
cbbUOM: TComboBox;
jvcuredtSellPrice: TcxCurrencyEdit;
lbl42: TLabel;
fedtDiscPercent: TcxCurrencyEdit;
jvcuredtDiscNominal: TcxCurrencyEdit;
lbl7: TLabel;
jvcuredtSellPriceDisc: TcxCurrencyEdit;
lbl10: TLabel;
lbl11: TLabel;
cbbPriceType: TComboBox;
pnl3: TPanel;
lbl5: TLabel;
lbl8: TLabel;
chkIsLimit: TCheckBox;
chkIsADS: TCheckBox;
jvcuredtPriceLimit: TcxCurrencyEdit;
jvcuredtPriceADS: TcxCurrencyEdit;
lblEdit: TcxLabel;
intedtQtyLimit: TcxCurrencyEdit;
intedtQtyADS: TcxCurrencyEdit;
lbl13: TLabel;
lbl14: TLabel;
fedtQty: TcxCurrencyEdit;
Label1: TLabel;
jvcuredtSellPriceCoret: TcxCurrencyEdit;
fedtMarkUp: TcxCurrencyEdit;
chkIsMailer: TCheckBox;
lblMaxQtyDisc: TLabel;
edtMaxQtyDisc: TcxCurrencyEdit;
Label2: TLabel;
Label3: TLabel;
edtUomPurchase: TEdit;
edtUOMSTock: TEdit;
edtPurchPrice: TcxCurrencyEdit;
edtAVGPrice: TcxCurrencyEdit;
Label4: TLabel;
edtSellMargin: TcxCurrencyEdit;
actSellPrice: TActionList;
actAddSellPrice: TAction;
Label6: TLabel;
lblView: TcxLabel;
Label5: TLabel;
cxGrid: TcxGrid;
cxGridViewSellingPrice: TcxGridDBTableView;
cxGridLevel1: TcxGridLevel;
cxGridViewSellingPriceColumn1: TcxGridDBColumn;
cxGridViewSellingPriceColumn2: TcxGridDBColumn;
cxGridViewSellingPriceColumn3: TcxGridDBColumn;
cxGridViewSellingPriceColumn4: TcxGridDBColumn;
cxGridViewSellingPriceColumn5: TcxGridDBColumn;
cxGridViewSellingPriceColumn6: TcxGridDBColumn;
cxGridViewSellingPriceColumn7: TcxGridDBColumn;
cxGridViewSellingPriceColumn8: TcxGridDBColumn;
cxGridViewSellingPriceColumn9: TcxGridDBColumn;
cxGridViewSellingPriceColumn10: TcxGridDBColumn;
cxGridViewSellingPriceColumn11: TcxGridDBColumn;
cxGridViewSellingPriceColumn12: TcxGridDBColumn;
cxGridViewSellingPriceColumn13: TcxGridDBColumn;
cxGridViewSellingPriceColumn14: TcxGridDBColumn;
cxGridViewSellingPriceColumn15: TcxGridDBColumn;
cxCurrencyEdit1: TcxCurrencyEdit;
btnCancel: TcxButton;
btnSave: TcxButton;
procedure lblCloseClick(Sender: TObject);
procedure lblAddClick(Sender: TObject);
procedure lblEditClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure chkIsLimitClick(Sender: TObject);
procedure chkIsADSClick(Sender: TObject);
procedure jvcuredtSellPriceChange(Sender: TObject);
procedure lblDeleteClick(Sender: TObject);
procedure fedtMarkUpChange(Sender: TObject);
procedure fedtDiscPercentExit(Sender: TObject);
procedure cbbUOMExit(Sender: TObject);
procedure jvcuredtDiscNominalExit(Sender: TObject);
// procedure actAddSellPriceExecute(Sender: TObject);
procedure Action1Execute(Sender: TObject);
procedure lblViewClick(Sender: TObject);
procedure cbbPriceTypeKeyPress(Sender: TObject; var Key: Char);
procedure cbbUOMKeyPress(Sender: TObject; var Key: Char);
procedure fedtQtyKeyPress(Sender: TObject; var Key: Char);
procedure jvcuredtSellPriceKeyPress(Sender: TObject; var Key: Char);
procedure fedtDiscPercentKeyPress(Sender: TObject; var Key: Char);
procedure jvcuredtDiscNominalKeyPress(Sender: TObject; var Key: Char);
procedure jvcuredtSellPriceDiscKeyPress(Sender: TObject;
var Key: Char);
procedure jvcuredtSellPriceCoretKeyPress(Sender: TObject;
var Key: Char);
procedure edtSellMarginKeyPress(Sender: TObject; var Key: Char);
procedure chkIsLimitKeyPress(Sender: TObject; var Key: Char);
procedure intedtQtyLimitKeyPress(Sender: TObject; var Key: Char);
procedure jvcuredtPriceLimitKeyPress(Sender: TObject; var Key: Char);
procedure chkIsADSExit(Sender: TObject);
procedure chkIsLimitExit(Sender: TObject);
procedure chkIsADSKeyPress(Sender: TObject; var Key: Char);
procedure intedtQtyADSKeyPress(Sender: TObject; var Key: Char);
procedure jvcuredtPriceADSKeyPress(Sender: TObject; var Key: Char);
procedure chkIsMailerExit(Sender: TObject);
procedure chkIsMailerKeyPress(Sender: TObject; var Key: Char);
procedure cxGridViewSellingPriceEditing(Sender: TcxCustomGridTableView; AItem:
TcxCustomGridTableItem; var AAllow: Boolean);
procedure fedtMarkUpKeyPress(Sender: TObject; var Key: Char);
procedure edtMaxQtyDiscKeyPress(Sender: TObject; var Key: Char);
procedure edtSellMarginExit(Sender: TObject);
private
SaveMode: TSaveMode;
// FBHJ : TBarangHargaJual;
// FBarang : TNewBarang;
FProductCode: string;
FLastCogs: Real;
FUOMLama: string;
sScale : TStrings;
sKodeUOM : TStrings;
sKodeBarang : String;
iIDBarang : Integer;
sUomBuy : string;
dUomBuyConv : Double;
//arrIdTpHarga: array of Integer;
//arrSatuan: array of record
// Code : String;
// Scale : Real;
// end;
procedure SetProductCode(const Value: string);
procedure SetLastCogs(const Value: Real);
procedure ParseDataGrid();
procedure ParseDataComboPriceType();
procedure SetDiscon(isDiscPersen: Boolean);
function AddData(): Boolean;
procedure SetMarkUp;
procedure SetSellingMargin;
procedure AdvColGrdAddCheckBox(aCol: integer; aRow: integer; aValue: integer);
procedure SetAttributDefault;
procedure SetAttributEnable(aValue: Boolean);
procedure SetAttributReadOnly(aValue: Boolean);
// function EditData(intID: Integer): Boolean;
// function DeleteData(intID: Integer): Boolean;
public
// FSelfIsStore: Integer;
FSelfUnitId : Integer;
FTpApp : TTipeApp;
function getBarisKosong: Integer;
function GetHasilCheckBox(checkBox: TCheckBox): Integer;
function GetIDBArangFromKode(kodeBarang: String): Integer;
procedure ParseDataCbbUOM;
procedure setCheckBox(checkBox: TCheckBox; aNilai : Integer);
procedure ShowSellingPrice(AProductCode: String);
published
property ProductCode: string read FProductCode write SetProductCode;
property LastCOGS: Real read FLastCogs write SetLastCogs;
end;
var
fraSellingPrice: TfraSellingPrice;
const
_kolBHJSatCode = 0;
_kolBHJConvValue = 1;
_kolTPHRGName = 2;
_kolBHJSellPrice = 3;
_kolBHJDiscPersen = 4;
_kolBHJDiscNominal = 5;
_kolBHJSellPriceDisc = 6;
_kolBHJIsLimitQTY = 7;
_KolBHJIsQtySubsidy = 8;
_kolID = 14;
_kolIsMailer = 9;
_kolPurChaseRp = 10;
_kolPurchaseUom = 11;
_kolAvgRp = 12;
_kolAvgUom = 13;
implementation
uses uConn, ufrmProduct, uTSCommonDlg, uConstanta, ufraProductSupplier;
{$R *.dfm}
{ TfraSellingPrice }
procedure TfraSellingPrice.AdvColGrdAddCheckBox(aCol: integer; aRow: integer; aValue: integer);
begin
{
if aValue = 1 then
strgGrid.AddCheckBox(aCol , aRow, True , False)
else
strgGrid.AddCheckBox(aCol, aRow, False , False);
strgGrid.Alignments[aCol,aRow] := taCenter;
}
end;
procedure TfraSellingPrice.SetProductCode(const Value: string);
begin
FProductCode := Value;
end;
procedure TfraSellingPrice.SetLastCogs(const Value: Real);
begin
FLastCogs:= Value;
end;
procedure TfraSellingPrice.ParseDataComboPriceType();
var
sSQL: string;
begin
sSQL := ' select REF$TIPE_HARGA_ID, TPHRG_NAME '
+ ' from ref$tipe_HArga '
+ ' where TPHRG_UNT_ID = ' + IntToStr(FSelfUnitId);
// cQueryToComboObject(cbbPriceType, sSQL);
end;
procedure TfraSellingPrice.ShowSellingPrice(AProductCode: String);
var
sUOMLastPrice: string;
dLastPrice: Double;
dQtyConv : Double;
begin
if FTpApp = TSTORE then
begin
pnlAddEdit.Enabled := False
end
else
begin
pnlAddEdit.Enabled := True;
end;
lblAdd.Enabled := pnlAddEdit.Enabled;
lblEdit.Enabled := pnlAddEdit.Enabled;
lblDelete.Enabled := pnlAddEdit.Enabled;
// FBHJ := TBarangHargaJual.Create(Self);
// FBarang := TNewBarang.Create(Self);
sScale := TStringList.Create;
sKodeUOM := TStringList.Create;
sKodeBarang := frmProduct.cbpProductCode.Text;
iIDBarang := GetIDBArangFromKode(sKodeBarang);
// FBarang.LoadByKode(sKodeBarang);
// edtAVGPrice.Value := FBarang.HargaAverage;
// edtUOMStock.Text := FBarang.KodeSatuanStock.UOM;
// FBarang.GetLastPurchasePrice(dLastPrice,sUOMLastPrice);
edtPurchPrice.Value := dLastPrice;
edtUomPurchase.Text := sUOMLastPrice;
// fedtMarkUp.Value := RoundTo(FBarang.DefaultMarkUP,-2);
pnlAddEdit.Visible := false;
sUomBuy := edtUomPurchase.Text;
// dQtyConv := GetQtyConv(sUomBuy, sKodeBarang);
if dQtyConv <= 0 then
dQtyConv := 1;
dUomBuyConv := 1 / dQtyConv;
ParseDataGrid;
ParseDataComboPriceType;
cxGrid.SetFocus;
ParseDataCbbUOM;
end;
procedure TfraSellingPrice.lblCloseClick(Sender: TObject);
begin
fraSellingPrice.Parent := nil;
if (assigned(fraProductSupplier)) and (fraProductSupplier.Parent <> nil) then
begin
frmProduct.actProductSupplierExecute(nil);
end
else
frmProduct.SetActiveFooter5Button(True);
end;
procedure TfraSellingPrice.lblAddClick(Sender: TObject);
begin
if FSelfUnitId=0 then
begin
CommonDlg.ShowError('UNIT BELUM DIPILIH');
//frmMain.cbbUnit.SetFocus;
Exit;
end;
FUOMLama := '';
cbbPriceType.ItemIndex := cbbPriceType.Items.IndexOf('TOKO');
// jvcuredtSellPrice.Value := FBarang.GetSellPricePrice;
fedtDiscPercent.Value := 0;
jvcuredtDiscNominal.Value := 0;
jvcuredtSellPriceDisc.Value := 0;
chkIsLimit.Checked := False;
intedtQtyLimit.Value := 0;
jvcuredtPriceLimit.Value := 0;
chkIsLimitClick(Self);
chkIsADS.Checked := False;
intedtQtyADS.Value := 0;
jvcuredtPriceADS.Value := 0;
jvcuredtSellPriceCoret.Value:= 0;
cbbUOMExit(nil);
chkIsADSClick(Self);
SaveMode := smAdd;
pnlAddEdit.Visible := True;
end;
procedure TfraSellingPrice.lblEditClick(Sender: TObject);
var BHJID: Integer;
sUOMLastPurchase: string;
dLastPurchase: Double;
begin
SetAttributReadOnly(False);
SetAttributEnable(True);
// SetAttributDefault;
if FSelfUnitId=0 then
begin
CommonDlg.ShowError('UNIT BELUM DIPILIH');
//frmMain.cbbUnit.SetFocus;
Exit;
end;
{
if FBHJ.LoadByID(BHJID, FSelfUnitId) then
begin
FUOMLama := FBHJ.NewUOM.UOM;
cSetItemAtComboObject(cbbPriceType,FBHJ.TipeHargaID);
cSetItemAtComboObjectCode(cbbUOM, FBHJ.NewUOM.UOM);
fedtQty.Value := FBHJ.KonversiValue;
jvcuredtSellPrice.Value := FBHJ.SellPrice;
fedtDiscPercent.Value := FBHJ.DiscPersen;
jvcuredtDiscNominal.Value := FBHJ.DiscNominal;
jvcuredtSellPriceDisc.Value := FBHJ.SellPriceDisc;
jvcuredtSellPriceCoret.Value := FBHJ.SellPriceCoret;
setCheckBox(chkIsLimit,FBHJ.IsLimitQty);
intedtQtyLimit.Value := FBHJ.LimitQty;
jvcuredtPriceLimit.Value := FBHJ.LimitQtyPrice;
setCheckBox(chkIsADS,FBHJ.IsQtySubsidy);
intedtQtyADS.Value := FBHJ.QtySubsidy;
jvcuredtPriceADS.Value := FBHJ.QtySubsidyPrice;
edtMaxQtyDisc.Value := FBHJ.MaxQtyDisc;
chkIsMailer.Checked := FBHJ.IsMailer = 1;
edtAVGPrice.Value := FBHJ.NewBarang.HargaAverage;
edtUOMStock.Text := FBHJ.NewBarang.KodeSatuanStock.UOM;
FBHJ.NewBarang.GetLastPurchasePrice(dLastPurchase,sUOMLastPurchase);
edtPurchPrice.Value := dLastPurchase;
edtUomPurchase.Text := sUOMLastPurchase;
chkIsADSClick(Self);
SaveMode:= smEdit;
cbbUOMExit(nil);
end else
CommonDlg.ShowMessage('Tidak bisa load Data');
}
pnlAddEdit.Visible := true;
end;
procedure TfraSellingPrice.btnCancelClick(Sender: TObject);
begin
pnlAddEdit.Visible := false;
end;
function TfraSellingPrice.AddData(): Boolean;
var
iIsMailer: Integer;
aTipeHargaID: Integer;
aSellPriceDisc: Double;
aSellPriceCoret: Double;
aSellPrice: Double;
aRemark: string;
aQtySubsidyPrice: Double;
aQtySubsidy: Integer;
aUOM: string;
aNewUnit_ID: Integer;
aNewBarangKode: string;
aMarkUp: Double;
aLimitQtyPrice: Double;
aLimitQty: Integer;
aKonversiValue: Double;
aIsQtySubsidy: Integer;
aIsLimitQty: Integer;
aID: Integer;
aDiscPersen: Double;
aDiscNominal: Double;
aAlokasiDanaSupplierID: Integer;
begin
Result := False;
{if SaveMode = smAdd then
aID := 0
else
aID := FBHJ.ID;
aAlokasiDanaSupplierID := 0; // he he he ...........
aDiscNominal := jvcuredtDiscNominal.Value;
aDiscPersen := fedtDiscPercent.Value;
aIsLimitQty := GetHasilCheckBox(chkIsLimit);
aIsQtySubsidy := GetHasilCheckBox(chkIsADS);
aKonversiValue := fedtQty.Value;
aLimitQty := Floor( intedtQtyLimit.Value);
aLimitQtyPrice := jvcuredtPriceLimit.Value;
aMarkUp := fedtMarkUp.Value;
aNewBarangKode := sKodeBarang ;
aNewUnit_ID := FSelfUnitId;
aUOM := cGetIDfromComboCode(cbbUOM);
aQtySubsidy := Floor(intedtQtyADS.Value);
aQtySubsidyPrice := jvcuredtPriceADS.Value;
aRemark := '';
aSellPrice := jvcuredtSellPrice.Value ;
aSellPriceCoret := jvcuredtSellPriceCoret.Value;
aSellPriceDisc := jvcuredtSellPriceDisc.Value;
aTipeHargaID := cGetIDfromCombo(cbbPriceType) ;
if FUOMLama <> aUOM then
begin
if IsUOMSudahAdaTransaksi(FBHJ.NewBarang.Kode, FBHJ.NewUOM.UOM) then
begin
CommonDlg.ShowError('Setting Harga Tidak Bisa Diubah' + #13 + 'Sudah Ada Transaksi Yang Memakai Setting Harga Tersebut');
cRollbackTrans;
Exit;
end;
end;
if FBHJ.IsSettingHargaJualSudahAda(FSelfUnitId, aNewBarangKode, aUOM, aTipeHargaID, aID) then
begin
CommonDlg.ShowError('Barang, Satuan , Dan Tipe Harga Sudah Diinput');
cbbUOM.SetFocus;
Exit;
end;
if (aSellPrice < 0) or (aSellPriceDisc < 0) or (aSellPriceCoret < 0) then
begin
CommonDlg.ShowMessage('Tidak boleh ada nilai minus');
Exit;
end;
iIsMailer := 0;
if chkIsMailer.Checked then
iIsMailer := 1;
FBHJ.UpdateData(
aAlokasiDanaSupplierID,
aDiscNominal,
aDiscPersen,
aID,
aIsLimitQty,
aIsQtySubsidy,
aKonversiValue,
aLimitQty,
aLimitQtyPrice,
aMarkUp,
aNewBarangKode,
aNewUnit_ID,
aUOM,
aQtySubsidy,
aQtySubsidyPrice,
aRemark,
aSellPrice,
aSellPriceCoret,
aSellPriceDisc,
aTipeHargaID,
iIsMailer,
edtMaxQtyDisc.Value);
try
// if FBHJ.ExecuteGenerateSQL then
if FBHJ.ExecuteGenerateSQLByUnit then
begin
// if not IsUOMSudahAdaKonversi(FBHJ.NewBarang.Kode, FBHJ.NewUOM.UOM, FBHJ.NewUnit.ID) then
// begin
// CommonDlg.ShowError('KOnversi UOM ' + FBHJ.NewUOM.UOM + ' Tidak Ditemukan');
// Exit;
// cRollbackTrans;
// end;
//
cCommitTrans;
Result := True;
CommonDlg.ShowMessage('Berhasil Menyimpan Data');
ParseDataGrid;
end
else begin
cRollbackTrans;
CommonDlg.ShowMessage('Gagal Menyimpan Data');
end;
finally
cRollbackTrans;
end;
pnlAddEdit.Visible := false;
}
end;
procedure TfraSellingPrice.btnSaveClick(Sender: TObject);
begin
if cbbUOM.Text='' then
begin
CommonDlg.ShowError('UOM Belum Dipilih');
cbbUOM.SetFocus;
Exit;
end;
if fedtQty.Value <= 0 then
begin
CommonDlg.ShowError('Konversi UOM Masih Salah');
fedtQty.SetFocus;
Exit;
end;
// if IsUOMSudahAdaTransaksi(frmProduct.cbpProductCode.Text, cGetIDfromComboCode(cbbUOM)) then
// begin
// CommonDlg.ShowError('Setting Harga Tidak Bisa Disimpan' + #13 + 'KonversiUOM Tidak Ditemukan');
// cRollbackTrans;
// Exit;
// end;
cbbUOMExit(nil);
AddData;
end;
procedure TfraSellingPrice.ParseDataGrid;
var //data: TResultDataSet;
iBaris : Integer;
sSQL : string;
sBrgCode : string;
sUom : string;
dHrgAvg : Double;
sUomAvg : string;
dPurch : Double;
sUomPurch : string;
// i: Integer;
begin
dHrgAvg := 0;
dPurch := 0;
// cClearGrid(strgGrid,False);
sSQL := 'SELECT BHJ.BHJ_SAT_CODE, BHJ.BHJ_CONV_VALUE, TH.TPHRG_NAME, BHJ.BHJ_SELL_PRICE, '
+ ' BHJ.BHJ_DISC_PERSEN, BHJ.BHJ_DISC_NOMINAL, BHJ.BHJ_SELL_PRICE_DISC, '
+ ' BHJ.BHJ_IS_LIMIT_QTY, BHJ.BHJ_IS_QTY_SUBSIDY, BHJ.BHJ_ID,'
+ ' BHJ.BHJ_IS_MAILER, BHJ.BHJ_BRG_CODE'
+ ' FROM BARANG_HARGA_JUAL BHJ '
+ ' LEFT JOIN REF$TIPE_HARGA TH ON BHJ.BHJ_TPHRG_ID=TH.TPHRG_ID '
+ ' AND BHJ.BHJ_TPHRG_UNT_ID=TH.TPHRG_UNT_ID '
+ ' WHERE BHJ.BHJ_BRG_CODE = ' + QuotedStr(sKodeBarang)
+ ' and BHJ.BHJ_UNT_ID = ' + intTostr(FSelfUnitId);
{with cOpenQuery(sSQL) do
begin
try
iBaris := getBarisKosong;
if iBaris = 0 then
begin
strgGrid.AddRow;
iBaris := strgGrid.RowCount - 1;
end;
if not Eof then
begin
sBrgCode := FieldByName('BHJ_BRG_CODE').AsString;
sSQL := 'SELECT BRG_HARGA_AVERAGE, BRG_SAT_CODE_STOCK'
+ ' FROM BARANG'
+ ' WHERE BRG_CODE = '+ Quot(sBrgCode);
with cOpenQuery(sSQL) do
begin
try
dHrgAvg := Fields[0].AsFloat;
sUomAvg := Fields[1].AsString;
finally
Free;
end;
end;
sSQL := 'select b.dod_price,b.dod_sat_code_order '
+ ' from dord a,do_detil b'
+ ' where a.do_no = b.dod_do_no'
+ ' and a.do_unt_id = b.dod_do_unt_id'
+ ' and a.do_unt_id = ' + IntToStr(FSelfUnitId)
+ ' and b.dod_qty_order_recv <> 0'
+ ' and b.dod_brg_code = ' + Quot(sBrgCode)
+ ' order by a.do_date desc';
with cOpenQuery(sSQL) do
begin
try
dPurch := Fields[0].AsFloat;
sUomPurch := Fields[1].AsString;
finally
free;
end;
end;
end;
while not Eof do
begin
strgGrid.Cells[_kolBHJSatCode, iBaris] := FieldByName('BHJ_SAT_CODE').AsString;
strgGrid.Cells[_kolBHJConvValue, iBaris] := FieldByName('BHJ_CONV_VALUE').AsString;
strgGrid.Cells[_kolTPHRGName, iBaris] := FieldByName('TPHRG_NAME').AsString;
strgGrid.Cells[_kolBHJSellPrice, iBaris] := FieldByName('BHJ_SELL_PRICE').AsString;
strgGrid.Cells[_kolBHJDiscPersen, iBaris] := FieldByName('BHJ_DISC_PERSEN').AsString;
strgGrid.Cells[_kolBHJDiscNominal, iBaris] := FieldByNAme('BHJ_DISC_NOMINAL').AsString;
strgGrid.Cells[_kolBHJSellPriceDisc, iBaris] := FieldByName('BHJ_SELL_PRICE_DISC').AsString;
// strgGrid.Cells[_kolBHJIsLimitQty, iBaris] := FieldByName('BHJ_IS_LIMIT_QTY').AsString;
AdvColGrdAddCheckBox(_kolBHJIsLimitQty, iBaris, FieldByName('BHJ_IS_LIMIT_QTY').AsInteger);
// strgGrid.Cells[_kolBHJisQtySubsidy, iBaris] := FieldByName('BHJ_IS_QTY_SUBSIDY').AsString;
AdvColGrdAddCheckBox(_kolBHJisQtySubsidy, iBaris, FieldByName('BHJ_IS_QTY_SUBSIDY').AsInteger);
// strgGrid.Cells[_kolIsMailer, iBaris] := FieldByName('BHJ_IS_MAILER').AsString;
AdvColGrdAddCheckBox(_kolIsMailer, iBaris, FieldByName('BHJ_IS_MAILER').AsInteger);
sUom := FieldByName('BHJ_SAT_CODE').AsString;
strgGrid.Cells[_kolPurChaseRp, iBaris] := FormatFloat('#,###,##0.00', dPurch);
strgGrid.Cells[_kolPurchaseUom, iBaris] := sUomPurch;
strgGrid.Cells[_kolAvgRp, iBaris] := FormatFloat('#,###,##0.00',
dHrgAvg * GetQtyConvFromTo(sUom, sUomAvg, sBrgCode));
strgGrid.Cells[_kolAvgUom, iBaris] := sUomAvg;
strgGrid.Cells[_kolID, iBaris] := FieldByName('BHJ_ID').AsString;
Next;
if not Eof then
begin
strgGrid.AddRow;
Inc(iBaris);
end;
end;
finally
Free;
end;
end;
strgGrid.ColWidths[_kolID] := 0;
strgGrid.ColWidths[_kolPurChaseRp] := 0;
strgGrid.ColWidths[_kolPurchaseUom] := 0;
strgGrid.ColWidths[_kolAvgRp] := 0;
strgGrid.ColWidths[_kolAvgUom] := 0;
}
end;
procedure TfraSellingPrice.chkIsLimitClick(Sender: TObject);
begin
if chkIsLimit.Checked then
begin
intedtQtyLimit.Enabled:= True;
jvcuredtPriceLimit.Enabled:= True;
end
else
begin
intedtQtyLimit.Enabled:= False;
jvcuredtPriceLimit.Enabled:= False;
end;
end;
procedure TfraSellingPrice.chkIsADSClick(Sender: TObject);
begin
if chkIsADS.Checked then
begin
intedtQtyADS.Enabled:= True;
jvcuredtPriceADS.Enabled:= True;
end
else
begin
intedtQtyADS.Enabled:= False;
jvcuredtPriceADS.Enabled:= False;
end;
end;
procedure TfraSellingPrice.SetDiscon(isDiscPersen: Boolean);
begin
{
jvcuredtSellPriceDisc.Value := (((100 - fedtDiscPercent.Value) / 100) *
jvcuredtSellPrice.Value) - jvcuredtDiscNominal.Value;
}
if isDiscPersen then
jvcuredtDiscNominal.Value := jvcuredtSellPrice.Value * fedtDiscPercent.Value / 100
else if jvcuredtSellPrice.Value <> 0 then
fedtDiscPercent.Value := jvcuredtDiscNominal.Value / jvcuredtSellPrice.Value * 100
else begin
fedtDiscPercent.Value := 0;
end;
jvcuredtSellPriceDisc.Value := (((100 - fedtDiscPercent.Value) / 100) *
jvcuredtSellPrice.Value);
end;
procedure TfraSellingPrice.jvcuredtSellPriceChange(Sender: TObject);
begin
SetDiscon(True);
SetMarkUp;
SetSellingMargin;
end;
procedure TfraSellingPrice.lblDeleteClick(Sender: TObject);
var //i: Integer;
bhjID: Integer;
// isChecked,isSuccesfully: Boolean;
begin
if (CommonDlg.Confirm('Are you sure you wish to delete detail selling price ?') = mrYes) then
begin
{try
bhjID := StrToInt(strgGrid.cells[_kolID,strgGrid.Row]);
if FBHJ.LoadByID(bhjID, FSelfUnitId) then
begin
if FBHJ.RemoveFromDB then
begin
if IsUOMSudahAdaTransaksi(FBHJ.NewBarang.Kode, FBHJ.NewUOM.UOM) then
begin
CommonDlg.ShowError('Setting Harga Tidak Bisa Dihapus' + #13 + 'Sudah Ada Transaksi Yang Memakai Setting Harga Tersebut');
cRollbackTrans;
Exit;
end;
cCommitTrans;
FUOMLama := '';
CommonDlg.ShowConfirm(atDelete)
end else begin
cRollbackTrans;
CommonDlg.ShowMessage('gagal menghapus data');
end;
end else begin
cRollbackTrans;
CommonDlg.ShowMessage('Barang tersebut tidak bisa ditampilkan ');
end;
finally
cRollbackTrans;
end; }
end;
ParseDataGrid;
end;
procedure TfraSellingPrice.fedtMarkUpChange(Sender: TObject);
//var MarkUpNominal: Real;
begin
{MarkUpNominal:= (fedtMarkUp.Value/100) * LastCOGS!;
jvcuredtSellPrice.Value:= LastCOGS + MarkUpNominal;
}
end;
procedure TfraSellingPrice.fedtDiscPercentExit(Sender: TObject);
begin
SetDiscon(True);
end;
function TfraSellingPrice.getBarisKosong: Integer;
var
i: Integer;
begin
Result := 0;
{ for i := 0 to strgGrid.RowCount - 1 do
begin
if strgGrid.Cells[2, i] = '' then
begin
Result := i;
Exit;
end;
end;
if (Result = 0) then
begin
strgGrid.AddRow;
Result := strgGrid.RowCount - 1;
end; }
end;
function TfraSellingPrice.GetHasilCheckBox(checkBox: TCheckBox): Integer;
begin
Result := 0;
if checkBox.Checked = True then
Result := 1
end;
function TfraSellingPrice.GetIDBArangFromKode(kodeBarang: String): Integer;
begin
Result := 0;
end;
procedure TfraSellingPrice.ParseDataCbbUOM;
var
// i: Integer;
sSQL: string;
begin
sScale := TStringList.Create;
sKodeUOM := TStringList.Create;
sSQL := ' select distinct a.konvsat_sat_code_from, b.sat_name '
+ ' from ref$konversi_satuan a, ref$satuan b '
+ ' where a.konvsat_brg_code = ' + Quotedstr(sKodeBarang)
+ ' and b.sat_Code = a.konvsat_sat_code_from ';
// cQueryToComboObjectCode(cbbUOM,sSQL);
end;
procedure TfraSellingPrice.setCheckBox(checkBox: TCheckBox; aNilai : Integer);
begin
if aNilai = 1 then
checkBox.Checked := True
else if aNilai = 0 then
checkBox.Checked := False;
end;
procedure TfraSellingPrice.cbbUOMExit(Sender: TObject);
var
sSQL: string;
begin
{edtUOMSTock.Text := cGetIDfromComboCode(cbbUOM);
sSQL := 'select distinct konvsat_scale '
+ ' from ref$Konversi_satuan '
+ ' where konvsat_sat_code_from = ' + Quot(cGetIDfromComboCode(cbbUOM))
+ ' and konvsat_brg_code = ' + Quot(sKodeBarang);
with cOpenQuery(sSQL) do
begin
try
if not FieldByName('konvsat_scale').IsNull then
fedtQty.Value:= StrToFloat(FieldByName('konvsat_scale').AsString)
else
fedtQty.Value := 0;
edtAVGPrice.Value := FBarang.HargaAverage * fedtQty.Value;
SetMarkUp;
SetSellingMargin;
finally
Free
end;
end; }
end;
procedure TfraSellingPrice.SetMarkUp;
var
dSelisihHarga: Double;
begin
dSelisihHarga := jvcuredtSellPrice.Value - edtAVGPrice.Value;
if edtAVGPrice.Value <> 0 then
fedtMarkUp.Value := RoundTo(dSelisihHarga / edtAVGPrice.Value * 100,-2)
else
fedtMarkUp.Value := 0;
end;
procedure TfraSellingPrice.SetSellingMargin;
var
dUomCurPrice : Double;
begin
if fedtQty.Value <> 0 then
dUomCurPrice := fedtQty.Value
else
dUomCurPrice := 1;
{
if FBarang.HargaAverage<>0 then
edtSellMargin.Value := RoundTo(((jvcuredtSellPrice.Value - FBarang.HargaAverage)
* 100 * dUomCurPrice * dUomBuyConv) / FBarang.HargaAverage,-2)
else
edtSellMargin.Value := 0;
}
end;
procedure TfraSellingPrice.jvcuredtDiscNominalExit(Sender: TObject);
begin
SetDiscon(False);
end;
procedure TfraSellingPrice.Action1Execute(Sender: TObject);
begin
if FSelfUnitId=0 then
begin
CommonDlg.ShowError('UNIT BELUM DIPILIH');
//frmMain.cbbUnit.SetFocus;
Exit;
end;
FUOMLama := '';
cbbPriceType.ItemIndex := cbbPriceType.Items.IndexOf('TOKO');
// jvcuredtSellPrice.Value := FBarang.GetSellPricePrice;
fedtDiscPercent.Value := 0;
jvcuredtDiscNominal.Value := 0;
jvcuredtSellPriceDisc.Value := 0;
chkIsLimit.Checked := False;
intedtQtyLimit.Value := 0;
jvcuredtPriceLimit.Value := 0;
chkIsLimitClick(Self);
chkIsADS.Checked := False;
intedtQtyADS.Value := 0;
jvcuredtPriceADS.Value := 0;
cbbUOMExit(nil);
chkIsADSClick(Self);
SaveMode := smAdd;
pnlAddEdit.Visible := True;
end;
procedure TfraSellingPrice.lblViewClick(Sender: TObject);
begin
lblEditClick(self);
SetAttributReadOnly(True);
SetAttributEnable(False);
SetAttributDefault;
end;
procedure TfraSellingPrice.SetAttributDefault;
begin
fedtqty.Properties.ReadOnly := True;
jvcuredtSellPriceDisc.Properties.ReadOnly := True;
edtSellMargin.Properties.ReadOnly := True;
fedtMarkUp.Properties.ReadOnly := True;
edtMaxQtyDisc.Properties.ReadOnly := True;
edtPurchPrice.Properties.ReadOnly := True;
edtUomPurchase.ReadOnly := True;
edtAvgPrice.Properties.ReadOnly := True;
edtUomStock.ReadOnly := True;
end;
procedure TfraSellingPrice.SetAttributEnable(aValue: Boolean);
begin
cbbPriceType.Enabled := aValue;
cbbUOM.Enabled := aValue;
chkIsLimit.Enabled := aValue;
chkIsADS.Enabled := aValue;
chkIsMailer.Enabled := aValue;
btnSave.Enabled := aValue;
btnCancel.Enabled := aValue;
end;
procedure TfraSellingPrice.SetAttributReadOnly(aValue: Boolean);
begin
jvcuredtSellPrice.Properties.ReadOnly := aValue;
fedtDiscPercent.Properties.ReadOnly := aValue;
jvcuredtDiscNominal.Properties.ReadOnly := aValue;
jvcuredtSellPriceCoret.Properties.ReadOnly := aValue;
intedtQtyLimit.Properties.ReadOnly := aValue;
intedtQtyADS.Properties.ReadOnly := aValue;
jvcuredtPriceLimit.Properties.ReadOnly := aValue;
jvcuredtPriceADS.Properties.ReadOnly := aValue;
end;
procedure TfraSellingPrice.cbbPriceTypeKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
cbbUOM.SetFocus;
cbbUOM.SelectAll;
end;
end;
procedure TfraSellingPrice.cbbUOMKeyPress(Sender: TObject; var Key: Char);
var
sSQL: string;
begin
{
edtUOMSTock.Text := cGetIDfromComboCode(cbbUOM);
sSQL := 'select distinct konvsat_scale '
+ ' from ref$Konversi_satuan '
+ ' where konvsat_sat_code_from = ' + Quot(cGetIDfromComboCode(cbbUOM))
+ ' and konvsat_brg_code = ' + Quot(sKodeBarang);
with cOpenQuery(sSQL) do
begin
try
if not FieldByName('konvsat_scale').IsNull then
fedtQty.Value:= StrToFloat(FieldByName('konvsat_scale').AsString)
else
fedtQty.Value := 0;
edtAVGPrice.Value := FBarang.HargaAverage * fedtQty.Value;
SetMarkUp;
SetSellingMargin;
finally
Free
end;
end; }
if (Key = Chr(VK_RETURN)) then
begin
fedtQty.SetFocus;
fedtQty.SelectAll;
end;
end;
procedure TfraSellingPrice.fedtQtyKeyPress(Sender: TObject; var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
jvcuredtSellPrice.SetFocus;
jvcuredtSellPrice.SelectAll;
end;
end;
procedure TfraSellingPrice.jvcuredtSellPriceKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
fedtDiscPercent.SetFocus;
fedtDiscPercent.SelectAll;
end;
end;
procedure TfraSellingPrice.fedtDiscPercentKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = Chr(VK_RETURN) then
begin
jvcuredtDiscNominal.SetFocus;
SetDiscon(True);
end
end;
procedure TfraSellingPrice.jvcuredtDiscNominalKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = Chr(VK_RETURN) then
begin
jvcuredtSellPriceDisc.SetFocus;
SetDiscon(False);
end
end;
procedure TfraSellingPrice.jvcuredtSellPriceDiscKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
jvcuredtSellPriceCoret.SetFocus;
jvcuredtSellPriceCoret.SelectAll;
end;
end;
procedure TfraSellingPrice.jvcuredtSellPriceCoretKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
edtSellMargin.SetFocus;
edtSellMargin.SelectAll;
end;
end;
procedure TfraSellingPrice.edtSellMarginKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
chkIsLimit.SetFocus;
end;
end;
procedure TfraSellingPrice.chkIsLimitKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
intedtQtyLimit.SetFocus;
intedtQtyLimit.SelectAll;
end;
end;
procedure TfraSellingPrice.intedtQtyLimitKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
jvcuredtPriceLimit.SetFocus;
jvcuredtPriceLimit.SelectAll;
end;
end;
procedure TfraSellingPrice.jvcuredtPriceLimitKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
chkIsADS.SetFocus;
end;
end;
procedure TfraSellingPrice.chkIsADSExit(Sender: TObject);
begin
if chkIsADS.Checked then
begin
intedtQtyADS.Enabled:= True;
jvcuredtPriceADS.Enabled:= True;
end
else
begin
intedtQtyADS.Enabled:= False;
jvcuredtPriceADS.Enabled:= False;
end;
end;
procedure TfraSellingPrice.chkIsLimitExit(Sender: TObject);
begin
if chkIsLimit.Checked then
begin
intedtQtyLimit.Enabled:= True;
jvcuredtPriceLimit.Enabled:= True;
end
else
begin
intedtQtyLimit.Enabled:= False;
jvcuredtPriceLimit.Enabled:= False;
end;
end;
procedure TfraSellingPrice.chkIsADSKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
intedtQtyADS.SetFocus;
intedtQtyADS.SelectAll;
end;
end;
procedure TfraSellingPrice.intedtQtyADSKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
jvcuredtPriceADS.SetFocus;
jvcuredtPriceADS.SelectAll;
end;
end;
procedure TfraSellingPrice.jvcuredtPriceADSKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
chkIsMailer.SetFocus;
end;
end;
procedure TfraSellingPrice.chkIsMailerExit(Sender: TObject);
begin
if chkIsADS.Checked then
begin
intedtQtyADS.Enabled:= True;
jvcuredtPriceADS.Enabled:= True;
end
else
begin
intedtQtyADS.Enabled:= False;
jvcuredtPriceADS.Enabled:= False;
end;
end;
procedure TfraSellingPrice.chkIsMailerKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
fedtMarkUp.SetFocus;
fedtMarkUp.SelectAll;
end;
end;
procedure TfraSellingPrice.cxGridViewSellingPriceEditing(Sender:
TcxCustomGridTableView; AItem: TcxCustomGridTableItem; var AAllow: Boolean);
begin
// if(ACol = 0)and(strgGrid.Cells[1,ARow]<>'')then
// CanEdit := true
// else
// CanEdit := false;
end;
procedure TfraSellingPrice.fedtMarkUpKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
edtMaxQtyDisc.SetFocus;
edtMaxQtyDisc.SelectAll;
end;
end;
procedure TfraSellingPrice.edtMaxQtyDiscKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
btnSave.SetFocus;
end;
end;
procedure TfraSellingPrice.edtSellMarginExit(Sender: TObject);
begin
// FormatFloat('%.2n',edtSellMargin.Value);
end;
End.
|
{******************************************************************************}
{ }
{ Delphi OPENSSL Library }
{ Copyright (c) 2016 Luca Minuti }
{ https://bitbucket.org/lminuti/delphi-openssl }
{ }
{******************************************************************************}
{ }
{ 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. }
{ }
{******************************************************************************}
// enc - symmetric cipher routines
// https://www.openssl.org/docs/manmaster/apps/enc.html
unit OpenSSL.EncUtils;
interface
uses
System.SysUtils, System.Classes, System.Generics.Collections, System.SyncObjs,
OpenSSL.Core, OpenSSL.Api_11;
type
TCipherName = string;
TCipherProc = function (): PEVP_CIPHER cdecl;
TCipherInfo = record
Name: TCipherName;
Proc: TCipherProc;
end;
TCipherList = class(TList<TCipherInfo>) { TThreadList }
private
FLock: TCriticalSection;
private
function LockList: TList<TCipherInfo>;
procedure UnlockList;
public
constructor Create; reintroduce;
destructor Destroy; override;
function Count: Integer;
function GetProc(const Name: TCipherName): TCipherProc;
end;
TPassphraseType = (ptNone, ptPassword, ptKeys);
TPassphrase = record
private
FType: TPassphraseType;
FValue: TBytes;
FKey: TBytes;
FInitVector: TBytes;
public
class operator Implicit(const Value: string): TPassphrase;
class operator Implicit(const Value: TBytes): TPassphrase;
constructor Create(const Key, InitVector: TBytes); overload;
constructor Create(const Password: string; Encoding: TEncoding); overload;
end;
TEncUtil = class(TOpenSSLBase)
private
class var
FCipherList: TCipherList;
class constructor Create;
class destructor Destroy;
private
FPassphrase: TPassphrase;
FBase64: Boolean;
FCipherProc: TCipherProc;
FCipher: TCipherName;
procedure SetCipher(const Value: TCipherName);
public
class procedure RegisterCipher(const Name: TCipherName; Proc: TCipherProc);
class procedure RegisterDefaultCiphers;
class procedure SupportedCiphers(Ciphers: TStrings);
public
constructor Create; override;
// will be encoded in UTF8
property Passphrase: TPassphrase read FPassphrase write FPassphrase;
// Encryption algorithm
property Cipher: TCipherName read FCipher write SetCipher;
// Apply a further base64 encoding to the encrypted buffer
property UseBase64: Boolean read FBase64 write FBase64;
procedure Encrypt(InputStream: TStream; OutputStream: TStream); overload;
procedure Encrypt(const InputFileName, OutputFileName: TFileName); overload;
procedure Decrypt(InputStream: TStream; OutputStream: TStream); overload;
procedure Decrypt(const InputFileName, OutputFileName: TFileName); overload;
end;
implementation
const
SALT_MAGIC: AnsiString = 'Salted__';
SALT_MAGIC_LEN: Integer = 8;
SALT_SIZE = 8;
{ TEncUtil }
procedure TEncUtil.Decrypt(InputStream, OutputStream: TStream);
var
Context: PEVP_CIPHER_CTX;
Key: TBytes;
InitVector: TBytes;
InputBuffer: TBytes;
OutputLen: Integer;
OutputBuffer: TBytes;
Base64Buffer: TBytes;
Cipher: PEVP_CIPHER;
Salt: TBytes;
BuffStart: Integer;
InputStart: Integer;
begin
if Assigned(FCipherProc) then
Cipher := FCipherProc()
else
Cipher := EVP_aes_256_cbc();
if FBase64 then
begin
SetLength(Base64Buffer, InputStream.Size);
InputStream.ReadBuffer(Base64Buffer[0], InputStream.Size);
InputBuffer := Base64Decode(Base64Buffer);
end
else
begin
SetLength(InputBuffer, InputStream.Size);
InputStream.ReadBuffer(InputBuffer[0], InputStream.Size);
end;
if FPassphrase.FType = ptPassword then
begin
SetLength(Salt, SALT_SIZE);
if (AnsiString(TEncoding.ASCII.GetString(InputBuffer, 0, SALT_MAGIC_LEN)) = SALT_MAGIC) then
begin
if Length(FPassphrase.FValue) = 0 then
raise EOpenSSL.Create('Password needed');
Move(InputBuffer[SALT_MAGIC_LEN], Salt[0], SALT_SIZE);
EVP_GetKeyIV(FPassphrase.FValue, Cipher, Salt, Key, InitVector);
InputStart := SALT_MAGIC_LEN + SALT_SIZE;
end
else
begin
EVP_GetKeyIV(FPassphrase.FValue, Cipher, nil, Key, InitVector);
InputStart := 0;
end;
end
else if FPassphrase.FType = ptKeys then
begin
Key := FPassphrase.FKey;
InitVector := FPassphrase.FInitVector;
InputStart := 0;
end
else
raise EOpenSSL.Create('Password needed');
Context := EVP_CIPHER_CTX_new();
if Context = nil then
RaiseOpenSSLError('Cannot initialize context');
try
if EVP_DecryptInit_ex(Context, Cipher, nil, @Key[0], @InitVector[0]) <> 1 then
RaiseOpenSSLError('Cannot initialize decryption process');
SetLength(OutputBuffer, InputStream.Size);
BuffStart := 0;
if EVP_DecryptUpdate(Context, @OutputBuffer[BuffStart], @OutputLen, @InputBuffer[InputStart], Length(InputBuffer) - InputStart) <> 1 then
RaiseOpenSSLError('Cannot decrypt');
Inc(BuffStart, OutputLen);
if EVP_DecryptFinal_ex(Context, @OutputBuffer[BuffStart], @OutputLen) <> 1 then
RaiseOpenSSLError('Cannot finalize decryption process');
Inc(BuffStart, OutputLen);
if BuffStart > 0 then
OutputStream.WriteBuffer(OutputBuffer[0], BuffStart);
finally
EVP_CIPHER_CTX_free(Context);
end;
end;
procedure TEncUtil.Encrypt(InputStream, OutputStream: TStream);
var
Context: PEVP_CIPHER_CTX;
Key: TBytes;
InitVector: TBytes;
InputBuffer: TBytes;
OutputLen: Integer;
OutputBuffer: TBytes;
Base64Buffer: TBytes;
Salt: TBytes;
cipher: PEVP_CIPHER;
BlockSize: Integer;
BuffStart: Integer;
begin
BuffStart := 0;
SetLength(Salt, 0);
if Assigned(FCipherProc) then
cipher := FCipherProc()
else
cipher := EVP_aes_256_cbc();
if FPassphrase.FType = ptPassword then
begin
salt := EVP_GetSalt;
EVP_GetKeyIV(FPassphrase.FValue, cipher, salt, key, InitVector);
end
else if FPassphrase.FType = ptKeys then
begin
Key := FPassphrase.FKey;
InitVector := FPassphrase.FInitVector;
end
else
raise EOpenSSL.Create('Password needed');
SetLength(InputBuffer, InputStream.Size);
InputStream.ReadBuffer(InputBuffer[0], InputStream.Size);
Context := EVP_CIPHER_CTX_new();
if Context = nil then
RaiseOpenSSLError('Cannot initialize context');
try
if EVP_EncryptInit_ex(Context, cipher, nil, @Key[0], @InitVector[0]) <> 1 then
RaiseOpenSSLError('Cannot initialize encryption process');
BlockSize := EVP_CIPHER_CTX_block_size(Context);
if Length(salt) > 0 then
begin
SetLength(OutputBuffer, Length(InputBuffer) + BlockSize + SALT_MAGIC_LEN + PKCS5_SALT_LEN);
Move(PAnsiChar(SALT_MAGIC)^, OutputBuffer[BuffStart], SALT_MAGIC_LEN);
Inc(BuffStart, SALT_MAGIC_LEN);
Move(salt[0], OutputBuffer[BuffStart], PKCS5_SALT_LEN);
Inc(BuffStart, PKCS5_SALT_LEN);
end
else
SetLength(OutputBuffer, Length(InputBuffer) + BlockSize);
if EVP_EncryptUpdate(Context, @OutputBuffer[BuffStart], @OutputLen, @InputBuffer[0], Length(InputBuffer)) <> 1 then
RaiseOpenSSLError('Cannot encrypt');
Inc(BuffStart, OutputLen);
if EVP_EncryptFinal_ex(Context, @OutputBuffer[BuffStart], @OutputLen) <> 1 then
RaiseOpenSSLError('Cannot finalize encryption process');
Inc(BuffStart, OutputLen);
SetLength(OutputBuffer, BuffStart);
if BuffStart > 0 then
begin
if FBase64 then
begin
Base64Buffer := Base64Encode(OutputBuffer);
OutputStream.WriteBuffer(Base64Buffer[0], Length(Base64Buffer));
end
else
OutputStream.WriteBuffer(OutputBuffer[0], BuffStart);
end;
finally
EVP_CIPHER_CTX_free(Context);
end;
end;
procedure TEncUtil.Encrypt(const InputFileName, OutputFileName: TFileName);
var
InputFile, OutputFile: TStream;
begin
InputFile := TFileStream.Create(InputFileName, fmOpenRead);
try
OutputFile := TFileStream.Create(OutputFileName, fmCreate);
try
Encrypt(InputFile, OutputFile);
finally
OutputFile.Free;
end;
finally
InputFile.Free;
end;
end;
class procedure TEncUtil.RegisterCipher(const Name: TCipherName;
Proc: TCipherProc);
var
Value: TCipherInfo;
begin
Value.Name := Name;
Value.Proc := Proc;
FCipherList.Add(Value);
end;
class procedure TEncUtil.RegisterDefaultCiphers;
begin
if FCipherList.Count = 0 then
begin
// AES
RegisterCipher('AES', EVP_aes_256_cbc);
RegisterCipher('AES-128', EVP_aes_128_cbc);
RegisterCipher('AES-192', EVP_aes_192_cbc);
RegisterCipher('AES-256', EVP_aes_256_cbc);
RegisterCipher('AES-CBC', EVP_aes_256_cbc);
RegisterCipher('AES-128-CBC', EVP_aes_128_cbc);
RegisterCipher('AES-192-CBC', EVP_aes_192_cbc);
RegisterCipher('AES-256-CBC', EVP_aes_256_cbc);
RegisterCipher('AES-CFB', EVP_aes_256_cfb128);
RegisterCipher('AES-128-CFB', EVP_aes_128_cfb128);
RegisterCipher('AES-192-CFB', EVP_aes_192_cfb128);
RegisterCipher('AES-256-CFB', EVP_aes_256_cfb128);
RegisterCipher('AES-CFB1', EVP_aes_256_cfb1);
RegisterCipher('AES-128-CFB1', EVP_aes_128_cfb1);
RegisterCipher('AES-192-CFB1', EVP_aes_192_cfb1);
RegisterCipher('AES-256-CFB1', EVP_aes_256_cfb1);
RegisterCipher('AES-CFB8', EVP_aes_256_cfb8);
RegisterCipher('AES-128-CFB8', EVP_aes_128_cfb8);
RegisterCipher('AES-192-CFB8', EVP_aes_192_cfb8);
RegisterCipher('AES-256-CFB8', EVP_aes_256_cfb8);
RegisterCipher('AES-ECB', EVP_aes_256_ecb);
RegisterCipher('AES-128-ECB', EVP_aes_128_ecb);
RegisterCipher('AES-192-ECB', EVP_aes_192_ecb);
RegisterCipher('AES-256-ECB', EVP_aes_256_ecb);
RegisterCipher('AES-OFB', EVP_aes_256_ofb);
RegisterCipher('AES-128-OFB', EVP_aes_128_ofb);
RegisterCipher('AES-192-OFB', EVP_aes_192_ofb);
RegisterCipher('AES-256-OFB', EVP_aes_256_ofb);
// Blowfish
RegisterCipher('BF', EVP_bf_cbc);
RegisterCipher('BF-CBC', EVP_bf_cbc);
RegisterCipher('BF-ECB', EVP_bf_ecb);
RegisterCipher('BF-CBF', EVP_bf_cfb64);
RegisterCipher('BF-OFB', EVP_bf_ofb);
// DES
RegisterCipher('DES-CBC', EVP_des_cbc);
RegisterCipher('DES', EVP_des_cbc);
RegisterCipher('DES-CFB', EVP_des_cfb64);
RegisterCipher('DES-OFB', EVP_des_ofb);
RegisterCipher('DES-ECB', EVP_des_ecb);
// Two key triple DES EDE
RegisterCipher('DES-EDE-CBC', EVP_des_ede_cbc);
RegisterCipher('DES-EDE', EVP_des_ede);
RegisterCipher('DES-EDE-CFB', EVP_des_ede_cfb64);
RegisterCipher('DES-EDE-OFB', EVP_des_ede_ofb);
// Two key triple DES EDE
RegisterCipher('DES-EDE3-CBC', EVP_des_ede3_cbc);
RegisterCipher('DES-EDE3', EVP_des_ede3);
RegisterCipher('DES3', EVP_des_ede3);
RegisterCipher('DES-EDE3-CFB', EVP_des_ede3_cfb64);
RegisterCipher('DES-EDE3-OFB', EVP_des_ede3_ofb);
// DESX algorithm
RegisterCipher('DESX', EVP_desx_cbc);
// IDEA algorithm
RegisterCipher('IDEA-CBC', EVP_idea_cbc);
RegisterCipher('IDEA', EVP_idea_cbc);
RegisterCipher('IDEA-CFB', EVP_idea_cfb64);
RegisterCipher('IDEA-ECB', EVP_idea_ecb);
RegisterCipher('IDEA-OFB', EVP_idea_ofb);
// RC2
RegisterCipher('RC2-CBC', EVP_rc2_cbc);
RegisterCipher('RC2', EVP_rc2_cbc);
RegisterCipher('RC2-CFB', EVP_rc2_cfb64);
RegisterCipher('RC2-ECB', EVP_rc2_ecb);
RegisterCipher('RC2-OFB', EVP_rc2_ofb);
RegisterCipher('RC2-64-CBC', nil);
RegisterCipher('RC2-40-CBC', nil);
// RC4
RegisterCipher('RC4', EVP_rc4);
RegisterCipher('RC4-40', EVP_rc4_40);
end;
end;
procedure TEncUtil.SetCipher(const Value: TCipherName);
begin
FCipherProc := FCipherList.GetProc(Value);
if @FCipherProc = nil then
raise EOpenSSL.CreateFmt('Cipher not found: "%s"', [Value]);
FCipher := Value;
end;
class procedure TEncUtil.SupportedCiphers(Ciphers: TStrings);
var
CipherInfo: TCipherInfo;
LocalCipherList: TList<TCipherInfo>;
begin
RegisterDefaultCiphers;
Ciphers.Clear;
LocalCipherList := FCipherList.LockList;
try
for CipherInfo in LocalCipherList do
Ciphers.Add(CipherInfo.Name);
finally
FCipherList.UnlockList;
end;
end;
class constructor TEncUtil.Create;
begin
FCipherList := TCipherList.Create;
end;
constructor TEncUtil.Create;
begin
inherited Create;
TEncUtil.RegisterDefaultCiphers;
end;
procedure TEncUtil.Decrypt(const InputFileName, OutputFileName: TFileName);
var
InputFile, OutputFile: TStream;
begin
InputFile := TFileStream.Create(InputFileName, fmOpenRead);
try
OutputFile := TFileStream.Create(OutputFileName, fmCreate);
try
Decrypt(InputFile, OutputFile);
finally
OutputFile.Free;
end;
finally
InputFile.Free;
end;
end;
class destructor TEncUtil.Destroy;
begin
FCipherList.Free;
end;
{ TCipherList }
function TCipherList.Count: Integer;
var
LocalCipherList: TList<TCipherInfo>;
begin
LocalCipherList := LockList;
try
Result := LocalCipherList.Count;
finally
UnlockList;
end;
end;
constructor TCipherList.Create;
begin
inherited Create;
FLock := TCriticalSection.Create;
end;
destructor TCipherList.Destroy;
begin
FreeAndNil(FLock);
inherited;
end;
function TCipherList.GetProc(const Name: TCipherName): TCipherProc;
var
CipherInfo: TCipherInfo;
LocalCipherList: TList<TCipherInfo>;
begin
Result := nil;
LocalCipherList := LockList;
try
for CipherInfo in LocalCipherList do
if CipherInfo.Name = Name then
Result := CipherInfo.Proc;
finally
UnlockList;
end;
end;
function TCipherList.LockList: TList<TCipherInfo>;
begin
FLock.Enter;
Result := Self;
end;
procedure TCipherList.UnlockList;
begin
FLock.Leave;
end;
{ TPassphrase }
constructor TPassphrase.Create(const Key, InitVector: TBytes);
begin
FType := ptKeys;
FKey := Key;
FInitVector := InitVector;
end;
constructor TPassphrase.Create(const Password: string; Encoding: TEncoding);
begin
FType := ptPassword;
FValue := Encoding.GetBytes(Password);
end;
class operator TPassphrase.Implicit(const Value: string): TPassphrase;
begin
Result.FType := ptPassword;
Result.FValue := TEncoding.UTF8.GetBytes(Value);
end;
class operator TPassphrase.Implicit(const Value: TBytes): TPassphrase;
begin
Result.FType := ptPassword;
Result.FValue := Value;
end;
end.
|
unit uRepMonthFilter;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uRepParentFilter, cxControls, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, cxDropDownEdit, StdCtrls, siComp;
type
TRepMonthFilter = class(TRepParentFilter)
cbxMonth: TcxComboBox;
procedure FormCreate(Sender: TObject);
private
procedure SetMonth(IDLanguage : Integer);
public
function GetValue: Variant; override;
function GetFilterString: String; override;
end;
implementation
uses DateUtils, uDMReport, uDateTimeFunctions;
{$R *.dfm}
function TRepMonthFilter.GetFilterString: String;
begin
if Trim(cbxMonth.Text) <> '' then
Result := lblFilter.Caption + ' ' + cbxMonth.Text+'; ';
end;
procedure TRepMonthFilter.SetMonth(IDLanguage: Integer);
var
i : Integer;
begin
for i := 0 to cbxMonth.Properties.Items.Count-1 do
case IDLanguage of
L_ENGLISH : cbxMonth.Properties.Items[i] := AEnglishLongMonth[i+1];
L_PORTUGUESE : cbxMonth.Properties.Items[i] := APortuguesLongMonth[i+1];
L_SPANISH : cbxMonth.Properties.Items[i] := AEspanholLongMonth[i+1];
end;
end;
function TRepMonthFilter.GetValue: Variant;
begin
Result := cbxMonth.ItemIndex+1;
end;
procedure TRepMonthFilter.FormCreate(Sender: TObject);
begin
inherited;
SetMonth(DMReport.LanguageDispatcher.ActiveLanguage);
cbxMonth.ItemIndex := MonthOf(Now)-1;
end;
initialization
RegisterClass(TRepMonthFilter)
end.
|
unit UTanggal;
interface
uses UUI,UTipe;
function getTanggal(Input:string):Tanggal;
{Menerima Input string tanggal dalam format dd/mm/yy lalu isi ke bentuk
variabel Tanggal}
function nextTanggal(Input:Tanggal):Tanggal;
{Mengembalikan tipe data Tanggal dari Input yang telah dimajukan 1 hari}
function selisihTanggal(Input1:Tanggal; Input2:Tanggal):integer;
{Mengembalikan jarak dalam hari antara 2 tanggal, asumsi Input1 lebih duluan}
function isTanggalSama(Input1:Tanggal; Input2:Tanggal):boolean;
{Mengembalikan apakah tanggal Input1 dan Input2 sama}
function isTanggalDuluan(Input1:Tanggal; Input2:Tanggal):Boolean;
{mencari tanggal mana yang lebih duluan, akan bernilai true saat Input1 lebih dahulu
dari Input2}
implementation
function isTanggalSama(Input1:Tanggal; Input2:Tanggal):boolean;
{kamus lokal}
var
Sama:boolean;
{Algoritma - isTanggalSama}
begin
{cek apkah sama hari, bulan dan tahunnya}
Sama := Input1.Hari = Input2.Hari;
if(sama)then
begin
Sama := Sama and (Input1.Bulan = Input2.Bulan);
if(sama)then
begin
Sama := Sama and (Input1.Tahun = Input2.Tahun);
end;
end;
isTanggalSama := Sama;
end;
function maxHari(Input:Tanggal):integer;
{Kamus}
var
x:Tanggal;
{Algoritma}
begin
x:=Input;
case (x.Bulan) of
1 : begin
MaxHari:=31;
end;
2 :begin
{cek kabisat sederhana}
if (x.Tahun mod 4 = 0) then
begin
if(x.Tahun mod 100 = 0)then
begin
if(x.Tahun mod 400 = 0)then
begin
{habis dibagi 400 = kabisat}
MaxHari:=29;
end else
begin
{tidak habus dibagi 400 tapi bisa dibagi 100}
MaxHari:=28;
end;
end else
begin
{Habis dibagi 4 tapi tidak habis dibagi 100 = kabisat}
MaxHari:=29;
end;
end else
begin
{tidak habis dibagi 4}
MaxHari:=28;
end;
end;
3 : begin
MaxHari:=31;
end;
4 :begin
MaxHari:=30;
end;
5 : begin
MaxHari:=31;
end;
6 :begin
MaxHari:=30;
end;
7 : begin
MaxHari:=31;
end;
8 :begin
MaxHari:=31;
end;
9 : begin
MaxHari:=30;
end;
10 :begin
MaxHari:=31;
end;
11 : begin
MaxHari:=30;
end;
12 :begin
MaxHari:=31;
end;
end;
end;
function getTanggal(Input:string):Tanggal;
{Kamus}
var
i : integer;
str : string; //string sementara
indeks : integer;
x:Tanggal; //variabel sementara Tanggal
KodeError:integer;
{Algoritma}
begin
indeks:=1;
str := '';
while (indeks<=3) do
begin
{iterasi sampai akhir}
for i:=1 to length(Input) do
begin
{Cek apakah karakter pemisah}
if (Input[i]='/') then
begin
indeks:=indeks+1;
str := ''; {str direset biar diisi sama yang baru}
end else
begin
{set string sementara}
str := str + Input[i];
if (indeks=1) then {indeks 1 = hari}
begin
{ubah ke integer}
Val(str,x.Hari,KodeError);
if(KodeError<>0)then
begin
writeError('UTanggal','Hari bukan integer');
end;
end else
if (indeks=2) then {indeks 2 = bulan}
begin
{ubah ke integer}
Val(str,x.Bulan,KodeError);
if(KodeError<>0)then
begin
writeError('UTanggal','Bulan bukan integer')
end else
begin
{cek bulan valid}
if (x.Bulan>12) or (x.Bulan<1) then
begin
writeError('UTanggal','Bulan tidak valid')
end;
end;
end else {indeks 3 = tahun}
begin
{ubah ke integer}
Val(str,x.Tahun,KodeError);
if(KodeError<>0)then
begin
writeError('UTanggal','Tahun bukan integer');
end else
begin
{cek tahun valid}
if (x.Tahun<0) then
begin
writeError('UTanggal','Tahun tidak valid');
end;
end;
end;
end;
end;
end;
{cek hari valid sesuai bulan}
if (x.Hari>MaxHari(x)) or (x.Hari<1) then
begin
writeError('UTanggal','Hari tidak valid');
end;
getTanggal:=x;
end;
function nextTanggal(Input:Tanggal):Tanggal;
{Kamus}
var
x:Tanggal; {tanggal yang didapat dari getTanggal}
y:Tanggal; {variabel tanggal sementara untuk nextTanggal}
{Algoritma}
begin
x:=Input;
{Kasus khusus jika bulan 12 (bisa ganti tahun)}
if (x.Bulan=12) then
begin
if (x.Hari=MaxHari(Input)) then
begin
{Ganti tahun}
y.Tahun:=x.Tahun+1;
y.Bulan:=1;
y.Hari:=1;
end else
begin
y.Hari:=x.Hari+1;
y.Tahun:=x.Tahun;
y.Bulan:=x.Bulan;
end;
end else
if (x.Hari=MaxHari(Input)) then
begin
y.Tahun:=x.Tahun;
y.Bulan:=x.Bulan+1;
y.Hari:=1;
end else
begin
y.Hari:=x.Hari+1;
y.Tahun:=x.Tahun;
y.Bulan:=x.Bulan;
end;
nextTanggal:=y;
end;
function selisihTanggal(Input1:Tanggal; Input2:Tanggal):integer;
{Kamus Lokal}
var
jarak:integer;
{Algoritma - selisihTanggal}
begin
jarak:=0;
{terus ulangi sampai tanggal sama}
while((Input1.Hari<>Input2.Hari) or (Input1.Bulan<>Input2.Bulan) or (Input1.Tahun<>Input2.Tahun)) do
begin
{next tanggal sampai sama}
Input1:=nextTanggal(Input1);
jarak:=jarak+1;
end;
selisihTanggal:=jarak;
end;
function isTanggalDuluan(Input1:Tanggal; Input2:Tanggal):Boolean;
{Kamus lokal}
var
x,y : Tanggal; //x adalah Input1, y adalah Input2
hasil : Boolean; //variabel sementara isTanggalDuluan
{Algoritma}
begin
x:=Input1; y:=Input2;
{cek tanggal duluan mulai dari tahun sampai hari}
if (x.Tahun > y.Tahun) then
begin
hasil:=False;
end
else if (x.Tahun < y.Tahun) then
begin
hasil:=True;
end
else {x.Tahun = y.Tahun}
begin
if (x.Bulan > y.Bulan) then
begin
hasil:=False;
end
else if (x.Bulan < y.Bulan) then
begin
hasil:=True;
end
else {x.Bulan = y.Bulan}
begin
if (x.Hari >= y.Hari) then
begin
hasil:=False;
end
else if (x.Hari < y.Hari) then
begin
hasil:=True;
end;
end;
end;
isTanggalDuluan:=hasil;
end;
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: clootie@ixbt.com) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://clootie.narod.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: EffectParamUnit.pas,v 1.17 2007/02/05 22:21:05 clootie Exp $
*----------------------------------------------------------------------------*)
//--------------------------------------------------------------------------------------
// File: EffectParam.cpp
//
// Starting point for new Direct3D applications
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
{$I DirectX.inc}
unit EffectParamUnit;
interface
uses
Windows, Messages, SysUtils, Math, StrSafe,
DXTypes, Direct3D9, D3DX9, dxerr9,
DXUT, DXUTcore, DXUTenum, DXUTmisc, DXUTgui, DXUTSettingsDlg;
{.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders
{.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
// SCROLL_TIME dictates the time one scroll op takes, in seconds.
const
SCROLL_TIME = 0.5;
type
PMeshListData = ^TMeshListData;
TMeshListData = record
wszName: PWideChar; // array[0..MAX_PATH-1] of WideChar;
wszFile: PWideChar; // array[0..MAX_PATH-1] of WideChar;
dwNumMat: DWORD; // Number of materials. To be filled in when loading this mesh.
end;
var
g_MeshListData: array[0..6] of TMeshListData =
(
(wszName: 'Car'; wszFile: 'car2.x'; dwNumMat: 0),
(wszName: 'Banded Earth'; wszFile: 'sphereband.x'; dwNumMat: 0),
(wszName: 'Dwarf'; wszFile: 'dwarf\DwarfWithEffectInstance.x'; dwNumMat: 0),
(wszName: 'Virus'; wszFile: 'cytovirus.x'; dwNumMat: 0),
(wszName: 'Car'; wszFile: 'car2.x'; dwNumMat: 0),
(wszName: 'Banded Earth'; wszFile: 'sphereband.x'; dwNumMat: 0),
(wszName: 'Dwarf'; wszFile: 'dwarf\DwarfWithEffectInstance.x'; dwNumMat: 0)
);
type
TMeshVertex = packed record
Position: TD3DXVector3;
Normal: TD3DXVector3;
Tex: TD3DXVector2;
// const static D3DVERTEXELEMENT9 Decl[4];
end;
const
TMeshVertex_Decl: array[0..3] of TD3DVertexElement9 =
(
(Stream: 0; Offset: 0; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_POSITION; UsageIndex: 0),
(Stream: 0; Offset: 12; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_NORMAL; UsageIndex: 0),
(Stream: 0; Offset: 24; _Type: D3DDECLTYPE_FLOAT2; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_TEXCOORD; UsageIndex: 0),
{D3DDECL_END()}(Stream:$FF; Offset:0; _Type:D3DDECLTYPE_UNUSED; Method:TD3DDeclMethod(0); Usage:TD3DDeclUsage(0); UsageIndex:0)
);
type
TMeshMaterial = class
private
m_pEffect: ID3DXEffect;
m_hParam: TD3DXHandle;
m_pTexture: IDirect3DTexture9;
public
constructor Create;
destructor Destroy; override;
procedure Assign(const rhs: TMeshMaterial);
end;
PMeshMaterialArray = ^TMeshMaterialArray;
TMeshMaterialArray = array[0..MaxInt div SizeOf(TMeshMaterial)-1] of TMeshMaterial;
TEffectMesh = class
private
m_wszMeshFile: array[0..MAX_PATH-1] of WideChar;
m_pMesh: ID3DXMesh;
m_pMaterials: array of TMeshMaterial; // TPMeshMaterialArray;
m_dwNumMaterials: DWORD;
public
constructor Create; overload;
constructor Copy(const old: TEffectMesh);
destructor Destroy; override;
procedure Assign(const rhs: TEffectMesh);
function Create(wszFileName: PWideChar; pd3dDevice: IDirect3DDevice9): HRESULT; overload;
procedure Render(const pd3dDevice: IDirect3DDevice9);
property NumMaterials: DWORD read m_dwNumMaterials;
property Mesh: ID3DXMesh read m_pMesh;
end;
CMeshArcBall = class(CD3DArcBall)
public
procedure OnBegin(nX, nY: Integer; const pmInvViewRotate: TD3DXMatrixA16);
procedure OnMove(nX, nY: Integer; const pmInvViewRotate: TD3DXMatrixA16);
function HandleMessages(hWnd: HWND; uMsg: Cardinal; wParam: WPARAM; lParam: LPARAM; const pmInvViewRotate: TD3DXMatrixA16): LRESULT;
end;
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
var
g_pFont: ID3DXFont; // Font for drawing text
g_pTextSprite: ID3DXSprite; // Sprite for batching draw text calls
g_pEffect: ID3DXEffect; // D3DX effect interface
g_pDecl: IDirect3DVertexDeclaration9; // Vertex decl for meshes
g_pDefaultTex: IDirect3DTexture9; // Default texture
g_pEnvMapTex: IDirect3DCubeTexture9; // Environment map texture
g_dwShaderFlags: DWORD = D3DXFX_NOT_CLONEABLE; // Shader creation flag for all effects
g_Camera: CModelViewerCamera; // Camera for navigation
g_ArcBall: array of CMeshArcBall;
g_bShowHelp: Boolean = True; // If true, it renders the UI control text
g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs
g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog
g_HUD: CDXUTDialog; // dialog for standard controls
g_SampleUI: CDXUTDialog; // dialog for sample specific controls
g_pEffectPool: ID3DXEffectPool; // Effect pool for sharing parameters
g_Meshes: array of TEffectMesh; // List of meshes being rendered
g_amWorld: array of TD3DXMatrixA16; // World transform for the meshes
g_nActiveMesh: Integer = 0;
g_mScroll: TD3DXMatrixA16; // Scroll matrix
g_fAngleToScroll: Single = 0.0; // Total angle to scroll the meshes in radian, in current scroll op
g_fAngleLeftToScroll: Single = 0.0; // Angle left to scroll the meshes in radian
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
const
IDC_TOGGLEFULLSCREEN = 1;
IDC_TOGGLEREF = 3;
IDC_CHANGEDEVICE = 4;
IDC_SHARE = 5;
IDC_SCROLLLEFT = 6;
IDC_SCROLLRIGHT = 7;
IDC_MESHNAME = 8;
IDC_MATCOUNT = 9;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
procedure OnLostDevice(pUserContext: Pointer); stdcall;
procedure OnDestroyDevice(pUserContext: Pointer); stdcall;
procedure InitApp;
procedure RenderText;
procedure CreateCustomDXUTobjects;
procedure DestroyCustomDXUTobjects;
implementation
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
{ TMeshMaterial }
constructor TMeshMaterial.Create;
begin
inherited Create;
m_pEffect := nil;
m_hParam := nil;
m_pTexture := nil;
end;
destructor TMeshMaterial.Destroy;
begin
m_pEffect := nil;
m_pTexture := nil;
inherited;
end;
procedure TMeshMaterial.Assign(const rhs: TMeshMaterial);
begin
m_pEffect := rhs.m_pEffect;
m_hParam := rhs.m_hParam;
m_pTexture := rhs.m_pTexture;
end;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
constructor TEffectMesh.Create;
begin
inherited Create;
m_pMesh := nil;
m_pMaterials := nil;
m_dwNumMaterials := 0;
end;
constructor TEffectMesh.Copy(const old: TEffectMesh);
begin
raise Exception.Create('TEffectMesh.Copy is finally called :-)');
m_wszMeshFile:= old.m_wszMeshFile;
m_pMesh:= old.m_pMesh;
m_pMaterials:= old.m_pMaterials;
m_dwNumMaterials:= old.m_dwNumMaterials;
end;
destructor TEffectMesh.Destroy;
var
i: Integer;
begin
for i:= 0 to Length(m_pMaterials) - 1 do m_pMaterials[i].Free;
m_pMaterials:= nil;
m_dwNumMaterials := 0;
m_pMesh := nil;
inherited;
end;
procedure TEffectMesh.Render(const pd3dDevice: IDirect3DDevice9);
var
i: Integer;
pMat: TMeshMaterial;
cPasses: LongWord;
p: Integer;
begin
for i := 0 to m_dwNumMaterials - 1 do
begin
pMat := m_pMaterials[i];
V_(pMat.m_pEffect.ApplyParameterBlock(pMat.m_hParam));
V_(pMat.m_pEffect._Begin(@cPasses, 0));
for p := 0 to cPasses - 1 do
begin
V_(pMat.m_pEffect.BeginPass(p));
V_(m_pMesh.DrawSubset(i));
V_(pMat.m_pEffect.EndPass);
end;
V_(pMat.m_pEffect._End);
end;
end;
procedure TEffectMesh.Assign(const rhs: TEffectMesh);
var
i: Integer;
begin
StringCchCopy(m_wszMeshFile, MAX_PATH, rhs.m_wszMeshFile);
m_dwNumMaterials := rhs.m_dwNumMaterials;
m_pMesh := rhs.m_pMesh;
for i:= 0 to Length(m_pMaterials) - 1 do m_pMaterials[i].Free;
SetLength(m_pMaterials, m_dwNumMaterials);
for i := 0 to m_dwNumMaterials - 1 do
begin
m_pMaterials[i] := TMeshMaterial.Create;
m_pMaterials[i].Assign(rhs.m_pMaterials[i]);
end;
end;
const
INVALID_FILE_ATTRIBUTES = DWORD(-1);
type
PD3DXEffectInstanceArray = ^TD3DXEffectInstanceArray;
TD3DXEffectInstanceArray = array[0..MaxInt div SizeOf(TD3DXEffectInstance)-1] of TD3DXEffectInstance;
PD3DXMaterialArray = ^TD3DXMaterialArray;
TD3DXMaterialArray = array[0..0] of TD3DXMaterial;
function TEffectMesh.Create(wszFileName: PWideChar; pd3dDevice: IDirect3DDevice9): HRESULT;
var
str: array[0..MAX_PATH-1] of WideChar;
wszMeshPath: array[0..MAX_PATH-1] of WideChar;
pAdjacency: ID3DXBuffer;
pMaterials: ID3DXBuffer;
pEffectInstance: ID3DXBuffer;
dwNumMaterials: DWORD;
bHasNormals: Boolean;
pCloneMesh: ID3DXMesh;
pLastBSlash: PWideChar;
pXMats: PD3DXMaterialArray;
pEI: PD3DXEffectInstanceArray;
i: Integer;
wszFxName: array[0..MAX_PATH-1] of WideChar;
szTmp: array[0..MAX_PATH-1] of WideChar;
hTech: TD3DXHandle;
param: Integer;
hHandle: TD3DXHandle;
desc: TD3DXParameterDesc;
EffectDefault: PD3DXEffectDefault;
wszTexName: array[0..MAX_PATH-1] of WideChar;
hTexture: TD3DXHandle;
begin
// Save the mesh filename
StringCchCopy(m_wszMeshFile, MAX_PATH, wszFileName);
Result:= DXUTFindDXSDKMediaFile(wszMeshPath, MAX_PATH, m_wszMeshFile);
if V_Failed(Result) then Exit;
Result:= D3DXLoadMeshFromXW(wszMeshPath, D3DXMESH_MANAGED, pd3dDevice,
@pAdjacency, @pMaterials, @pEffectInstance,
@dwNumMaterials, m_pMesh);
if V_Failed(Result) then Exit;
bHasNormals := (m_pMesh.GetFVF and D3DFVF_NORMAL) <> 0;
Result:= m_pMesh.CloneMesh(m_pMesh.GetOptions, @TMeshVertex_Decl, pd3dDevice, pCloneMesh);
if V_Failed(Result) then Exit;
// m_pMesh := nil; //Clootie: not needed in Delphi
m_pMesh := pCloneMesh;
// Extract the path of the mesh file
pLastBSlash := WideStrRScan(wszMeshPath, '\');
if (pLastBSlash <> nil) then (pLastBSlash + 1)^ := #0
else StringCchCopy(wszMeshPath, MAX_PATH, '.\');
// Ensure the mesh has correct normals.
if not bHasNormals then
D3DXComputeNormals(m_pMesh, pAdjacency.GetBufferPointer);
// Allocate material array
try
SetLength(m_pMaterials, dwNumMaterials);
for i := 0 to dwNumMaterials - 1 do
m_pMaterials[i] := TMeshMaterial.Create;
except
Result:= E_OUTOFMEMORY;
Exit;
end;
pXMats := pMaterials.GetBufferPointer;
pEI := pEffectInstance.GetBufferPointer;
for i := 0 to dwNumMaterials - 1 do
begin
// Obtain the effect
Result := S_OK;
// Try the mesh's directory
StringCchCopy(str, MAX_PATH, wszMeshPath);
MultiByteToWideChar(CP_ACP, 0, pEI[i].pEffectFilename, -1, str + lstrlenW(str), MAX_PATH);
if (pEI[i].pEffectFilename = nil) then Result:= E_FAIL;
MultiByteToWideChar(CP_ACP, 0, pEI[i].pEffectFilename, -1, wszFxName, MAX_PATH);
if SUCCEEDED(Result) then
begin
StringCchCopy(szTmp, MAX_PATH, 'SharedFx\');
StringCchCat(szTmp, MAX_PATH, wszFxName);
Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, szTmp);
if FAILED(Result) then
begin
// Search the SDK paths
Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, wszFxName);
end;
end;
if SUCCEEDED(Result) then
DXUTGetGlobalResourceCache.CreateEffectFromFile(pd3dDevice, str, nil, nil, g_dwShaderFlags, g_pEffectPool,
m_pMaterials[i].m_pEffect, nil);
if (m_pMaterials[i].m_pEffect = nil) then
begin
// No valid effect for this material. Use the default.
m_pMaterials[i].m_pEffect := g_pEffect;
end;
// Set the technique this material should use
m_pMaterials[i].m_pEffect.FindNextValidTechnique(nil, hTech);
m_pMaterials[i].m_pEffect.SetTechnique(hTech);
// Create a parameter block to include all parameters for the effect.
m_pMaterials[i].m_pEffect.BeginParameterBlock;
EffectDefault:= pEI[i].pDefaults;
for param := 0 to pEI[i].NumDefaults - 1 do
begin
// hHandle := m_pMaterials[i].m_pEffect.GetParameterByName(nil, pEI[i].pDefaults[param].pParamName);
hHandle := m_pMaterials[i].m_pEffect.GetParameterByName(nil, EffectDefault.pParamName);
if (hHandle <> nil) then
begin
m_pMaterials[i].m_pEffect.GetParameterDesc(hHandle, desc);
if (desc._Type = D3DXPT_BOOL) or
(desc._Type = D3DXPT_INT) or
(desc._Type = D3DXPT_FLOAT) or
(desc._Type = D3DXPT_STRING) then
begin
{m_pMaterials[i].m_pEffect.SetValue(pEI[i].pDefaults[param].pParamName,
pEI[i].pDefaults[param].pValue,
pEI[i].pDefaults[param].NumBytes);}
m_pMaterials[i].m_pEffect.SetValue(TD3DXHandle(EffectDefault.pParamName),
EffectDefault.pValue,
EffectDefault.NumBytes);
end;
end;
Inc(EffectDefault);
end;
// Obtain the texture
Result := S_OK;
if Assigned(pXMats[i].pTextureFilename) then
begin
// Try the mesh's directory first.
StringCchCopy(str, MAX_PATH, wszMeshPath);
MultiByteToWideChar(CP_ACP, 0, pXMats[i].pTextureFilename, -1, str + lstrlenW(str), MAX_PATH);
// If the texture file is not in the same directory as the mesh, search the SDK paths.
if (GetFileAttributesW(str) = INVALID_FILE_ATTRIBUTES) then
begin
// Search the SDK paths
MultiByteToWideChar(CP_ACP, 0, pXMats[i].pTextureFilename, -1, wszTexName, MAX_PATH);
Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, wszTexName);
end;
if SUCCEEDED(Result) then
DXUTGetGlobalResourceCache.CreateTextureFromFile(pd3dDevice, str, m_pMaterials[i].m_pTexture);
end;
if (m_pMaterials[i].m_pTexture = nil) then
begin
// No texture or texture fails to load. Use the default texture.
m_pMaterials[i].m_pTexture := g_pDefaultTex;
end;
// Include the texture in the parameter block if the effect requires one.
hTexture := m_pMaterials[i].m_pEffect.GetParameterByName(nil, 'g_txScene');
if Assigned(hTexture) then
m_pMaterials[i].m_pEffect.SetTexture(hTexture, m_pMaterials[i].m_pTexture);
// Include the environment map texture in the parameter block if the effect requires one.
hTexture := m_pMaterials[i].m_pEffect.GetParameterByName(nil, 'g_txEnvMap');
if Assigned(hTexture) then
m_pMaterials[i].m_pEffect.SetTexture(hTexture, g_pEnvMapTex);
// Save the parameter block
m_pMaterials[i].m_hParam := m_pMaterials[i].m_pEffect.EndParameterBlock;
end;
pAdjacency := nil;
pMaterials := nil;
pEffectInstance := nil;
m_dwNumMaterials := dwNumMaterials;
Result:= S_OK;
end;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
{ CMeshArcBall }
procedure CMeshArcBall.OnBegin(nX, nY: Integer; const pmInvViewRotate: TD3DXMatrixA16);
var
v: TD3DXVector4;
begin
m_bDrag := True;
m_qDown := m_qNow;
m_vDownPt := ScreenToVector(nX, nY);
D3DXVec3Transform(v, m_vDownPt, pmInvViewRotate);
m_vDownPt := PD3DXVector3(@v)^;
end;
procedure CMeshArcBall.OnMove(nX, nY: Integer; const pmInvViewRotate: TD3DXMatrixA16);
var
v: TD3DXVector4;
begin
if (m_bDrag) then
begin
m_vCurrentPt := ScreenToVector(nX, nY);
D3DXVec3Transform(v, m_vCurrentPt, pmInvViewRotate);
m_vCurrentPt := PD3DXVector3(@v)^;
D3DXQuaternionMultiply(m_qNow, m_qDown, QuatFromBallPoints(m_vDownPt, m_vCurrentPt));
end;
end;
function CMeshArcBall.HandleMessages(hWnd: HWND; uMsg: Cardinal;
wParam: WPARAM; lParam: LPARAM;
const pmInvViewRotate: TD3DXMatrixA16): LRESULT;
var
iMouseX: Integer;
iMouseY: Integer;
begin
// Current mouse position
iMouseX := LOWORD(lParam);
iMouseY := HIWORD(lParam);
Result:= iTrue;
case uMsg of
WM_LBUTTONDOWN,
WM_LBUTTONDBLCLK:
begin
SetCapture(hWnd);
OnBegin(iMouseX, iMouseY, pmInvViewRotate);
end;
WM_LBUTTONUP:
begin
ReleaseCapture;
OnEnd;
end;
WM_CAPTURECHANGED:
begin
if (THandle(lParam) <> hWnd) then
begin
ReleaseCapture;
OnEnd;
end;
end;
WM_MOUSEMOVE:
begin
if (MK_LBUTTON and wParam <> 0) then
begin
OnMove(iMouseX, iMouseY, pmInvViewRotate);
end;
end;
else
Result:= iFalse;
end;
end;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
procedure InitApp;
var
iY: Integer;
i: Integer;
l: LongWord;
vecEye: TD3DXVector3;
vecAt: TD3DXVector3;
begin
// Initialize dialogs
g_SettingsDlg.Init(g_DialogResourceManager);
g_HUD.Init(g_DialogResourceManager);
g_SampleUI.Init(g_DialogResourceManager);
g_HUD.SetCallback(OnGUIEvent);
iY := 10; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2);
g_SampleUI.SetCallback(OnGUIEvent);
iY := 0; g_SampleUI.AddStatic(IDC_MESHNAME, 'Mesh Name', 0, iY, 160, 20);
Inc(iY, 20); g_SampleUI.AddStatic(IDC_MATCOUNT, 'Number of materials: 0', 0, iY, 160, 20);
Inc(iY, 24); g_SampleUI.AddButton(IDC_SCROLLLEFT, '<<', 5, iY, 70, 24);
g_SampleUI.AddButton(IDC_SCROLLRIGHT, '>>', 85, iY, 70, 24);
Inc(iY, 32); g_SampleUI.AddCheckBox(IDC_SHARE, 'Enable shared parameters', 0, iY, 160, 24, True);
// Initialize the arcball
for i := 0 to High(g_MeshListData) do // SizeOf(g_MeshListData)/SizeOf(g_MeshListData[0]); ++i )
begin
// g_ArcBall.Add(CMeshArcBall);
l:= Length(g_ArcBall);
SetLength(g_ArcBall, l+1);
g_ArcBall[l]:= CMeshArcBall.Create;
g_ArcBall[l].SetTranslationRadius(2.0);
end;
// Setup the cameras
vecEye := D3DXVector3(0.0, 0.0, -5.0);
vecAt := D3DXVector3(0.0, 0.0, -3.0);
g_Camera.SetViewParams(vecEye, vecAt);
g_Camera.SetButtonMasks(0, MOUSE_WHEEL, 0);
g_Camera.SetRadius(5.0, 1.0);
end;
//--------------------------------------------------------------------------------------
// Called during device initialization, this code checks the device for some
// minimum set of capabilities, and rejects those that don't pass by returning false.
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
var
pD3D: IDirect3D9;
begin
Result := False;
// Skip backbuffer formats that don't support alpha blending
pD3D := DXUTGetD3DObject;
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat))
then Exit;
// Needs PS 1.1 support
if (pCaps.PixelShaderVersion < D3DPS_VERSION(1,1)) then Exit;
Result := True;
end;
//--------------------------------------------------------------------------------------
// This callback function is called immediately before a device is created to allow the
// application to modify the device settings. The supplied pDeviceSettings parameter
// contains the settings that the framework has selected for the new device, and the
// application can make any desired changes directly to this structure. Note however that
// DXUT will not correct invalid device settings so care must be taken
// to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail.
//--------------------------------------------------------------------------------------
{static} var s_bFirstTime: Boolean = True;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
var
bSvp, bHvp, bPHvp, bMvp: Boolean;
begin
// Turn vsync off
pDeviceSettings.pp.PresentationInterval := D3DPRESENT_INTERVAL_IMMEDIATE;
g_SettingsDlg.DialogControl.GetComboBox(DXUTSETTINGSDLG_PRESENT_INTERVAL).Enabled := False;
// If device doesn't support HW T&L or doesn't support 2.0 vertex shaders in HW
// then switch to SWVP.
if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or
(pCaps.VertexShaderVersion < D3DVS_VERSION(2,0))
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// If the hardware cannot do vertex blending, use software vertex processing.
if (pCaps.MaxVertexBlendMatrices < 2)
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// If using hardware vertex processing, change to mixed vertex processing
// so there is a fallback.
if (pDeviceSettings.BehaviorFlags and D3DCREATE_HARDWARE_VERTEXPROCESSING = 0)
then pDeviceSettings.BehaviorFlags := D3DCREATE_MIXED_VERTEXPROCESSING;
// Add mixed vp to the available vp choices in device settings dialog.
DXUTGetEnumeration.GetPossibleVertexProcessingList(bSvp, bHvp, bPHvp, bMvp);
DXUTGetEnumeration.SetPossibleVertexProcessingList(bSvp, False, False, True);
// Debugging vertex shaders requires either REF or software vertex processing
// and debugging pixel shaders requires REF.
{$IFDEF DEBUG_VS}
if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then
with pDeviceSettings do
begin
BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING;
BehaviorFlags := BehaviorFlags and not D3DCREATE_MIXED_VERTEXPROCESSING;
BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE;
BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING;
end;
{$ENDIF}
{$IFDEF DEBUG_PS}
pDeviceSettings.DeviceType := D3DDEVTYPE_REF;
{$ENDIF}
// For the first device created if its a REF device, optionally display a warning dialog box
if s_bFirstTime then
begin
s_bFirstTime := False;
if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning;
end;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// created, which will happen during application initialization and windowed/full screen
// toggles. This is the best location to create D3DPOOL_MANAGED resources since these
// resources need to be reloaded whenever the device is destroyed. Resources created
// here should be released in the OnDestroyDevice callback.
//--------------------------------------------------------------------------------------
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
str: WideString;
lr: TD3DLockedRect;
i, l: Integer;
NewMesh: TEffectMesh;
mW: TD3DXMatrixA16;
pVerts: Pointer;
vCtr: TD3DXVector3;
fRadius: Single;
m: TD3DXMatrixA16;
pD3DSD: PD3DSurfaceDesc;
begin
Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
// Create the effect pool object if shared param is enabled
if g_SampleUI.CheckBox[IDC_SHARE].Checked then
begin
Result:= D3DXCreateEffectPool(g_pEffectPool);
if V_Failed(Result) then Exit;
end;
// Create the vertex decl
Result:= pd3dDevice.CreateVertexDeclaration(@TMeshVertex_Decl, g_pDecl);
if V_Failed(Result) then Exit;
pd3dDevice.SetVertexDeclaration(g_pDecl);
// Create the 1x1 white default texture
Result:= pd3dDevice.CreateTexture(1, 1, 1, 0, D3DFMT_A8R8G8B8,
D3DPOOL_MANAGED, g_pDefaultTex, nil);
if V_Failed(Result) then Exit;
Result:= g_pDefaultTex.LockRect(0, lr, nil, 0);
if V_Failed(Result) then Exit;
PDWORD(lr.pBits)^ := D3DCOLOR_RGBA(255, 255, 255, 255);
Result:= g_pDefaultTex.UnlockRect(0);
if V_Failed(Result) then Exit;
// Create the environment map texture
Result:= DXUTFindDXSDKMediaFile(str, 'lobby\lobbycube.dds');
if V_Failed(Result) then Exit;
Result:= D3DXCreateCubeTextureFromFileW(pd3dDevice, PWideChar(str), g_pEnvMapTex);
if V_Failed(Result) then Exit;
// Initialize the font
Result:= DXUTGetGlobalResourceCache.CreateFont(pd3dDevice, 15, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
'Arial', g_pFont);
if V_Failed(Result) then Exit;
// Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the
// shader debugger. Debugging vertex shaders requires either REF or software vertex
// processing, and debugging pixel shaders requires REF. The
// D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the
// shader debugger. It enables source level debugging, prevents instruction
// reordering, prevents dead code elimination, and forces the compiler to compile
// against the next higher available software target, which ensures that the
// unoptimized shaders do not exceed the shader model limitations. Setting these
// flags will cause slower rendering since the shaders will be unoptimized and
// forced into software. See the DirectX documentation for more information about
// using the shader debugger.
{$IFDEF DEBUG}
// Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
g_dwShaderFlags := g_dwShaderFlags or D3DXSHADER_DEBUG;
{$ENDIF}
{$IFDEF DEBUG_VS}
g_dwShaderFlags := g_dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
{$ENDIF}
{$IFDEF DEBUG_PS}
g_dwShaderFlags := g_dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
{$ENDIF}
// Read the D3DX effect file
Result:= DXUTFindDXSDKMediaFile(str, 'EffectParam.fx');
if V_Failed(Result) then Exit;
// If this fails, there should be debug output as to
// they the .fx file failed to compile
Result:= DXUTGetGlobalResourceCache.CreateEffectFromFile(pd3dDevice, PWideChar(str), nil, nil, g_dwShaderFlags,
g_pEffectPool, g_pEffect, nil);
if V_Failed(Result) then Exit;
// Create the meshes
for i := 0 to High(g_MeshListData) do // ; i < SizeOf(g_MeshListData)/SizeOf(g_MeshListData[0]); ++i )
begin
NewMesh := TEffectMesh.Create;
if SUCCEEDED(NewMesh.Create(g_MeshListData[i].wszFile, DXUTGetD3DDevice)) then
begin
// g_Meshes.Add(NewMesh);
l:= Length(g_Meshes);
SetLength(g_Meshes, l+1);
g_Meshes[l]:= NewMesh;
pVerts := nil;
D3DXMatrixIdentity(mW);
if SUCCEEDED(NewMesh.Mesh.LockVertexBuffer(0, pVerts)) then
begin
if SUCCEEDED(D3DXComputeBoundingSphere(pVerts,
NewMesh.Mesh.GetNumVertices,
NewMesh.Mesh.GetNumBytesPerVertex,
vCtr, fRadius)) then
begin
D3DXMatrixTranslation(mW, -vCtr.x, -vCtr.y, -vCtr.z);
D3DXMatrixScaling(m, 1.0 / fRadius,
1.0 / fRadius,
1.0 / fRadius);
D3DXMatrixMultiply(mW, mW, m);
end;
NewMesh.Mesh.UnlockVertexBuffer;
end;
g_MeshListData[i].dwNumMat := NewMesh.NumMaterials;
// g_amWorld.Add(mW);
l:= Length(g_amWorld);
SetLength(g_amWorld, l+1);
g_amWorld[l]:= mW;
// Set the arcball window size
pD3DSD := DXUTGetBackBufferSurfaceDesc;
g_ArcBall[Length(g_ArcBall)-1].SetWindow(pD3DSD.Width, pD3DSD.Height);
end;
end;
g_SampleUI.Static[IDC_MESHNAME].Text := g_MeshListData[g_nActiveMesh].wszName;
g_SampleUI.Static[IDC_MATCOUNT].Text := PWideChar(WideFormat('Number of materials: %u', [g_MeshListData[g_nActiveMesh].dwNumMat]));
D3DXMatrixIdentity(g_mScroll);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// reset, which will happen after a lost device scenario. This is the best location to
// create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever
// the device is lost. Resources created here should be released in the OnLostDevice
// callback.
//--------------------------------------------------------------------------------------
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
fAspectRatio: Single;
i: Integer;
begin
Result:= g_DialogResourceManager.OnResetDevice;
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnResetDevice;
if V_Failed(Result) then Exit;
if Assigned(g_pFont) then
begin
Result:= g_pFont.OnResetDevice;
if V_Failed(Result) then Exit;
end;
if Assigned(g_pEffect) then
begin
Result:= g_pEffect.OnResetDevice;
if V_Failed(Result) then Exit;
end;
// Create a sprite to help batch calls when drawing many lines of text
Result:= D3DXCreateSprite(pd3dDevice, g_pTextSprite);
if V_Failed(Result) then Exit;
// Setup the camera's projection parameters
fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.1, 1000.0);
for i := 0 to Length(g_ArcBall) - 1 do
g_ArcBall[i].SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height);
g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0);
g_HUD.SetSize(170, 170);
g_SampleUI.SetLocation((pBackBufferSurfaceDesc.Width-170) div 2, pBackBufferSurfaceDesc.Height-120);
g_SampleUI.SetSize(170, 120);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called once at the beginning of every frame. This is the
// best location for your application to handle updates to the scene, but is not
// intended to contain actual rendering calls, which should instead be placed in the
// OnFrameRender callback.
//--------------------------------------------------------------------------------------
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
fFrameAngleToScroll: Single;
m: TD3DXMatrixA16;
begin
// Update the scroll matrix
fFrameAngleToScroll := g_fAngleToScroll * fElapsedTime / SCROLL_TIME;
if (Abs(fFrameAngleToScroll) > Abs(g_fAngleLeftToScroll)) then
fFrameAngleToScroll := g_fAngleLeftToScroll;
g_fAngleLeftToScroll := g_fAngleLeftToScroll - fFrameAngleToScroll;
D3DXMatrixRotationY(m, fFrameAngleToScroll);
D3DXMatrixMultiply(g_mScroll, g_mScroll, m);
// Update the camera's position based on user input
g_Camera.FrameMove(fElapsedTime);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called at the end of every frame to perform all the
// rendering calls for the scene, and it will also be called if the window needs to be
// repainted. After this function has returned, DXUT will call
// IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain
//--------------------------------------------------------------------------------------
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
mWorld, mWorldView, mViewProj: TD3DXMatrixA16;
mWorldViewProjection: TD3DXMatrixA16;
vLightView: TD3DXVector4;
fAngleDelta: Single;
i: Integer;
mRot, mTrans, m: TD3DXMatrixA16;
mViewInv: TD3DXMatrixA16;
begin
// If the settings dialog is being shown, then
// render it instead of rendering the app's scene
if g_SettingsDlg.Active then
begin
g_SettingsDlg.OnRender(fElapsedTime);
Exit;
end;
// Clear the render target and the zbuffer
V_(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 66, 75, 121), 1.0, 0));
// Render the scene
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
// Get the projection & view matrix from the camera class
D3DXMatrixMultiply(mViewProj, g_Camera.GetViewMatrix^, g_Camera.GetProjMatrix^);
// Update the effect's variables. Instead of using strings, it would
// be more efficient to cache a handle to the parameter by calling
// ID3DXEffect::GetParameterByName
///////////////////////////////////////////////////////////////////////
D3DXMatrixInverse(mViewInv, nil, g_Camera.GetViewMatrix^);
// g_pEffect.SetMatrix('g_mViewInv', mViewInv);
///////////////////////////////////////////////////////////////////////
vLightView := D3DXVector4(0.0, 0.0, -10.0, 1.0);
V_(g_pEffect.SetVector('g_vLight', vLightView));
fAngleDelta := D3DX_PI * 2.0 / Length(g_Meshes);
for i := 0 to Length(g_Meshes) - 1 do
begin
D3DXMatrixMultiply(mWorld, g_ArcBall[i].GetRotationMatrix^, g_ArcBall[i].GetTranslationMatrix^);
D3DXMatrixMultiply(mWorld, g_amWorld[i], mWorld);
D3DXMatrixTranslation(mTrans, 0.0, 0.0, -3.0);
D3DXMatrixRotationY(mRot, fAngleDelta * (i - g_nActiveMesh));
// mWorld *= mTrans * mRot * g_mScroll;
D3DXMatrixMultiply(m, mTrans, mRot);
D3DXMatrixMultiply(m, m, g_mScroll);
D3DXMatrixMultiply(mWorld, mWorld, m);
D3DXMatrixMultiply(mWorldView, mWorld, g_Camera.GetViewMatrix^);
D3DXMatrixMultiply(mWorldViewProjection, mWorld, mViewProj);
///////////////////////////////////////////////////////////////////
// V(g_pEffect.SetMatrix('g_mWorldViewProjection', mWorldViewProjection));
// V(g_pEffect.SetMatrix('g_mWorldView', mWorldView));
///////////////////////////////////////////////////////////////////
V(g_pEffect.SetMatrix('g_mWorld', mWorld));
V(g_pEffect.SetMatrix('g_mView', g_Camera.GetViewMatrix^));
V(g_pEffect.SetMatrix('g_mProj', g_Camera.GetProjMatrix^));
g_Meshes[i].Render(pd3dDevice);
end;
RenderText;
V_(g_HUD.OnRender(fElapsedTime));
V_(g_SampleUI.OnRender(fElapsedTime));
V_(pd3dDevice.EndScene);
end;
if (g_fAngleLeftToScroll = 0.0) then D3DXMatrixIdentity(g_mScroll);
end;
//--------------------------------------------------------------------------------------
// Render the help and statistics text. This function uses the ID3DXFont interface for
// efficient text rendering.
//--------------------------------------------------------------------------------------
procedure RenderText;
var
txtHelper: CDXUTTextHelper;
pd3dsdBackBuffer: PD3DSurfaceDesc;
begin
// The helper object simply helps keep track of text position, and color
// and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr );
// If NULL is passed in as the sprite object, then it will work however the
// pFont->DrawText() will not be batched together. Batching calls will improves performance.
txtHelper := CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15);
// Output statistics
txtHelper._Begin;
txtHelper.SetInsertionPos(5, 5);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0));
txtHelper.DrawTextLine(DXUTGetFrameStats(True)); // Show FPS
txtHelper.DrawTextLine(DXUTGetDeviceStats);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
txtHelper.DrawFormattedTextLine('Number of meshes: %d'#10, [Length(g_Meshes)]);
// Draw help
if g_bShowHelp then
begin
pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc;
txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-15*6);
txtHelper.SetForegroundColor(D3DXColor(1.0, 0.75, 0.0, 1.0));
txtHelper.DrawTextLine('Controls (F1 to hide):');
txtHelper.SetInsertionPos(40, pd3dsdBackBuffer.Height-15*5);
txtHelper.DrawTextLine('Rotate Mesh: Left mouse drag'#10+
'Zoom: Mouse wheel'#10+
'Quit: ESC');
end else
begin
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
txtHelper.DrawTextLine('Press F1 for help');
end;
// Draw shared param description
txtHelper.SetInsertionPos(5, 50);
if Assigned(g_pEffectPool) then
begin
txtHelper.SetForegroundColor(D3DXColor(0.0, 1.0, 0.0, 1.0));
txtHelper.DrawTextLine('Shared parameters are enabled. When updating transformation'#10+
'matrices on one effect object, all effect objects automatically'#10+
'see the updated values.');
end else
begin
txtHelper.SetForegroundColor(D3DXColor(1.0, 0.0, 0.0, 1.0));
txtHelper.DrawTextLine('Shared parameters are disabled. When transformation matrices'#10+
'are updated on the default effect object (diffuse only), only that'#10+
'effect object has the up-to-date values. All other effect objects'#10+
'do not have valid matrices for rendering.');
end;
txtHelper._End;
txtHelper.Free;
end;
//--------------------------------------------------------------------------------------
// Before handling window messages, DXUT passes incoming windows
// messages to the application through this callback function. If the application sets
// *pbNoFurtherProcessing to TRUE, then DXUT will not process this message.
//--------------------------------------------------------------------------------------
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
var
mViewRotate: TD3DXMatrixA16;
begin
Result:= 0;
// Always allow dialog resource manager calls to handle global messages
// so GUI state is updated correctly
pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
if g_SettingsDlg.IsActive then
begin
g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam);
Exit;
end;
// Give the dialogs a chance to handle the message first
pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
// Pass all remaining windows messages to camera so it can respond to user input
g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam);
mViewRotate := g_Camera.GetViewMatrix^;
mViewRotate._41 := 0.0; mViewRotate._42 := 0.0; mViewRotate._43 := 0.0;
D3DXMatrixInverse(mViewRotate, nil, mViewRotate);
if (Length(g_ArcBall) > 0) then
g_ArcBall[g_nActiveMesh].HandleMessages(hWnd, uMsg, wParam, lParam, mViewRotate);
end;
//--------------------------------------------------------------------------------------
// As a convenience, DXUT inspects the incoming windows messages for
// keystroke messages and decodes the message parameters to pass relevant keyboard
// messages to the application. The framework does not remove the underlying keystroke
// messages, which are still passed to the application's MsgProc callback.
//--------------------------------------------------------------------------------------
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
begin
if bKeyDown then
begin
case nChar of
VK_F1: g_bShowHelp := not g_bShowHelp;
end;
end;
end;
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
begin
case nControlID of
IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen;
IDC_TOGGLEREF: DXUTToggleREF;
IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active;
IDC_SHARE:
begin
// Shared param status changed. Destroy and recreate everything
// with or without effect pool as appropriate.
if (DXUTGetD3DDevice <> nil) then
begin
// We need to call the callbacks of the resource manager or the ref
// count will not reach 0.
OnLostDevice(nil);
DXUTGetGlobalResourceCache.OnLostDevice;
OnDestroyDevice(nil);
DXUTGetGlobalResourceCache.OnDestroyDevice;
OnCreateDevice(DXUTGetD3DDevice, DXUTGetBackBufferSurfaceDesc^, nil);
DXUTGetGlobalResourceCache.OnCreateDevice(DXUTGetD3DDevice);
OnResetDevice(DXUTGetD3DDevice, DXUTGetBackBufferSurfaceDesc^, nil);
DXUTGetGlobalResourceCache.OnResetDevice(DXUTGetD3DDevice);
end;
end;
IDC_SCROLLLEFT,
IDC_SCROLLRIGHT:
begin
// Only scroll if we have more than one mesh
if (Length(g_Meshes) <= 1) then Exit;
// Only scroll if we are not already scrolling
if (g_fAngleLeftToScroll <> 0.0) then Exit;
// Compute the angle to scroll
{g_fAngleToScroll = g_fAngleLeftToScroll = nControlID == IDC_SCROLLLEFT ? -D3DX_PI * 2.0f / g_Meshes.GetSize() :
D3DX_PI * 2.0f / g_Meshes.GetSize();}
g_fAngleLeftToScroll := IfThen(nControlID = IDC_SCROLLLEFT,
-D3DX_PI * 2.0 / Length(g_Meshes),
D3DX_PI * 2.0 / Length(g_Meshes));
g_fAngleToScroll := g_fAngleLeftToScroll;
// Initialize the scroll matrix to be reverse full-angle rotation,
// then gradually decrease to zero (identity).
D3DXMatrixRotationY(g_mScroll, -g_fAngleToScroll);
// Update front mesh index
if (nControlID = IDC_SCROLLLEFT) then
begin
Inc(g_nActiveMesh);
if (g_nActiveMesh = Length(g_Meshes)) then g_nActiveMesh := 0;
end else
begin
Dec(g_nActiveMesh);
if (g_nActiveMesh < 0) then g_nActiveMesh := Length(g_Meshes) - 1;
end;
// Update mesh name and material count
g_SampleUI.Static[IDC_MESHNAME].Text := g_MeshListData[g_nActiveMesh].wszName;
g_SampleUI.Static[IDC_MATCOUNT].Text := PWideChar(WideFormat('Number of materials: %u', [g_MeshListData[g_nActiveMesh].dwNumMat]));
end;
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// entered a lost state and before IDirect3DDevice9::Reset is called. Resources created
// in the OnResetDevice callback should be released here, which generally includes all
// D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for
// information about lost devices.
//--------------------------------------------------------------------------------------
procedure OnLostDevice; stdcall;
begin
g_DialogResourceManager.OnLostDevice;
g_SettingsDlg.OnLostDevice;
if Assigned(g_pFont) then g_pFont.OnLostDevice;
if Assigned(g_pEffect) then g_pEffect.OnLostDevice;
g_pTextSprite := nil;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// been destroyed, which generally happens as a result of application termination or
// windowed/full screen toggles. Resources created in the OnCreateDevice callback
// should be released here, which generally includes all D3DPOOL_MANAGED resources.
//--------------------------------------------------------------------------------------
procedure OnDestroyDevice; stdcall;
var
i: Integer;
begin
g_DialogResourceManager.OnDestroyDevice;
g_SettingsDlg.OnDestroyDevice;
g_pEffect := nil;
g_pFont := nil;
g_pDefaultTex := nil;
g_pEffectPool := nil;
g_pDecl := nil;
g_pEnvMapTex := nil;
for i := 0 to Length(g_Meshes) - 1 do g_Meshes[i].Destroy;
g_Meshes := nil;
g_amWorld := nil;
end;
procedure CreateCustomDXUTobjects;
begin
g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs
g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog
g_Camera:= CModelViewerCamera.Create; // A model viewing camera
g_HUD:= CDXUTDialog.Create; // dialog for standard controls
g_SampleUI:= CDXUTDialog.Create; // dialog for sample specific controls
end;
procedure DestroyCustomDXUTobjects;
begin
FreeAndNil(g_DialogResourceManager);
FreeAndNil(g_SettingsDlg);
FreeAndNil(g_Camera);
FreeAndNil(g_HUD);
FreeAndNil(g_SampleUI);
end;
end.
|
//
// Generated by JavaToPas v1.5 20160510 - 150202
////////////////////////////////////////////////////////////////////////////////
unit android.view.WindowId;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.os;
type
JWindowId_FocusObserver = interface; // merged
JWindowId = interface;
JWindowIdClass = interface(JObjectClass)
['{C099E2D5-2968-4B4C-B6F9-C8A85B4EC410}']
function _GetCREATOR : JParcelable_Creator; cdecl; // A: $19
function describeContents : Integer; cdecl; // ()I A: $1
function equals(otherObj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function isFocused : boolean; cdecl; // ()Z A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure registerFocusObserver(observer : JWindowId_FocusObserver) ; cdecl;// (Landroid/view/WindowId$FocusObserver;)V A: $1
procedure unregisterFocusObserver(observer : JWindowId_FocusObserver) ; cdecl;// (Landroid/view/WindowId$FocusObserver;)V A: $1
procedure writeToParcel(&out : 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/view/WindowId$FocusObserver')]
JWindowId = interface(JObject)
['{F03794C1-277D-4FFE-B038-A246D855F6BE}']
function describeContents : Integer; cdecl; // ()I A: $1
function equals(otherObj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function isFocused : boolean; cdecl; // ()Z A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure registerFocusObserver(observer : JWindowId_FocusObserver) ; cdecl;// (Landroid/view/WindowId$FocusObserver;)V A: $1
procedure unregisterFocusObserver(observer : JWindowId_FocusObserver) ; cdecl;// (Landroid/view/WindowId$FocusObserver;)V A: $1
procedure writeToParcel(&out : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1
end;
TJWindowId = class(TJavaGenericImport<JWindowIdClass, JWindowId>)
end;
// Merged from: c:\users\anonymous\documents\rad studio\java2pas\android-n\android.view.WindowId_FocusObserver.pas
JWindowId_FocusObserverClass = interface(JObjectClass)
['{A904BCAE-F483-4719-A4E6-A33F1DA684E1}']
function init : JWindowId_FocusObserver; cdecl; // ()V A: $1
procedure onFocusGained(JWindowIdparam0 : JWindowId) ; cdecl; // (Landroid/view/WindowId;)V A: $401
procedure onFocusLost(JWindowIdparam0 : JWindowId) ; cdecl; // (Landroid/view/WindowId;)V A: $401
end;
[JavaSignature('android/view/WindowId_FocusObserver')]
JWindowId_FocusObserver = interface(JObject)
['{B891E8CD-887F-4018-B54D-3618DA02E734}']
procedure onFocusGained(JWindowIdparam0 : JWindowId) ; cdecl; // (Landroid/view/WindowId;)V A: $401
procedure onFocusLost(JWindowIdparam0 : JWindowId) ; cdecl; // (Landroid/view/WindowId;)V A: $401
end;
TJWindowId_FocusObserver = class(TJavaGenericImport<JWindowId_FocusObserverClass, JWindowId_FocusObserver>)
end;
implementation
end.
|
unit AST.Classes;
interface
uses AST.Lexer, AST.Intf, AST.Parser.Utils, AST.Parser.ProcessStatuses, System.SysUtils;
type
TASTItemTypeID = Integer;
TASTTokenId = Integer;
TASTItem = class;
TASTProject = class;
TASTModule = class;
TASTDeclaration = class;
TASTExpression = class;
TASTExpressionArray = array of TASTExpression;
TASTUnitClass = class of TASTModule;
TCompilerResult = (
CompileNone,
CompileInProgress,
CompileSuccess,
CompileFail,
CompileSkip
);
TASTItem = class(TPooledObject)
private
fParent: TASTItem;
fNext: TASTItem;
//function GetItemTypeID: TASTItemTypeID; virtual; abstract;
protected
function GetDisplayName: string; virtual;
public
constructor Create(Parent: TASTItem); virtual;
// property TypeID: TASTItemTypeID read GetItemTypeID;
property Next: TASTItem read fNext write fNext;
property DisplayName: string read GetDisplayName;
property Parent: TASTItem read fParent;
end;
TASTItemClass = class of TASTItem;
TASTProjectSettings = class(TInterfacedObject, IASTProjectSettings)
end;
TASTProject = class(TInterfacedObject, IASTProject)
private
fOnProgress: TASTProgressEvent;
fOnConsoleProc: TASTRrojectConsoleWriteEvent;
procedure SetOnProgress(const Value: TASTProgressEvent);
procedure SetOnConsoleWrite(const Value: TASTRrojectConsoleWriteEvent);
function GetOnProgress: TASTProgressEvent;
function GetOnConsoleWrite: TASTRrojectConsoleWriteEvent;
protected
function GetUnitClass: TASTUnitClass; virtual; abstract;
function GetPointerSize: Integer; virtual; abstract;
function GetNativeIntSize: Integer; virtual; abstract;
function GetTotalLinesParsed: Integer; virtual;
function GetTotalUnitsParsed: Integer; virtual;
function GetTotalUnitsIntfOnlyParsed: Integer; virtual;
public
constructor Create(const Name: string); virtual; abstract;
property OnProgress: TASTProgressEvent read GetOnProgress write SetOnProgress;
procedure CosoleWrite(const Module: IASTModule; Line: Integer; const Message: string);
end;
TASTParentItem = class(TASTItem)
private
fFirstChild: TASTItem;
fLastChild: TASTItem;
protected
function GetDisplayName: string; override;
public
procedure AddChild(Item: TASTItem);
property FirstChild: TASTItem read fFirstChild;
property LastChild: TASTItem read fLastChild;
end;
TASTBlock = class(TASTParentItem)
private
function GetIsLoopBody: Boolean;
function GetIsTryBlock: Boolean;
public
property IsLoopBody: Boolean read GetIsLoopBody;
property IsTryBlock: Boolean read GetIsTryBlock;
end;
TEnumASTDeclProc = reference to procedure (const Module: TASTModule; const Decl: TASTDeclaration);
TASTModule = class(TInterfacedObject, IASTModule)
private
fProject: IASTProject;
fFileName: string;
protected
fTotalLinesParsed: Integer;
function GetModuleName: string; virtual;
function GetSource: string; virtual; abstract;
procedure SetFileName(const Value: string);
procedure Progress(StatusClass: TASTProcessStatusClass); virtual;
public
property Name: string read GetModuleName;
property FileName: string read fFileName write SetFileName;
property Project: IASTProject read fProject;
function GetFirstFunc: TASTDeclaration; virtual; abstract;
function GetFirstVar: TASTDeclaration; virtual; abstract;
function GetFirstType: TASTDeclaration; virtual; abstract;
function GetFirstConst: TASTDeclaration; virtual; abstract;
function GetTotalLinesParsed: Integer;
constructor Create(const Project: IASTProject; const FileName: string; const Source: string = ''); virtual;
constructor CreateFromFile(const Project: IASTProject; const FileName: string); virtual;
procedure EnumIntfDeclarations(const Proc: TEnumASTDeclProc); virtual; abstract;
procedure EnumAllDeclarations(const Proc: TEnumASTDeclProc); virtual; abstract;
property TotalLinesParsed: Integer read GetTotalLinesParsed;
end;
TASTDeclaration = class(TASTItem)
protected
fID: TIdentifier;
fModule: TASTModule;
function GetDisplayName: string; override;
public
property ID: TIdentifier read fID write fID;
property Name: string read fID.Name write FID.Name;
property TextPosition: TTextPosition read FID.TextPosition write FID.TextPosition;
property SourcePosition: TTextPosition read FID.TextPosition;
property Module: TASTModule read fModule;
end;
TASTDeclarations = array of TASTDeclaration;
TASTOperation = class(TASTItem)
end;
TASTOperationClass = class of TASTOperation;
TASTOpOpenRound = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpCloseRound = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpPlus = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpMinus = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpEqual = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpNotEqual = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpGrater = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpGraterEqual = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpLess = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpLessEqual = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpMul = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpDiv = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpIntDiv = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpMod = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpBinAnd = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpBinOr = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpBinXor = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpBinNot = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpLogicalAnd = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpLogicalOr = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpLogicalNot = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpShr = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpShl = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpRawCast = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpDynCast = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpCastCheck = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTOpCallProc = class(TASTOperation)
private
fProc: TASTDeclaration;
fArgs: TASTExpressionArray;
protected
function GetDisplayName: string; override;
public
property Proc: TASTDeclaration read fProc write fProc;
procedure AddArg(const Expr: TASTExpression);
end;
TASTOpArrayAccess = class(TASTOperation)
private
fIndexes: TASTExpressionArray;
protected
function GetDisplayName: string; override;
public
property Indexes: TASTExpressionArray read fIndexes write fIndexes;
procedure AddIndex(Expr: TASTExpression);
end;
TASTOpMemberAccess = class(TASTOperation)
protected
function GetDisplayName: string; override;
end;
TASTEIDecl = class(TASTOperation)
private
fDecl: TASTDeclaration;
fSPos: TTextPosition;
protected
function GetDisplayName: string; override;
public
constructor Create(Decl: TASTDeclaration; const SrcPos: TTextPosition); reintroduce;
end;
TASTExpression = class(TASTParentItem)
protected
function GetDisplayName: string; override;
public
procedure AddSubItem(ItemClass: TASTOperationClass);
procedure AddDeclItem(Decl: TASTDeclaration; const SrcPos: TTextPosition);
function AddOperation<TASTClass: TASTOperation>: TASTClass;
end;
TASTKeyword = class(TASTItem)
end;
TASTOpAssign = class(TASTItem)
private
fDst: TASTExpression;
fSrc: TASTExpression;
protected
function GetDisplayName: string; override;
public
property Dst: TASTExpression read fDst write fDst;
property Src: TASTExpression read fSrc write fSrc;
end;
TASTKWGoTo = class(TASTKeyword)
private
fLabel: TASTDeclaration;
protected
function GetDisplayName: string; override;
public
property LabelDecl: TASTDeclaration read fLabel write fLabel;
end;
TASTKWLabel = class(TASTKeyword)
private
fLabel: TASTDeclaration;
protected
function GetDisplayName: string; override;
public
property LabelDecl: TASTDeclaration read fLabel write fLabel;
end;
TASTCall = class(TASTExpression)
end;
TASTVariable = class(TASTDeclaration)
end;
TASTKWExit = class(TASTKeyword)
private
fExpression: TASTExpression;
protected
function GetDisplayName: string; override;
public
property Expression: TASTExpression read fExpression write fExpression;
end;
TASTKWIF = class(TASTKeyword)
type
TASTKWIfThenBlock = class(TASTBlock) end;
TASTKWIfElseBlock = class(TASTBlock) end;
private
fExpression: TASTExpression;
fThenBody: TASTBlock;
fElseBody: TASTBlock;
protected
function GetDisplayName: string; override;
public
constructor Create(Parent: TASTItem = nil); override;
property Expression: TASTExpression read fExpression write fExpression;
property ThenBody: TASTBlock read fThenBody write fThenBody;
property ElseBody: TASTBlock read fElseBody write fElseBody;
end;
TASTKWLoop = class(TASTKeyword)
private
fBody: TASTBlock;
public
constructor Create(Parent: TASTItem = nil); override;
property Body: TASTBlock read fBody;
end;
TASTKWWhile = class(TASTKWLoop)
private
fExpression: TASTExpression;
protected
function GetDisplayName: string; override;
public
property Expression: TASTExpression read fExpression write fExpression;
end;
TASTKWRepeat = class(TASTKWLoop)
private
fExpression: TASTExpression;
protected
function GetDisplayName: string; override;
public
property Expression: TASTExpression read fExpression write fExpression;
end;
TDirection = (dForward, dBackward);
TASTKWFor = class(TASTKWLoop)
private
fExprInit: TASTExpression;
fExprTo: TASTExpression;
fDirection: TDirection;
protected
function GetDisplayName: string; override;
public
property ExprInit: TASTExpression read fExprInit write fExprInit;
property ExprTo: TASTExpression read fExprTo write fExprTo;
property Direction: TDirection read fDirection write fDirection;
end;
TASTKWForIn = class(TASTKWLoop)
private
fVar: TASTExpression;
fList: TASTExpression;
protected
function GetDisplayName: string; override;
public
property VarExpr: TASTExpression read fVar write fVar;
property ListExpr: TASTExpression read fList write fList;
end;
TASTKWBreak = class(TASTKeyword)
protected
function GetDisplayName: string; override;
end;
TASTKWContinue = class(TASTKeyword)
protected
function GetDisplayName: string; override;
end;
TASTKWRaise = class(TASTKeyword)
private
fExpr: TASTExpression;
protected
function GetDisplayName: string; override;
public
property Expression: TASTExpression read fExpr write fExpr;
end;
TASTKWInherited = class(TASTKeyword)
private
fExpr: TASTExpression;
protected
function GetDisplayName: string; override;
public
property Expression: TASTExpression read fExpr write fExpr;
end;
TASTKWWith = class(TASTKeyword)
private
fExpressions: TASTExpressionArray;
fBody: TASTBlock;
protected
function GetDisplayName: string; override;
public
constructor Create(Parent: TASTItem); override;
property Expressions: TASTExpressionArray read fExpressions;
property Body: TASTBlock read fBody;
procedure AddExpression(const Expr: TASTExpression);
end;
TASTExpBlockItem = class(TASTItem)
private
fExpression: TASTExpression;
fBody: TASTBlock;
public
constructor Create(Parent: TASTItem); override;
property Expression: TASTExpression read fExpression;
property Body: TASTBlock read fBody;
end;
TASTKWTryExceptItem = class(TASTExpBlockItem)
protected
function GetDisplayName: string; override;
end;
TASTKWInheritedCall = class(TASTKeyword)
private
fProc: TASTExpression;
protected
function GetDisplayName: string; override;
end;
TASTKWCase = class(TASTKeyword)
private
fExpression: TASTExpression;
fFirstItem: TASTExpBlockItem;
fLastItem: TASTExpBlockItem;
fElseBody: TASTBlock;
protected
function GetDisplayName: string; override;
public
constructor Create(Parent: TASTItem); override;
function AddItem(Expression: TASTExpression): TASTExpBlockItem;
property Expression: TASTExpression read fExpression write fExpression;
property FirstItem: TASTExpBlockItem read fFirstItem;
property ElseBody: TASTBlock read fElseBody;
end;
TASTKWTryBlock = class(TASTKeyword)
private
fBody: TASTBlock;
fFinallyBody: TASTBlock;
fFirstExceptBlock: TASTKWTryExceptItem;
fLastExceptBlock: TASTKWTryExceptItem;
protected
function GetDisplayName: string; override;
public
constructor Create(Parent: TASTItem); override;
property Body: TASTBlock read fBody;
property FinallyBody: TASTBlock read fFinallyBody write fFinallyBody;
property FirstExceptBlock: TASTKWTryExceptItem read fFirstExceptBlock;
property LastExceptBlock: TASTKWTryExceptItem read fLastExceptBlock;
function AddExceptBlock(Expression: TASTExpression): TASTKWTryExceptItem;
end;
TASTKWDeclSection = class(TASTKeyword)
private
fDecls: TASTDeclarations;
public
procedure AddDecl(const Decl: TASTDeclaration);
property Decls: TASTDeclarations read fDecls;
end;
TASTKWInlineVarDecl = class(TASTKWDeclSection)
private
fExpression: TASTExpression;
protected
function GetDisplayName: string; override;
public
property Expression: TASTExpression read fExpression write fExpression;
end;
TASTKWInlineConstDecl = class(TASTKeyword)
protected
function GetDisplayName: string; override;
end;
TASTKWAsm = class(TASTKeyword)
protected
function GetDisplayName: string; override;
end;
TASTFunc = class(TASTDeclaration)
private
fBody: TASTBlock;
protected
property Body: TASTBlock read fBody;
end;
TASTType = class(TASTDeclaration)
end;
implementation
uses System.StrUtils;
procedure TASTParentItem.AddChild(Item: TASTItem);
begin
if Assigned(fLastChild) then
fLastChild.Next := Item
else
fFirstChild := Item;
fLastChild := Item;
end;
{ TASTExpression }
procedure TASTExpression.AddDeclItem(Decl: TASTDeclaration; const SrcPos: TTextPosition);
var
Item: TASTEIDecl;
begin
Item := TASTEIDecl.Create(Decl, SrcPos);
AddChild(Item);
end;
function TASTExpression.AddOperation<TASTClass>: TASTClass;
begin
Result := TASTClass.Create(Self);
AddChild(Result);
end;
procedure TASTExpression.AddSubItem(ItemClass: TASTOperationClass);
var
Item: TASTOperation;
begin
Item := ItemClass.Create(Self);
AddChild(Item);
end;
{ TASTUnit }
constructor TASTModule.Create(const Project: IASTProject; const FileName: string; const Source: string);
begin
fProject := Project;
fFileName := FileName;
end;
function TASTExpression.GetDisplayName: string;
var
Item: TASTItem;
begin
Result := '';
Item := FirstChild;
while Assigned(Item) do
begin
Result := AddStringSegment(Result, Item.DisplayName, ' ');
Item := Item.Next;
end;
end;
{ TASTItem }
constructor TASTItem.Create(Parent: TASTItem);
begin
CreateFromPool;
fParent := Parent;
end;
function TASTItem.GetDisplayName: string;
begin
Result := '';
end;
{ TASTKWExit }
function TASTKWExit.GetDisplayName: string;
var
ExprStr: string;
begin
if Assigned(fExpression) then
ExprStr := fExpression.DisplayName;
Result := 'return ' + ExprStr;
end;
function TASTParentItem.GetDisplayName: string;
begin
end;
{ TASTEIOpenRound }
function TASTOpOpenRound.GetDisplayName: string;
begin
Result := '(';
end;
{ TASTEICloseRound }
function TASTOpCloseRound.GetDisplayName: string;
begin
Result := ')';
end;
{ TASTEIPlus }
function TASTOpPlus.GetDisplayName: string;
begin
Result := '+';
end;
{ TASTEIMinus }
function TASTOpMinus.GetDisplayName: string;
begin
Result := '-';
end;
{ TASTEIMul }
function TASTOpMul.GetDisplayName: string;
begin
Result := '*';
end;
{ TASTEIDiv }
function TASTOpDiv.GetDisplayName: string;
begin
Result := '/';
end;
{ TASTEIIntDiv }
function TASTOpIntDiv.GetDisplayName: string;
begin
Result := 'div';
end;
{ TASTEIMod }
function TASTOpMod.GetDisplayName: string;
begin
Result := 'mod';
end;
{ TASTEIEqual }
function TASTOpEqual.GetDisplayName: string;
begin
Result := '=';
end;
{ TASTEINotEqual }
function TASTOpNotEqual.GetDisplayName: string;
begin
Result := '<>';
end;
{ TASTEIGrater }
function TASTOpGrater.GetDisplayName: string;
begin
Result := '>';
end;
{ TASTEIGraterEqual }
function TASTOpGraterEqual.GetDisplayName: string;
begin
Result := '>=';
end;
{ TASTEILess }
function TASTOpLess.GetDisplayName: string;
begin
Result := '<';
end;
{ TASTEILessEqual }
function TASTOpLessEqual.GetDisplayName: string;
begin
Result := '<=';
end;
{ TASTEIVariable }
constructor TASTEIDecl.Create(Decl: TASTDeclaration; const SrcPos: TTextPosition);
begin
CreateFromPool;
fDecl := Decl;
fSPos := SrcPos;
end;
function TASTEIDecl.GetDisplayName: string;
begin
Result := fDecl.DisplayName;
end;
{ TASTDeclaration }
function TASTDeclaration.GetDisplayName: string;
begin
Result := fID.Name;
end;
{ TASTKWAssign }
function TASTOpAssign.GetDisplayName: string;
begin
Result := fDst.DisplayName + ' := ' + fSrc.DisplayName;
end;
{ TASTKWIF }
constructor TASTKWIF.Create(Parent: TASTItem);
begin
inherited;
fThenBody := TASTKWIfThenBlock.Create(Self);
end;
function TASTKWIF.GetDisplayName: string;
begin
Result := 'IF ' + fExpression.DisplayName;
end;
{ TASTKWhile }
function TASTKWWhile.GetDisplayName: string;
begin
Result := 'while ' + fExpression.DisplayName;
end;
{ TASTRepeat }
function TASTKWRepeat.GetDisplayName: string;
begin
Result := 'repeat ' + fExpression.DisplayName;
end;
{ TASTKWWith }
procedure TASTKWWith.AddExpression(const Expr: TASTExpression);
begin
fExpressions := fExpressions + [Expr];
end;
constructor TASTKWWith.Create(Parent: TASTItem);
begin
inherited;
fBody := TASTBlock.Create(Self);
end;
function TASTKWWith.GetDisplayName: string;
begin
Result := 'with ';
end;
{ TASTKWFor }
function TASTKWFor.GetDisplayName: string;
begin
Result := 'for ' + fExprInit.DisplayName + ' ' + ifthen(fDirection = dForward, 'to', 'downto') + ' ' + fExprTo.DisplayName;
end;
{ TASTKWLoop }
constructor TASTKWLoop.Create(Parent: TASTItem = nil);
begin
inherited;
fBody := TASTBlock.Create(Self);
end;
{ TASTKWSwitch }
function TASTKWCase.AddItem(Expression: TASTExpression): TASTExpBlockItem;
begin
Result := TASTExpBlockItem.Create(Self);
Result.fExpression := Expression;
if Assigned(fLastItem) then
fLastItem.Next := Result
else
fFirstItem := Result;
fLastItem := Result;
end;
constructor TASTKWCase.Create(Parent: TASTItem);
begin
inherited;
fElseBody := TASTBlock.Create(Self);
end;
function TASTKWCase.GetDisplayName: string;
begin
Result := 'case ' + fExpression.DisplayName;
end;
{ TASTKWSwitchItem }
constructor TASTExpBlockItem.Create(Parent: TASTItem);
begin
inherited;
fBody := TASTBlock.Create(Self);
end;
{ TASTBody }
function TASTBlock.GetIsLoopBody: Boolean;
var
Item: TASTItem;
begin
Result := fParent is TASTKWLoop;
if not Result then
begin
Item := fParent;
while Assigned(Item) do
begin
if (Item is TASTBlock) and TASTBlock(Item).IsLoopBody then
Exit(True);
Item := Item.Parent;
end;
end;
end;
function TASTBlock.GetIsTryBlock: Boolean;
begin
Result := fParent.ClassType = TASTKWTryBlock;
end;
{ TASTKWBreak }
function TASTKWBreak.GetDisplayName: string;
begin
Result := 'break';
end;
{ TASTKContinue }
function TASTKWContinue.GetDisplayName: string;
begin
Result := 'continue';
end;
{ TASTKWTryBlock }
function TASTKWTryBlock.AddExceptBlock(Expression: TASTExpression): TASTKWTryExceptItem;
begin
Result := TASTKWTryExceptItem.Create(Self);
Result.fExpression := Expression;
if Assigned(fLastExceptBlock) then
fLastExceptBlock.Next := Result
else
fFirstExceptBlock := Result;
fLastExceptBlock := Result;
end;
constructor TASTKWTryBlock.Create(Parent: TASTItem);
begin
inherited;
fBody := TASTBlock.Create(Self);
end;
function TASTKWTryBlock.GetDisplayName: string;
begin
Result := 'try';
end;
{ TASTKWInherited }
function TASTKWInherited.GetDisplayName: string;
begin
Result := 'inherited call';
if Assigned(Expression) then
Result := Result + ' ' + Expression.DisplayName;
end;
{ TASTKWRaise }
function TASTKWRaise.GetDisplayName: string;
begin
Result := 'raise';
if Assigned(Expression) then
Result := Result + ' ' + Expression.DisplayName;
end;
{ TASTKWImmVarDecl }
function TASTKWInlineVarDecl.GetDisplayName: string;
begin
Result := 'var';
if Assigned(fExpression) then
Result := Result + ' = ' + fExpression.DisplayName;
end;
{ TASTKWImmConstDecl }
function TASTKWInlineConstDecl.GetDisplayName: string;
begin
Result := 'const';
end;
{ TASTKWDeclSection }
procedure TASTKWDeclSection.AddDecl(const Decl: TASTDeclaration);
begin
fDecls := fDecls + [Decl];
end;
{ TASTKWGoTo }
function TASTKWGoTo.GetDisplayName: string;
begin
Result := 'goto ' + fLabel.DisplayName;
end;
{ TASTKWLabel }
function TASTKWLabel.GetDisplayName: string;
begin
Result := 'label ' + fLabel.DisplayName + ':';
end;
{ TASTKWTryExceptItem }
function TASTKWTryExceptItem.GetDisplayName: string;
begin
if Assigned(fExpression) then
Result := fExpression.DisplayName + ': '
else
Result := '';
end;
{ TASTKWAsm }
function TASTKWAsm.GetDisplayName: string;
begin
Result := 'asm';
end;
{ TASTKWInheritedCall }
function TASTKWInheritedCall.GetDisplayName: string;
begin
Result := 'inherited ' + fProc.DisplayName;
end;
{ TASTEICallProc }
procedure TASTOpCallProc.AddArg(const Expr: TASTExpression);
begin
fArgs := fArgs + [Expr];
end;
function TASTOpCallProc.GetDisplayName: string;
var
SArgs: string;
begin
for var Arg in fArgs do
SArgs := AddStringSegment(SArgs, Arg.DisplayName, ', ');
Result := 'call ' + fProc.DisplayName + '(' + SArgs + ')';
end;
{ TASTKWForIn }
function TASTKWForIn.GetDisplayName: string;
begin
Result := 'for ' + fVar.DisplayName + ' in ' + fList.DisplayName;
end;
{ TASTOpArrayAccess }
procedure TASTOpArrayAccess.AddIndex(Expr: TASTExpression);
begin
fIndexes := fIndexes + [Expr];
end;
function TASTOpArrayAccess.GetDisplayName: string;
var
SIndexes: string;
begin
for var Expr in fIndexes do
SIndexes := AddStringSegment(SIndexes, Expr.DisplayName, ', ');
Result := '[' + SIndexes + ']';
end;
{ TASTOpMemberAccess }
function TASTOpMemberAccess.GetDisplayName: string;
begin
Result := '.';
end;
{ TASTOpShr }
function TASTOpShr.GetDisplayName: string;
begin
Result := 'shr';
end;
{ TASTOpShl }
function TASTOpShl.GetDisplayName: string;
begin
Result := 'shl';
end;
{ TASTOpRawCast }
function TASTOpRawCast.GetDisplayName: string;
begin
Result := 'rawcast';
end;
{ TASTOpDynCast }
function TASTOpDynCast.GetDisplayName: string;
begin
Result := 'dyncast';
end;
{ TASTOpCastCheck }
function TASTOpCastCheck.GetDisplayName: string;
begin
Result := 'castcheck';
end;
{ TASTOpBinAnd }
function TASTOpBinAnd.GetDisplayName: string;
begin
Result := 'band';
end;
{ TASTOpBinOr }
function TASTOpBinOr.GetDisplayName: string;
begin
Result := 'bor';
end;
{ TASTOpBinXor }
function TASTOpBinXor.GetDisplayName: string;
begin
Result := 'bxor';
end;
{ TASTOpBinNot }
function TASTOpBinNot.GetDisplayName: string;
begin
Result := 'bnot';
end;
{ TASTOpLogicalAnd }
function TASTOpLogicalAnd.GetDisplayName: string;
begin
Result := 'land';
end;
{ TASTOpLogicalOr }
function TASTOpLogicalOr.GetDisplayName: string;
begin
Result := 'lor';
end;
{ TASTOpLogicalNot }
function TASTOpLogicalNot.GetDisplayName: string;
begin
Result := 'lnot';
end;
constructor TASTModule.CreateFromFile(const Project: IASTProject; const FileName: string);
begin
fFileName := FileName;
end;
function TASTModule.GetModuleName: string;
begin
Result := ExtractFileName(fFileName);
end;
function TASTModule.GetTotalLinesParsed: Integer;
begin
Result := fTotalLinesParsed;
end;
procedure TASTModule.Progress(StatusClass: TASTProcessStatusClass);
var
Event: TASTProgressEvent;
begin
Event := fProject.OnProgress;
if Assigned(Event) then
Event(Self, StatusClass);
end;
procedure TASTModule.SetFileName(const Value: string);
begin
fFileName := Value;
end;
{ TASTProject }
procedure TASTProject.CosoleWrite(const Module: IASTModule; Line: Integer; const Message: string);
begin
if Assigned(fOnConsoleProc) then
fOnConsoleProc(Module, Line, Message);
end;
function TASTProject.GetOnConsoleWrite: TASTRrojectConsoleWriteEvent;
begin
Result := fOnConsoleProc;
end;
function TASTProject.GetOnProgress: TASTProgressEvent;
begin
Result := fOnProgress;
end;
function TASTProject.GetTotalLinesParsed: Integer;
begin
Result := 0;
end;
function TASTProject.GetTotalUnitsIntfOnlyParsed: Integer;
begin
Result := 0;
end;
function TASTProject.GetTotalUnitsParsed: Integer;
begin
Result := 0;
end;
procedure TASTProject.SetOnConsoleWrite(const Value: TASTRrojectConsoleWriteEvent);
begin
fOnConsoleProc := Value;
end;
procedure TASTProject.SetOnProgress(const Value: TASTProgressEvent);
begin
fOnProgress := Value;
end;
end.
|
unit uNewPosTransaction;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
StrUtils, uNewUnit, uTSBaseClass, uNewBarangHargaJual, uNewBeginningBalance,
uNewVoucherLain, uNewPOSTransactionCard, uNewBarangStockSirkulasi,
FireDAC.Comp.Client;
type
TPOSTransactionItem = class(TCollectionItem)
private
FBarangCode: string;
FBarangHargaJual: TBarangHargaJual;
FBarangHargaJualID: string;
FCOGS: Double;
FDATE_CREATE: TDateTime;
FDATE_MODIFY: TDateTime;
FDiscMan: Double;
FDisc_Card: Double;
FDISC_GMC_NOMINAL: Double;
FID: string;
FIsBKP: Boolean;
FIsDiscAMC: Boolean;
FLastCost: Double;
FNewUnit: TUnit;
FNewUnitID: string;
// FOPC_UNIT: TUnit;
// FOPC_UNITID: Integer;
// FOPM_UNIT: TUnit;
// FOPM_UNITID: Integer;
FOP_CREATE: string;
FOP_MODIFY: string;
FOto_Code: string;
FPPN: Double;
FPPNBM: Double;
FQty: Double;
FSellPrice: Double;
FSellPriceDisc: Double;
FTipeBarangID: string;
FTotal: Double;
FTotalBeforeTax: Double;
FTotalCeil: Double;
FTransNo: string;
FUomCode: string;
function GetBarangHargaJual: TBarangHargaJual;
function GetNewUnit: TUnit;
// function GetOPC_UNIT: TUnit;
// function GetOPM_UNIT: TUnit;
procedure SetNewUnit(Value: TUnit);
public
constructor Create(aCollection : TCollection); override;
destructor Destroy; override;
procedure ClearProperties;
function CustomTableName: string;
function GenerateRemoveSQL: TStrings; virtual;
function GenerateSQL(AHeader_ID: string): TStrings;
function GetFieldNameFor_BarangCode: string; dynamic;
function GetFieldNameFor_BarangHargaJual: string; dynamic;
// function GetFieldNameFor_BarangHargaJualUnit: string; dynamic;
function GetFieldNameFor_COGS: string; dynamic;
function GetFieldNameFor_DATE_CREATE: string; dynamic;
function GetFieldNameFor_DATE_MODIFY: string; dynamic;
function GetFieldNameFor_DISC_GMC_NOMINAL: string; dynamic;
function GetFieldNameFor_ID: string; dynamic;
function GetFieldNameFor_IsBKP: string; dynamic;
function GetFieldNameFor_IsDiscAMC: string; dynamic;
function GetFieldNameFor_LastCost: string; dynamic;
function GetFieldNameFor_NewUnit: string; dynamic;
// function GetFieldNameFor_OPC_UNIT: string; dynamic;
// function GetFieldNameFor_OPM_UNIT: string; dynamic;
function GetFieldNameFor_OP_CREATE: string; dynamic;
function GetFieldNameFor_OP_MODIFY: string; dynamic;
function GetFieldNameFor_PPN: string; dynamic;
function GetFieldNameFor_PPNBM: string; dynamic;
function GetFieldNameFor_Qty: string; dynamic;
function GetFieldNameFor_SellPrice: string; dynamic;
function GetFieldNameFor_SellPriceDisc: string; dynamic;
function GetFieldNameFor_TipeBarang: string; dynamic;
function GetFieldNameFor_Total: string; dynamic;
function GetFieldNameFor_TotalBeforeTax: string; dynamic;
function GetFieldNameFor_TotalCeil: string; dynamic;
function GetFieldNameFor_TransDiscCard: string; dynamic;
function GetFieldNameFor_TransDiscMan: string; dynamic;
function GetFieldNameFor_TransID: string; dynamic;
function GetFieldNameFor_TransNo: string; dynamic;
function GetFieldNameFor_TransOtoCode: string; dynamic;
// function GetFieldNameFor_TransUnit: string; dynamic;
function GetFieldNameFor_UomCode: string; dynamic;
function GetFieldPrefix: string;
function GetGeneratorName: string; dynamic;
function RemoveFromDB: Boolean;
property BarangCode: string read FBarangCode write FBarangCode;
property BarangHargaJual: TBarangHargaJual read GetBarangHargaJual write
FBarangHargaJual;
property COGS: Double read FCOGS write FCOGS;
property DATE_CREATE: TDateTime read FDATE_CREATE write FDATE_CREATE;
property DATE_MODIFY: TDateTime read FDATE_MODIFY write FDATE_MODIFY;
property DiscMan: Double read FDiscMan write FDiscMan;
property Disc_Card: Double read FDisc_Card write FDisc_Card;
property DISC_GMC_NOMINAL: Double read FDISC_GMC_NOMINAL write
FDISC_GMC_NOMINAL;
property ID: string read FID write FID;
property IsBKP: Boolean read FIsBKP write FIsBKP;
property IsDiscAMC: Boolean read FIsDiscAMC write FIsDiscAMC;
property LastCost: Double read FLastCost write FLastCost;
property NewUnit: TUnit read GetNewUnit write SetNewUnit;
// property OPC_UNIT: TUnit read GetOPC_UNIT write SetOPC_UNIT;
// property OPM_UNIT: TUnit read GetOPM_UNIT write SetOPM_UNIT;
property OP_CREATE: string read FOP_CREATE write FOP_CREATE;
property OP_MODIFY: string read FOP_MODIFY write FOP_MODIFY;
property Oto_Code: string read FOto_Code write FOto_Code;
property PPN: Double read FPPN write FPPN;
property PPNBM: Double read FPPNBM write FPPNBM;
property Qty: Double read FQty write FQty;
property SellPrice: Double read FSellPrice write FSellPrice;
property SellPriceDisc: Double read FSellPriceDisc write FSellPriceDisc;
property TipeBarangID: string read FTipeBarangID write FTipeBarangID;
property Total: Double read FTotal write FTotal;
property TotalBeforeTax: Double read FTotalBeforeTax write FTotalBeforeTax;
property TotalCeil: Double read FTotalCeil write FTotalCeil;
property TransNo: string read FTransNo write FTransNo;
property UomCode: string read FUomCode write FUomCode;
published
end;
TPOSTransactionItems = class(TCollection)
private
function GetPOSTransactionItem(Index: Integer): TPOSTransactionItem;
procedure SetPOSTransactionItem(Index: Integer; Value: TPOSTransactionItem);
public
function Add: TPOSTransactionItem;
function CustomTableName: string;
function GetFieldNameFor_Header: string;
// function GetFieldNameFor_HeaderUNT: string;
procedure LoadByHeaderID(aHeader_ID: string);
property POSTransactionItem[Index: Integer]: TPOSTransactionItem read
GetPOSTransactionItem write SetPOSTransactionItem; default;
end;
TPOSTransaction = class(TSBaseClass)
private
FBarangStockSirkulasi: TBArangStockSirkulasiItems;
FBayarCard: Double;
FBayarCash: Double;
FBeginningBalance: TBeginningBalance;
FBeginningBalanceID: string;
FDATE_CREATE: TDateTime;
FDATE_MODIFY: TDateTime;
FDiscAMCNominal: Double;
FDiscAMCPersen: Double;
FID: string;
FIsActive: Boolean;
FIsPending: Boolean;
FKuponBotolNo: String;
FMemberID: string;
FNewUnit: TUnit;
FNewUnitID: string;
FNo: string;
// FOPC_UNIT: TUnit;
// FOPC_UNITID: Integer;
// FOPM_UNIT: TUnit;
// FOPM_UNITID: Integer;
FOP_CREATE: string;
FOP_MODIFY: string;
FPembulat: Double;
FPOSTransactionItems: TPOSTransactionItems;
FReturNo: TStrings;
FTanggal: TDateTime;
FTotalBayar: Double;
FTotalDiscAMC: Double;
FTotalPPN: Double;
FTotalTransaction: Double;
FTransactionCard: TPOSTransactionCard;
FTRANS_DISC_CARD: Double;
FTrans_Struk: TSTrings;
FVoucherLains: TVoucherLainItems;
FVoucherNo: TStrings;
Q1: TFDQuery;
Q2: TFDQuery;
function FLoadFromDB(aSQL : String): Boolean;
function GetBarangStockSirkulasi: TBArangStockSirkulasiItems;
function GetBeginningBalance: TBeginningBalance;
function GetNewUnit: TUnit;
// function GetOPC_UNIT: TUnit;
// function GetOPM_UNIT: TUnit;
function GetPOSTransactionItems: TPOSTransactionItems;
function GetReturNo: TStrings;
function GetTransactionCard: TPOSTransactionCard;
function GetTrans_Struk: TSTrings;
function GetVoucherLains: TVoucherLainItems;
function GetVoucherNo: TStrings;
procedure SetNewUnit(Value: TUnit);
public
constructor Create(AOwner : TComponent); override;
constructor CreateWithUser(AOwner: TComponent; AUserID: string);
destructor Destroy; override;
procedure ClearProperties;
function CustomSQLTask: Tstrings;
function CustomSQLTaskPrior: Tstrings;
function CustomTableName: string;
function GenerateInterbaseMetaData: TStrings;
function GenerateJurnal(aRumus : String; aMultiPurpose : Integer; aUnitID :
Integer; aFlagRumus : Integer; aTipe : Integer; aRekCode : String): Double;
function GenerateJurnalHPP(aRumus : String; aMultiPurpose : Integer; aUnitID :
Integer; aFlagRumus : Integer; aTipe : Integer): Double;
function GenerateSQL(ARepeatCount: Integer = 1): TStrings;
function GenerateSQL_TransactionItems(aPOSTransactionItems:
TPOSTransactionItems): TStrings;
function GetFieldNameFor_BayarCard: string; dynamic;
function GetFieldNameFor_BayarCash: string; dynamic;
function GetFieldNameFor_BeginningBalance: string; dynamic;
// function GetFieldNameFor_BeginningBalanceUnit: string; dynamic;
function GetFieldNameFor_DATE_CREATE: string; dynamic;
function GetFieldNameFor_DATE_MODIFY: string; dynamic;
function GetFieldNameFor_DiscAMCNominal: string; dynamic;
function GetFieldNameFor_DiscAMCPersen: string; dynamic;
function GetFieldNameFor_ID: string; dynamic;
function GetFieldNameFor_IsActive: string; dynamic;
function GetFieldNameFor_IsPending: string; dynamic;
function GetFieldNameFor_KuponBotolNo: string; dynamic;
function GetFieldNameFor_KuponBotolStatus: string; dynamic;
function GetFieldNameFor_KuponBotolTransPOS: string; dynamic;
function GetFieldNameFor_KuponBotolUnit: string; dynamic;
function GetFieldNameFor_MemberID: string; dynamic;
// function GetFieldNameFor_MemberUnit: string; dynamic;
function GetFieldNameFor_NewUnit: string; dynamic;
function GetFieldNameFor_No: string; dynamic;
// function GetFieldNameFor_OPC_UNIT: string; dynamic;
// function GetFieldNameFor_OPM_UNIT: string; dynamic;
function GetFieldNameFor_OP_CREATE: string; dynamic;
function GetFieldNameFor_OP_MODIFY: string; dynamic;
function GetFieldNameFor_Pembulat: string; dynamic;
function GetFieldNameFor_POSTransactionItems: string; dynamic;
function GetFieldNameFor_ReturNo: string; dynamic;
function GetFieldNameFor_ReturTransPOS: string; dynamic;
function GetFieldNameFor_ReturUnit: string; dynamic;
function GetFieldNameFor_Tanggal: string; dynamic;
function GetFieldNameFor_TotalBayar: string; dynamic;
function GetFieldNameFor_TotalDiscAMC: string; dynamic;
function GetFieldNameFor_TotalPPN: string; dynamic;
function GetFieldNameFor_TotalTransaction: string; dynamic;
function GetFieldNameFor_TransCardDisc: string; dynamic;
function GetFieldNameFor_TransStruk: string; dynamic;
function GetFieldNameFor_VoucherNo: string; dynamic;
function GetFieldNameFor_VoucherStatus: string; dynamic;
function GetFieldNameFor_VoucherTransPOS: string; dynamic;
function GetFieldNameFor_VoucherUnit: string; dynamic;
function GetFieldPrefix: string;
function GetGeneratorName: string; dynamic;
class function GetHeaderFlag: Integer;
function GetHPPdanPersediaanBarang(aMerchandizeGroupID : Integer; aUnitID :
Integer; aTipe : Integer): Double;
procedure GetMember(var aKodeMember: String; var aNamaMember : String);
function GetNominalCard(aRekCode : String): Double;
function GetNominalCashBack(aRekCode : String): Double;
function GetNominalCharge: Double;
function GetNominalDiscountGMC(aNoBukti : String): Double;
function GetNominalKasBank: Double;
function GetNominalKuponBotol: Double;
function GetNominalPembulatan: Double;
function GetNominalPiutangVoucher: Double;
function GetNominalPPN: Double;
function GetNominalTransaction(aNoBukti : String): Double;
function GetNoTransaksi: string;
function GetPenjualanBarang(aMerchandizeGroupID : Integer; aUnitID : Integer;
aTipe : Integer): Double;
function GetPlannedID: string;
function GetTableNameFor_KuponBotol: string; dynamic;
function GetTableNameFor_Retur: string; dynamic;
function GetTableNameFor_Voucher: string; dynamic;
function GetTransactionDate: TDateTime;
function IsBalanceUsed(aBalance_ID, aUnitID: string): Boolean;
function LoadByID(AID : Integer; AUnitID: Integer): Boolean;
function LoadByTrans_No(aTransNo, aUnitID: String): Boolean;
function LoadDataJurnal(aDate1 : TDateTime; aDate2 : TDateTime; aUnitID :
Integer): Boolean;
function LoadDataJurnalByNo(aNoBukti : String; aUnitID : Integer): Boolean;
function RemoveFromDB: Boolean;
function SaveAllToDB: Boolean;
function SaveKuponBotolToDB: Boolean;
function SaveReturToDB: Boolean;
function SaveToDB: Boolean;
function SaveTransactionCardToDB: Boolean;
function SaveVoucherLainToDB: Boolean;
function SaveVoucherToDB: Boolean;
procedure UpdateData(ABayarCard, ABayarCash: Double; ABeginningBalance_ID:
string; ADiscAMCNominal, ADiscAMCPersen: Double; AID: string; AIsActive:
Boolean; AMemberID, ANewUnit_ID, ANo: string; APembulat: Double; ATanggal:
TDateTime; ATotalBayar, ATotalDiscAMC, ATotalPPN, ATotalTransaction:
Double; AKuponBotolNo: String; AVoucherNo: TStrings; aUserID: string;
aTransDiscCard: Double; aISJURNAL: Integer = 0; aIsPending: Boolean =
False);
procedure UpdatePOSTransactionItems(ABarangHargaJual_ID: string; ACOGS: Double;
AID: string; AIsBKP, AIsDiscAMC: Boolean; ALastCost, APPN, APPNBM, AQty,
ASellPrice, ASellPriceDisc, ATotal, ATotalBeforeTax, ATotalCeil: Double;
ATransNo, AUnitID, ABarangCode, ATipeBarangID: string; aDISC_GMC_NOMINAL:
Double; aUomCode: string; aDisc_Card: Double = 0; aDisc_Man: Double = 0;
aOtoCode: String = '');
function UpdateStatusJurnal(aStatus : Integer; aUnitID : Integer; aDate :
TDateTime): Boolean;
function UpdateTransStruk(lTransStruk: TStrings; IDTrans: string): Boolean;
property BarangStockSirkulasi: TBArangStockSirkulasiItems read
GetBarangStockSirkulasi write FBarangStockSirkulasi;
property BayarCard: Double read FBayarCard write FBayarCard;
property BayarCash: Double read FBayarCash write FBayarCash;
property BeginningBalance: TBeginningBalance read GetBeginningBalance write
FBeginningBalance;
property DATE_CREATE: TDateTime read FDATE_CREATE write FDATE_CREATE;
property DATE_MODIFY: TDateTime read FDATE_MODIFY write FDATE_MODIFY;
property DiscAMCNominal: Double read FDiscAMCNominal write FDiscAMCNominal;
property DiscAMCPersen: Double read FDiscAMCPersen write FDiscAMCPersen;
property ID: string read FID write FID;
property IsActive: Boolean read FIsActive write FIsActive;
property IsPending: Boolean read FIsPending write FIsPending;
property KuponBotolNo: String read FKuponBotolNo write FKuponBotolNo;
property MemberID: string read FMemberID write FMemberID;
property NewUnit: TUnit read GetNewUnit write SetNewUnit;
property No: string read FNo write FNo;
// property OPC_UNIT: TUnit read GetOPC_UNIT write SetOPC_UNIT;
// property OPM_UNIT: TUnit read GetOPM_UNIT write SetOPM_UNIT;
property OP_CREATE: string read FOP_CREATE write FOP_CREATE;
property OP_MODIFY: string read FOP_MODIFY write FOP_MODIFY;
property Pembulat: Double read FPembulat write FPembulat;
property POSTransactionItems: TPOSTransactionItems read
GetPOSTransactionItems write FPOSTransactionItems;
property ReturNo: TStrings read GetReturNo write FReturNo;
property Tanggal: TDateTime read FTanggal write FTanggal;
property TotalBayar: Double read FTotalBayar write FTotalBayar;
property TotalDiscAMC: Double read FTotalDiscAMC write FTotalDiscAMC;
property TotalPPN: Double read FTotalPPN write FTotalPPN;
property TotalTransaction: Double read FTotalTransaction write
FTotalTransaction;
property TransactionCard: TPOSTransactionCard read GetTransactionCard write
FTransactionCard;
property TRANS_DISC_CARD: Double read FTRANS_DISC_CARD write FTRANS_DISC_CARD;
property Trans_Struk: TSTrings read GetTrans_Struk write FTrans_Struk;
property VoucherLains: TVoucherLainItems read GetVoucherLains write
FVoucherLains;
property VoucherNo: TStrings read GetVoucherNo write FVoucherNo;
end;
function GetListPendingTransAll: string;
function GetListPendingTransByUserID(aUserID: string): string;
function GetListPendingTransByUserIDAndDate(aUserID: string; aDate: TDateTime):
string;
function GetListPendingTransDetailByHeaderID(aHeaderID: string): string;
implementation
uses DB, Math, udmMain, FireDAC.Stan.Error, uAppUtils;
function GetListPendingTransAll: string;
begin
// Result :=
// 'SELECT MEMBER.MEMBER_CARD_NO as "No Kartu", MEMBER.MEMBER_NAME as "Nama Member", '
// + ' TRANSAKSI.TRANS_NO as "No Transaksi", TRANSAKSI.TRANS_DATE as "Tanggal Trans", '
// + ' TRANSAKSI.TRANS_TOTAL_TRANSACTION as "Total", '
// + ' TRANSAKSI.TRANS_IS_ACTIVE, TRANSAKSI.TRANS_ID, '
// + ' TRANSAKSI.TRANS_MEMBER_ID, TRANSAKSI.TRANS_MEMBER_UNT_ID '
// + ' FROM MEMBER '
// + ' INNER JOIN TRANSAKSI ON (MEMBER.MEMBER_ID = TRANSAKSI.TRANS_MEMBER_ID) '
// + ' AND (MEMBER.MEMBER_UNT_ID = TRANSAKSI.TRANS_MEMBER_UNT_ID) '
// + ' WHERE (TRANSAKSI.TRANS_IS_PENDING = 1) '
// + ' AND OPC_UNIT = ' + IntToStr(aUnit_ID)
// + ' ORDER BY MEMBER.MEMBER_CARD_NO, TRANSAKSI.TRANS_NO';
Result := 'SELECT M.MEMBER_CARD_NO as "No Kartu", '
+ ' M.MEMBER_NAME as "Nama Member", '
+ ' T.TRANS_NO as "No Transaksi", '
+ ' T.TRANS_DATE as "Tanggal Trans", '
+ ' T.TRANS_TOTAL_TRANSACTION as "Total", '
+ ' T.TRANS_IS_ACTIVE, '
+ ' T.TRANSAKSI_ID, '
+ ' T.MEMBER_ID '
+ ' FROM MEMBER M '
+ ' INNER JOIN TRANSAKSI T ON (M.MEMBER_ID = T.MEMBER_ID) '
+ ' WHERE (T.TRANS_IS_PENDING = 1) '
+ ' ORDER BY M.MEMBER_CARD_NO, T.TRANS_NO';
end;
function GetListPendingTransDetailByHeaderID(aHeaderID: string): string;
begin
// Result :=
// 'SELECT transd.TRANSD_ID, transd.TRANSD_UNT_ID,TRANSD_BRG_CODE, '
// + ' transd.TRANSD_TRANS_NO, transd.TRANSD_BHJ_ID, '
// + ' transd.TRANSD_BHJ_UNT_ID, transd.TRANSD_QTY, '
// + ' bhj.BHJ_SAT_CODE, '
// + ' transd.TRANSD_SELL_PRICE, bhj.BHJ_SELL_PRICE, '
// + ' bhj.BHJ_TPHRG_ID, bhj.BHJ_TPHRG_UNT_ID, '
// + ' transd.TRANSD_DISC_MAN, transd.OTO_CODE '
// + ' FROM TRANSAKSI_DETIL transd'
// + ' INNER JOIN BARANG_HARGA_JUAL bhj ON (transd.TRANSD_BHJ_ID = bhj.BHJ_ID) '
// + ' AND (transd.TRANSD_BHJ_UNT_ID = bhj.BHJ_UNT_ID) '
// + ' WHERE transd.TRANSD_TRANS_ID = ' + IntToStr(aHeaderID)
// + ' AND transd.TRANSD_TRANS_UNT_ID = ' + IntToStr(aUnit_ID)
// + ' ORDER BY transd.TRANSD_ID';
Result := 'SELECT TD.TRANSAKSI_DETIL_ID, '
+ ' TD.TRANSD_BRG_CODE, '
+ ' TD.TRANSD_TRANS_NO, '
+ ' TD.BARANG_HARGA_JUAL_ID, '
+ ' TD.TRANSD_QTY, '
+ ' S.SAT_CODE, '
+ ' TD.TRANSD_SELL_PRICE, '
+ ' BHJ.BHJ_SELL_PRICE, '
+ ' BHJ.REF$TIPE_HARGA_ID, '
+ ' TD.TRANSD_DISC_MAN, '
+ ' TD.OTO_CODE '
+ ' FROM TRANSAKSI_DETIL TD'
+ ' INNER JOIN BARANG_HARGA_JUAL BHJ ON (TD.BARANG_HARGA_JUAL_ID = BHJ.BARANG_HARGA_JUAL_ID) '
+ ' INNER JOIN REF$SATUAN S ON S.REF$SATUAN_ID = BHJ.REF$SATUAN_ID '
+ ' WHERE TD.TRANSAKSI_ID = ' + QuotedStr(aHeaderID)
+ ' ORDER BY TD.TRANSAKSI_DETIL_ID';
end;
function GetListPendingTransByUserID(aUserID: string): string;
begin
// Result :=
// 'SELECT MEMBER.MEMBER_CARD_NO as "No Kartu", MEMBER.MEMBER_NAME as "Nama Member", '
// + ' TRANSAKSI.TRANS_NO as "No Transaksi", TRANSAKSI.TRANS_DATE as "Tanggal Trans", '
// + ' TRANSAKSI.TRANS_TOTAL_TRANSACTION as "Total", '
// + ' TRANSAKSI.TRANS_IS_ACTIVE, TRANSAKSI.TRANS_ID, '
// + ' TRANSAKSI.TRANS_MEMBER_ID, TRANSAKSI.TRANS_MEMBER_UNT_ID '
// + ' FROM MEMBER '
// + ' INNER JOIN TRANSAKSI ON (MEMBER.MEMBER_ID = TRANSAKSI.TRANS_MEMBER_ID) '
// + ' AND (MEMBER.MEMBER_UNT_ID = TRANSAKSI.TRANS_MEMBER_UNT_ID) '
// + ' WHERE (TRANSAKSI.TRANS_IS_PENDING = 1) '
// + ' AND OPC_UNIT = ' + IntToStr(aUnit_ID)
// + ' AND OP_CREATE = ' + IntToStr(aUserID)
// + ' ORDER BY MEMBER.MEMBER_CARD_NO, TRANSAKSI.TRANS_NO';
Result := 'SELECT M.MEMBER_CARD_NO as "No Kartu", '
+ ' M.MEMBER_NAME as "Nama Member", '
+ ' T.TRANS_NO as "No Transaksi", '
+ ' T.TRANS_DATE as "Tanggal Trans", '
+ ' T.TRANS_TOTAL_TRANSACTION as "Total", '
+ ' T.TRANS_IS_ACTIVE, '
+ ' T.TRANSAKSI_ID, '
+ ' T.MEMBER_ID '
+ ' FROM MEMBER M '
+ ' INNER JOIN TRANSAKSI T ON (M.MEMBER_ID = T.MEMBER_ID) '
+ ' WHERE (T.TRANS_IS_PENDING = 1) '
+ ' AND T.OP_CREATE = ' + QuotedStr(aUserID)
+ ' ORDER BY M.MEMBER_CARD_NO, T.TRANS_NO';
end;
function GetListPendingTransByUserIDAndDate(aUserID: string; aDate: TDateTime):
string;
begin
// Result := 'SELECT MEMBER.MEMBER_CARD_NO as "No Kartu", MEMBER.MEMBER_NAME as "Nama Member", '
// + ' TRANSAKSI.TRANS_NO as "No Transaksi", TRANSAKSI.TRANS_DATE as "Tanggal Trans", '
// + ' TRANSAKSI.TRANS_TOTAL_TRANSACTION as "Total", '
// + ' TRANSAKSI.TRANS_IS_ACTIVE, TRANSAKSI.TRANS_ID, '
// + ' TRANSAKSI.TRANS_MEMBER_ID, TRANSAKSI.TRANS_MEMBER_UNT_ID '
// + ' FROM MEMBER '
// + ' INNER JOIN TRANSAKSI ON (MEMBER.MEMBER_ID = TRANSAKSI.TRANS_MEMBER_ID) '
// + ' AND (MEMBER.MEMBER_UNT_ID = TRANSAKSI.TRANS_MEMBER_UNT_ID) '
// + ' WHERE (TRANSAKSI.TRANS_IS_PENDING = 1) '
// + ' AND TRANSAKSI.OPC_UNIT = ' + QuotedStr(aUnit_ID)
// + ' AND TRANSAKSI.OP_CREATE = ' + QuotedStr(aUserID)
// + ' AND CAST(TRANSAKSI.TRANS_DATE AS DATE) = ' + TAppUtils.QuotD(aDate)
// + ' ORDER BY MEMBER.MEMBER_CARD_NO, TRANSAKSI.TRANS_NO';
Result := 'SELECT M.MEMBER_CARD_NO as "No Kartu", '
+ ' M.MEMBER_NAME as "Nama Member", '
+ ' T.TRANS_NO as "No Transaksi", '
+ ' T.TRANS_DATE as "Tanggal Trans", '
+ ' T.TRANS_TOTAL_TRANSACTION as "Total", '
+ ' T.TRANS_IS_ACTIVE, '
+ ' T.TRANSAKSI_ID, '
+ ' T.MEMBER_ID '
+ ' FROM MEMBER M '
+ ' INNER JOIN TRANSAKSI T ON (M.MEMBER_ID = T.MEMBER_ID) '
+ ' WHERE (T.TRANS_IS_PENDING = 1) '
+ ' AND T.OP_CREATE = ' + QuotedStr(aUserID)
+ ' AND DATE(T.TRANS_DATE) = ' + TAppUtils.QuotD(aDate)
+ ' ORDER BY M.MEMBER_CARD_NO, T.TRANS_NO';
end;
{
***************************** TPOSTransactionItem ******************************
}
constructor TPOSTransactionItem.Create(aCollection : TCollection);
begin
inherited Create(ACollection);
end;
destructor TPOSTransactionItem.Destroy;
begin
ClearProperties;
inherited Destroy;
end;
procedure TPOSTransactionItem.ClearProperties;
begin
TransNo := '';
TotalCeil := 0;
TotalBeforeTax := 0;
Total := 0;
SellPriceDisc := 0;
SellPrice := 0;
Qty := 0;
PPNBM := 0;
PPN := 0;
OP_MODIFY := '';
OP_CREATE := '';
LastCost := 0;
IsDiscAMC := FALSE;
IsBKP := FALSE;
ID := '';
COGS := 0;
BarangCode := '';
TipeBarangID := '';
FBarangHargaJualID := '';
FNewUnitID := '';
DISC_GMC_NOMINAL := 0;
Disc_Card := 0;
FreeAndNil(FBarangHargaJual);
FreeAndNil(FNewUnit);
// FreeAndNil(FOPC_UNIT);
// FreeAndNil(FOPM_UNIT);
end;
function TPOSTransactionItem.CustomTableName: string;
begin
Result := 'transaksi_detil';
end;
{
******************************** TCodeTemplate *********************************
}
function TPOSTransactionItem.GenerateRemoveSQL: TStrings;
var
S: string;
begin
Result := TStringList.Create;
S:= 'DELETE FROM ' + CustomTableName +
' WHERE ' + GetFieldNameFor_ID + ' = ' + QuotedStr(FID);
// ' AND ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(FNewUnitID) + ';';
Result.Append(S);
end;
function TPOSTransactionItem.GenerateSQL(AHeader_ID: string): TStrings;
var
sSQL: string;
sPrec: string;
begin
Result := TStringList.Create;
DATE_MODIFY := cGetServerDateTime;
// FOPM_UNITID := FNewUnitID;
sPrec := Get_Price_Precision;
// If FID <= 0 then
if FID = '' then
begin
//Generate Insert SQL
OP_CREATE := OP_MODIFY;
DATE_CREATE := DATE_MODIFY;
// FOPC_UNITID := FOPM_UNITID;
// FID := cGetNextID(GetFieldNameFor_ID, CustomTableName);
FID := cGetNextIDGUIDToString;
sSQL := 'insert into ' + CustomTableName + ' ('
+ GetFieldNameFor_BarangCode + ', '
+ GetFieldNameFor_TipeBarang + ', '
+ GetFieldNameFor_BarangHargaJual + ', '
// + GetFieldNameFor_BarangHargaJualUnit + ', '
+ GetFieldNameFor_COGS + ', '
+ GetFieldNameFor_DATE_CREATE + ', '
+ GetFieldNameFor_ID + ', '
+ GetFieldNameFor_IsBKP + ', '
+ GetFieldNameFor_IsDiscAMC + ', '
+ GetFieldNameFor_LastCost + ', '
+ GetFieldNameFor_NewUnit + ', '
// + GetFieldNameFor_OPC_UNIT + ', '
+ GetFieldNameFor_OP_CREATE + ', '
+ GetFieldNameFor_PPN + ', '
+ GetFieldNameFor_PPNBM + ', '
+ GetFieldNameFor_DISC_GMC_NOMINAL + ', '
+ GetFieldNameFor_Qty + ', '
+ GetFieldNameFor_SellPrice + ', '
+ GetFieldNameFor_SellPriceDisc + ', '
+ GetFieldNameFor_Total + ', '
+ GetFieldNameFor_TotalBeforeTax + ', '
+ GetFieldNameFor_TotalCeil + ', '
// + GetFieldNameFor_TransUnit + ', '
+ GetFieldNameFor_TransID + ', '
+ GetFieldNameFor_TransDiscCard + ', '
+ GetFieldNameFor_UomCode + ', '
+ GetFieldNameFor_TransNo + ', '
+ GetFieldNameFor_TransDiscMan +', '
+ GetFieldNameFor_TransOtoCode
+ ') values ('
+ QuotedStr(BarangCode) + ', '
+ QuotedStr(TipeBarangID) + ', '
+ QuotedStr(FBarangHargaJualID) + ', '
// + QuotedStr(FNewUnitID) + ', '
+ FormatFloat(sPrec, FCOGS) + ', '
+ TAppUtils.QuotDT(FDATE_CREATE) + ', '
+ QuotedStr(FID) + ', '
// + cGetNextIDDetail(GetFieldNameFor_ID, CustomTableName) + ', '
+ IfThen(FIsBKP,'1','0') + ', '
+ IfThen(FIsDiscAMC,'1','0') + ', '
+ FormatFloat(sPrec, FLastCost) + ', '
+ QuotedStr(FNewUnitID) + ', '
// + InttoStr(FOPC_UNITID) + ', '
+ QuotedStr(FOP_CREATE) + ', '
+ FormatFloat('0.00', FPPN) + ', '
+ FormatFloat('0.00', FPPNBM) + ', '
+ FormatFloat(sPrec, FDISC_GMC_NOMINAL) + ', '
+ FormatFloat('0.000', FQty) + ', '
+ FormatFloat(sPrec, FSellPrice) + ', '
+ FormatFloat(sPrec, FSellPriceDisc) + ', '
+ FormatFloat(sPrec, FTotal) + ', '
+ FormatFloat(sPrec, FTotalBeforeTax) + ', '
+ FormatFloat(sPrec, FTotalCeil) + ', '
// + InttoStr(FNewUnitID) + ', '
+ QuotedStr(AHeader_ID) + ', '
+ FormatFloat(sPrec, FDisc_Card) + ', '
+ QuotedStr(FUomCode) + ', '
+ QuotedStr(FTransNo) + ', '
+ FormatFloat(sPrec, FDiscMan) + ', '
+ QuotedStr(FOto_Code)
+ ');';
end
else
begin
//generate Update SQL
sSQL := 'update ' + CustomTableName + ' set '
+ GetFieldNameFor_BarangHargaJual + ' = ' + QuotedStr(FBarangHargaJualID)
+ ', ' + GetFieldNameFor_BarangCode + ' = ' + QuotedStr(BarangCode)
+ ', ' + GetFieldNameFor_TipeBarang + ' = ' + QuotedStr(TipeBarangID)
+ ', ' + GetFieldNameFor_COGS + ' = ' + FormatFloat(sPrec, FCOGS)
+ ', ' + GetFieldNameFor_DATE_MODIFY + ' = ' + TAppUtils.QuotDT(FDATE_MODIFY)
+ ', ' + GetFieldNameFor_IsBKP + ' = ' + IfThen(FIsBKP,'1','0')
+ ', ' + GetFieldNameFor_IsDiscAMC + ' = ' + IfThen(FIsDiscAMC,'1','0')
+ ', ' + GetFieldNameFor_LastCost + ' = ' + FormatFloat(sPrec, FLastCost)
+ ', ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(FNewUnitID)
// + ', ' + GetFieldNameFor_OPM_UNIT + ' = ' + IntToStr(FOPM_UNITID)
+ ', ' + GetFieldNameFor_OP_MODIFY + ' = ' + QuotedStr(FOP_MODIFY)
+ ', ' + GetFieldNameFor_PPN + ' = ' + FormatFloat('0.00', FPPN)
+ ', ' + GetFieldNameFor_PPNBM + ' = ' + FormatFloat('0.00', FPPNBM)
+ ', ' + GetFieldNameFor_DISC_GMC_NOMINAL + ' = ' + FormatFloat(sPrec, FDISC_GMC_NOMINAL)
+ ', ' + GetFieldNameFor_Qty + ' = ' + FormatFloat('0.000', FQty)
+ ', ' + GetFieldNameFor_SellPrice + ' = ' + FormatFloat(sPrec, FSellPrice)
+ ', ' + GetFieldNameFor_SellPriceDisc + ' = ' + FormatFloat(sPrec, FSellPriceDisc)
+ ', ' + GetFieldNameFor_Total + ' = ' + FormatFloat(sPrec, FTotal)
+ ', ' + GetFieldNameFor_TotalBeforeTax + ' = ' + FormatFloat(sPrec, FTotalBeforeTax)
+ ', ' + GetFieldNameFor_TotalCeil + ' = ' + FormatFloat(sPrec, FTotalCeil)
+ ', ' + GetFieldNameFor_TransNo + ' = ' + QuotedStr(FTransNo)
// + ', ' + GetFieldNameFor_TransUnit + ' = ' + IntToStr(FNewUnitID)
+ ', ' + GetFieldNameFor_TransDiscCard + ' = ' + FormatFloat(sPrec, FDisc_Card)
+ ', ' + GetFieldNameFor_TransID + ' = ' + QuotedStr(AHeader_ID)
+ ', ' + GetFieldNameFor_UomCode + ' = ' + QuotedStr(FUomCode)
+ ', ' + GetFieldNameFor_TransDiscMan + ' = ' + FormatFloat(sPrec, FDiscMan)
+ ', ' + GetFieldNameFor_TransOtoCode + ' = ' + QuotedStr(FOto_Code)
+ ' where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(FID);
// + ' and ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(FNewUnitID) + ';';
end;
Result.Append(sSQL);
end;
function TPOSTransactionItem.GetBarangHargaJual: TBarangHargaJual;
begin
// Result := nil;
if FBarangHargaJual = nil then
begin
FBarangHargaJual := TBarangHargaJual.Create(nil);
FBarangHargaJual.LoadByID(FBarangHargaJualID);
end;
Result := FBarangHargaJual;
end;
function TPOSTransactionItem.GetFieldNameFor_BarangCode: string;
begin
Result := GetFieldPrefix + 'brg_code';
// Result := 'BARANG_ID';
end;
function TPOSTransactionItem.GetFieldNameFor_BarangHargaJual: string;
begin
// Result := GetFieldPrefix + 'bhj_id';
Result := 'BARANG_HARGA_JUAL_ID';
end;
//function TPOSTransactionItem.GetFieldNameFor_BarangHargaJualUnit: string;
//begin
// Result := GetFieldPrefix + 'bhj_unt_id';
//end;
function TPOSTransactionItem.GetFieldNameFor_COGS: string;
begin
Result := GetFieldPrefix + 'COGS';
end;
function TPOSTransactionItem.GetFieldNameFor_DATE_CREATE: string;
begin
Result := 'DATE_CREATE';
end;
function TPOSTransactionItem.GetFieldNameFor_DATE_MODIFY: string;
begin
Result := 'DATE_MODIFY';
end;
function TPOSTransactionItem.GetFieldNameFor_DISC_GMC_NOMINAL: string;
begin
Result := GetFieldPrefix + 'DISC_GMC_NOMINAL';
end;
function TPOSTransactionItem.GetFieldNameFor_ID: string;
begin
// Result := GetFieldPrefix + 'ID';
Result := 'TRANSAKSI_DETIL_ID'
end;
function TPOSTransactionItem.GetFieldNameFor_IsBKP: string;
begin
Result := GetFieldPrefix + 'Is_BKP';
end;
function TPOSTransactionItem.GetFieldNameFor_IsDiscAMC: string;
begin
Result := GetFieldPrefix + 'brg_is_gmc';
end;
function TPOSTransactionItem.GetFieldNameFor_LastCost: string;
begin
Result := GetFieldPrefix + 'last_cost';
end;
function TPOSTransactionItem.GetFieldNameFor_NewUnit: string;
begin
// Result := GetFieldPrefix + 'unt_id';
Result := 'AUT$UNIT_ID';
end;
//function TPOSTransactionItem.GetFieldNameFor_OPC_UNIT: string;
//begin
// Result := 'OPC_UNIT';
//end;
//function TPOSTransactionItem.GetFieldNameFor_OPM_UNIT: string;
//begin
// Result := 'OPM_UNIT';
//end;
function TPOSTransactionItem.GetFieldNameFor_OP_CREATE: string;
begin
Result := 'OP_CREATE';
end;
function TPOSTransactionItem.GetFieldNameFor_OP_MODIFY: string;
begin
Result := 'OP_MODIFY';
end;
function TPOSTransactionItem.GetFieldNameFor_PPN: string;
begin
Result := GetFieldPrefix + 'PPN';
end;
function TPOSTransactionItem.GetFieldNameFor_PPNBM: string;
begin
Result := GetFieldPrefix + 'PPNBM';
end;
function TPOSTransactionItem.GetFieldNameFor_Qty: string;
begin
Result := GetFieldPrefix + 'qty';
end;
function TPOSTransactionItem.GetFieldNameFor_SellPrice: string;
begin
Result := GetFieldPrefix + 'Sell_Price';
end;
function TPOSTransactionItem.GetFieldNameFor_SellPriceDisc: string;
begin
Result := GetFieldPrefix + 'Sell_Price_Disc';
end;
function TPOSTransactionItem.GetFieldNameFor_TipeBarang: string;
begin
// Result := GetFieldPrefix + 'tpbrg_id';
Result := 'REF$TIPE_BARANG_ID';
end;
function TPOSTransactionItem.GetFieldNameFor_Total: string;
begin
Result := GetFieldPrefix + 'Total';
end;
function TPOSTransactionItem.GetFieldNameFor_TotalBeforeTax: string;
begin
Result := GetFieldPrefix + 'Total_b4_Tax';
end;
function TPOSTransactionItem.GetFieldNameFor_TotalCeil: string;
begin
Result := GetFieldPrefix + 'Total_Ceil';
end;
function TPOSTransactionItem.GetFieldNameFor_TransDiscCard: string;
begin
Result := GetFieldPrefix + 'DISC_CARD';
end;
function TPOSTransactionItem.GetFieldNameFor_TransDiscMan: string;
begin
Result := GetFieldPrefix + 'DISC_MAN';
end;
function TPOSTransactionItem.GetFieldNameFor_TransID: string;
begin
// Result := GetFieldPrefix + 'trans_id';
Result := 'TRANSAKSI_ID'
end;
function TPOSTransactionItem.GetFieldNameFor_TransNo: string;
begin
Result := GetFieldPrefix + 'Trans_No';
end;
function TPOSTransactionItem.GetFieldNameFor_TransOtoCode: string;
begin
Result := 'OTO_CODE';
end;
//function TPOSTransactionItem.GetFieldNameFor_TransUnit: string;
//begin
// Result := GetFieldPrefix + 'trans_unt_id';
//end;
function TPOSTransactionItem.GetFieldNameFor_UomCode: string;
begin
Result := GetFieldPrefix + 'sat_code';
end;
function TPOSTransactionItem.GetFieldPrefix: string;
begin
Result := 'transd_';
end;
function TPOSTransactionItem.GetGeneratorName: string;
begin
Result := 'GEN_' + CustomTableName + '_ID';
end;
function TPOSTransactionItem.GetNewUnit: TUnit;
begin
if (FNewUnit = Nil) then
begin
FNewUnit:= TUnit.Create(Application);
FNewUnit.LoadByID(FNewUnitID);
end;
Result := FNewUnit;
end;
//function TPOSTransactionItem.GetOPC_UNIT: TUnit;
//begin
// if (FOPC_UNIT = Nil) then
// begin
// FOPC_UNIT:= TUnit.Create(Application);
// FOPC_UNIT.LoadByID(IntToStr(FOPC_UNITID));
// end;
// Result := FOPC_UNIT;
//end;
//function TPOSTransactionItem.GetOPM_UNIT: TUnit;
//begin
// if (FOPM_UNIT = Nil) then
// begin
// FOPM_UNIT:= TUnit.Create(Application);
// FOPM_UNIT.LoadByID(IntToStr(FOPM_UNITID));
// end;
// Result := FOPM_UNIT;
//end;
function TPOSTransactionItem.RemoveFromDB: Boolean;
var
sSQL: string;
begin
Result := False;
sSQL := 'delete from ' + CustomTableName
+ ' where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(FID);
// + ' and ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(FNewUnitID);
if cExecSQL(sSQL,dbtPOS, False) then
Result := True; //SimpanBlob(sSQL,TPOSTransaction.GetHeaderFlag);
end;
procedure TPOSTransactionItem.SetNewUnit(Value: TUnit);
begin
FNewUnitID := Value.ID;
end;
//procedure TPOSTransactionItem.SetOPC_UNIT(Value: TUnit);
//begin
//end;
//procedure TPOSTransactionItem.SetOPM_UNIT(Value: TUnit);
//begin
//end;
{
***************************** TPOSTransactionItems *****************************
}
function TPOSTransactionItems.Add: TPOSTransactionItem;
begin
Result := (inherited Add) as TPOSTransactionItem;
end;
function TPOSTransactionItems.CustomTableName: string;
begin
Result := 'transaksi_detil';
end;
function TPOSTransactionItems.GetFieldNameFor_Header: string;
begin
// Result := 'transd_trans_id';
Result := 'TRANSAKSI_ID'
end;
//function TPOSTransactionItems.GetFieldNameFor_HeaderUNT: string;
//begin
// Result := 'TRANSD_TRANS_UNT_ID';
//end;
function TPOSTransactionItems.GetPOSTransactionItem(Index: Integer):
TPOSTransactionItem;
begin
Result := (Inherited Items[Index]) as TPOSTransactionItem;
end;
procedure TPOSTransactionItems.LoadByHeaderID(aHeader_ID: string);
var
sSQL: string;
begin
sSQL := 'Select * '
+ ' from ' + CustomTableName
+ ' where ' + GetFieldNameFor_Header + ' = ' + QuotedStr(aHeader_ID);
// + ' and ' + GetFieldNameFor_HeaderUNT + ' = ' + IntToStr(aUnitID);
with cOpenQuery(sSQL) do
Begin
self.Clear;
while not eof do
begin
with Self.Add do
begin
FBarangHargaJualID := FieldByName(GetFieldNameFor_BarangHargaJual).AsString;
FCOGS := FieldByName(GetFieldNameFor_COGS).AsFloat;
FID := FieldByName(GetFieldNameFor_ID).AsString;
FNewUnitID := FieldByName(GetFieldNameFor_NewUnit).AsString;
FIsBKP := FieldValues[GetFieldNameFor_IsBKP];
FIsDiscAMC := FieldValues[GetFieldNameFor_IsDiscAMC];
FLastCost := FieldByName(GetFieldNameFor_LastCost).AsFloat;
FPPN := FieldByName(GetFieldNameFor_PPN).AsFloat;
FPPNBM := FieldByName(GetFieldNameFor_PPNBM).AsFloat;
FQty := FieldByName(GetFieldNameFor_Qty).AsFloat;
FSellPrice := FieldByName(GetFieldNameFor_SellPrice).AsFloat;
FSellPriceDisc := FieldByName(GetFieldNameFor_SellPriceDisc).AsFloat;
FTotal := FieldByName(GetFieldNameFor_Total).AsFloat;
FTotalBeforeTax := FieldByName(GetFieldNameFor_TotalBeforeTax).AsFloat;
FTotalCeil := FieldByName(GetFieldNameFor_TotalCeil).AsFloat;
FTransNo := FieldByName(GetFieldNameFor_TransNo).AsString;
FBarangCode := FieldByName(GetFieldNameFor_BarangCode).AsString;
FDISC_GMC_NOMINAL := FieldByName(GetFieldNameFor_DISC_GMC_NOMINAL).AsFloat;
FDisc_Card := FieldByName(GetFieldNameFor_TransDiscCard).AsFloat;
FTipeBarangID := FieldByname(GetFieldNameFor_TipeBarang).AsString;
FUomCode := FieldByname(GetFieldNameFor_UomCode).AsString;
end;
Next;
end;
free;
End;
end;
procedure TPOSTransactionItems.SetPOSTransactionItem(Index: Integer; Value:
TPOSTransactionItem);
begin
Inherited Items[Index] := Value;
end;
{
******************************* TPOSTransaction ********************************
}
constructor TPOSTransaction.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
end;
constructor TPOSTransaction.CreateWithUser(AOwner: TComponent; AUserID: string);
begin
Create(AOwner);
OP_MODIFY := AUserID;
end;
destructor TPOSTransaction.Destroy;
begin
ClearProperties;
inherited Destroy;
end;
procedure TPOSTransaction.ClearProperties;
begin
TotalTransaction := 0;
TotalDiscAMC := 0;
TotalPPN := 0;
TotalBayar := 0;
Pembulat := 0;
OP_MODIFY := '';
OP_CREATE := '';
No := '';
MemberID := '';
IsActive := FALSE;
IsPending := FALSE;
ID := '';
DiscAMCPersen := 0;
DiscAMCNominal := 0;
BayarCash := 0;
BayarCard := 0;
KuponBotolNo := '';
TRANS_DISC_CARD := 0;
FreeAndNil(FReturNo);
FreeAndNil(FVoucherNo);
FreeAndNil(FBeginningBalance);
FreeAndNil(FNewUnit);
// FreeAndNil(FOPC_UNIT);
// FreeAndNil(FOPM_UNIT);
FreeAndNil(FPOSTransactionItems);
If Assigned(FTrans_Struk) then FreeAndNil(FTrans_Struk);
if Q1 <> nil then FreeAndNil(Q1);
if Q2 <> nil then FreeAndNil(Q2);
end;
function TPOSTransaction.CustomSQLTask: Tstrings;
begin
result := nil;
end;
function TPOSTransaction.CustomSQLTaskPrior: Tstrings;
begin
result := nil;
end;
function TPOSTransaction.CustomTableName: string;
begin
result := 'transaksi';
end;
function TPOSTransaction.FLoadFromDB(aSQL : String): Boolean;
begin
Result := False;
State := csNone;
ClearProperties;
with cOpenQuery(aSQL) do
begin
try
if not EOF then
begin
FBayarCard := FieldByName(GetFieldNameFor_BayarCard).AsFloat;
FBayarCash := FieldByName(GetFieldNameFor_BayarCash).AsFloat;
FBeginningBalanceID := FieldByName(GetFieldNameFor_BeginningBalance).AsString;
FDATE_CREATE := FieldByName(GetFieldNameFor_DATE_CREATE).AsDateTime;
FDATE_MODIFY := FieldByName(GetFieldNameFor_DATE_MODIFY).AsDateTime;
FDiscAMCNominal := FieldByName(GetFieldNameFor_DiscAMCNominal).AsFloat;
FDiscAMCPersen := FieldByName(GetFieldNameFor_DiscAMCPersen).AsFloat;
FID := FieldByName(GetFieldNameFor_ID).AsString;
FIsActive := FieldValues[GetFieldNameFor_IsActive];
FMemberID := FieldByName(GetFieldNameFor_MemberID).AsString;
FNewUnitID := FieldByName(GetFieldNameFor_NewUnit).AsString;
FNo := FieldByName(GetFieldNameFor_No).AsString;
// FOPC_UNITID := FieldByName(GetFieldNameFor_OPC_UNIT).AsInteger;
// FOPM_UNITID := FieldByName(GetFieldNameFor_OPM_UNIT).AsInteger;
FOP_CREATE := FieldByName(GetFieldNameFor_OP_CREATE).AsString;
FOP_MODIFY := FieldByName(GetFieldNameFor_OP_MODIFY).AsString;
FPembulat := FieldByName(GetFieldNameFor_Pembulat).AsFloat;
//FPOSTransactionItems.Clear;
//FPOSTransactionItems.LoadByID(FieldValues['ID'] );
FTanggal := FieldByName(GetFieldNameFor_Tanggal).AsDateTime;
FTotalBayar := FieldByName(GetFieldNameFor_TotalBayar).AsFloat;
FTotalDiscAMC := FieldByName(GetFieldNameFor_TotalDiscAMC).AsFloat;
FTotalPPN := FieldByName(GetFieldNameFor_TotalPPN).AsFloat;
FTotalTransaction := FieldByName(GetFieldNameFor_TotalTransaction).AsFloat;
FIsPending := FieldValues[GetFieldNameFor_IsPending];
FTRANS_DISC_CARD := FieldByName(GetFieldNameFor_TransCardDisc).AsFloat;
// FTrans_Struk := FieldByName(GetFieldNameFor_TransStruk).AsBlob;
Self.State := csLoaded;
Result := True;
end;
finally
Free;
end;
End;
end;
function TPOSTransaction.GenerateInterbaseMetaData: TStrings;
begin
Result := TStringList.Create;
Result.Append( '' );
Result.Append( 'Create Table ''+ CustomTableName +'' ( ' );
Result.Append( 'TRMSBaseClass_ID Integer not null, ' );
Result.Append( 'BayarCard double precision Not Null , ' );
Result.Append( 'BayarCash double precision Not Null , ' );
Result.Append( 'BeginningBalance_ID Integer Not Null, ' );
Result.Append( 'DATE_CREATE Date Not Null , ' );
Result.Append( 'DATE_MODIFY Date Not Null , ' );
Result.Append( 'DiscAMCNominal double precision Not Null , ' );
Result.Append( 'DiscAMCPersen double precision Not Null , ' );
Result.Append( 'ID Integer Not Null Unique, ' );
Result.Append( 'IsActive Boolean Not Null , ' );
Result.Append( 'IsPending Boolean Not Null , ' );
Result.Append( 'MemberID Integer Not Null , ' );
Result.Append( 'NewUnit_ID Integer Not Null, ' );
Result.Append( 'No Varchar(30) Not Null , ' );
Result.Append( 'OPC_UNIT_ID Integer Not Null, ' );
Result.Append( 'OPM_UNIT_ID Integer Not Null, ' );
Result.Append( 'OP_CREATE Integer Not Null , ' );
Result.Append( 'OP_MODIFY Integer Not Null , ' );
Result.Append( 'Pembulat double precision Not Null , ' );
Result.Append( 'Tanggal Date Not Null , ' );
Result.Append( 'TotalBayar double precision Not Null , ' );
Result.Append( 'TotalDiscAMC double precision Not Null , ' );
Result.Append( 'TotalTransaction double precision Not Null , ' );
Result.Append( 'Stamp TimeStamp ' );
Result.Append( ' ); ' );
end;
function TPOSTransaction.GenerateJurnal(aRumus : String; aMultiPurpose :
Integer; aUnitID : Integer; aFlagRumus : Integer; aTipe : Integer; aRekCode
: String): Double;
begin
Result := 0;
if aFlagRumus = 0 then
Result := GetNominalKasBank
else if aFlagRumus = 1 then
Result := 0
else if aFlagRumus = 2 then
Result := GetNominalPiutangVoucher
else if aFlagRumus = 3 then
Result := 0
else if aFlagRumus = 4 then
begin
if aRekCode = '1120206000' then
Result := GetNominalCashBack(aRekCode)
else
Result := GetNominalCard(aRekCode)
end
else if aFlagRumus = 5 then
Result := GetNominalKuponBotol
else if aFlagRumus = 6 then
Result := GetNominalDiscountGMC('')
else if aFlagRumus = 7 then
Result := GetNominalPembulatan
else if aFlagRumus = 8 then
Result := GetNominalPPN
else if aFlagRumus = 9 then
Result := GetPenjualanBarang(aMultiPurpose, aUnitID, aTipe)
else if aFlagRumus = 10 then
Result := GetPenjualanBarang(aMultiPurpose, aUnitID, aTipe)
else if aFlagRumus = 11 then
Result := GetNominalCharge;
end;
function TPOSTransaction.GenerateJurnalHPP(aRumus : String; aMultiPurpose :
Integer; aUnitID : Integer; aFlagRumus : Integer; aTipe : Integer): Double;
begin
Result := 0;
if (aFlagRumus = 0) then
Result := GetPenjualanBarang(aMultiPurpose, aUnitID, aTipe)
else if (aFlagRumus = 1) then
Result := GetHPPdanPersediaanBarang(aMultiPurpose, aUnitID, aTipe);
end;
function TPOSTransaction.GenerateSQL(ARepeatCount: Integer = 1): TStrings;
var
sSQL: string;
// i: Integer;
ssSQL: TStrings;
sPrec : String;
begin
Result := TStringList.Create;
if State = csNone then
begin
raise Exception.create('Tidak bisa generate dalam Mode csNone')
end;
sPrec := Get_Price_Precision;
ssSQL := CustomSQLTaskPrior;
if ssSQL <> nil then
begin
Result.AddStrings(ssSQL);
end;
ssSQL := nil;
DATE_MODIFY := cGetServerDateTime;
// FOPM_UNITID := FNewUnitID;
// If FID <= 0 then
If FID = '' then
begin
//Generate Insert SQL
OP_CREATE := OP_MODIFY;
DATE_CREATE := DATE_MODIFY;
// FOPC_UNITID := FOPM_UNITID;
// FID := cGetNextID(GetFieldNameFor_ID, CustomTableName);
FID := cGetNextIDGUIDToString;
sSQL := 'insert into ' + CustomTableName + ' ('
+ GetFieldNameFor_BayarCard + ', '
+ GetFieldNameFor_BayarCash + ', '
+ GetFieldNameFor_BeginningBalance + ', '
// + GetFieldNameFor_BeginningBalanceUnit + ', '
// + GetFieldNameFor_DATE_CREATE + ', '
+ GetFieldNameFor_DiscAMCNominal + ', '
+ GetFieldNameFor_DiscAMCPersen + ', '
+ GetFieldNameFor_ID + ', '
+ GetFieldNameFor_IsActive + ', '
+ GetFieldNameFor_IsPending + ', '
+ GetFieldNameFor_MemberID + ', '
// + GetFieldNameFor_MemberUnit + ', '
+ GetFieldNameFor_NewUnit + ', '
+ GetFieldNameFor_No + ', '
// + GetFieldNameFor_OPC_UNIT + ', '
+ GetFieldNameFor_OP_CREATE + ', '
+ GetFieldNameFor_Pembulat + ', '
+ GetFieldNameFor_Tanggal + ', '
+ GetFieldNameFor_TotalBayar + ', '
+ GetFieldNameFor_TotalDiscAMC + ', '
+ GetFieldNameFor_TotalPPN + ', '
+ GetFieldNameFor_TransCardDisc + ', '
+ GetFieldNameFor_TotalTransaction + ') values ('
+ FormatFloat(sPrec, FBayarCard) + ', '
+ FormatFloat(sPrec, FBayarCash) + ', '
+ QuotedStr(FBeginningBalanceID) + ', '
// + QuotedStr(FNewUnitID) + ', '
// + QuotDT(FDATE_CREATE) + ', '
+ FormatFloat(sPrec, FDiscAMCNominal) + ', '
+ FormatFloat('0.00', FDiscAMCPersen) + ', '
+ QuotedStr(FID) + ', '
+ IfThen(FIsActive,'1','0') + ', '
+ IfThen(FIsPending,'1','0') + ', '
+ QuotedStr(FMemberID) + ', '
// + QuotedStr(FNewUnitID) + ', '
+ QuotedStr(FNewUnitID) + ', '
+ QuotedStr(FNo) + ', '
// + InttoStr(FOPC_UNITID) + ', '
+ QuotedStr(FOP_CREATE) + ', '
+ FormatFloat(sPrec, FPembulat) + ', '
+ TAppUtils.QuotDT(FTanggal) + ', '
+ FormatFloat(sPrec, FTotalBayar) + ', '
+ FormatFloat(sPrec, FTotalDiscAMC) + ', '
+ FormatFloat(sPrec, FTotalPPN) + ', '
+ FormatFloat(sPrec, FTRANS_DISC_CARD) + ', '
+ FormatFloat(sPrec, FTotalTransaction) + ');';
Result.Append(sSQL);
sSQL := 'update setuppos '
+ ' set setuppos_counter_no = ' + IntToStr(BeginningBalance.POS.CounterNo + 1)
+ ' where setuppos_id = ' + QuotedStr(BeginningBalance.POS.ID)
+ ' and AUT$UNIT_ID = ' + QuotedStr(FNewUnitID) + ';';
Result.Append(sSQL);
end
else
begin
//generate Update SQL
sSQL := 'update ' + CustomTableName + ' set '
+ GetFieldNameFor_BayarCard + ' = ' + FormatFloat(sPrec, FBayarCard)
+ ', ' + GetFieldNameFor_BayarCash + ' = ' + FormatFloat(sPrec, FBayarCash)
+ ', ' + GetFieldNameFor_BeginningBalance + ' = ' + QuotedStr(FBeginningBalanceID)
// + ', ' + GetFieldNameFor_BeginningBalanceUnit + ' = ' + QuotedStr(FNewUnitID)
+ ', ' + GetFieldNameFor_DATE_MODIFY + ' = ' + TAppUtils.QuotDT(FDATE_MODIFY)
+ ', ' + GetFieldNameFor_DiscAMCNominal + ' = ' + FormatFloat(sPrec, FDiscAMCNominal)
+ ', ' + GetFieldNameFor_DiscAMCPersen + ' = ' + FormatFloat('0.00', FDiscAMCPersen)
+ ', ' + GetFieldNameFor_IsActive + ' = ' + IfThen(FIsActive,'1','0')
+ ', ' + GetFieldNameFor_IsPending + ' = ' + IfThen(FIsPending,'1','0')
+ ', ' + GetFieldNameFor_MemberID + ' = ' + QuotedStr(FMemberID)
// + ', ' + GetFieldNameFor_MemberUnit + ' = ' + QuotedStr(FNewUnitID)
+ ', ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(FNewUnitID)
+ ', ' + GetFieldNameFor_No + ' = ' + QuotedStr(FNo)
// + ', ' + GetFieldNameFor_OPM_UNIT + ' = ' + IntToStr(FOPM_UNITID)
+ ', ' + GetFieldNameFor_OP_MODIFY + ' = ' + QuotedStr(FOP_MODIFY)
+ ', ' + GetFieldNameFor_Pembulat + ' = ' + FormatFloat(sPrec, FPembulat)
+ ', ' + GetFieldNameFor_Tanggal + ' = ' + TAppUtils.QuotDT(FTanggal)
+ ', ' + GetFieldNameFor_TotalBayar + ' = ' + FormatFloat(sPrec, FTotalBayar)
+ ', ' + GetFieldNameFor_TotalDiscAMC + ' = ' + FormatFloat(sPrec, FTotalDiscAMC)
+ ', ' + GetFieldNameFor_TotalPPN + ' = ' + FormatFloat(sPrec, FTotalPPN)
+ ', ' + GetFieldNameFor_TotalTransaction + ' = ' + FormatFloat(sPrec, FTotalTransaction)
+ ', ' + GetFieldNameFor_TransCardDisc + ' = ' + FormatFloat(sPrec, FTRANS_DISC_CARD)
+ ' where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(FID)
+ ' and ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(FNewUnitID) + ';';
Result.Append(sSQL);
end;
//generating Collections SQL
Result.AddStrings(GenerateSQL_TransactionItems(POSTransactionItems));
// for i := 0 to POSTransactionItems.Count - 1 do
// begin
// Result.AddStrings(POSTransactionItems[i].GenerateSQL(FID));
// end;
ssSQL := CustomSQLTask;
if ssSQL <> nil then
begin
Result.AddStrings(ssSQL);
end;
FreeAndNil(ssSQL)
end;
{
******************************** TCodeTemplate *********************************
}
function TPOSTransaction.GenerateSQL_TransactionItems(aPOSTransactionItems:
TPOSTransactionItems): TStrings;
var
isRemove: Boolean;
h: Integer;
i: Integer;
aTempPOSTransactionItems: TPOSTransactionItems;
begin
Result := TStringList.Create;
aTempPOSTransactionItems:= TPOSTransactionItems.Create(TPOSTransactionItem);
Try
if (aPOSTransactionItems = nil) then exit;
if (aPOSTransactionItems.Count = 0) then
Begin
exit;
end;
aTempPOSTransactionItems.Clear;
aTempPOSTransactionItems.LoadByHeaderID(ID); //
for h:= 0 to aTempPOSTransactionItems.Count - 1 do
begin
isRemove:= True;
for i:= 0 to aPOSTransactionItems.Count - 1 do
begin
if (aTempPOSTransactionItems[h].ID = aPOSTransactionItems[i].ID) then
begin
isRemove:= False;
Break;
end;
end;
if isRemove then
begin
Result.AddStrings(aTempPOSTransactionItems[h].GenerateRemoveSQL);
end;
end;
for i := 0 to aPOSTransactionItems.Count - 1 do
begin
Result.AddStrings(aPOSTransactionItems[i].GenerateSQL(ID));
end;
finally
aTempPOSTransactionItems.Free;
end;
end;
function TPOSTransaction.GetBarangStockSirkulasi: TBArangStockSirkulasiItems;
begin
try
if FBarangStockSirkulasi = nil then
begin
FBarangStockSirkulasi := TBarangStockSirkulasiItems.Create(TBarangStockSirkulasiItem);
FBarangStockSirkulasi.Clear;
FBarangStockSirkulasi.LoadByNoBukti(FNo, StrToInt(FNewUnitID), GetHeaderFlag);
end;
finally
Result := FBarangStockSirkulasi;
end;
end;
function TPOSTransaction.GetBeginningBalance: TBeginningBalance;
begin
// Result := nil;
if FBeginningBalance = nil then
begin
FBeginningBalance := TBeginningBalance.Create(Self);
FBeginningBalance.LoadByID(FBeginningBalanceID,FNewUnitID);
end;
Result := FBeginningBalance;
end;
function TPOSTransaction.GetFieldNameFor_BayarCard: string;
begin
Result := GetFieldPrefix + 'bayar_card';
end;
function TPOSTransaction.GetFieldNameFor_BayarCash: string;
begin
Result := GetFieldPrefix + 'bayar_cash';
end;
function TPOSTransaction.GetFieldNameFor_BeginningBalance: string;
begin
// Result := GetFieldPrefix + 'balance_id';
Result := 'BEGINNING_BALANCE_ID';
end;
//function TPOSTransaction.GetFieldNameFor_BeginningBalanceUnit: string;
//begin
// Result := GetFieldPrefix + 'balance_unt_id';
//end;
function TPOSTransaction.GetFieldNameFor_DATE_CREATE: string;
begin
Result := 'DATE_CREATE';
end;
function TPOSTransaction.GetFieldNameFor_DATE_MODIFY: string;
begin
Result := 'DATE_MODIFY';
end;
function TPOSTransaction.GetFieldNameFor_DiscAMCNominal: string;
begin
Result := GetFieldPrefix + 'disc_gmc_nominal';
end;
function TPOSTransaction.GetFieldNameFor_DiscAMCPersen: string;
begin
Result := GetFieldPrefix + 'disc_gmc_persen';
end;
function TPOSTransaction.GetFieldNameFor_ID: string;
begin
// Result := GetFieldPrefix + 'ID';
Result := 'TRANSAKSI_ID';
end;
function TPOSTransaction.GetFieldNameFor_IsActive: string;
begin
Result := GetFieldPrefix + 'is_active';
end;
function TPOSTransaction.GetFieldNameFor_IsPending: string;
begin
Result := GetFieldPrefix + 'is_pending';
end;
function TPOSTransaction.GetFieldNameFor_KuponBotolNo: string;
begin
Result := 'tkb_no';
end;
function TPOSTransaction.GetFieldNameFor_KuponBotolStatus: string;
begin
Result := 'tkb_status';
end;
function TPOSTransaction.GetFieldNameFor_KuponBotolTransPOS: string;
begin
Result := 'tkb_pos_trans_no';
end;
function TPOSTransaction.GetFieldNameFor_KuponBotolUnit: string;
begin
Result := 'tkb_unt_id';
end;
function TPOSTransaction.GetFieldNameFor_MemberID: string;
begin
// Result := GetFieldPrefix + 'member_id';
Result := 'MEMBER_ID';
end;
//function TPOSTransaction.GetFieldNameFor_MemberUnit: string;
//begin
// Result := GetFieldPrefix + 'member_unt_id';
//end;
function TPOSTransaction.GetFieldNameFor_NewUnit: string;
begin
// Result := GetFieldPrefix + 'UNT_ID';
Result := 'AUT$UNIT_ID';
end;
function TPOSTransaction.GetFieldNameFor_No: string;
begin
Result := GetFieldPrefix + 'No';
end;
//function TPOSTransaction.GetFieldNameFor_OPC_UNIT: string;
//begin
// Result := 'OPC_UNIT';
//end;
//function TPOSTransaction.GetFieldNameFor_OPM_UNIT: string;
//begin
// Result := 'OPM_UNIT';
//end;
function TPOSTransaction.GetFieldNameFor_OP_CREATE: string;
begin
Result := 'OP_CREATE';
end;
function TPOSTransaction.GetFieldNameFor_OP_MODIFY: string;
begin
Result := 'OP_MODIFY';
end;
function TPOSTransaction.GetFieldNameFor_Pembulat: string;
begin
Result := GetFieldPrefix + 'pembulat';
end;
function TPOSTransaction.GetFieldNameFor_POSTransactionItems: string;
begin
Result := GetFieldPrefix + 'POSTransactionItems_ID';
end;
function TPOSTransaction.GetFieldNameFor_ReturNo: string;
begin
Result := 'TRANSRET_NO';
end;
function TPOSTransaction.GetFieldNameFor_ReturTransPOS: string;
begin
Result := 'TRANSRET_POS_TRANS_NO';
end;
function TPOSTransaction.GetFieldNameFor_ReturUnit: string;
begin
Result := 'TRANSRET_UNT_ID';
end;
function TPOSTransaction.GetFieldNameFor_Tanggal: string;
begin
Result := GetFieldPrefix + 'date';
end;
function TPOSTransaction.GetFieldNameFor_TotalBayar: string;
begin
Result := GetFieldPrefix + 'total_bayar';
end;
function TPOSTransaction.GetFieldNameFor_TotalDiscAMC: string;
begin
Result := GetFieldPrefix + 'total_disc_gmc';
end;
function TPOSTransaction.GetFieldNameFor_TotalPPN: string;
begin
Result := GetFieldPrefix + 'TOTAL_PPN';
end;
function TPOSTransaction.GetFieldNameFor_TotalTransaction: string;
begin
Result := GetFieldPrefix + 'total_transaction';
end;
function TPOSTransaction.GetFieldNameFor_TransCardDisc: string;
begin
Result := GetFieldPrefix + 'DISC_CARD';
end;
function TPOSTransaction.GetFieldNameFor_TransStruk: string;
begin
Result := GetFieldPrefix + 'STRUK';;
end;
function TPOSTransaction.GetFieldNameFor_VoucherNo: string;
begin
Result := 'vcrd_no';
end;
function TPOSTransaction.GetFieldNameFor_VoucherStatus: string;
begin
Result := 'vcrd_status';
end;
function TPOSTransaction.GetFieldNameFor_VoucherTransPOS: string;
begin
Result := 'vcrd_pos_trans_no';
end;
function TPOSTransaction.GetFieldNameFor_VoucherUnit: string;
begin
// Result := 'vcrd_vcr_unt_id';
Result := 'AUT$UNIT_ID';
end;
function TPOSTransaction.GetFieldPrefix: string;
begin
Result := 'trans_';
end;
function TPOSTransaction.GetGeneratorName: string;
begin
Result := 'GEN_' + CustomTableName + '_ID';
end;
class function TPOSTransaction.GetHeaderFlag: Integer;
begin
result := 4930;
end;
function TPOSTransaction.GetHPPdanPersediaanBarang(aMerchandizeGroupID :
Integer; aUnitID : Integer; aTipe : Integer): Double;
begin
Result := 0;
Q1.First;
while not Q1.Eof do
begin
if (Q1.FieldByName('MERCHANGRUP_ID').AsInteger = aMerchandizeGroupID) and
(Q1.FieldByName('TRANSD_UNT_ID').AsInteger = aUnitID) then
begin
if (aTipe = 1) then
begin
if (Q1.FieldByName('TRANSD_TPBRG_ID').AsInteger in [1, 4, 6, 7]) then
begin
Result := Result + (Q1.FieldByName('BSS_HARGA_TRANSAKSI').AsFloat * Q1.FieldByName('TRANSD_QTY').AsFloat);
end;
end
else
begin
if aMerchandizeGroupID = 33 then
begin
if (Q1.FieldByName('TRANSD_TPBRG_ID').AsInteger = aTipe) then
begin
Result := Result + (Q1.FieldByName('BSS_HARGA_TRANSAKSI').AsFloat * Q1.FieldByName('TRANSD_QTY').AsFloat);
end;
end
else
begin
if (Q1.FieldByName('TRANSD_TPBRG_ID').AsInteger in [2, 3]) then
begin
Result := Result + (Q1.FieldByName('BSS_HARGA_TRANSAKSI').AsFloat * Q1.FieldByName('TRANSD_QTY').AsFloat);
end;
end;
end;
Result := RoundTo(Result, -2);
end;
Q1.Next;
end;
end;
procedure TPOSTransaction.GetMember(var aKodeMember: String; var aNamaMember :
String);
var
sSQL: string;
begin
sSQL := 'select member_card_no, member_name '
+ ' from member'
+ ' where member_id = ' + QuotedStr(MemberID);
// + ' and member_unt_id = ' + IntToStr(FNewUnitID);
with cOpenQuery(sSQL) do
begin
try
while not eof do
begin
aKodeMember := FieldByName('member_card_no').AsString;
aNamaMember := FieldByName('member_name').AsString;
Next;
end;
finally
Free;
end;
end;
end;
function TPOSTransaction.GetNewUnit: TUnit;
begin
if FNewUnit = nil then
begin
FNewUnit := TUnit.Create(Self);
FNewUnit.LoadByID(FNewUnitID);
end;
Result := FNewUnit;
end;
function TPOSTransaction.GetNominalCard(aRekCode : String): Double;
begin
Result := 0;
Q2.First;
while not Q2.eof do
begin
if Q2.FieldByName('CARD_REK_CODE').AsString = aRekCode then
begin
Result := Result + Q2.FieldByName('TRANS_BAYAR_CARD').AsFloat + Q2.FieldByName('TRANS_DISC_CARD').AsFloat;
end;
Q2.Next;
end;
end;
function TPOSTransaction.GetNominalCashBack(aRekCode : String): Double;
begin
Result := 0;
Q2.First;
while not Q2.eof do
begin
if Q2.FieldByName('CARD_REK_CASH_BACK').AsString = aRekCode then
begin
Result := Result + Q2.FieldByName('TRANSC_CASHBACK_NILAI').AsFloat;
end;
Q2.Next;
end;
end;
function TPOSTransaction.GetNominalCharge: Double;
begin
Result := 0;
Q2.First;
while not Q2.eof do
begin
Result := Result + Q2.FieldByName('TRANSC_CHARGE').AsFloat;
Q2.Next;
end;
end;
function TPOSTransaction.GetNominalDiscountGMC(aNoBukti : String): Double;
begin
Result := 0;
Q1.First;
while not Q1.eof do
begin
if aNoBukti = '' then
Result := Result + (Q1.FieldByName('TRANSD_DISC_GMC_NOMINAL').AsFloat * Q1.FieldByName('TRANSD_QTY').AsFloat)
else
begin
if aNoBukti = Q1.FieldByName('TRANS_NO').AsString then
Result := Result + (Q1.FieldByName('TRANSD_DISC_GMC_NOMINAL').AsFloat * Q1.FieldByName('TRANSD_QTY').AsFloat)
end;
Q1.Next;
end;
end;
function TPOSTransaction.GetNominalKasBank: Double;
begin
Result := 0;
Q2.First;
while not Q2.Eof do
begin
Result := Result + (Q2.FieldByName('TRANS_BAYAR_CASH').AsFloat - Q2.FieldByName('TRANSC_CASHBACK_NILAI').AsFloat);
Q2.Next;
end;
end;
function TPOSTransaction.GetNominalKuponBotol: Double;
begin
Result := 0;
Q2.First;
while not Q2.eof do
begin
Result := Result + Q2.FieldByName('TKB_SELL_PRICE_DISC').AsFloat;
Q2.Next;
end;
end;
function TPOSTransaction.GetNominalPembulatan: Double;
var
dPembulatan1: Double;
dPembulatan2: Double;
dSubTotal: Double;
begin
Result := 0;
Q2.First;
while not Q2.eof do
begin
dSubTotal := Q2.FieldByName('TRANS_TOTAL_TRANSACTION').AsFloat;
dPembulatan1 := RoundTo(dSubTotal - GetNominalTransaction(Q2.FieldByName('TRANS_NO').AsString), -2);
dPembulatan1 := dPembulatan1 + dSubTotal - Ceil(dSubTotal);
dPembulatan2 := GetNominalDiscountGMC(Q2.FieldByName('TRANS_NO').AsString) - Q2.FieldByName('TRANS_DISC_GMC_NOMINAL').AsFloat;
Result := Result + (dPembulatan2 - dPembulatan1) + Q2.FieldByName('TRANS_PEMBULAT').AsFloat;
//Result := Result + Q2.FieldByName('TRANS_PEMBULAT').AsFloat;
Q2.Next;
end;
end;
function TPOSTransaction.GetNominalPiutangVoucher: Double;
begin
Result := 0;
Q2.First;
while not Q2.eof do
begin
Result := Result + Q2.FieldByName('VCRD_NOMINAL').AsFloat;
Q2.Next;
end;
end;
function TPOSTransaction.GetNominalPPN: Double;
var
dNominal: Double;
begin
Result := 0;
{Q2.First;
while not Q2.Eof do
begin
Result := Result + Q2.FieldByName('TRANS_TOTAL_PPN').AsFloat;
Q2.Next;
end;}
Q1.First;
while not Q1.Eof do
begin
dNominal := Q1.FieldByName('TRANSD_SELL_PRICE_DISC').AsFloat * Q1.FieldByName('TRANSD_QTY').AsFloat;
dNominal := (dNominal * Q1.FieldByName('TRANSD_PPN').AsFloat) / (Q1.FieldByName('TRANSD_PPN').AsFloat + 100);
Result := Result + RoundTo(dNominal, -2);
Q1.Next;
end;
end;
function TPOSTransaction.GetNominalTransaction(aNoBukti : String): Double;
begin
Result := 0;
Q1.First;
while not Q1.eof do
begin
if aNoBukti = '' then
Result := Result + (Q1.FieldByName('TRANSD_SELL_PRICE_DISC').AsFloat * Q1.FieldByName('TRANSD_QTY').AsFloat)
else
begin
if aNoBukti = Q1.FieldByName('TRANS_NO').AsString then
Result := Result + (Q1.FieldByName('TRANSD_SELL_PRICE_DISC').AsFloat * Q1.FieldByName('TRANSD_QTY').AsFloat);
end;
Q1.Next;
end;
end;
function TPOSTransaction.GetNoTransaksi: string;
begin
Result := '';
Q2.First;
if not Q2.Eof then Result := Q2.FieldByName('TRANS_NO').AsString;
end;
//function TPOSTransaction.GetOPC_UNIT: TUnit;
//begin
// if FOPC_UNIT = nil then
// begin
// FOPC_UNIT := TUnit.Create(Self);
// FOPC_UNIT.LoadByID(FOPC_UNITID);
// end;
// Result := FOPC_UNIT;
//end;
//function TPOSTransaction.GetOPM_UNIT: TUnit;
//begin
// if FOPM_UNIT = nil then
// begin
// FOPM_UNIT := TUnit.Create(Self);
// FOPM_UNIT.LoadByID(FOPM_UNITID);
// end;
// Result := FOPM_UNIT;
//end;
function TPOSTransaction.GetPenjualanBarang(aMerchandizeGroupID : Integer;
aUnitID : Integer; aTipe : Integer): Double;
var
dPPn: Double;
//dNominalStlhDisc: Double;
dNominal: Double;
begin
Result := 0;
Q1.First;
while not Q1.Eof do
begin
dNominal := 0;
dPPn := 0;
if (Q1.FieldByName('MERCHANGRUP_ID').AsInteger = aMerchandizeGroupID) and
(Q1.FieldByName('TRANSD_UNT_ID').AsInteger = aUnitID) then
begin
if (aTipe = 1) then
begin
if (Q1.FieldByName('TRANSD_TPBRG_ID').AsInteger in [1, 4, 6, 7]) then
begin
dNominal := Q1.FieldByName('TRANSD_SELL_PRICE_DISC').AsFloat * Q1.FieldByName('TRANSD_QTY').AsFloat;
//dNominalStlhDisc := (Q1.FieldByName('TRANSD_SELL_PRICE_DISC').AsFloat - Q1.FieldByName('TRANSD_DISC_GMC_NOMINAL').AsFloat) * Q1.FieldByName('TRANSD_QTY').AsFloat;
dPPn := (dNominal * Q1.FieldByName('TRANSD_PPN').AsFloat) / (100 + Q1.FieldByName('TRANSD_PPN').AsFloat);
end;
end
else
begin
if aMerchandizeGroupID = 33 then
begin
if (Q1.FieldByName('TRANSD_TPBRG_ID').AsInteger = aTipe) then
begin
dNominal := Q1.FieldByName('TRANSD_SELL_PRICE_DISC').AsFloat * Q1.FieldByName('TRANSD_QTY').AsFloat;
//dNominalStlhDisc := (Q1.FieldByName('TRANSD_SELL_PRICE_DISC').AsFloat - Q1.FieldByName('TRANSD_DISC_GMC_NOMINAL').AsFloat) * Q1.FieldByName('TRANSD_QTY').AsFloat;
dPPn := (dNominal * Q1.FieldByName('TRANSD_PPN').AsFloat) / (100 + Q1.FieldByName('TRANSD_PPN').AsFloat);
end;
end
else
begin
if (Q1.FieldByName('TRANSD_TPBRG_ID').AsInteger in [2, 3]) then
begin
dNominal := Q1.FieldByName('TRANSD_SELL_PRICE_DISC').AsFloat * Q1.FieldByName('TRANSD_QTY').AsFloat;
//dNominalStlhDisc := (Q1.FieldByName('TRANSD_SELL_PRICE_DISC').AsFloat - Q1.FieldByName('TRANSD_DISC_GMC_NOMINAL').AsFloat) * Q1.FieldByName('TRANSD_QTY').AsFloat;
dPPn := (dNominal * Q1.FieldByName('TRANSD_PPN').AsFloat) / (100 + Q1.FieldByName('TRANSD_PPN').AsFloat);
end;
end;
end;
dPPn := RoundTo(dPPn, -2);
dNominal := dNominal - dPPn;
Result := Result + dNominal;
end;
Q1.Next;
end;
end;
function TPOSTransaction.GetPlannedID: string;
begin
Result := '';
if State = csNone then
begin
Raise exception.create('Tidak bisa GetPlannedID di Mode csNone');
exit;
end
else if state = csCreated then
begin
// Result := cGetNextID(GetFieldNameFor_ID, CustomTableName);
Result := cGetNextIDGUIDToString;
end
else if State = csLoaded then
begin
Result := FID;
end;
end;
function TPOSTransaction.GetPOSTransactionItems: TPOSTransactionItems;
begin
if FPOSTransactionItems = nil then
begin
FPOSTransactionItems := TPOSTransactionItems.Create(TPOSTransactionItem);
FPOSTransactionItems.clear;
FPOSTransactionItems.LoadByHeaderID(ID);
end;
Result := FPOSTransactionItems;
end;
function TPOSTransaction.GetReturNo: TStrings;
begin
if FReturNo = nil then
begin
FReturNo := TStringList.Create;
end;
Result := FReturNo;
end;
function TPOSTransaction.GetTableNameFor_KuponBotol: string;
begin
Result := 'trans_kupon_botol';
end;
function TPOSTransaction.GetTableNameFor_Retur: string;
begin
Result := 'TRANSAKSI_RETUR_NOTA';
end;
function TPOSTransaction.GetTableNameFor_Voucher: string;
begin
Result := 'voucher_detil';
end;
function TPOSTransaction.GetTransactionCard: TPOSTransactionCard;
begin
if FTransactionCard = nil then
begin
FTransactionCard := TPOSTransactionCard.Create(Self);
FTransactionCard.LoadByTransNo(No,FNewUnitID);
end;
Result := FTransactionCard;
end;
function TPOSTransaction.GetTransactionDate: TDateTime;
begin
Result := 0;
Q2.First;
if not Q2.Eof then Result := Q2.FieldByName('TRANS_DATE').AsDateTime;
end;
function TPOSTransaction.GetTrans_Struk: TSTrings;
var
lStream: TStream;
S: string;
begin
If not Assigned(FTrans_Struk) then
begin
S := 'Select ' + GetFieldNameFor_TransStruk + ' from '
+ CustomTableName + ' where ' + GetFieldNameFor_ID
+ ' = ' + QuotedStr(Self.ID);
with cOpenQuery(s) do
begin
Try
If not eof then
begin
If not Fields[0].IsNull then
begin
FTrans_Struk := TStringList.Create;
lStream := CreateBlobStream(Fields[0], bmRead);
Try
FTrans_Struk.LoadFromStream(lStream);
Finally
lStream.Free;
end;
end;
end;
Finally
free;
end;
end;
end;
Result := FTrans_Struk;
end;
function TPOSTransaction.GetVoucherLains: TVoucherLainItems;
begin
if FVoucherLains = nil then
begin
FVoucherLains := TVoucherLainItems.Create(TVoucherLainItem);
end;
Result := FVoucherLains;
end;
function TPOSTransaction.GetVoucherNo: TStrings;
begin
if FVoucherNo = nil then
begin
FVoucherNo := TStringList.Create;
end;
Result := FVoucherNo;
end;
function TPOSTransaction.IsBalanceUsed(aBalance_ID, aUnitID: string): Boolean;
var
sSQL: string;
begin
Result := False;
sSQL := 'select count(' + GetFieldNameFor_BeginningBalance + ') as jml '
+ ' from ' + CustomTableName
+ ' where ' + GetFieldNameFor_BeginningBalance + ' = ' + QuotedStr(aBalance_ID) + ';';
// + ' and ' + GetFieldNameFor_BeginningBalanceUnit + ' = ' + QuotedStr(AUnitID) + ';';
with cOpenQuery(sSQL) do
begin
try
if not EOF then
begin
if FieldByName('jml').AsInteger > 0 then
Result := True;
end;
finally
Free;
end;
End;
end;
function TPOSTransaction.LoadByID(AID : Integer; AUnitID: Integer): Boolean;
var
sSQL: string;
begin
sSQL := 'select * from ' + CustomTableName
+ ' where ' + GetFieldNameFor_ID + ' = ' + IntToStr(AID)
+ ' and ' + GetFieldNameFor_NewUnit + ' = ' + IntToStr(AUnitID);
Result := FloadFromDB(sSQL);
end;
function TPOSTransaction.LoadByTrans_No(aTransNo, aUnitID: String): Boolean;
var
sSQL: string;
begin
sSQL := 'select * from ' + CustomTableName
+ ' where ' + GetFieldNameFor_No + ' = ' + QuotedStr(aTransNo)
+ ' and ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(AUnitID) + ';';
Result := FloadFromDB(sSQL);
end;
function TPOSTransaction.LoadDataJurnal(aDate1 : TDateTime; aDate2 : TDateTime;
aUnitID : Integer): Boolean;
var
s: string;
begin
Result := False;
Q1 := TFDQuery.Create(nil);
s := 'Select a.TRANS_NO, d.MERCHANGRUP_ID, b.TRANSD_UNT_ID, b.TRANSD_TPBRG_ID, '
+ ' b.TRANSD_SELL_PRICE_DISC, b.TRANSD_QTY, b.TRANSD_PPN, g.BSS_HARGA_TRANSAKSI, b.TRANSD_DISC_GMC_NOMINAL,'
+ ' b.TRANSD_TOTAL, b.TRANSD_TOTAL_B4_TAX'
+ ' FROM TRANSAKSI a'
+ ' INNER JOIN TRANSAKSI_DETIL b ON a.TRANS_NO = b.TRANSD_TRANS_NO AND a.TRANS_UNT_ID = b.TRANSD_TRANS_UNT_ID'
+ ' INNER JOIN BARANG_HARGA_JUAL f ON b.TRANSD_BHJ_ID = f.BHJ_ID AND b.TRANSD_BHJ_UNT_ID = f.BHJ_UNT_ID'
+ ' INNER JOIN BARANG_STOK_SIRKULASI g ON f.BHJ_BRG_CODE = g.BSS_BRG_CODE'
+ ' AND f.BHJ_SAT_CODE = g.BSS_SAT_CODE '
+ ' AND a.TRANS_NO = g.BSS_DOC_NO'
+ ' LEFT JOIN BARANG c ON b.TRANSD_BRG_CODE = c.BRG_CODE'
+ ' LEFT JOIN REF$KATEGORI e ON e.KAT_ID = c.BRG_KAT_ID '
+ ' LEFT JOIN REF$SUB_GRUP h ON h.SUBGRUP_ID = e.KAT_SUBGRUP_ID '
+ ' LEFT JOIN REF$MERCHANDISE_GRUP d ON h.SUBGRUP_MERCHANGRUP_ID = d.MERCHANGRUP_ID'
+ ' WHERE a.TRANS_DATE BETWEEN ' + TAppUtils.QuotD(aDate1)
+ ' AND ' + TAppUtils.QuotD(aDate2, TRUE)
+ ' AND a.TRANS_UNT_ID = ' + IntToStr(aUnitID)
+ ' AND (a.TRANS_IS_PENDING = 0 OR a.TRANS_IS_PENDING is NULL)'
+ ' AND (TRANS_IS_JURNAL = 0 OR TRANS_IS_JURNAL IS NULL)'
+ ' ORDER BY a.TRANS_NO';
Q1 := cOpenQuery(s);
s := 'Select a.TRANS_NO, a.TRANS_DATE, a.TRANS_TOTAL_TRANSACTION, a.TRANS_DISC_GMC_NOMINAL, a.TRANS_PEMBULAT, a.TRANS_DISC_CARD,'
+ ' a.TRANS_BAYAR_CARD, a.TRANS_BAYAR_CASH, a.TRANS_TOTAL_PPN, sum(b.TKB_SELL_PRICE_DISC) as TKB_SELL_PRICE_DISC,'
+ ' SUM(c.TRANSC_CASHBACK_NILAI) as TRANSC_CASHBACK_NILAI, d.CARD_REK_CODE, d.CARD_REK_CASH_BACK,'
+ ' SUM(e.VCRD_NOMINAL) as VCRD_NOMINAL, SUM(c.TRANSC_CHARGE) as TRANSC_CHARGE'
+ ' FROM TRANSAKSI a LEFT JOIN TRANS_KUPON_BOTOL b On a.TRANS_NO = b.TKB_POS_TRANS_NO And a.TRANS_UNT_ID = b.TKB_UNT_ID'
+ ' LEFT JOIN VOUCHER_DETIL e ON a.TRANS_NO = e.VCRD_POS_TRANS_NO And a.TRANS_UNT_ID = e.VCRD_UNT_ID'
+ ' LEFT JOIN TRANSAKSI_CARD c ON a.TRANS_NO = c.TRANSC_TRANS_NO'
+ ' AND a.TRANS_UNT_ID = c.TRANSC_TRANS_UNT_ID'
+ ' LEFT JOIN REF$CREDIT_CARD d ON c.TRANSC_CARD_ID = d.CARD_ID'
+ ' AND c.TRANSC_CARD_UNT_ID = d.CARD_UNT_ID'
+ ' WHERE a.TRANS_DATE BETWEEN ' + TAppUtils.QuotD(aDate1)
+ ' AND ' + TAppUtils.QuotD(aDate2, TRUE)
+ ' AND a.TRANS_UNT_ID = ' + IntToStr(aUnitID)
+ ' AND (a.TRANS_IS_JURNAL = 0 OR a.TRANS_IS_JURNAL IS NULL)'
+ ' AND (a.TRANS_IS_PENDING = 0 OR a.TRANS_IS_PENDING is NULL)'
+ ' GROUP BY a.TRANS_NO, a.TRANS_DATE, a.TRANS_TOTAL_TRANSACTION, a.TRANS_DISC_GMC_NOMINAL, a.TRANS_PEMBULAT,'
+ ' a.TRANS_BAYAR_CARD, a.TRANS_BAYAR_CASH, a.TRANS_TOTAL_PPN, d.CARD_REK_CODE, d.CARD_REK_CASH_BACK, a.TRANS_DISC_CARD';
Q2 := cOpenQuery(s);
if not Q1.Eof then Result := True;
end;
function TPOSTransaction.LoadDataJurnalByNo(aNoBukti : String; aUnitID :
Integer): Boolean;
var
s: string;
begin
Result := False;
Q1 := TFDQuery.Create(nil);
s := 'Select a.TRANS_NO, d.MERCHANGRUP_ID, b.TRANSD_UNT_ID, b.TRANSD_TPBRG_ID, '
+ ' b.TRANSD_SELL_PRICE_DISC, b.TRANSD_QTY, b.TRANSD_PPN, g.BSS_HARGA_TRANSAKSI, b.TRANSD_DISC_GMC_NOMINAL,'
+ ' b.TRANSD_TOTAL, b.TRANSD_TOTAL_B4_TAX'
+ ' FROM TRANSAKSI a'
+ ' INNER JOIN TRANSAKSI_DETIL b ON a.TRANS_NO = b.TRANSD_TRANS_NO AND a.TRANS_UNT_ID = b.TRANSD_TRANS_UNT_ID'
+ ' INNER JOIN BARANG_HARGA_JUAL f ON b.TRANSD_BHJ_ID = f.BHJ_ID AND b.TRANSD_BHJ_UNT_ID = f.BHJ_UNT_ID'
+ ' INNER JOIN BARANG_STOK_SIRKULASI g ON f.BHJ_BRG_CODE = g.BSS_BRG_CODE'
+ ' AND f.BHJ_SAT_CODE = g.BSS_SAT_CODE '
+ ' AND a.TRANS_NO = g.BSS_DOC_NO'
+ ' LEFT JOIN BARANG c ON b.TRANSD_BRG_CODE = c.BRG_CODE'
+ ' LEFT JOIN REF$KATEGORI e ON e.KAT_ID = c.BRG_KAT_ID '
+ ' LEFT JOIN REF$SUB_GRUP h ON h.SUBGRUP_ID = e.KAT_SUBGRUP_ID '
+ ' LEFT JOIN REF$MERCHANDISE_GRUP d ON h.SUBGRUP_MERCHANGRUP_ID = d.MERCHANGRUP_ID'
+ ' WHERE a.TRANS_NO = ' + QuotedStr(aNoBukti)
+ ' AND a.TRANS_UNT_ID = ' + IntToStr(aUnitID)
+ ' AND (a.TRANS_IS_PENDING = 0 OR a.TRANS_IS_PENDING is NULL)'
+ ' AND (TRANS_IS_JURNAL = 0 OR TRANS_IS_JURNAL IS NULL)'
+ ' ORDER BY a.TRANS_NO';
Q1 := cOpenQuery(s);
s := 'Select a.TRANS_NO, a.TRANS_DATE, a.TRANS_TOTAL_TRANSACTION, a.TRANS_DISC_GMC_NOMINAL, a.TRANS_PEMBULAT, a.TRANS_DISC_CARD,'
+ ' a.TRANS_BAYAR_CARD, a.TRANS_BAYAR_CASH, a.TRANS_TOTAL_PPN, sum(b.TKB_SELL_PRICE_DISC) as TKB_SELL_PRICE_DISC,'
+ ' SUM(c.TRANSC_CASHBACK_NILAI) as TRANSC_CASHBACK_NILAI, d.CARD_REK_CODE, d.CARD_REK_CASH_BACK,'
+ ' SUM(e.VCRD_NOMINAL) as VCRD_NOMINAL, SUM(c.TRANSC_CHARGE) as TRANSC_CHARGE'
+ ' FROM TRANSAKSI a LEFT JOIN TRANS_KUPON_BOTOL b On a.TRANS_NO = b.TKB_POS_TRANS_NO And a.TRANS_UNT_ID = b.TKB_UNT_ID'
+ ' LEFT JOIN VOUCHER_DETIL e ON a.TRANS_NO = e.VCRD_POS_TRANS_NO And a.TRANS_UNT_ID = e.VCRD_UNT_ID'
+ ' LEFT JOIN TRANSAKSI_CARD c ON a.TRANS_NO = c.TRANSC_TRANS_NO'
+ ' AND a.TRANS_UNT_ID = c.TRANSC_TRANS_UNT_ID'
+ ' LEFT JOIN REF$CREDIT_CARD d ON c.TRANSC_CARD_ID = d.CARD_ID'
+ ' AND c.TRANSC_CARD_UNT_ID = d.CARD_UNT_ID'
+ ' WHERE a.TRANS_NO = ' + QuotedStr(aNoBukti)
+ ' AND a.TRANS_UNT_ID = ' + IntToStr(aUnitID)
+ ' AND (a.TRANS_IS_JURNAL = 0 OR a.TRANS_IS_JURNAL IS NULL)'
+ ' AND (a.TRANS_IS_PENDING = 0 OR a.TRANS_IS_PENDING is NULL)'
+ ' GROUP BY a.TRANS_NO, a.TRANS_DATE, a.TRANS_TOTAL_TRANSACTION, a.TRANS_DISC_GMC_NOMINAL, a.TRANS_PEMBULAT,'
+ ' a.TRANS_BAYAR_CARD, a.TRANS_BAYAR_CASH, a.TRANS_TOTAL_PPN, d.CARD_REK_CODE, d.CARD_REK_CASH_BACK, a.TRANS_DISC_CARD';
Q2 := cOpenQuery(s);
if not Q1.Eof then Result := True;
end;
function TPOSTransaction.RemoveFromDB: Boolean;
var
sSQL: string;
begin
Result := False;
sSQL := 'delete from ' + CustomTableName
+ ' where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(FID)
+ ' and ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(FNewUnitID);
if cExecSQL(sSQL,dbtPOS, False) then
Result := True; //SimpanBlob(sSQL,GetHeaderFlag);
end;
function TPOSTransaction.SaveAllToDB: Boolean;
begin
Result := False;
if SaveToDB then
if SaveTransactionCardToDB then
if SaveKuponBotolToDB then
if SaveVoucherToDB then
if SaveReturToDB then
if SaveVoucherLainToDB then
Result := True;
end;
function TPOSTransaction.SaveKuponBotolToDB: Boolean;
var
ssSQL: TStrings;
sSQL: string;
begin
Result := False;
sSQL := 'update ' + GetTableNameFor_KuponBotol
+ ' set ' + GetFieldNameFor_KuponBotolStatus + ' = ' + QuotedStr('CLOSE')
+ ', ' + GetFieldNameFor_KuponBotolTransPOS + ' = ' + QuotedStr(No)
+ ' where ' + GetFieldNameFor_KuponBotolNo + ' = ' + QuotedStr(KuponBotolNo)
// + ' and ' + GetFieldNameFor_KuponBotolUnit + ' = ' + QuotedStr(FNewUnitID)
+ ';';
ssSQL := TStringList.Create;
ssSQL.Add(sSQL);
//ssSQL.SaveToFile(cGetAppPath + 'POS_KuponBotol.SQL');
FreeAndNil(ssSQL);
if cExecSQL(sSQL, dbtPOS, False) then
// if SimpanBlob(sSQL,GetHeaderFlag) then
Result := True;
end;
function TPOSTransaction.SaveReturToDB: Boolean;
var
i: Integer;
sSQL: string;
ssSQL: TStrings;
begin
Result := False;
if ReturNo.Count = 0 then
begin
Result := True;
Exit;
end;
ssSQL := TStringList.Create;
for i := 0 to ReturNo.Count - 1 do // Iterate
begin
sSQL := 'update ' + GetTableNameFor_Retur
+ ' set ' + GetFieldNameFor_ReturTransPOS + ' = ' + QuotedStr(No)
+ ' , ' + GetFieldNameFor_DATE_MODIFY + ' = ' + TAppUtils.QuotDT(DATE_MODIFY)
+ ' where ' + GetFieldNameFor_ReturNo + ' = ' + QuotedStr(ReturNo[i])
+ ' and ' + GetFieldNameFor_ReturUnit + ' = ' + QuotedStr(FNewUnitID) + ';';
ssSQL.Add(sSQL);
end; // for
//ssSQL.SaveToFile(cGetAppPath + 'POS_TransRetur.SQL');
try
try
if cExecSQL(ssSQL) then
// if SimpanBlob(ssSQL,GetHeaderFlag) then
Result := True;
except
end;
finally
FreeAndNil(ssSQL);
end;
end;
function TPOSTransaction.SaveToDB: Boolean;
var
ssSQL: TStrings;
begin
Result := False;
try
ssSQL := GenerateSQL;
//ssSQL.SaveToFile(cGetAppPath + 'POS_Transaction.SQL');
//try
if cExecSQL(ssSQL) then
// if SimpanBlob(ssSQL,GetHeaderFlag) then
Result := True;
//except
//end;
finally
FreeAndNil(ssSQL);
end;
end;
function TPOSTransaction.SaveTransactionCardToDB: Boolean;
begin
// Result := False;
if FTransactionCard = nil then
begin
Result := True;
Exit;
end;
Result := TransactionCard.SaveToDB;
end;
function TPOSTransaction.SaveVoucherLainToDB: Boolean;
var
i: Integer;
ssSQL: TStrings;
begin
Result := False;
if VoucherLains.Count = 0 then
begin
Result := True;
Exit;
end;
ssSQL := TStringList.Create;
for i := 0 to VoucherLains.Count - 1 do // Iterate
begin
ssSQL.AddStrings(VoucherLains[i].VoucherLain.GenerateSQL);
end; // for
//ssSQL.SaveToFile(cGetAppPath + 'POS_VoucherLain.SQL');
try
//try
if cExecSQL(ssSQL) then
// if SimpanBlob(ssSQL,GetHeaderFlag) then
Result := True;
//except
//end;
finally
FreeAndNil(ssSQL);
end;
end;
function TPOSTransaction.SaveVoucherToDB: Boolean;
var
i: Integer;
sSQL: string;
ssSQL: TStrings;
begin
Result := False;
if VoucherNo.Count = 0 then
begin
Result := True;
Exit;
end;
ssSQL := TStringList.Create;
for i := 0 to VoucherNo.Count - 1 do // Iterate
begin
sSQL := 'update ' + GetTableNameFor_Voucher
+ ' set ' + GetFieldNameFor_VoucherStatus + ' = ' + QuotedStr('CLOSE')
+ ', ' + GetFieldNameFor_VoucherTransPOS + ' = ' + QuotedStr(No)
+ ' where ' + GetFieldNameFor_VoucherNo + ' = ' + QuotedStr(VoucherNo[i])
+ ' and ' + GetFieldNameFor_VoucherUnit + ' = ' + QuotedStr(FNewUnitID) + ';';
ssSQL.Add(sSQL);
end; // for
//ssSQL.SaveToFile(cGetAppPath + 'POS_Voucher.SQL');
try
//try
if cExecSQL(ssSQL) then
// if SimpanBlob(ssSQL,GetHeaderFlag) then
Result := True;
//except
//end;
finally
FreeAndNil(ssSQL);
end;
end;
procedure TPOSTransaction.SetNewUnit(Value: TUnit);
begin
FNewUnitID := Value.ID;
end;
//procedure TPOSTransaction.SetOPC_UNIT(Value: TUnit);
//begin
// FOPC_UNITID := Value.ID;
//end;
//procedure TPOSTransaction.SetOPM_UNIT(Value: TUnit);
//begin
// FOPM_UNITID := Value.ID;
//end;
procedure TPOSTransaction.UpdateData(ABayarCard, ABayarCash: Double;
ABeginningBalance_ID: string; ADiscAMCNominal, ADiscAMCPersen: Double; AID:
string; AIsActive: Boolean; AMemberID, ANewUnit_ID, ANo: string; APembulat:
Double; ATanggal: TDateTime; ATotalBayar, ATotalDiscAMC, ATotalPPN,
ATotalTransaction: Double; AKuponBotolNo: String; AVoucherNo: TStrings;
aUserID: string; aTransDiscCard: Double; aISJURNAL: Integer = 0;
aIsPending: Boolean = False);
var
i: integer;
begin
FBayarCard := ABayarCard;
FBayarCash := ABayarCash;
FBeginningBalanceID := ABeginningBalance_ID;
FDiscAMCNominal := ADiscAMCNominal;
FDiscAMCPersen := ADiscAMCPersen;
FID := AID;
FIsActive := AIsActive;
FMemberID := AMemberID;
FNewUnitID := ANewUnit_ID;
FNo := Trim(ANo);
FPembulat := APembulat;
FTanggal := ATanggal;
FTotalBayar := ATotalBayar;
FTotalDiscAMC := ATotalDiscAMC;
FTotalPPN := ATotalPPN;
FTotalTransaction := ATotalTransaction;
FKuponBotolNo := AKuponBotolNo;
FIsPending := aIsPending;
FOP_MODIFY := aUserID;
FTRANS_DISC_CARD := aTransDiscCard;
if AVoucherNo <> nil then
begin
// VoucherNo.AddStrings(AVoucherNo);
for i := 0 to AVoucherNo.Count - 1 do
begin
if LeftStr(AVoucherNo[i],3) = 'RN/' then
ReturNo.Add(AVoucherNo[i])
else
VoucherNo.Add(AVoucherNo[i]);
end;
end;
State := csCreated;
end;
procedure TPOSTransaction.UpdatePOSTransactionItems(ABarangHargaJual_ID:
string; ACOGS: Double; AID: string; AIsBKP, AIsDiscAMC: Boolean; ALastCost,
APPN, APPNBM, AQty, ASellPrice, ASellPriceDisc, ATotal, ATotalBeforeTax,
ATotalCeil: Double; ATransNo, AUnitID, ABarangCode, ATipeBarangID: string;
aDISC_GMC_NOMINAL: Double; aUomCode: string; aDisc_Card: Double = 0;
aDisc_Man: Double = 0; aOtoCode: String = '');
begin
//Generate penambahan detail
with POSTransactionItems.Add do
Begin
BarangCode := ABarangCode;
TipeBarangID := ATipeBarangID;
FBarangHargaJualID := ABarangHargaJual_ID;
FCOGS := ACOGS;
FID := AID;
FIsBKP := AIsBKP;
FIsDiscAMC := AIsDiscAMC;
FLastCost := ALastCost;
FPPN := APPN;
FPPNBM := APPNBM;
FQty := AQty;
FSellPrice := ASellPrice;
FSellPriceDisc := ASellPriceDisc;
FTotal := ATotal;
FTotalBeforeTax := ATotalBeforeTax;
FTotalCeil := ATotalCeil;
FDISC_GMC_NOMINAL := aDISC_GMC_NOMINAL;
FTransNo := Trim(ATransNo);
FNewUnitID := AUnitID;
FDisc_Card := aDisc_Card;
FUomCode := aUomCode;
FDiscMan := aDisc_Man;
FOto_Code := aOtoCode;
end
end;
function TPOSTransaction.UpdateStatusJurnal(aStatus : Integer; aUnitID :
Integer; aDate : TDateTime): Boolean;
var
s: string;
begin
Result := False;
s := 'Update TRANSAKSI set TRANS_IS_JURNAL = ' + IntToStr(aStatus)
+ ' Where DATE(TRANS_DATE) BETWEEN ' + TAppUtils.QuotD(aDate)
+ ' AND ' + TAppUtils.QuotD(aDate, True)
// + ' AND TRANS_UNT_ID = ' + IntToStr(aUnitID)
+ ';';
if cExecSQL(s, dbtPOS, False) then
Result := True; //SimpanBlob(s, GetHeaderFlag);
end;
function TPOSTransaction.UpdateTransStruk(lTransStruk: TStrings; IDTrans:
string): Boolean;
var
lQ: TFDQuery;
lStream: TMemoryStream;
begin
Result := True;
If not Assigned(lTransStruk) then exit;
lStream := TMemoryStream.Create;
lTransStruk.SaveToStream(lStream);
lQ := TFDQuery.Create(Self);
lQ.Connection := dmMain.dbPOS;
lQ.Transaction := dmMain.TransPOS;
Try
Try
If not lQ.Transaction.Active then lQ.Transaction.StartTransaction;
lQ.SQL.Add('Update ' + CustomTableName + ' set '
+ GetFieldNameFor_TransStruk + '= :lBlob '
//+ ',' + GetFieldNameFor_OP_MODIFY + ' = :lModify '
+ ' where ' + GetFieldNameFor_ID + ' = :lID');
lQ.ParamByName('lBlob').LoadFromStream(lStream, ftBlob);
lQ.ParamByName('lID').AsString := IDTrans;
lQ.ExecSQL;
If lQ.Transaction.Active then lQ.Transaction.Commit;
except
If lQ.Transaction.Active then lQ.Transaction.Rollback;
Result := False;
end;
finally
lStream.Free;
lQ.Free;
end;
end;
end.
|
unit U_ClassConfig;
interface
Type
TConfig = Class
Strict Private
// Class Var FInstance : TConfig;
private
FConfirmaGravacao: Boolean;
FConfirmaCancelamento: Boolean;
procedure SetConfirmaCancelamento(const Value: Boolean);
procedure SetConfirmaGravacao(const Value: Boolean);
Public
CLass function GetInstance : TConfig;
property ConfirmaGravacao : Boolean read FConfirmaGravacao write SetConfirmaGravacao;
property ConfirmaCancelamento : Boolean read FConfirmaCancelamento write SetConfirmaCancelamento;
End;
implementation
uses
System.SysUtils;
{ TConfig }
class function TConfig.GetInstance: TConfig;
begin
Result := nil;
{
if not Assigned(Finstance) then
FInstance := TConfig.Create;
Result := finstance;
}
end;
procedure TConfig.SetConfirmaCancelamento(const Value: Boolean);
begin
FConfirmaCancelamento := Value;
end;
procedure TConfig.SetConfirmaGravacao(const Value: Boolean);
begin
FConfirmaGravacao := Value;
end;
end.
|
unit uFaceRecornizerTrainer;
interface
uses
Winapi.Windows,
System.Types,
System.SysUtils,
System.Classes,
System.Math,
Vcl.Graphics,
Dmitry.Utils.System,
Dmitry.Utils.Files,
Dmitry.Graphics.Types,
OpenCV.Utils,
GraphicCrypt,
uLogger,
uMemory,
uDBClasses,
uDBContext,
uDBManager,
uDBEntities,
uImageLoader,
uFaceDetection,
uFaceAnalyzer,
uFaceRecognizer;
type
TFaceRecornizerTrainer = class
public
procedure Train;
end;
procedure TrainIt;
implementation
const
FaceWidth = 64;
FaceHeight = 64;
FaceWidthToLoad = 128;
FaceHeightToLoad = 128;
var
TotalSuccess, TotalFail, PartialSuccess, Fail, Success, FailQuaility, SuccessQuality, TotalFaces: Integer;
procedure TrainIt;
var
FR: TFaceRecornizerTrainer;
begin
FR := TFaceRecornizerTrainer.Create;
try
FR.Train;
finally
F(FR);
end;
end;
procedure ProcessFacesOnImage(MI: TMediaItem; Bitmap: TBitmap; ImageAreas: TPersonAreaCollection; Detector: TFaceDetectionManager; Recognizer: IFaceRecognizer; MinFaceScore: Byte; Logger: TStrings);
var
I, J, PersonId: Integer;
Area: TPersonArea;
DR: TFaceScoreResults;
FaceSample, FaceImage: TBitmap;
FileName: string;
PersonResults: TFaceRecognitionResults;
DistanceLimit: Double;
PersonFound, HasPartialSuccess, IsFail, IsSuccess: Boolean;
PartialPosition: Integer;
begin
for I := 0 to ImageAreas.Count - 1 do
begin
Area := ImageAreas[I];
DR := ProcessFaceAreaOnImage(MI, Bitmap, Area, Detector, MinFaceScore);
try
if DR = nil then
Continue;
Inc(TotalFaces);
IsFail := False;
IsSuccess := False;
HasPartialSuccess := False;
PartialPosition := 0;
FaceSample := TBitmap.Create;
try
DR.GenerateSample(FaceSample, FaceWidth, FaceHeight);
FileName := FormatEx('d:\Faces\{0}', [Area.PersonID]);
CreateDirA(FileName);
FileName := FileName + FormatEx('\Face_{0}_{1}_{2}.bmp', [DR.TotalScore, Area.ID, Area.ImageID]);
FaceSample.SaveToFile(FileName);
PersonResults := Recognizer.RecognizeFace(FaceSample, 5);
try
if PersonResults.Count > 0 then
begin
PersonId := PersonResults[0].PersonId;
DistanceLimit := LogN(9, Recognizer.GetFacesCount - 1) / 2.2;
PersonFound := PersonId = Area.PersonID;
if PersonFound then
begin
Inc(TotalSuccess);
Inc(SuccessQuality, DR.TotalScore);
end
else
begin
Inc(TotalFail);
Inc(FailQuaility, DR.TotalScore);
end;
if (PersonResults[0].Distance <= DistanceLimit) then
begin
if PersonFound then
IsSuccess := True
else
IsFail := True;
end;
if not PersonFound then
begin
for J := 0 to PersonResults.Count - 1 do
if PersonResults[J].IsValid and (PersonResults[J].PersonId = Area.PersonID) then
begin
HasPartialSuccess := True;
PartialPosition := J + 1;
end;
end;
if IsSuccess then
Inc(Success);
if IsFail then
Inc(Fail);
if HasPartialSuccess then
Inc(PartialSuccess);
//1: Faces: XXX
//2: MinDistance: XXX
//3: Threshold: XXX
//4: IsFailed: 1/0
//5: IsSuccess: 1/0
//6: Position: 0-5
Logger.Add(FormatEx('{1}{0}{2}{0}{3}{0}{4}{0}{5}{0}{6}{0}{7}{0}{8}', [#9,
Recognizer.GetFacesCount,
PersonResults[0].Distance,
DistanceLimit,
not PersonFound,
PersonFound,
HasPartialSuccess,
PartialPosition,
PersonResults[0].HasNegative
]));
Logger.SaveToFile('D:\train.txt');
end;
finally
F(PersonResults);
end;
//TODO do not train always?
if not IsSuccess then
begin
FaceImage := nil;
if DR.FaceImage <> nil then
begin
FaceImage := TBitmap.Create;
FaceImage.Assign(DR.FaceImage);
end;
if Recognizer.TrainFace(FaceSample, FaceImage, Area.PersonID, Area.ID, DR.TotalScore) then
begin
//PersonId := Recognizer.DetectFace(FaceSample, DR.TotalScore);
//if (PersonId <> Area.PersonID) and (PersonId > 0) then
// Inc(TotalFail);
end;
end;
finally
F(FaceSample);
end;
finally
F(DR);
end;
end;
end;
{ TFaceRecornizerTrainer }
procedure TFaceRecornizerTrainer.Train;
var
N, I, J: Integer;
DBContext: IDBContext;
Media: IMediaRepository;
People: IPeopleRepository;
TopImages: TMediaItemCollection;
ImageAreas: TPersonAreaCollection;
Area, MinArea: TPersonArea;
MI: TMediaItem;
ImageInfo: ILoadImageInfo;
FaceMinSize, ImageSize, RequiredImageSize: TSize;
Proportions: Double;
FaceRect: TRect;
B: TBitmap;
Detector: TFaceDetectionManager;
Recognizer: IFaceRecognizer;
MaxFaces: Integer;
FacesPerPerson: Integer;
PicturesToProcess: Integer;
FaceScore: Integer;
Infos: TStrings;
begin
Infos := TStringList.Create;
try
MaxFaces := 80;
FacesPerPerson := 10;
PicturesToProcess := 100;
FaceScore := 0;
for N in [1] do
begin
Infos.Add(FormatEx('SEPARATOR:{0}', [#9]));
Infos.Add(FormatEx('MaxFaces = {0}, FacesPerPerson = {1}, PicturesToProcess = {2}, FaceScore = {3}', [MaxFaces, FacesPerPerson, PicturesToProcess, FaceScore]));
Detector := TFaceDetectionManager.Create;
Recognizer := TFaceEigenRecognizer.Create(FaceWidth, FaceHeight, FacesPerPerson, MaxFaces);
try
TotalSuccess := 0;
TotalFail := 0;
FailQuaility := 0;
SuccessQuality := 0;
Success := 0;
Fail := 0;
PartialSuccess := 0;
TotalFaces := 0;
DBContext := DBManager.DBContext;
Media := DBContext.Media;
People := DBContext.People;
TopImages := Media.GetTopImagesWithPersons(Now - 2000, PicturesToProcess);
try
for I := 0 to TopImages.Count - 1 do
begin
MI := TopImages[I];
if FileExists(MI.FileName) and not ValidCryptGraphicFile(MI.FileName) then
begin
ImageAreas := People.GetAreasOnImage(MI.ID);
try
if (ImageAreas.Count > 0) then
begin
ImageSize.Width := MI.Width;
ImageSize.Height := MI.Height;
FaceMinSize := ImageSize;
MinArea := ImageAreas[0];
//search for minimum face
for J := 0 to ImageAreas.Count - 1 do
begin
Area := ImageAreas[J];
if ((Area.Width < FaceMinSize.Width) or (Area.Height < FaceMinSize.Height)) and (FaceMinSize.Height > 0) and (FaceMinSize.Height > 0) then
MinArea := Area;
end;
FaceRect := CalculateRectOnImage(MinArea, ImageSize);
if (FaceRect.Width > 0) and (FaceRect.Height > 0) then
begin
//calculate proportions to load image to reach min image size with required size of person image
Proportions := Min(FaceRect.Width / FaceWidthToLoad, FaceRect.Height / FaceHeightToLoad);
RequiredImageSize.Width := Floor(ImageSize.Width / Proportions);
RequiredImageSize.Height := Floor(ImageSize.Height / Proportions);
if LoadImageFromPath(MI, 1, '', [ilfGraphic, ilfDontUpdateInfo, ilfUseCache], ImageInfo, RequiredImageSize.Width, RequiredImageSize.Height) then
begin
B := ImageInfo.GenerateBitmap(MI, RequiredImageSize.Width, RequiredImageSize.Height, pf24Bit, clBlack, [ilboFreeGraphic, ilboRotate]);
try
ProcessFacesOnImage(MI, B, ImageAreas, Detector, Recognizer, FaceScore, Infos);
finally
F(B);
end;
end;
end;
end;
finally
F(ImageAreas);
end;
end;
end;
finally
F(TopImages);
end;
Recognizer.SaveState('D:\TrainSaved');
finally
F(Detector);
Recognizer := nil;
end;
Infos.Add(FormatEx('DONE', []));
Infos.Add(FormatEx('TotalSuccess{0}TotalFail{0}Success{0}Fail{0}PartialSuccess{0}TotalFaces', [#9]));
Infos.Add(FormatEx('{1}{0}{2}{0}{3}{0}{4}{0}{5}{0}{6}', [#9, TotalSuccess, TotalFail, Success, Fail, PartialSuccess, TotalFaces]));
Infos.SaveToFile('D:\train.txt');
end;
finally
F(Infos);
end;
end;
end.
|
unit uCommonDevice;
interface
uses
SysUtils, uModbus;
type
TCommonModbusDevice = class
protected
FModbus: TModBus;
FIdent: TModbusIdentification;
public
constructor Create;
destructor Destroy; override;
function Open(Port, Speed, Adr: integer): TModbusError; overload;
function Open(Port, Speed: integer): boolean; overload;
function Open(Host: string; Port: integer; Adr: integer): TModbusError; overload;
function Close: boolean;
function ReadDeviceIdentification(Addr: byte; var Ident: TModbusIdentification): TModbusError;
function FindFirst: byte;
function FindNext(FromID: byte): byte;
function Connect: boolean;
procedure SetTimeOut(Value: byte);
property DeviceInfo: TModbusIdentification read FIdent;
end;
implementation
function TCommonModbusDevice.ReadDeviceIdentification(Addr: byte;
var Ident: TModbusIdentification): TModbusError;
var
s,
dataout: ansistring;
k: integer;
begin
Ident.Company := '';
Ident.Product := '';
Ident.Version := '';
for k := 0 to 3 do
begin
Result := FModbus.CallFunction(Addr, 43, 14, #$01 + ansichar(k), dataout);
if Result <> merNone then exit;
s := Copy(dataout, 11, ord(dataout[10]));
if Pos(#$0, s) > 0 then
s := Copy(s, 1, Pos(#$0, s) - 1);
case k of
0: Ident.Company := s;
1: Ident.Product := s;
2: Ident.Version := s;
3: Ident.VendorURL := s;
else
end;
if dataout[6] <> #$FF then break; // больше нечего тащить
end;
end;
procedure TCommonModbusDevice.SetTimeOut(Value: byte);
begin
FModbus.TimeOut := Value;
end;
function TCommonModbusDevice.Close: boolean;
begin
Result := false;
try
FModbus.Free;
Result := true;
except
end;
FModbus := nil;
end;
function TCommonModbusDevice.Connect: boolean;
begin
if FModbus = nil then
begin
Result := false;
exit;
end;
Result := FModbus.Connected;
end;
constructor TCommonModbusDevice.Create;
begin
FModbus := nil;
inherited;
end;
destructor TCommonModbusDevice.Destroy;
begin
try
FModbus.Free;
except
end;
inherited;
end;
function TCommonModbusDevice.FindFirst: byte;
begin
Result := FModbus.FindFirst;
end;
function TCommonModbusDevice.FindNext(FromID: byte): byte;
begin
Result := FModbus.FindNext(FromID);
end;
function TCommonModbusDevice.Open(Port, Speed: integer): boolean;
begin
Result := false;
try
FModbus := TModbus.Create(Port, Speed);
if FModbus.Connected then
Result := true;
except
FModbus := nil;
end;
end;
function TCommonModbusDevice.Open(Port, Speed, Adr: integer): TModbusError;
begin
FIdent.Company := '';
FIdent.Product := '';
FIdent.Version := '';
FModbus := TModbus.Create(Port, Speed);
try
result := ReadDeviceIdentification(Adr, FIdent);
if result <> merNone then
FreeAndNil(FModbus);//.Free;
except
FreeAndNil(FModbus);//.Free;
end;
end;
function TCommonModbusDevice.Open(Host: string; Port: integer; Adr: integer): TModbusError;
begin
FIdent.Company := '';
FIdent.Product := '';
FIdent.Version := '';
try
FModbus := TModbus.Create(Host, Port);
Result := ReadDeviceIdentification(Adr, FIdent);
if result <> merNone then
FModbus.Destroy;
except
FModbus := nil;
end;
end;
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmTabs3x
Purpose : Rewrite of the original Delphi Win3x tab with future enhancements
(Win2k)
Date : 05-15-1999
Author : Ryan J. Mills
Version : 1.92
================================================================================}
unit rmTabs3x;
interface
{$I CompilerDefines.INC}
uses Windows, Classes, Graphics, Forms, Controls, Messages;
type
TScrollBtn = (sbLeft, sbRight);
TTabType = (ttWin3x, ttWin2k);
TrmScroller = class(TCustomControl)
private
{ property usage }
FMin: Longint;
FMax: Longint;
FPosition: Longint;
FOnClick: TNotifyEvent;
FChange: Integer;
{ private usage }
Bitmap: TBitmap;
Pressed: Boolean;
Down: Boolean;
Current: TScrollBtn;
pWidth: Integer;
pHeight: Integer;
{ property access methods }
procedure SetMin(Value: Longint);
procedure SetMax(Value: Longint);
procedure SetPosition(Value: Longint);
{ private methods }
function CanScrollLeft: Boolean;
function CanScrollRight: Boolean;
procedure DoMouseDown(X: Integer);
procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;
procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message WM_LBUTTONDBLCLK;
procedure WMMouseMove(var Message: TWMMouseMove); message WM_MOUSEMOVE;
procedure WMLButtonUp(var Message: TWMLButtonUp); message WM_LBUTTONUP;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Paint; override;
published
property OnClick: TNotifyEvent read FOnClick write FOnClick;
property Min: Longint read FMin write SetMin default 0;
property Max: Longint read FMax write SetMax default 0;
property Position: Longint read FPosition write SetPosition default 0;
property Change: Integer read FChange write FChange default 1;
end;
TrmTabSet = class;
TrmTabList = class(TStringList)
private
Tabs: TrmTabSet;
public
procedure Insert(Index: Integer; const S: string); override;
procedure Delete(Index: Integer); override;
function Add(const S: string): Integer; override;
procedure Put(Index: Integer; const S: string); override;
procedure Clear; override;
procedure AddStrings(Strings: TStrings); override;
end;
{ eash TEdgeType is made up of one or two of these parts }
TEdgePart = (epSelectedLeft, epUnselectedLeft, epSelectedRight,
epUnselectedRight);
{ represents the intersection between two tabs, or the edge of a tab }
TEdgeType = (etNone, etFirstIsSel, etFirstNotSel, etLastIsSel, etLastNotSel,
etNotSelToSel, etSelToNotSel, etNotSelToNotSel);
TTabStyle = (tsStandard, tsOwnerDraw);
TMeasureTabEvent = procedure(Sender: TObject; Index: Integer; var TabWidth: Integer) of object;
TDrawTabEvent = procedure(Sender: TObject; TabCanvas: TCanvas; R: TRect; Index: Integer; Selected: Boolean) of object;
TTabChangeEvent = procedure(Sender: TObject; NewTab: Integer; var AllowChange: Boolean) of object;
TrmTabSet = class(TCustomControl)
private
{ property instance variables }
FStartMargin: Integer;
FEndMargin: Integer;
FTabs: TStrings;
FTabIndex: Integer;
FFirstIndex: Integer;
FVisibleTabs: Integer;
FSelectedColor: TColor;
FUnselectedColor: TColor;
FBackgroundColor: TColor;
FDitherBackground: Boolean;
FAutoScroll: Boolean;
FStyle: TTabStyle;
FOwnerDrawHeight: Integer;
FOnMeasureTab: TMeasureTabEvent;
FOnDrawTab: TDrawTabEvent;
FOnChange: TTabChangeEvent;
FTabType: TTabType;
{ private instance variables }
TabPositions: TList;
FTabHeight: Integer;
{ FTopEdge, FBottomEdge: integer;}
FScroller: TrmScroller;
FDoFix: Boolean;
FDisabledTabs: TStrings;
fEdgeWidth: integer;
{ property access methods }
procedure SetSelectedColor(Value: TColor);
procedure SetUnselectedColor(Value: TColor);
procedure SetBackgroundColor(Value: TColor);
procedure SetDitherBackground(Value: Boolean);
procedure SetAutoScroll(Value: Boolean);
procedure SetStartMargin(Value: Integer);
procedure SetEndMargin(Value: Integer);
procedure SetTabIndex(Value: Integer);
procedure SetFirstIndex(Value: Integer);
procedure SetTabList(Value: TStrings);
procedure SetTabStyle(Value: TTabStyle);
procedure SetTabHeight(Value: Integer);
procedure SetTabType(const Value: TTabType);
procedure SetDisabledTabList(const Value: TStrings);
{ private methods }
procedure WMSize(var Message: TWMSize); message WM_SIZE;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure PaintEdge(Canvas: TCanvas; X, Y, H: Integer; Edge: TEdgeType);
procedure CreateBrushPattern(Bitmap: TBitmap);
function Calc3xTabPositions(Start, Stop: Integer; Canvas: TCanvas; First: Integer): Integer;
function Calc2kTabPositions(Start, Stop: Integer; Canvas: TCanvas; First: Integer): Integer;
procedure CreateScroller;
procedure FixTabPos;
procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE;
procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR;
procedure ScrollClick(Sender: TObject);
procedure ReadIntData(Reader: TReader);
procedure ReadBoolData(Reader: TReader);
procedure SetEdgeWidth(const Value: integer);
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure Paint; override;
procedure DrawTab(TabCanvas: TCanvas; R: TRect; Index: Integer; Selected: Boolean); virtual;
function CanChange(NewIndex: Integer): Boolean;
procedure MeasureTab(Index: Integer; var TabWidth: Integer); virtual;
procedure DefineProperties(Filer: TFiler); override;
procedure Paint2k;
procedure Paint3x;
function TabEnabled(index:integer):boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function ItemAtPos(Pos: TPoint): Integer;
function ItemRect(Item: Integer): TRect;
procedure SelectNext(Direction: Boolean);
procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
property Canvas;
property FirstIndex: Integer read FFirstIndex write SetFirstIndex default 0;
published
property Align;
property Anchors;
property AutoScroll: Boolean read FAutoScroll write SetAutoScroll default True;
property BackgroundColor: TColor read FBackgroundColor write SetBackgroundColor default clBtnFace;
property Constraints;
property DitherBackground: Boolean read FDitherBackground write SetDitherBackground default True;
property DragCursor;
property DragKind;
property DragMode;
property EdgeWidth : integer read fEdgeWidth write SetEdgeWidth default 9; //This controls the angle of the tab edges
property Enabled;
property DisabledTabs: TStrings read FDisabledTabs write SetDisabledTabList;
property EndMargin: Integer read FEndMargin write SetEndMargin default 5;
property Font;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property StartMargin: Integer read FStartMargin write SetStartMargin default 5;
property SelectedColor: TColor read FSelectedColor write SetSelectedColor default clBtnFace;
property Style: TTabStyle read FStyle write SetTabStyle default tsStandard;
property TabHeight: Integer read FOwnerDrawHeight write SetTabHeight default 20;
property Tabs: TStrings read FTabs write SetTabList;
property TabIndex: Integer read FTabIndex write SetTabIndex default -1;
property TabType: TTabType read fTabType write SetTabType default ttWin3x;
property UnselectedColor: TColor read FUnselectedColor write SetUnselectedColor default clWindow;
property Visible;
property VisibleTabs: Integer read FVisibleTabs;
property OnClick;
property OnChange: TTabChangeEvent read FOnChange write FOnChange;
property OnDragDrop;
property OnDragOver;
property OnDrawTab: TDrawTabEvent read FOnDrawTab write FOnDrawTab;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMeasureTab: TMeasureTabEvent read FOnMeasureTab write FOnMeasureTab;
property OnStartDock;
property OnStartDrag;
end;
implementation
uses Consts, SysUtils, rmLibrary;
{$R rmTabs3x.RES}
type
TTabPos = record
Size, StartPos: Word;
end;
{ TrmScroller }
constructor TrmScroller.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csOpaque];
Bitmap := TBitmap.Create;
pWidth := 24;
pHeight := 13;
FMin := 0;
FMax := 0;
FPosition := 0;
FChange := 1;
end;
destructor TrmScroller.Destroy;
begin
Bitmap.Free;
inherited Destroy;
end;
procedure TrmScroller.Paint;
begin
with Canvas do
begin
{ paint left button }
if CanScrollLeft then
begin
if Down and (Current = sbLeft) then
Bitmap.Handle := LoadBitmap(HInstance, 'RMSBLEFTDN')
else
Bitmap.Handle := LoadBitmap(HInstance, 'RMSBLEFT');
end
else
Bitmap.Handle := LoadBitmap(HInstance, 'RMSBLEFTDIS');
Draw(0, 0, Bitmap);
{ paint right button }
if CanScrollRight then
begin
if Down and (Current = sbRight) then
Bitmap.Handle := LoadBitmap(HInstance, 'RMSBRIGHTDN')
else
Bitmap.Handle := LoadBitmap(HInstance, 'RMSBRIGHT');
end
else
Bitmap.Handle := LoadBitmap(HInstance, 'RMSBRIGHTDIS');
Draw((pWidth div 2) - 1, 0, Bitmap);
end;
end;
procedure TrmScroller.WMSize(var Message: TWMSize);
begin
inherited;
Width := pWidth - 1;
Height := pHeight;
end;
procedure TrmScroller.SetMin(Value: Longint);
begin
if Value < FMax then FMin := Value;
end;
procedure TrmScroller.SetMax(Value: Longint);
begin
if Value > FMin then FMax := Value;
end;
procedure TrmScroller.SetPosition(Value: Longint);
begin
if Value <> FPosition then
begin
if Value < Min then Value := Min;
if Value > Max then Value := Max;
FPosition := Value;
Invalidate;
if Assigned(FOnClick) then
FOnClick(Self);
end;
end;
function TrmScroller.CanScrollLeft: Boolean;
begin
Result := Position > Min;
end;
function TrmScroller.CanScrollRight: Boolean;
begin
Result := Position < Max;
end;
procedure TrmScroller.DoMouseDown(X: Integer);
begin
if X < pWidth div 2 then
Current := sbLeft
else
Current := sbRight;
case Current of
sbLeft:
if not CanScrollLeft then Exit;
sbRight:
if not CanScrollRight then Exit;
end;
Pressed := True;
Down := True;
Invalidate;
SetCapture(Handle);
end;
procedure TrmScroller.WMLButtonDown(var Message: TWMLButtonDown);
begin
DoMouseDown(Message.XPos);
end;
procedure TrmScroller.WMLButtonDblClk(var Message: TWMLButtonDblClk);
begin
DoMouseDown(Message.XPos);
end;
procedure TrmScroller.WMMouseMove(var Message: TWMMouseMove);
var
P: TPoint;
R: TRect;
begin
if Pressed then
begin
P := Point(Message.XPos, Message.YPos);
R := Rect(0, 0, pWidth div 2, pHeight);
if Current = sbRight then OffsetRect(R, pWidth div 2, 0);
if PtInRect(R, P) <> Down then
begin
Down := not Down;
Invalidate;
end;
end;
end;
procedure TrmScroller.WMLButtonUp(var Message: TWMLButtonUp);
var
NewPos: Longint;
begin
ReleaseCapture;
Pressed := False;
if Down then
begin
Down := False;
NewPos := Position;
case Current of
sbLeft: Dec(NewPos, Change);
sbRight: Inc(NewPos, Change);
end;
Position := NewPos;
end;
end;
{ TrmTabList }
function TrmTabList.Add(const S: string): Integer;
begin
Result := inherited Add(S);
if Tabs <> nil then
Tabs.Invalidate;
end;
procedure TrmTabList.Insert(Index: Integer; const S: string);
begin
inherited Insert(Index, S);
if Tabs <> nil then
begin
if Index <= Tabs.FTabIndex then Inc(Tabs.FTabIndex);
Tabs.Invalidate;
end;
end;
procedure TrmTabList.Delete(Index: Integer);
var
OldIndex: Integer;
begin
OldIndex := Tabs.Tabindex;
inherited Delete(Index);
if OldIndex < Count then
Tabs.FTabIndex := OldIndex
else
Tabs.FTabIndex := Count - 1;
Tabs.Invalidate;
Tabs.Invalidate;
if OldIndex = Index then Tabs.Click; { deleted selected tab }
end;
procedure TrmTabList.Put(Index: Integer; const S: string);
begin
inherited Put(Index, S);
if Tabs <> nil then
Tabs.Invalidate;
end;
procedure TrmTabList.Clear;
begin
inherited Clear;
Tabs.FTabIndex := -1;
Tabs.Invalidate;
end;
procedure TrmTabList.AddStrings(Strings: TStrings);
begin
SendMessage(Tabs.Handle, WM_SETREDRAW, 0, 0);
inherited AddStrings(Strings);
SendMessage(Tabs.Handle, WM_SETREDRAW, 1, 0);
Tabs.Invalidate;
end;
{ TrmTabSet }
constructor TrmTabSet.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := [csCaptureMouse, csDoubleClicks, csOpaque];
fEdgeWidth := 9;
Width := 185;
Height := 21;
TabPositions := TList.Create;
fTabHeight := 20;
FTabs := TrmTabList.Create;
TrmTabList(FTabs).Tabs := Self;
FDisabledTabs := TStringList.create;
CreateScroller;
FTabIndex := -1;
FFirstIndex := 0;
FVisibleTabs := 0; { set by draw routine }
FStartMargin := 5;
FEndMargin := 5;
{ initialize default values }
FSelectedColor := clBtnFace;
FUnselectedColor := clWindow;
FBackgroundColor := clBtnFace;
FDitherBackground := True;
fTabType := ttWin3x;
FAutoScroll := True;
FStyle := tsStandard;
FOwnerDrawHeight := 20;
ParentFont := False;
Font.Name := String(DefFontData.Name);
Font.Height := DefFontData.Height;
Font.Style := [];
{ create the edge bitmaps }
end;
procedure TrmTabSet.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
with Params.WindowClass do
style := style and not (CS_VREDRAW or CS_HREDRAW);
end;
procedure TrmTabSet.CreateScroller;
begin
FScroller := TrmScroller.Create(Self);
with FScroller do
begin
Parent := Self;
Top := 3;
Min := 0;
Max := 0;
Position := 0;
Visible := False;
OnClick := ScrollClick;
end;
end;
destructor TrmTabSet.Destroy;
begin
FTabs.Free;
TabPositions.Free;
inherited Destroy;
end;
procedure TrmTabSet.ScrollClick(Sender: TObject);
begin
FirstIndex := TrmScroller(Sender).Position;
end;
{ cache the tab position data, and return number of visible tabs }
function TrmTabSet.Calc3xTabPositions(Start, Stop: Integer; Canvas: TCanvas;
First: Integer): Integer;
var
Index: Integer;
TabPos: TTabPos;
W: Integer;
begin
TabPositions.Count := 0; { erase all previously cached data }
Index := First;
while (Start < Stop) and (Index < Tabs.Count) do
begin
with Canvas do
begin
TabPos.StartPos := Start;
W := TextWidth(Tabs[Index]);
{ Owner }
if (FStyle = tsOwnerDraw) then MeasureTab(Index, W);
TabPos.Size := W;
Inc(Start, TabPos.Size + EdgeWidth); { next usable position }
if Start <= Stop then
begin
TabPositions.Add(Pointer(TabPos)); { add to list }
Inc(Index);
end;
end;
end;
Result := Index - First;
end;
function TrmTabSet.ItemAtPos(Pos: TPoint): Integer;
var
TabPos: TTabPos;
I: Integer;
begin
Result := -1;
if (Pos.Y < 0) or (Pos.Y > ClientHeight) then Exit;
for I := 0 to TabPositions.Count - 1 do
begin
Pointer(TabPos) := TabPositions[I];
if (Pos.X >= TabPos.StartPos) and (Pos.X <= TabPos.StartPos + TabPos.Size) then
begin
Result := I;
Exit;
end;
end;
end;
function TrmTabSet.ItemRect(Item: Integer): TRect;
var
TabPos: TTabPos;
wYPos : integer;
begin
wyPos := 0;
if align = altop then
wypos := clientheight - fTabHeight;
if (TabPositions.Count > 0) and (Item >= 0) and (Item < TabPositions.Count) then
begin
Pointer(TabPos) := TabPositions[Item];
Result := Rect(TabPos.StartPos, wYPos, TabPos.StartPos + TabPos.Size, wYPos+FTabHeight);
InflateRect(Result, 1, -2);
end
else
Result := Rect(0, 0, 0, 0);
end;
procedure TrmTabSet.Paint;
begin
case ftabtype of
ttWin3x: Paint3x;
ttWin2k: Paint2k;
end;
end;
procedure TrmTabSet.Paint3x;
var
MemBitmap, BrushBitmap: TBitmap;
TabStart, LastTabPos: Integer;
TabPos: TTabPos;
Tab: Integer;
Leading: TEdgeType;
Trailing: TEdgeType;
isFirst, isLast, isSelected, isPrevSelected: Boolean;
R: TRect;
wYPos : integer;
begin
if not HandleAllocated then Exit;
MemBitmap := TBitmap.create;
try
{ Set the size of the off-screen bitmap. Make sure that it is tall enough to
display the entire tab, even if the screen won't display it all. This is
required to avoid problems with using FloodFill. }
MemBitmap.Width := ClientWidth;
if ClientHeight < FTabHeight + 5 then
MemBitmap.Height := FTabHeight + 5
else
MemBitmap.Height := ClientHeight;
wyPos := 0;
if align = altop then
wypos := clientheight - fTabHeight;
MemBitmap.Canvas.Font := Self.Canvas.Font;
TabStart := StartMargin + EdgeWidth; { where does first text appear? }
LastTabPos := Width - EndMargin; { tabs draw until this position }
FScroller.Left := Width - FScroller.Width - 2;
{ do initial calculations for how many tabs are visible }
FVisibleTabs := Calc3xTabPositions(TabStart, LastTabPos, MemBitmap.Canvas,
FirstIndex);
{ enable the scroller if FAutoScroll = True and not all tabs are visible }
if AutoScroll and (FVisibleTabs < Tabs.Count) then
begin
Dec(LastTabPos, FScroller.Width - 4);
{ recalc the tab positions }
FVisibleTabs := Calc3xTabPositions(TabStart, LastTabPos, MemBitmap.Canvas,
FirstIndex);
{ set the scroller's range }
FScroller.Visible := True;
ShowWindow(FScroller.Handle, SW_SHOW);
FScroller.Min := 0;
FScroller.Max := Tabs.Count - VisibleTabs;
FScroller.Position := FirstIndex;
end
else if VisibleTabs >= Tabs.Count then
begin
FScroller.Visible := False;
ShowWindow(FScroller.Handle, SW_HIDE);
end;
if FDoFix then
begin
FixTabPos;
FVisibleTabs := Calc3xTabPositions(TabStart, LastTabPos, MemBitmap.Canvas,
FirstIndex);
end;
FDoFix := False;
{ draw background of tab area }
with MemBitmap.Canvas do
begin
BrushBitmap := TBitmap.create;
try
CreateBrushPattern(BrushBitmap);
Brush.Bitmap := BrushBitmap;
FillRect(Rect(0, 0, MemBitmap.Width, MemBitmap.Height));
Pen.Width := 1;
if align <> alTop then
begin
Pen.Color := clBtnShadow;
MoveTo(0, 0);
LineTo(MemBitmap.Width + 1, 0);
Pen.Color := clWindowFrame;
MoveTo(0, 1);
LineTo(MemBitmap.Width + 1, 1);
end
else
begin
Pen.Color := clBtnHighlight;
MoveTo(0, height-1);
LineTo(MemBitmap.Width + 1, height-1);
Pen.Color := cl3DLight;
MoveTo(0, height);
LineTo(MemBitmap.Width + 1, height);
end
finally
BrushBitmap.free;
end;
end;
for Tab := 0 to TabPositions.Count - 1 do
begin
Pointer(TabPos) := TabPositions[Tab];
isFirst := Tab = 0;
isLast := Tab = VisibleTabs - 1;
isSelected := Tab + FirstIndex = TabIndex;
isPrevSelected := (Tab + FirstIndex) - 1 = TabIndex;
{ Rule: every tab paints its leading edge, only the last tab paints a
trailing edge }
Trailing := etNone;
if isLast then
begin
if isSelected then
Trailing := etLastIsSel
else
Trailing := etLastNotSel;
end;
if isFirst then
begin
if isSelected then
Leading := etFirstIsSel
else
Leading := etFirstNotSel;
end
else { not first }
begin
if isPrevSelected then
Leading := etSelToNotSel
else if isSelected then
Leading := etNotSelToSel
else
Leading := etNotSelToNotSel;
end;
{ draw leading edge }
if Leading <> etNone then
PaintEdge(MemBitmap.Canvas, TabPos.StartPos - EdgeWidth, wypos, FTabHeight - 1, Leading);
{ set up the canvas }
R := Rect(TabPos.StartPos, wypos, TabPos.StartPos + TabPos.Size, wypos+FTabHeight);
with MemBitmap.Canvas do
begin
if isSelected then
Brush.Color := SelectedColor
else
Brush.Color := UnselectedColor;
ExtTextOut(Handle, TabPos.StartPos, wypos, ETO_OPAQUE, @R,
nil, 0, nil);
end;
{ restore font for drawing the text }
MemBitmap.Canvas.Font := Self.Canvas.Font;
{ Owner }
if (FStyle = tsOwnerDraw) then
DrawTab(MemBitmap.Canvas, R, Tab + FirstIndex, isSelected)
else
begin
with MemBitmap.Canvas do
begin
Inc(R.Top, 2);
if TabEnabled(Tab + FirstIndex) then
Font.Color := clWindowText
else
Font.Color := clGrayText;
DrawText(Handle, PChar(Tabs[Tab + FirstIndex]),
Length(Tabs[Tab + FirstIndex]), R, DT_CENTER);
end;
end;
{ draw trailing edge }
if Trailing <> etNone then
PaintEdge(MemBitmap.Canvas, TabPos.StartPos + TabPos.Size, wypos, FTabHeight - 1, Trailing);
{ draw connecting lines above and below the text }
with MemBitmap.Canvas do
begin
Pen.Color := clWindowFrame;
if align<>alTop then
begin
MoveTo(TabPos.StartPos, FTabHeight-1);
LineTo(TabPos.StartPos + TabPos.Size, FTabHeight-1);
if isSelected then
begin
Pen.Color := clBtnShadow;
MoveTo(TabPos.StartPos, FTabHeight - 2);
LineTo(TabPos.StartPos + TabPos.Size, FTabHeight - 2);
end
else
begin
Pen.Color := clWindowFrame;
MoveTo(TabPos.StartPos, 1);
LineTo(TabPos.StartPos + TabPos.Size, 1);
Pen.Color := clBtnShadow;
MoveTo(TabPos.StartPos, 0);
LineTo(TabPos.StartPos + TabPos.Size + 1, 0);
end;
end
else
begin
MoveTo(TabPos.StartPos, wypos);
LineTo(TabPos.StartPos + TabPos.Size, wypos);
if isSelected then
begin
Pen.Color := clBtnHighlight;
MoveTo(TabPos.StartPos, wypos+1);
LineTo(TabPos.StartPos + TabPos.Size, wypos+1);
end;
end
end;
end;
{ draw onto the screen }
Canvas.Draw(0, 0, MemBitmap);
finally
MemBitmap.free;
end;
end;
procedure TrmTabSet.Paint2k;
var
MemBitmap: TBitmap;
TabStart, LastTabPos: Integer;
TabPos: TTabPos;
Tab: Integer;
isFirst, isSelected: Boolean;
R: TRect;
loop: integer;
wYPos : integer;
begin
if not HandleAllocated then Exit;
MemBitmap := TBitmap.create;
try
{ Set the size of the off-screen bitmap. Make sure that it is tall enough to
display the entire tab, even if the screen won't display it all. This is
required to avoid problems with using FloodFill. }
MemBitmap.Width := ClientWidth;
if ClientHeight < FTabHeight + 5 then
MemBitmap.Height := FTabHeight + 5
else
MemBitmap.Height := ClientHeight;
wyPos := 0;
if align = altop then
wypos := clientheight - fTabHeight;
MemBitmap.Canvas.Font := Self.Canvas.Font;
TabStart := StartMargin + EdgeWidth; { where does first text appear? }
LastTabPos := Width - EndMargin; { tabs draw until this position }
FScroller.Left := Width - FScroller.Width - 2;
{ do initial calculations for how many tabs are visible }
FVisibleTabs := Calc2kTabPositions(TabStart, LastTabPos, MemBitmap.Canvas, FirstIndex);
{ enable the scroller if FAutoScroll = True and not all tabs are visible }
if AutoScroll and (FVisibleTabs < Tabs.Count) then
begin
Dec(LastTabPos, FScroller.Width - 4);
{ recalc the tab positions }
FVisibleTabs := Calc2kTabPositions(TabStart, LastTabPos, MemBitmap.Canvas, FirstIndex);
{ set the scroller's range }
FScroller.Visible := True;
ShowWindow(FScroller.Handle, SW_SHOW);
FScroller.Min := 0;
FScroller.Max := Tabs.Count - VisibleTabs;
FScroller.Position := FirstIndex;
end
else if VisibleTabs >= Tabs.Count then
begin
FScroller.Visible := False;
ShowWindow(FScroller.Handle, SW_HIDE);
end;
if FDoFix then
begin
FixTabPos;
FVisibleTabs := Calc2kTabPositions(TabStart, LastTabPos, MemBitmap.Canvas, FirstIndex);
end;
FDoFix := False;
{ draw background of tab area }
with MemBitmap.Canvas do
begin
Brush.Color := clBtnShadow;
FillRect(Rect(0, 0, MemBitmap.Width, MemBitmap.Height));
if align<>altop then
begin
Pen.Color := clbtnFace;
for loop := 0 to 1 do
begin
MoveTo(0, loop);
LineTo(MemBitmap.Width + 1, loop);
end;
Pen.Color := clWindowFrame;
MoveTo(0, 2);
LineTo(MemBitmap.Width + 1, 2);
end
else
begin
Pen.Color := clbtnFace;
for loop := clientheight-2 to clientheight do
begin
MoveTo(0, loop);
LineTo(MemBitmap.Width + 1, loop);
end;
Pen.Color := clBtnHighlight;
MoveTo(0, clientHeight-3);
LineTo(MemBitmap.Width + 1, clientheight-3);
end;
end;
for Tab := 0 to TabPositions.Count - 1 do
begin
if not TabEnabled(Tab + FirstIndex) then
continue;
Pointer(TabPos) := TabPositions[Tab];
isFirst := Tab = 0;
isSelected := Tab + FirstIndex = TabIndex;
R := Rect(TabPos.StartPos - (EdgeWidth div 2), wypos, (TabPos.StartPos + TabPos.Size) + (EdgeWidth div 2), wypos+FTabHeight);
with MemBitmap.Canvas do
begin
if isSelected then
begin
Brush.Color := clBtnFace;
FillRect(R);
Font.Color := clBtnText;
Inc(R.Top, 1);
if Align = albottom then
R := Rect(TabPos.StartPos, wypos+2, TabPos.StartPos + TabPos.Size, wypos+FTabHeight);
DrawText(Handle, PChar(Tabs[Tab + FirstIndex]), Length(Tabs[Tab + FirstIndex]), R, DT_CENTER);
Pen.Color := clBtnHighlight;
if align <> alTop then
begin
MoveTo(TabPos.StartPos - (EdgeWidth div 2), wYpos+2);
LineTo(TabPos.StartPos - (EdgeWidth div 2), wYpos+FTabHeight);
Pen.Color := cl3DDkShadow;
MoveTo(TabPos.StartPos + TabPos.Size + (EdgeWidth div 2), wYpos+2);
LineTo(TabPos.StartPos + TabPos.Size + (EdgeWidth div 2), wYpos+FTabHeight);
MoveTo(TabPos.StartPos - (EdgeWidth div 2), wYpos+FTabHeight);
LineTo(TabPos.StartPos + TabPos.Size + (EdgeWidth div 2), wYpos+FTabHeight);
Pen.Color := clBtnShadow;
MoveTo(TabPos.StartPos - (EdgeWidth div 2)+1, FTabHeight - 1);
LineTo(TabPos.StartPos + TabPos.Size + (EdgeWidth div 2)-1, FTabHeight - 1);
end
else
begin
MoveTo(TabPos.StartPos - (EdgeWidth div 2), wYpos);
LineTo(TabPos.StartPos - (EdgeWidth div 2), wYpos+FTabHeight-2);
MoveTo(TabPos.StartPos - (EdgeWidth div 2) + 1, wypos);
LineTo(TabPos.StartPos + TabPos.Size + (EdgeWidth div 2) - 1, wypos);
Pen.Color := cl3DDkShadow;
MoveTo(TabPos.StartPos + TabPos.Size + (EdgeWidth div 2), wYpos);
LineTo(TabPos.StartPos + TabPos.Size + (EdgeWidth div 2), wYpos+FTabHeight-2);
end;
end
else
begin
R := Rect(TabPos.StartPos, wypos+2, TabPos.StartPos + TabPos.Size, wypos+FTabHeight);
Brush.Style := bsClear;
if TabEnabled(Tab + FirstIndex) then
Font.Color := clBtnHighlight
else
Font.Color := cl3DDkShadow;
Inc(R.Top, 1);
if Align = alTop then
R := Rect(TabPos.StartPos, wypos, TabPos.StartPos + TabPos.Size, wypos+FTabHeight);
DrawText(Handle, PChar(Tabs[Tab + FirstIndex]), Length(Tabs[Tab + FirstIndex]), R, DT_CENTER);
if align <> altop then
begin
Pen.Color := clBtnHighlight;
if isFirst then
begin
MoveTo(TabPos.StartPos - (EdgeWidth div 2), 5);
LineTo(TabPos.StartPos - (EdgeWidth div 2), (2 + FTabHeight) - 3);
end;
MoveTo(TabPos.StartPos + TabPos.Size + (EdgeWidth div 2) + 1, 5);
LineTo(TabPos.StartPos + TabPos.Size + (EdgeWidth div 2) + 1, (2 + FTabHeight) - 3);
end
else
begin
Pen.Color := clBtnHighlight;
if isFirst then
begin
MoveTo(TabPos.StartPos - (EdgeWidth div 2), wypos);
LineTo(TabPos.StartPos - (EdgeWidth div 2), wypos + FTabHeight - 5);
end;
MoveTo(TabPos.StartPos + TabPos.Size + (EdgeWidth div 2) + 1, wypos);
LineTo(TabPos.StartPos + TabPos.Size + (EdgeWidth div 2) + 1, wypos + fTabHeight - 5);
end;
Pen.Color := clWindowFrame;
if align<>alTop then
begin
MoveTo(TabPos.StartPos, 2);
LineTo(TabPos.StartPos + TabPos.Size, 2);
end;
end;
end;
end;
{ draw onto the screen }
Canvas.Draw(0, 0, MemBitmap);
finally
MemBitmap.free;
end;
end;
procedure TrmTabSet.PaintEdge(Canvas: TCanvas; X, Y, H: Integer; Edge: TEdgeType);
procedure DrawBR(Canvas: TCanvas; X, Y, H: integer; FillColor:TColor);
begin
with Canvas do
begin
Pen.Color := FillColor;
Brush.Color := FillColor;
Polygon([ Point(X + EdgeWidth, Y),
Point(X + 1, Y + H),
Point(X, Y + H),
Point(X, Y),
Point(X + EdgeWidth, Y)]);
Pen.Color := clWindowFrame;
PolyLine([Point(X + EdgeWidth, Y), Point(X, Y + H)]);
if FillColor = SelectedColor then
begin
Pen.Color := clBtnShadow;
PolyLine([Point(X + EdgeWidth - 1, Y), Point(X - 1, Y + H)]);
end
else
begin
Pen.Color := clBtnShadow;
PolyLine([Point(X, 0), Point(X + EdgeWidth+1, 0)]);
Pen.Color := clWindowFrame;
PolyLine([Point(X, 1), Point(X + EdgeWidth+1, 1)]);
end;
end;
end;
procedure DrawBL(Canvas: TCanvas; X, Y, H: integer; FillColor:TColor);
begin
with Canvas do
begin
Pen.Color := FillColor;
Brush.Color := FillColor;
Polygon([ Point(X, Y),
Point(X + EdgeWidth - 1, Y + H),
Point(X + EdgeWidth, Y + H),
Point(X + EdgeWidth, Y),
Point(X, Y)]);
Pen.Color := clWindowFrame;
PolyLine([Point(X, Y), Point(X + EdgeWidth, Y + H)]);
if Fillcolor = SelectedColor then
begin
Pen.Color := clBtnHighlight;
PolyLine([Point(X + 1, Y), Point(X + EdgeWidth + 1, Y + H)]);
end
else
begin
Pen.Color := clBtnShadow;
PolyLine([Point(X, 0), Point(X + EdgeWidth+1, 0)]);
Pen.Color := clWindowFrame;
PolyLine([Point(X, 1), Point(X + EdgeWidth+1, 1)]);
end;
end;
end;
procedure DrawTR(Canvas: TCanvas; X, Y, H: integer; FillColor:TColor);
begin
with Canvas do
begin
Pen.Color := FillColor;
Brush.Color := FillColor;
Polygon([ Point(X + EdgeWidth, Y + H),
Point(X+1, Y),
Point(X, Y),
Point(X, Y + H),
Point(X + EdgeWidth, Y + H)]);
Pen.Color := clWindowFrame;
PolyLine([ Point(X, Y), Point(X+EdgeWidth, Y + h)]);
if FillColor = SelectedColor then
begin
Pen.Color := clBtnShadow;
PolyLine([ Point(X-1, Y), Point(X+EdgeWidth-1, Y + h)]);
end;
end;
end;
procedure DrawTL(Canvas: TCanvas; X, Y, H: integer; FillColor:TColor);
begin
with Canvas do
begin
Pen.Color := FillColor;
Brush.Color := FillColor;
Polygon([ Point(X, Y + H),
Point(X + EdgeWidth - 1, Y),
Point(X + EdgeWidth, Y),
Point(X + EdgeWidth, Y + H),
Point(X, Y + H)]);
Pen.Color := clWindowFrame;
PolyLine([ Point(X+EdgeWidth, Y), Point(X, Y + h)]);
if Fillcolor = SelectedColor then
begin
Pen.Color := clBtnHighlight;
PolyLine([Point(x+edgewidth+1,y), Point(x+1,y+h)]);
end;
end;
end;
begin
Canvas.Brush.Color := clWhite;
Canvas.Font.Color := clBlack;
case align of
alTop:
begin
case Edge of
etFirstIsSel:
DrawTL(Canvas, X, Y, H, SelectedColor);
etLastIsSel:
DrawTR(Canvas, X, Y, H, SelectedColor);
etFirstNotSel:
DrawTL(Canvas, X, Y, H, UnselectedColor);
etLastNotSel:
DrawTR(Canvas, X, Y, H, UnselectedColor);
etNotSelToSel:
begin
DrawTR(Canvas, X, Y, H, UnselectedColor);
DrawTL(Canvas, X, Y, H, SelectedColor);
end;
etSelToNotSel:
begin
DrawTL(Canvas, X, Y, H, UnselectedColor);
DrawTR(Canvas, X, Y, H, SelectedColor);
end;
etNotSelToNotSel:
begin
DrawTL(Canvas, X, Y, H, UnselectedColor);
DrawTR(Canvas, X, Y, H, UnselectedColor);
end;
end;
end;
else
begin
case Edge of
etFirstIsSel:
DrawBL(Canvas, X, Y, H, SelectedColor);
etLastIsSel:
DrawBR(Canvas, X, Y, H, SelectedColor);
etFirstNotSel:
DrawBL(Canvas, X, Y, H, UnselectedColor);
etLastNotSel:
DrawBR(Canvas, X, Y, H, UnselectedColor);
etNotSelToSel:
begin
DrawBR(Canvas, X, Y, H, UnselectedColor);
DrawBL(Canvas, X, Y, H, SelectedColor);
end;
etSelToNotSel:
begin
DrawBL(Canvas, X, Y, H, UnselectedColor);
DrawBR(Canvas, X, Y, H, SelectedColor);
end;
etNotSelToNotSel:
begin
DrawBL(Canvas, X, Y, H, UnselectedColor);
DrawBR(Canvas, X, Y, H, UnselectedColor);
end;
end;
end;
end;
end;
procedure TrmTabSet.CreateBrushPattern(Bitmap: TBitmap);
var
X, Y: Integer;
begin
Bitmap.Width := 8;
Bitmap.Height := 8;
with Bitmap.Canvas do
begin
Brush.Style := bsSolid;
Brush.Color := FBackgroundColor;
FillRect(Rect(0, 0, Width, Height));
if FDitherBackground then
for Y := 0 to 7 do
for X := 0 to 7 do
if (Y mod 2) = (X mod 2) then { toggles between even/odd pixles }
Pixels[X, Y] := clWhite; { on even/odd rows }
end;
end;
procedure TrmTabSet.FixTabPos;
var
FLastVisibleTab: Integer;
function GetRightSide: Integer;
begin
Result := Width - EndMargin;
if AutoScroll and (FVisibleTabs < Tabs.Count - 1) then
Dec(Result, FScroller.Width + 4);
end;
function ReverseCalcNumTabs(Start, Stop: Integer; Canvas: TCanvas;
Last: Integer): Integer;
var
W: Integer;
begin
if HandleAllocated then
begin
Result := Last;
while (Start >= Stop) and (Result >= 0) do
with Canvas do
begin
W := TextWidth(Tabs[Result]);
if (FStyle = tsOwnerDraw) then MeasureTab(Result, W);
Dec(Start, W + EdgeWidth); { next usable position }
if Start >= Stop then Dec(Result);
end;
if (Start < Stop) or (Result < 0) then Inc(Result);
end
else
Result := FFirstIndex;
end;
begin
if Tabs.Count > 0 then
begin
FLastVisibleTab := FFirstIndex + FVisibleTabs - 1;
if FTabIndex > FLastVisibleTab then
FFirstIndex := ReverseCalcNumTabs(GetRightSide, StartMargin + EdgeWidth,
Canvas, FTabIndex)
else if (FTabIndex >= 0) and (FTabIndex < FFirstIndex) then
FFirstIndex := FTabIndex;
end;
end;
procedure TrmTabSet.SetSelectedColor(Value: TColor);
begin
if Value <> FSelectedColor then
begin
FSelectedColor := Value;
Invalidate;
end;
end;
procedure TrmTabSet.SetUnselectedColor(Value: TColor);
begin
if Value <> FUnselectedColor then
begin
FUnselectedColor := Value;
Invalidate;
end;
end;
procedure TrmTabSet.SetBackgroundColor(Value: TColor);
begin
if Value <> FBackgroundColor then
begin
FBackgroundColor := Value;
Invalidate;
end;
end;
procedure TrmTabSet.SetDitherBackground(Value: Boolean);
begin
if Value <> FDitherBackground then
begin
FDitherBackground := Value;
Invalidate;
end;
end;
procedure TrmTabSet.SetAutoScroll(Value: Boolean);
begin
if Value <> FAutoScroll then
begin
FAutoScroll := Value;
FScroller.Visible := False;
ShowWindow(FScroller.Handle, SW_HIDE);
Invalidate;
end;
end;
procedure TrmTabSet.SetStartMargin(Value: Integer);
begin
if Value <> FStartMargin then
begin
FStartMargin := Value;
Invalidate;
end;
end;
procedure TrmTabSet.SetEndMargin(Value: Integer);
begin
if Value <> FEndMargin then
begin
FEndMargin := Value;
Invalidate;
end;
end;
function TrmTabSet.CanChange(NewIndex: Integer): Boolean;
begin
if TabEnabled(NewIndex) then
begin
Result := true;
if Assigned(FOnChange) then
FOnChange(Self, NewIndex, Result);
end
else
result := false;
end;
procedure TrmTabSet.SetTabIndex(Value: Integer);
var
newValue:integer;
found : boolean;
nCount : integer;
begin
if Value <> FTabIndex then
begin
if (Value < -1) or (Value >= Tabs.Count) then
raise Exception.Create(SInvalidTabIndex);
if (value = -1) then
begin
FTabIndex := Value;
FixTabPos;
Click;
Invalidate;
end
else
if CanChange(Value) then
begin
FTabIndex := Value;
FixTabPos;
Click;
Invalidate;
end
else
begin
found := false;
newValue := Value+1;
nCount := 0;
while (newValue <> Value) do
begin
if newValue >= fTabs.count then
newValue := 0;
if (newValue < fTabs.count) and (not TabEnabled(newValue)) then
begin
inc(newValue);
inc(nCount);
end
else
begin
found := true;
break;
end;
if nCount >= fTabs.count then
begin
found := false;
newValue := -1;
break;
end;
end;
if (found and CanChange(newValue)) or (not found) then
begin
FTabIndex := newValue;
FixTabPos;
Click;
Invalidate;
end;
end;
end;
end;
procedure TrmTabSet.SelectNext(Direction: Boolean);
var
NewIndex: Integer;
begin
if Tabs.Count > 1 then
begin
NewIndex := TabIndex;
if Direction then
Inc(NewIndex)
else
Dec(NewIndex);
if NewIndex = Tabs.Count then
NewIndex := 0
else if NewIndex < 0 then
NewIndex := Tabs.Count - 1;
SetTabIndex(NewIndex);
end;
end;
procedure TrmTabSet.SetFirstIndex(Value: Integer);
begin
if (Value >= 0) and (Value < Tabs.Count) then
begin
FFirstIndex := Value;
Invalidate;
end;
end;
procedure TrmTabSet.SetTabList(Value: TStrings);
begin
FTabs.Assign(Value);
FTabIndex := -1;
if FTabs.Count > 0 then
TabIndex := 0
else
Invalidate;
end;
procedure TrmTabSet.SetTabStyle(Value: TTabStyle);
begin
if Value <> FStyle then
begin
FStyle := Value;
Invalidate;
end;
end;
procedure TrmTabSet.SetTabHeight(Value: Integer);
var
SaveHeight: Integer;
begin
if Value <> FOwnerDrawHeight then
begin
SaveHeight := FOwnerDrawHeight;
try
FOwnerDrawHeight := Value;
FTabHeight := value;
Invalidate;
except
FOwnerDrawHeight := SaveHeight;
fTabHeight := SaveHeight;
raise;
end;
end;
end;
procedure TrmTabSet.DrawTab(TabCanvas: TCanvas; R: TRect; Index: Integer;
Selected: Boolean);
begin
if Assigned(FOnDrawTab) then
FOnDrawTab(Self, TabCanvas, R, Index, Selected);
end;
procedure TrmTabSet.GetChildren(Proc: TGetChildProc; Root: TComponent);
begin
end;
procedure TrmTabSet.MeasureTab(Index: Integer; var TabWidth: Integer);
begin
if Assigned(FOnMeasureTab) then
FOnMeasureTab(Self, Index, TabWidth);
end;
procedure TrmTabSet.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
TabPos: TTabPos;
I: Integer;
Extra: Integer;
MinLeft: Integer;
MaxRight: Integer;
begin
inherited MouseDown(Button, Shift, X, Y);
if (Button = mbLeft) and (((align<>alTop) and (Y <= FTabHeight)) or ((align=alTop) and (y >= clientheight-FTabHeight))) then
begin
if Y < FTabHeight div 2 then
Extra := EdgeWidth div 3
else
Extra := EdgeWidth div 2;
for I := 0 to TabPositions.Count - 1 do
begin
Pointer(TabPos) := TabPositions[I];
MinLeft := TabPos.StartPos - Extra;
MaxRight := TabPos.StartPos + TabPos.Size + Extra;
if (X >= MinLeft) and (X <= MaxRight) and TabEnabled(FirstIndex + I) then
begin
SetTabIndex(FirstIndex + I);
Break;
end;
end;
end;
end;
procedure TrmTabSet.WMSize(var Message: TWMSize);
var
NumVisTabs, LastTabPos: Integer;
function CalcNumTabs(Start, Stop: Integer; Canvas: TCanvas;
First: Integer): Integer;
var
W: Integer;
begin
Result := First;
while (Start < Stop) and (Result < Tabs.Count) do
with Canvas do
begin
W := TextWidth(Tabs[Result]);
if (FStyle = tsOwnerDraw) then MeasureTab(Result, W);
Inc(Start, W + EdgeWidth); { next usable position }
if Start <= Stop then Inc(Result);
end;
end;
begin
inherited;
if Tabs.Count > 1 then
begin
LastTabPos := Width - EndMargin;
NumVisTabs := CalcNumTabs(StartMargin + EdgeWidth, LastTabPos, Canvas, 0);
if (FTabIndex = Tabs.Count) or (NumVisTabs > FVisibleTabs) or
(NumVisTabs = Tabs.Count) then FirstIndex := Tabs.Count - NumVisTabs;
FDoFix := True;
end;
Invalidate;
end;
procedure TrmTabSet.CMFontChanged(var Message: TMessage);
begin
inherited;
Canvas.Font := Font;
Invalidate;
end;
procedure TrmTabSet.WMGetDlgCode(var Message: TWMGetDlgCode);
begin
Message.Result := DLGC_WANTALLKEYS;
end;
procedure TrmTabSet.CMDialogChar(var Message: TCMDialogChar);
var
I: Integer;
begin
for I := 0 to FTabs.Count - 1 do
begin
if IsAccel(Message.CharCode, FTabs[I]) then
begin
Message.Result := 1;
if FTabIndex <> I then
SetTabIndex(I);
Exit;
end;
end;
inherited;
end;
procedure TrmTabSet.DefineProperties(Filer: TFiler);
begin
{ Can be removed after version 1.0 }
if Filer is TReader then inherited DefineProperties(Filer);
Filer.DefineProperty('TabOrder', ReadIntData, nil, False);
Filer.DefineProperty('TabStop', ReadBoolData, nil, False);
end;
procedure TrmTabSet.ReadIntData(Reader: TReader);
begin
Reader.ReadInteger;
end;
procedure TrmTabSet.ReadBoolData(Reader: TReader);
begin
Reader.ReadBoolean;
end;
procedure TrmTabSet.SetTabType(const Value: TTabType);
begin
fTabType := Value;
Invalidate;
end;
procedure TrmTabSet.SetDisabledTabList(const Value: TStrings);
begin
FDisabledTabs.Assign(Value);
Invalidate;
end;
function TrmTabSet.TabEnabled(index: integer): boolean;
begin
result := FDisabledTabs.IndexOf(fTabs[index]) = -1;
end;
function TrmTabSet.Calc2kTabPositions(Start, Stop: Integer;
Canvas: TCanvas; First: Integer): Integer;
var
Index: Integer;
TabPos: TTabPos;
W: Integer;
begin
TabPositions.Count := 0; { erase all previously cached data }
Index := First;
while (Start < Stop) and (Index < Tabs.Count) do
begin
with Canvas do
begin
if TabEnabled(index) then
begin
TabPos.StartPos := Start;
W := TextWidth(Tabs[Index]);
{ Owner }
if (FStyle = tsOwnerDraw) then MeasureTab(Index, W);
TabPos.Size := W;
Inc(Start, TabPos.Size + EdgeWidth); { next usable position }
end;
if Start <= Stop then
begin
TabPositions.Add(Pointer(TabPos)); { add to list }
Inc(Index);
end;
end;
end;
Result := Index - First;
end;
procedure TrmTabSet.SetEdgeWidth(const Value: integer);
begin
fEdgeWidth := Value;
Invalidate;
end;
end.
|
unit ufrmDialogCustomerVoucher;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls, StdCtrls,
System.Actions, Vcl.ActnList, ufraFooterDialog3Button;
type
TFormMode = (fmAdd, fmEdit);
TfrmDialogCostumerVoucher = class(TfrmMasterDialog)
lbl1: TLabel;
lbl2: TLabel;
lbl3: TLabel;
lbl4: TLabel;
edtName: TEdit;
edtContact: TEdit;
edtAddress: TEdit;
edtPhone: TEdit;
Label1: TLabel;
edtCode: TEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure footerDialogMasterbtnSaveClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtCodeKeyPress(Sender: TObject; var Key: Char);
procedure edtNameKeyPress(Sender: TObject; var Key: Char);
procedure edtContactKeyPress(Sender: TObject; var Key: Char);
procedure edtPhoneKeyPress(Sender: TObject; var Key: Char);
procedure edtAddressKeyPress(Sender: TObject; var Key: Char);
private
FFormMode: TFormMode;
FIsProcessSuccessfull: boolean;
FDataCustomerId: Integer;
procedure SetFormMode(const Value: TFormMode);
procedure SetIsProcessSuccessfull(const Value: boolean);
procedure SetDataCustomerId(const Value: Integer);
procedure showDataEdit(aId: Integer);
procedure prepareAddData;
function SaveData: boolean;
function UpdateData: boolean;
public
function cekkode(aKode :string; aUntId : integer): Boolean;
{ Public declarations }
published
property FormMode: TFormMode read FFormMode write SetFormMode;
property IsProcessSuccessfull: boolean read FIsProcessSuccessfull write SetIsProcessSuccessfull;
property DataCustomerId: Integer read FDataCustomerId write SetDataCustomerId;
end;
var
frmDialogCostumerVoucher: TfrmDialogCostumerVoucher;
implementation
uses
uTSCommonDlg;
{$R *.dfm}
function TfrmDialogCostumerVoucher.cekkode(aKode :string; aUntId : integer):
Boolean;
var
ssql : string;
begin
Result := False;
ssql:= ' select * from Customer_Voucher where '
+ ' upper(CUSTV_CODE) = upper(' + QuotedStr(aKode) + ')'
+ ' And CUSTV_UNT_ID = ' + IntToStr(aUntId);
// with cOpenQuery(ssql) do
// begin
// if not Eof then
// Result := True;
// end;
end;
procedure TfrmDialogCostumerVoucher.SetFormMode(const Value: TFormMode);
begin
FFormMode := Value;
end;
procedure TfrmDialogCostumerVoucher.SetIsProcessSuccessfull(
const Value: boolean);
begin
FIsProcessSuccessfull := Value;
end;
procedure TfrmDialogCostumerVoucher.SetDataCustomerId(const Value: Integer);
begin
FDataCustomerId:=Value;
end;
procedure TfrmDialogCostumerVoucher.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TfrmDialogCostumerVoucher.FormDestroy(Sender: TObject);
begin
inherited;
frmDialogCostumerVoucher := nil;
end;
procedure TfrmDialogCostumerVoucher.showDataEdit(aId: Integer);
begin
// with TCustomerVoucher.Create(self) do
// try
// if not LoadByID(aId,DialogUnit) then
// begin
// CommonDlg.ShowError('Data tdk ditemukan...');
// Exit;
// end;
// edtCode.Text:= CODE;
// edtName.Text:= NAME;
// edtAddress.Text:= ADDRESS;
// edtPhone.Text:= TELP;
// edtContact.Text:=CONTACT_PERSON;
// finally
// Free;
// end;
end;
procedure TfrmDialogCostumerVoucher.prepareAddData;
begin
edtCode.Clear;
edtName.Clear;
edtContact.Clear;
edtAddress.Clear;
edtPhone.Clear;
end;
procedure TfrmDialogCostumerVoucher.FormShow(Sender: TObject);
begin
inherited;
if (FFormMode = fmEdit) then
showDataEdit(FDataCustomerId)
else
prepareAddData();
edtCode.SetFocus;
end;
function TfrmDialogCostumerVoucher.SaveData: boolean;
begin
// with TCustomerVoucher.CreateWithUser(self,FLoginId) do
// try
// UpdateData(edtAddress.Text,edtCode.Text,edtContact.Text,0,0,edtName.Text,
// DialogUnit,edtPhone.Text);
// if SaveToDB then
// begin
// cCommitTrans;
// CommonDlg.ShowConfirmGlobal('Simpan sukses...');
// Result:=True;
// end
// else
// begin
// cRollbackTrans;
// CommonDlg.ShowError('Error Simpan...');
// Result:=False;
// end;
// finally
// Free;
// end;
end;
function TfrmDialogCostumerVoucher.UpdateData: boolean;
begin
// with TCustomerVoucher.CreateWithUser(self,FLoginId) do
// try
// if not LoadByID(DataCustomerId,DialogUnit) then
// begin
// CommonDlg.ShowError('Data tdk ditemukan...');
// Result:=False;
// Exit;
// end;
//
// UpdateData(edtAddress.Text,edtCode.Text,edtContact.Text,0,DataCustomerId,edtName.Text,
// DialogUnit,edtPhone.Text);
//
// if SaveToDB then
// begin
// cCommitTrans;
// CommonDlg.ShowConfirmGlobal('Simpan sukses...');
// Result:=True;
// end
// else
// begin
// cRollbackTrans;
// CommonDlg.ShowError('Error Simpan...');
// Result:=False;
// end;
// finally
// Free;
// end;
end;
procedure TfrmDialogCostumerVoucher.footerDialogMasterbtnSaveClick(
Sender: TObject);
begin
inherited;
if edtCode.Text='' then
begin
CommonDlg.ShowErrorEmpty('Code Voucher');
edtCode.SetFocus;
Exit;
end;
if cekkode(edtCode.Text,DialogUnit) then
begin
CommonDlg.ShowError('Code Voucher Sudah di pakai ');
edtCode.SetFocus;
Exit;
end;
if edtName.Text='' then
begin
CommonDlg.ShowErrorEmpty('Customer Name' );
edtName.SetFocus;
Exit;
end;
if (FormMode = fmAdd) then
begin
FIsProcessSuccessfull := SaveData;
if FIsProcessSuccessfull then
Close;
end
else
begin
FIsProcessSuccessfull := UpdateData;
if FIsProcessSuccessfull then
Close;
end; // end if
end;
procedure TfrmDialogCostumerVoucher.FormKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if (Key = VK_RETURN) and (ssCtrl in Shift) then
footerDialogMasterbtnSaveClick(Sender);
end;
procedure TfrmDialogCostumerVoucher.edtCodeKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
Key := UpCase(Key);
if Key = Chr(VK_Return) then
edtName.SetFocus;
end;
procedure TfrmDialogCostumerVoucher.edtNameKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key = Chr(VK_Return) then
edtContact.SetFocus;
end;
procedure TfrmDialogCostumerVoucher.edtContactKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key = Chr(VK_Return) then
edtPhone.SetFocus;
end;
procedure TfrmDialogCostumerVoucher.edtPhoneKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key = Chr(VK_Return) then
edtAddress.SetFocus;
end;
procedure TfrmDialogCostumerVoucher.edtAddressKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key = Chr(VK_Return) then
footerDialogMaster.btnSave.SetFocus;
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.IDE.EditorView;
interface
uses
ToolsAPI,
DesignIntf,
VCL.Forms,
Spring.Container,
DPM.IDE.ProjectTreeManager,
DPM.IDE.EditorViewFrame;
type
IDPMEditorView = interface
['{1DF76A55-76AC-4789-A35A-CA025583356A}']
procedure ProjectChanged;
procedure ProjectClosed(const projectName : string);
procedure ProjectLoaded(const projectName : string);
procedure ThemeChanged;
// procedure FilterToProject(const projectGroup : IOTAProjectGroup; const project : IOTAProject);
end;
TDPMEditorView = class(TInterfacedObject, INTACustomEditorView, INTACustomEditorView150, IDPMEditorView)
private
FContainer : TContainer;
FProject : IOTAProject;
FProjectGroup : IOTAProjectGroup;
FFrame : TDPMEditViewFrame;
FImageIndex : integer;
FCaption : string;
FProjectTreeManager : IDPMProjectTreeManager;
FIdentifier : string;
protected
//IDPMEditorView
procedure ProjectChanged;
procedure ThemeChanged;
procedure ProjectClosed(const projectName : string);
procedure ProjectLoaded(const projectName : string);
// procedure FilterToProject(const projectGroup : IOTAProjectGroup; const project : IOTAProject);
function CloneEditorView : INTACustomEditorView;
procedure CloseAllCalled(var ShouldClose : Boolean);
procedure DeselectView;
function EditAction(Action : TEditAction) : Boolean;
procedure FrameCreated(AFrame : TCustomFrame);
function GetCanCloneView : Boolean;
function GetCaption : string;
function GetEditState : TEditState;
function GetEditorWindowCaption : string;
function GetFrameClass : TCustomFrameClass;
function GetViewIdentifier : string;
procedure SelectView;
//INTACustomEditorView150
function GetImageIndex : Integer;
function GetTabHintText : string;
procedure Close(var Allowed : Boolean);
public
constructor Create(const container : TContainer; const projectGroup : IOTAProjectGroup; const project : IOTAProject; const imageIndex : integer; const projectTreeManager : IDPMProjectTreeManager);
destructor Destroy;override;
end;
implementation
uses
System.SysUtils,
DPM.Core.Utils.System;
{ TDPMEditorView }
function TDPMEditorView.CloneEditorView : INTACustomEditorView;
begin
result := nil;
end;
procedure TDPMEditorView.Close(var Allowed : Boolean);
begin
Allowed := FFrame.CanCloseView;
if Allowed then
begin
FFrame.Closing;
FFrame := nil;
end;
end;
procedure TDPMEditorView.CloseAllCalled(var ShouldClose : Boolean);
begin
//doesn't seem to get called???
ShouldClose := FFrame.CanCloseView;
if ShouldClose then
begin
FFrame.Closing;
FFrame := nil;
end;
end;
constructor TDPMEditorView.Create(const container : TContainer; const projectGroup : IOTAProjectGroup; const project : IOTAProject; const imageIndex : integer; const projectTreeManager : IDPMProjectTreeManager);
begin
FContainer := container;
FProjectGroup := projectGroup;
FProject := project; //can be nil
FImageIndex := imageIndex;
FProjectTreeManager := projectTreeManager;
FCaption := 'DPM';
Assert(FProjectGroup <> nil);
// if FProjectGroup <> nil then
// FIdentifier := 'DPM_GROUP_VIEW_' + ChangeFileExt(ExtractFileName(FProjectGroup.FileName), '')
// else
// FIdentifier := 'DPM_VIEW_' + ChangeFileExt(ExtractFileName(FProject.FileName), '');
// FIdentifier := StringReplace(FIdentifier, '.', '_', [rfReplaceAll]);
FIdentifier := 'DPM_EDITOR_VIEW'; //we only have 1 view now
end;
procedure TDPMEditorView.DeselectView;
begin
if FFrame <> nil then
FFrame.ViewDeselected;
end;
destructor TDPMEditorView.Destroy;
begin
inherited;
end;
function TDPMEditorView.EditAction(Action : TEditAction) : Boolean;
begin
result := false;
end;
//procedure TDPMEditorView.FilterToProject(const projectGroup : IOTAProjectGroup; const project : IOTAProject);
//var
// sFileName : string;
//begin
// FProjectGroup := projectGroup;
// FProject := project;
// if FFrame <> nil then
// begin
// if project <> nil then
// sFileName := project.FileName;
// FFrame.FilterToProject(sFileName);
// end;
//
//end;
procedure TDPMEditorView.FrameCreated(AFrame : TCustomFrame);
begin
FFrame := TDPMEditViewFrame(AFrame);
FFrame.Name := GetViewIdentifier;
FFrame.Configure(FProjectGroup, FProject, FContainer, FProjectTreeManager);
end;
function TDPMEditorView.GetCanCloneView : Boolean;
begin
result := false;
end;
function TDPMEditorView.GetCaption : string;
begin
result := FCaption;
end;
function TDPMEditorView.GetEditorWindowCaption : string;
begin
result := 'DPM Packages';
end;
function TDPMEditorView.GetEditState : TEditState;
begin
result := [];
end;
function TDPMEditorView.GetFrameClass : TCustomFrameClass;
begin
result := TDPMEditViewFrame;
end;
function TDPMEditorView.GetImageIndex : Integer;
begin
result := FImageIndex;
end;
function TDPMEditorView.GetTabHintText : string;
begin
result := GetCaption;
end;
function TDPMEditorView.GetViewIdentifier : string;
begin
result := FIdentifier;
end;
procedure TDPMEditorView.ProjectChanged;
begin
if FFrame <> nil then
FFrame.ProjectChanged;
end;
procedure TDPMEditorView.ProjectClosed(const projectName: string);
begin
if FFrame <> nil then
FFrame.ProjectClosed(projectName);
end;
procedure TDPMEditorView.ProjectLoaded(const projectName: string);
begin
if FFrame <> nil then
FFrame.ProjectLoaded(projectName);
end;
procedure TDPMEditorView.SelectView;
begin
//Note : For some reason this is getting called twice each time the view is selected.
if FFrame <> nil then
FFrame.ViewSelected;
end;
procedure TDPMEditorView.ThemeChanged;
begin
if FFrame <> nil then
FFrame.ThemeChanged;
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.SearchPath;
interface
uses
JsonDataObjects,
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Spec.Interfaces,
DPM.Core.Spec.Node;
type
TSpecSearchPath = class(TSpecNode, ISpecSearchPath)
private
FPath : string;
protected
function GetPath : string;
procedure SetPath(const value : string);
function IsGroup : Boolean; virtual;
function Clone : ISpecSearchPath; virtual;
function LoadFromJson(const jsonObject : TJsonObject) : Boolean; override;
constructor CreateClone(const logger : ILogger; const path : string);
public
constructor Create(const logger : ILogger); override;
end;
implementation
uses
Variants,
System.SysUtils;
{ TSpecSearchPath }
function TSpecSearchPath.Clone : ISpecSearchPath;
begin
result := TSpecSearchPath.CreateClone(logger, FPath);
end;
constructor TSpecSearchPath.Create(const logger : ILogger);
begin
inherited Create(logger);
end;
constructor TSpecSearchPath.CreateClone(const logger : ILogger; const path : string );
begin
inherited Create(logger);
FPath := path;
end;
function TSpecSearchPath.GetPath : string;
begin
result := FPath;
end;
function TSpecSearchPath.IsGroup : Boolean;
begin
result := false;
end;
function TSpecSearchPath.LoadFromJson(const jsonObject : TJsonObject) : Boolean;
begin
result := true;
FPath := jsonObject.S['path'];
if FPath = '' then
begin
result := false;
Logger.Error('Required property [path] not found');
end;
end;
procedure TSpecSearchPath.SetPath(const value : string);
begin
FPath := value;
end;
end.
|
program questao11;
{
Autor: Hugo Deiró Data: 03/06/2012
- Este programa calcula o aumento de um salário baseado em quanto ele
era anteriormente.
}
var
salario : real;
begin
write('Insira o salário: ');
readln(salario);
writeln;
if(salario > 0)then
begin
if(salario <= 280)then
begin
writeln('Salário anterior = ',salario:6:2);
writeln('Percentual de aumento = 20%');
writeln('Valor do aumento = ',salario*0.2:6:2);
writeln('Novo salário = ',(salario + salario*0.2):6:2);
end;
if(salario > 280) and (salario <= 700)then
begin
writeln('Salário anterior = ',salario:6:2);
writeln('Percentual de aumento = 15%');
writeln('Valor do aumento = ',salario*0.15:6:2);
writeln('Novo salário = ',(salario + salario*0.15):6:2);
end;
if(salario > 700) and (salario <= 1500)then
begin
writeln('Salário anterior = ',salario:6:2);
writeln('Percentual de aumento = 10%');
writeln('Valor do aumento = ',salario*0.1:6:2);
writeln('Novo salário = ',(salario + salario*0.1):6:2);
end;
if(salario > 1500)then
begin
writeln('Salário anterior = ',salario:6:2);
writeln('Percentual de aumento = 5%');
writeln('Valor do aumento = ',salario*0.05:6:2);
writeln('Novo salário = ',(salario + salario*0.05):6:2);
end;
end
else
writeln('O salário inserido é inválido!');
end.
|
program feldsortS125 (input, output);
{sortiert einzulesendes Feld von integer-Zahlen}
const
FELDGROESSE = 5;
type
tIndex = 1..FELDGROESSE;
tFeld = array [tIndex] of integer;
var
Eingabefeld : tFeld;
MinPos,
i : tIndex;
Tausch: integer;
function FeldMinimumPos (Feld: tFeld;
von, bis : tIndex) : tIndex;
{bestimmt die Position des Minimums im Feld zwischen von und bis,
1 <= von <= bis <= FELDGROESSE }
var
MinimumPos,
j : tIndex;
begin
MinimumPos:= von;
for j:= von+1 to bis do
if Feld[j] < Feld[MinimumPos] then
MinimumPos:= j;
FeldMinimumPos:=MinimumPos;
end;{FeldminimumPos}
begin
{Einlesen des Feldes}
writeln ('Geben Sie', FELDGROESSE ,' Werte ein: ');
for i:=1 to FELDGROESSE do
readln(Eingabefeld[i]);
{sortieren}
for i:=1 to FELDGROESSE - 1 do
begin
MinPos:= FeldMinimumPos (Eingabefeld, i, FELDGROESSE);
{Minimum gefunden, welches nun mit dem Element im Feld i
vertauscht werden muss}
Tausch:= Eingabefeld[MinPos];
Eingabefeld[MinPos]:=Eingabefeld[i];
Eingabefeld[i]:= Tausch
end;
{Ausgabe des sortierten Feldes}
for i:=1 to FELDGROESSE do
write(Eingabefeld[i] : 6);
writeln
end.{feldsort}
|
program HowToCreateHost;
uses
SwinGame, sgTypes, sgNetworking, SysUtils;
//----------------------------------------------------------------------------
// Init
//----------------------------------------------------------------------------
procedure InitPanel(var aMenuPanel : Panel);
begin
GUISetForegroundColor(ColorBlack);
GUISetBackgroundColor(ColorWhite);
ShowPanel(aMenuPanel);
ActivatePanel(aMenuPanel);
DrawGUIAsVectors(True);
end;
procedure SetLabelText();
begin
LabelSetText('MyIPLbl', 'My IP:');
LabelSetText('MyIPVal', MyIP());
LabelSetText('MyPorttLbl', 'Port: ');
LabelSetText('HostStatusLbl', 'Status: ');
LabelSetText('MsgsLbl', 'Message: ');
LabelSetText('ServerLbl', 'Server:');
LabelSetText('ServerPorttLbl', 'Port: ');
LabelSetText('ClientStatusLbl', 'Status: ');
LabelSetText('ServerVal', '127.0.0.1');
end;
//----------------------------------------------------------------------------
// Connect
//----------------------------------------------------------------------------
procedure CreateHost(var aMenuPanel : Panel; var aStatus : Boolean);
var
lPort : Integer;
begin
if TryStrToInt(TextBoxText('MyPortVal'), lPort) then
begin
CreateTCPHost(lPort);
LabelSetText('HostStatusVal', 'Listening...');
LabelSetText('HostLbl', 'Disconnect');
ListAddItem(aMenuPanel, 'MsgList', 'Now Listening for Connections....');
aStatus := True;
end;
end;
procedure ConnectToHost(aMenuPanel : Panel; var aStatus : Boolean; var lPeer : Connection);
var
lPort : Integer;
begin
if TryStrToInt(TextBoxText('ServerPortVal'), lPort) then
begin
lPeer := CreateTCPConnection(TextBoxText('ServerVal'), lPort);
if Assigned(lPeer) then
begin
LabelSetText('ClientStatusVal', 'Connected');
ListAddItem(aMenuPanel, 'MsgList', 'Connected to: ' + TextBoxText('ServerVal') + ':' + IntToStr(lPort));
LabelSetText('ConnLbl', 'Disconnect');
aStatus := True;
end;
end;
end;
procedure AcceptConnection(var aMenuPanel : Panel; var lPeer : Connection);
begin
if AcceptTCPConnection(); then
begin
lPeer := FetchConnection();
ListAddItem(aMenuPanel, 'MsgList', + 'Connected.');
end;
end;
//----------------------------------------------------------------------------
// Disconnect
//----------------------------------------------------------------------------
procedure DisconnectHost(var aMenuPanel : Panel; var aStatus : Boolean);
begin
CloseAllTCPReceiverSocket();
CloseAllTCPHostSocket();
LabelSetText('HostStatusVal', 'Idle');
LabelSetText('HostLbl', 'Connect');
ListAddItem(aMenuPanel, 'MsgList', 'Listening Sockets Closed.');
aStatus := False;
end;
procedure DisconnectFromAllHost(aMenuPanel : Panel; var aStatus : Boolean);
begin
BroadcastTCPMessage('[ClientDisconnect]');
CloseAllTCPSenderSocket();
LabelSetText('ClientStatusVal', 'Disconnected');
LabelSetText('ConnLbl', 'Connect');
ListAddItem(aMenuPanel, 'MsgList', 'You Disconnected.');
aStatus := False;
end;
//----------------------------------------------------------------------------
// Messages
//----------------------------------------------------------------------------
procedure ReceiveMessage(var aMenuPanel : Panel);
var
i : Integer;
begin
if (not TCPMessageReceived()) then exit;
for i:= 0 to GetMessageCount() - 1 do
begin
if (GetMessage() = '[ClientDisconnect]') then
begin
CloseTCPReceiverSocket(GetIPFromMessage(), GetPortFromMessage());
ListAddItem(aMenuPanel, 'MsgList', GetIPFromMessage() + ' Disconnected.');
end else begin
ListAddItem(aMenuPanel, 'MsgList', GetIPFromMessage() + ' said: ' + GetMessage());
ListSetActiveItemIndex(aMenuPanel, 'MsgList', ListItemCount('MsgList') - 1);
end;
DequeueTopMessage();
end;
end;
//----------------------------------------------------------------------------
// Input
//----------------------------------------------------------------------------
procedure HandleGUIInput(aChatPanel : Panel; var aServerStatus, aClientStatus : Boolean);
begin
//Server Connect and Disconnect
if (not aServerStatus) and (RegionClickedID() = 'HostBtn') then
CreateHost(aChatPanel, aServerStatus)
else if (aServerStatus) and (RegionClickedID() = 'HostBtn') then
DisconnectHost(aChatPanel, aServerStatus)
//Client Connect and Disconnect
else if (not aClientStatus) and (RegionClickedID() = 'ConnectBtn') then
ConnectToHost(aChatPanel, aClientStatus)
else if (aClientStatus) and (RegionClickedID() = 'ConnectBtn') then
DisconnectFromAllHost(aChatPanel, aClientStatus)
//Message Input
else if GUITextEntryComplete() and (GUITextBoxOfTextEntered() = TextBoxFromID('MsgVal')) then
begin
if (TextBoxText('MsgVal') = '') then exit;
if (Length(BroadcastTCPMessage(TextBoxText('MsgVal'))) <> 0) then
begin
ListAddItem(aChatPanel, 'MsgList', 'Host Disconnected.');
DisconnectFromAllHost(aChatPanel, aClientStatus);
exit;
end;
ListAddItem(aChatPanel, 'MsgList', 'You Say: ' + TextBoxText('MsgVal'));
ListSetActiveItemIndex(aChatPanel, 'MsgList', ListItemCount('MsgList') - 1);
TextBoxSetText('MsgVal', '');
GUISetActiveTextbox(TextBoxFromID('MsgVal'));
end;
end;
procedure Main();
var
lServerPanel, lClientPanel, lChatPanel : Panel;
//True for Listening, False for Idle.
lHostStatus : Boolean = False;
//True for Connected, False for Disconnected
lClientStatus : Boolean = False;
lPeer : Connection = nil;
begin
OpenGraphicsWindow('How To Create Host', 800, 600);
LoadDefaultColors();
LoadResourceBundle('MainMenu.txt');
lServerPanel := LoadPanel('hostpanel.txt');
lClientPanel := LoadPanel('clientpanel.txt');
lChatPanel := LoadPanel('ChatWindowPanel.txt');
InitPanel(lServerPanel);
InitPanel(lClientPanel);
InitPanel(lChatPanel);
SetLabelText();
repeat
ProcessEvents();
ClearScreen(ColorBlack);
DrawPanels();
UpdateInterface();
HandleGUIInput(lChatPanel, lHostStatus, lClientStatus);
if not lHostStatus then
AcceptConnection(lChatPanel, lPeer);
else
ConnectToHost(aMenuPanel : Panel; var aStatus : Boolean; var lPeer : Connection);
ReceiveMessage(lChatPanel);
RefreshScreen();
until WindowCloseRequested();
ReleaseAllResources();
end;
begin
Main();
end. |
unit UtilLib;
interface
uses
Classes,SysUtils;
type
TUtilLib=class(TObject)
public
class function SmallToBig(Small:Real):string;
end;
implementation
{ TUtilLib }
class function TUtilLib.SmallToBig(Small: Real): string;
var
j: Integer;
SmallMonth,BigMonth:string;
wei1,qianwei1:string[2];
qianwei,dianweizhi,qian:integer;
TempA:string;
TempB:string;
TempC:string;
begin
if Small=0 then
begin
Result:='零元整';
Exit;
end;
{------- 修改参数令值更精确 -------}
{小数点后的位置,需要的话也可以改动-2值}
qianwei:=-2;
{转换成货币形式,需要的话小数点后加多几个零}
Smallmonth:=formatfloat('0.00',small);
{---------------------------------}
dianweizhi :=pos('.',Smallmonth);{小数点的位置}
{循环小写货币的每一位,从小写的右边位置到左边}
for qian:=length(Smallmonth) downto 1 do
begin
{如果读到的不是小数点就继续}
if qian<>dianweizhi then
begin
{位置上的数转换成大写}
case strtoint(copy(Smallmonth,qian,1)) of
1:wei1:='壹'; 2:wei1:='贰';
3:wei1:='叁'; 4:wei1:='肆';
5:wei1:='伍'; 6:wei1:='陆';
7:wei1:='柒'; 8:wei1:='捌';
9:wei1:='玖'; 0:wei1:='零';
end;
{判断大写位置,可以继续增大到real类型的最大值}
case qianwei of
-3:qianwei1:='厘';
-2:qianwei1:='分';
-1:qianwei1:='角';
0 :qianwei1:='元';
1 :qianwei1:='拾';
2 :qianwei1:='佰';
3 :qianwei1:='仟';
4 :qianwei1:='万';
5 :qianwei1:='拾';
6 :qianwei1:='佰';
7 :qianwei1:='仟';
8 :qianwei1:='亿';
9 :qianwei1:='拾';
10:qianwei1:='佰';
11:qianwei1:='仟';
end;
inc(qianwei);
BigMonth :=wei1+qianwei1+BigMonth;{组合成大写金额}
if (wei1='零') and (Copy(BigMonth,5,2)='零') then
begin
if (Copy(BigMonth,3,2)='万') or (Copy(BigMonth,3,2)='亿') or
(Copy(BigMonth,3,2)='元') then
Delete(BigMonth,1,2)
else
Delete(BigMonth,1,4);
end;
if (Copy(BigMonth,1,2)='零') and //(Pos(Copy(BigMonth,3,2),'亿万元')=0) and
(Pos(Copy(BigMonth,3,2),'壹贰叁肆伍陆柒捌玖')=0) then
begin
if (Copy(BigMonth,Length(BigMonth)-3,4)= '零万') or
(Copy(BigMonth,Length(BigMonth)-3,4)= '零亿') or
(Copy(BigMonth,Length(BigMonth)-3,4)= '零元') or
(Copy(BigMonth,1,4)= '零万') or
(Copy(BigMonth,1,4)= '零亿') or
(Copy(BigMonth,1,4)= '零元') then
Delete(BigMonth,1,2)
else begin
Delete(BigMonth,3,2);
if (Copy(BigMonth,Length(BigMonth)-3,4)= '零万') or
(Copy(BigMonth,Length(BigMonth)-3,4)= '零亿') or
(Copy(BigMonth,Length(BigMonth)-3,4)= '零元') or
(Copy(BigMonth,1,4)= '零万') or
(Copy(BigMonth,1,4)= '零亿') or
(Copy(BigMonth,1,4)= '零元') then
Delete(BigMonth,1,2)
end;
end;
//除最后一位零
if Copy(BigMonth,Length(BigMonth)-1,2)= '零' then
Delete(BigMonth,Length(BigMonth)-1,2)
end;
end;
if Pos(Copy(BigMonth,Length(BigMonth)-1,2),'元角')>0 then
BigMonth:= BigMonth+'整';
j:= Pos('亿万',BigMonth);
if j>1 then
Delete(BigMonth,j+2,2);
//SmallTOBig:=BigMonth;
Result:=BigMonth;
if Copy(Result,1,2)='元' then
begin
Result:=Copy(Result,3,Length(Result)-2);
end;
TempA:=FormatFloat('0',small);
if Length(TempA)>5 then
begin
TempB:=(Copy(TempA,Length(TempA)-4,1));
TempC:=(Copy(TempA,Length(TempA)-3,1));
if (TempB='0') and (TempC<>'0') then
begin
Result:=StringReplace(Result,'万','万零',[rfReplaceAll]);
end;
end;
end;
end.
|
unit ThConnectionStringEdit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, dcedit, DB, ADODB;
type
TThConnectionStringEditForm = class(TForm)
Label1: TLabel;
ConnectionStringEdit: TDCEdit;
OkButton: TButton;
ADOConnection: TADOConnection;
procedure FormShow(Sender: TObject);
procedure ConnectionStringEditButton2Click(Sender: TObject);
private
{ Private declarations }
procedure ConnectionStringsToEditPopup;
function GetConnectionString: string;
procedure SetConnectionString(const Value: string);
public
{ Public declarations }
property ConnectionString: string read GetConnectionString
write SetConnectionString;
end;
var
ThConnectionStringEditForm: TThConnectionStringEditForm;
implementation
uses
AdoConEd, ThDataConnection;
{$R *.dfm}
procedure TThConnectionStringEditForm.FormShow(Sender: TObject);
begin
ConnectionStringsToEditPopup;
end;
procedure TThConnectionStringEditForm.ConnectionStringsToEditPopup;
begin
with TPopupListBox(ConnectionStringEdit.PopupWindow) do
Items.Assign(NeedConnectionStore.ConnectionStrings);
end;
procedure TThConnectionStringEditForm.ConnectionStringEditButton2Click(
Sender: TObject);
begin
EditConnectionString(AdoConnection);
ConnectionStringEdit.Text := AdoConnection.ConnectionString;
end;
function TThConnectionStringEditForm.GetConnectionString: string;
begin
Result := ConnectionStringEdit.Text;
end;
procedure TThConnectionStringEditForm.SetConnectionString(const Value: string);
begin
ConnectionStringEdit.Text := Value;
end;
end.
|
unit Main_U;
// Description: SDUPrettyPrint Test Application
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, Spin64;
type
TMain_F = class(TForm)
pbDisplayFile: TButton;
reReport: TRichEdit;
edFilename: TEdit;
Label1: TLabel;
seWidth: TSpinEdit64;
Label2: TLabel;
Label3: TLabel;
procedure pbDisplayFileClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Main_F: TMain_F;
implementation
{$R *.DFM}
uses
SDUGeneral;
procedure TMain_F.pbDisplayFileClick(Sender: TObject);
var
inputFile: TFileStream;
hexPrettyPrint: TStringList;
begin
inputFile:= TFileStream.Create(edFilename.text, (fmOpenRead or fmShareDenyNone));
try
hexPrettyPrint:= TStringList.Create();
try
SDUPrettyPrintHex(inputFile, 0, -1, hexPrettyPrint, seWidth.value);
reReport.lines.Add('Printed-printed hex representation of "'+edFilename.text+'":');
reReport.lines.AddStrings(hexPrettyPrint);
reReport.lines.Add('');
finally
hexPrettyPrint.Free();
end;
finally
inputFile.Free();
end;
end;
END.
|
unit Search_Unit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxControls,
cxContainer, cxEdit, cxTextEdit, st_ConstUnit;
type
TSearch_Form = class(TForm)
T_Label: TLabel;
Naim_Edit: TcxTextEdit;
Find_Button: TcxButton;
Cancel_Button: TcxButton;
procedure Cancel_ButtonClick(Sender: TObject);
procedure Find_ButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
procedure WMNCHitTest(var M: TWMNCHitTest); message wm_NCHitTest;
procedure FormIniLanguage();
public
PLanguageIndex: byte;
end;
var
Search_Form: TSearch_Form;
implementation
{$R *.dfm}
procedure TSearch_Form.FormIniLanguage();
begin
Caption:= st_ConstUnit.st_Search_Name[PLanguageIndex];
//названия кнопок
Find_Button.Caption := st_ConstUnit.st_FindNow[PLanguageIndex];
Cancel_Button.Caption := st_ConstUnit.st_Cancel[PLanguageIndex];
T_Label.Caption:= st_ConstUnit.st_NameLable[PLanguageIndex];
end;
procedure TSearch_Form.WMNCHitTest(var M: TWMNCHitTest);
begin
inherited; { вызов унаследованного обработчика }
if M.Result = htClient then{ Мышь сидит на окне? }
M.Result := htCaption; { Если да - то пусть Windows думает, что мышь на caption bar }
end;
procedure TSearch_Form.Cancel_ButtonClick(Sender: TObject);
begin
close;
end;
procedure TSearch_Form.Find_ButtonClick(Sender: TObject);
begin
ModalResult:=mrOk;
end;
procedure TSearch_Form.FormShow(Sender: TObject);
begin
FormIniLanguage();
end;
end.
|
unit AppRegistry;
interface
uses
Classes, Registry, ResStr, cxGridDBTableView,cxGridCustomView;
type
TAppRegistry = class(TRegistry)
private
fRootKeyName: string;
public
constructor Create (aRootKeyName: string);
function DeleteSubKey(aSubKey: string): boolean;
procedure OpenSubKey (aSubKey: string);
function ReadPropValString (aProperty: string; AllowCreation: boolean): string;
function ReadPropValBool (aProperty: string; AllowCreation: boolean): boolean;
function ReadPropValInt (aProperty: string; AllowCreation: boolean): integer;
function ReadPropValBinary (aProperty: string;
var aValue; maxSize: integer;
AllowCreation: boolean): integer;
procedure WritePropValString (aProperty: string; aValue: string);
procedure WritePropValBinary (aProperty: string; var aBuffer; aSize: integer);
procedure WritePropValBool (aProperty: string; aValue: boolean);
procedure WritePropValInt (aProperty: string; aValue: integer);
procedure SaveGridLayout (aStoreSubKey, aFormName: string; aTreeView: tcxGridDBTableView);
procedure RestoreGridLayout (aStoreSubKey, aFormName: string; aTreeView: tcxGridDBTableView);
end;
implementation
uses StrUtils, sysUtils, ResStrings;
constructor TAppRegistry.Create (aRootKeyName: string);
begin
inherited Create;
if RightStr(aRootKeyName,1) = '\' then
fRootKeyName := Copy(aRootKeyname, 1, Length(aRootKeyName) - 1)
else
fRootKeyName := aRootKeyName;
end;
procedure TAppRegistry.OpenSubKey (aSubKey: string);
var aKey: string;
aErr: string;
begin
if LeftStr (aSubKey, 1) = '\' then
aKey := fRootKeyName + aSubKey
else
aKey := fRootKeyName + '\' + aSubKey;
if (OpenKey(aKey, true)=false) then begin
aErr := Format (C_EXCEPT_REGISTRY_OPEN, [aKey]);
raise Exception.Create(aErr);
end;
end;
function TAppRegistry.ReadPropValString (aProperty: string; AllowCreation: boolean): string;
begin
if ValueExists(aProperty) then
Result := AnsiUpperCase(ReadString(aProperty))
else begin
if AllowCreation then
WriteString(aProperty, '');
Result := '';
end;
end;
function TAppRegistry.ReadPropValBinary (aProperty: string;
var aValue; maxSize: integer;
AllowCreation: boolean): integer;
var foo: integer;
begin
if ValueExists(aProperty) then
Result := ReadBinaryData(aProperty, aValue, maxSize)
else begin
if AllowCreation then
WritePropValBinary(aProperty, foo, 0);
Result := 0;
end;
end;
procedure TAppRegistry.WritePropValString (aProperty: string; aValue: string);
begin
WriteString(aProperty, aValue);
end;
procedure TAppRegistry.WritePropValBinary (aProperty: string; var aBuffer; aSize: integer);
begin
WriteBinaryData(aProperty, aBuffer, aSize);
end;
function TAppRegistry.ReadPropValBool (aProperty: string; AllowCreation: boolean): boolean;
begin
if ValueExists(aProperty) then
Result := ReadBool(aProperty)
else begin
if AllowCreation then
WriteBool(aProperty, false);
Result := false;
end;
end;
procedure TAppRegistry.WritePropValBool (aProperty: string; aValue: boolean);
begin
WriteBool(aProperty, aValue);
end;
function TAppRegistry.ReadPropValInt (aProperty: string; AllowCreation: boolean): integer;
begin
if ValueExists(aProperty) then
Result := ReadInteger(aProperty)
else begin
if AllowCreation then
WriteInteger(aProperty, 0);
Result := 0;
end;
end;
procedure TAppRegistry.WritePropValInt (aProperty: string; aValue: integer);
begin
WriteInteger(aProperty, aValue);
end;
procedure TAppRegistry.SaveGridLayout (aStoreSubKey, aFormName: string; aTreeView: tcxGridDBTableView);
var
aKey: string;
aSaveViewName: string;
begin
if LeftStr (aStoreSubKey, 1) = '\' then
aKey := fRootKeyName + aStoreSubKey
else
aKey := fRootKeyName + '\' + aStoreSubKey;
aSaveViewName := aFormName + '.' + aTreeView.Name;
//Save settings to the Registry
aTreeView.StoreToRegistry(aKey, False, [gsoUseFilter], aSaveViewName);
end;
procedure TAppRegistry.RestoreGridLayout (aStoreSubKey, aFormName: string; aTreeView: tcxGridDBTableView);
var
aKey: string;
aSaveViewName: string;
begin
if LeftStr (aStoreSubKey, 1) = '\' then
aKey := fRootKeyName + aStoreSubKey
else
aKey := fRootKeyName + '\' + aStoreSubKey;
aSaveViewName := aFormName + '.' + aTreeView.Name;
//Restore settings from the Registry
aTreeView.RestoreFromRegistry(aKey, False, False, [gsoUseFilter], aSaveViewName);
end;
function TAppRegistry.DeleteSubKey(aSubKey: string): boolean;
var aKey: string;
begin
if LeftStr (aSubKey, 1) = '\' then
aKey := fRootKeyName + aSubKey
else
aKey := fRootKeyName + '\' + aSubKey;
Result := DeleteKey(aKey);
end;
end.
|
unit uDM;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
uParentDM, Db, DBTables, uSystemTypes, uHandleError, uSystemConst,
IniFiles, ADODB, RCADOQuery, PowerADOQuery, LookUpADOQuery;
Const
TRIAL_LIMIT = 6000;
type
TOMSystem = Class
private
fStartMode : Char;
fValidLicense : Boolean;
public
property StartMode : Char read fStartMode write fStartMode;
property ValidLicense : Boolean read fValidLicense write fValidLicense;
end;
TDM = class(TParentDM)
quUsuario: TLookUpADOQuery;
dsLookUpUsuario: TDataSource;
quEmpresa: TLookUpADOQuery;
dsLookUpEmpresa: TDataSource;
quEmpresaIDEmpresa: TIntegerField;
quEmpresaCodigoEmpresa: TStringField;
quEmpresaEmpresa: TStringField;
dsLUContaCorrente: TDataSource;
quContaCorrente: TLookUpADOQuery;
quContaCorrenteIDContaCorrente: TIntegerField;
quContaCorrenteCodigoContaCorrente: TStringField;
dsLUQuitacaoMeio: TDataSource;
quQuitacaoMeio: TLookUpADOQuery;
dsLUPessoaTipo: TDataSource;
quPessoaTipo: TLookUpADOQuery;
dsLULancamentoTipo: TDataSource;
quLancamentoTipo: TLookUpADOQuery;
dsLUPessoa: TDataSource;
quPessoa: TLookUpADOQuery;
dsLUDocumentoTipo: TDataSource;
quDocumentoTipo: TLookUpADOQuery;
quDocumentoTipoIDDocumentoTipo: TIntegerField;
quDocumentoTipoCodigoDocumentoTipo: TStringField;
quDocumentoTipoDocumentoTipo: TStringField;
quLancamentoTipoIDLancamentoTipo: TIntegerField;
quLancamentoTipoLancamentoTipo: TStringField;
quLancamentoTipoPathName: TStringField;
quLancamentoTipoPath: TStringField;
dsLUCentroCusto: TDataSource;
quCentroCusto: TLookUpADOQuery;
dsLUMoeda: TDataSource;
quMoeda: TLookUpADOQuery;
quMoedaIDMoeda: TIntegerField;
quMoedaCodigoMoeda: TStringField;
quMoedaMoeda: TStringField;
quBanco: TLookUpADOQuery;
dsLUBanco: TDataSource;
quBancoIDBanco: TIntegerField;
quBancoCodigoBanco: TStringField;
quBancoBanco: TStringField;
quBancoAgencia: TLookUpADOQuery;
dsLUBancoAgencia: TDataSource;
quBancoAgenciaIDBancoAgencia: TIntegerField;
quBancoAgenciaCodigoBancoAgencia: TStringField;
quBancoAgenciaBancoAgencia: TStringField;
dsLUMenuItem: TDataSource;
quMenuItem: TLookUpADOQuery;
quMenuItemIDMenuItem: TIntegerField;
quMenuItemMenu: TStringField;
quMenuItemMenuItem: TStringField;
dsLUDesdobramentoTipo: TDataSource;
quDesdobramentoTipo: TLookUpADOQuery;
quDesdobramentoTipoIDDesdobramentoTipo: TIntegerField;
quDesdobramentoTipoIDDocumentoTipo: TIntegerField;
quDesdobramentoTipoDesdobramentoTipo: TStringField;
quDesdobramentoTipoCodigoDesdobramentoTipo: TStringField;
quDesdobramentoTipoIdentificadorDesdobramento: TStringField;
quDesdobramentoTipoHidden: TBooleanField;
quDesdobramentoTipoSystem: TBooleanField;
quDesdobramentoTipoDesativado: TBooleanField;
quContaCorrenteNumero: TStringField;
quLancamentoTipoCodigoContabil: TStringField;
quPessoaTipoIDTipoPessoa: TIntegerField;
quPessoaTipoTipoPessoa: TStringField;
quPessoaTipoJuridico: TIntegerField;
quPessoaTipoPathName: TStringField;
quPessoaIDPessoa: TIntegerField;
quPessoaCode: TIntegerField;
quPessoaPessoa: TStringField;
quPessoaDesativado: TIntegerField;
quPessoaHidden: TIntegerField;
quPessoaSystem: TBooleanField;
quQuitacaoMeioIDMeioPag: TIntegerField;
quQuitacaoMeioMeioPag: TStringField;
quCentroCustoIDCentroCusto: TIntegerField;
quCentroCustoCodigoCentroCusto: TStringField;
quCentroCustoCentroCusto: TStringField;
quLookUpStore: TLookUpADOQuery;
quLookUpStoreIDStore: TIntegerField;
quLookUpStoreName: TStringField;
dsLookUpStore: TDataSource;
LookUpUser: TLookUpADOQuery;
LookUpUserIDUser: TIntegerField;
LookUpUserSystemUser: TStringField;
dsLookUpUser: TDataSource;
LookUpEstado: TLookUpADOQuery;
LookUpEstadoIDEstado: TStringField;
LookUpEstadoEstado: TStringField;
dsLookUpEstado: TDataSource;
LookUpTipoPessoa: TLookUpADOQuery;
LookUpTipoPessoaIDTipoPessoa: TIntegerField;
LookUpTipoPessoaPathName: TStringField;
LookUpTipoPessoaPath: TStringField;
dsLookUpTipoPessoa: TDataSource;
LookUpPais: TLookUpADOQuery;
LookUpPaisIDPais: TIntegerField;
LookUpPaisCodPais: TStringField;
LookUpPaisPais: TStringField;
dsLookUpPais: TDataSource;
quLookUpMeioPagBatch: TLookUpADOQuery;
dsLookUpMeioPagBatch: TDataSource;
quLookUpMeioPagBatchIDMeioPag: TAutoIncField;
quLookUpMeioPagBatchMeioPag: TStringField;
quLookUpFornecedor: TLookUpADOQuery;
dsLookUpFornecedor: TDataSource;
quLookUpFornecedorIDPessoa: TAutoIncField;
quLookUpFornecedorIDFornecedor: TAutoIncField;
quLookUpFornecedorPessoa: TStringField;
quLookUpFornecedorCode: TIntegerField;
quCompany: TLookUpADOQuery;
IntegerField1: TIntegerField;
StringField1: TStringField;
StringField2: TStringField;
dsCompany: TDataSource;
quUsuarioIDUser: TAutoIncField;
quUsuarioCodSystemUser: TStringField;
quUsuarioSystemUser: TStringField;
quUserType: TLookUpADOQuery;
quUserTypeIDUserType: TIntegerField;
quUserTypeName: TStringField;
dsLookUpUserType: TDataSource;
spGetNextID: TADOStoredProc;
quSrvParam: TADOQuery;
quSrvParamIDParam: TIntegerField;
quSrvParamSrvParameter: TStringField;
quSrvParamSrvValue: TStringField;
quLookupSaleTax: TLookUpADOQuery;
dsLookupSaleTax: TDataSource;
quLookupSaleTaxIDTaxCategory: TIntegerField;
quLookupSaleTaxTaxCategory: TStringField;
quLookupPurchaseTax: TLookUpADOQuery;
LookupPurchaseTax: TDataSource;
quLookupPurchaseTaxIDTaxCategory: TIntegerField;
quLookupPurchaseTaxTaxCategory: TStringField;
quLookUpMunicipio: TLookUpADOQuery;
dsLookUpMunicipio: TDataSource;
quLookUpMunicipioIDMunicipio: TIntegerField;
quLookUpMunicipioCodigo: TStringField;
quLookUpMunicipioDescricao: TStringField;
procedure DMDestroy(Sender: TObject);
procedure DMCreate(Sender: TObject);
function quMoedaClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
function quQuitacaoMeioClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
function quContaCorrenteClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
function quBancoClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
function quBancoAgenciaClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
function quPessoaClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
function quEmpresaClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
function quLancamentoTipoClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
function quCentroCustoClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
function quDocumentoTipoClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
function quDesdobramentoTipoClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
function quUsuarioClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
function quLookUpMunicipioClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
private
{ Private declarations }
FHandleError : THandleError;
slProperty : TStringList;
FIDMoedaPadrao : Integer;
FIDMoedaCotacaoPadrao : Integer;
FMoedaPadrao : String;
FSiglaMoedaPadrao : String;
FIDDefaultCompany : Integer;
FTaxInCost : Boolean;
procedure InitMoedaPadrao;
function GetIDCentroCustoPadrao : Integer;
function GetIDMoedaPadrao : Integer;
function GetIDMoedaCotacaoPadrao : Integer;
function GetMoedaPadrao : String;
function GetSiglaMoedaPadrao : String;
function GetIDDefaultCompany : Integer;
function GetTaxInCost : Boolean;
public
{ Public declarations }
SitAberto, SitParteQuitado, SitQuitado,
SitCancelado, SitJuridico : Integer;
fSystem : TOMSystem; //System information
sSisUser : string;
function GetNextID(Const sTabela: String): LongInt;
procedure CreateLancSituacao;
procedure SetError(ErrorType: Integer; sSource, sError: String);
function GetPaymentMediaType(IDMeioPag: Integer): Integer;
function GetPropertyValues(MProperty: String): TStringList;
procedure PropertyValuesRefresh;
function NewQuery: TADOQuery;
function RunSQL(RunSQL:String): Boolean;
function RunSQLEx(RunSQL:String): Integer;
property IDCentroCustoPadrao : Integer read GetIDCentroCustoPadrao;
property IDMoedaCotacaoPadrao : Integer read GetIDMoedaCotacaoPadrao;
property IDMoedaPadrao : Integer read GetIDMoedaPadrao;
property MoedaPadrao : String read GetMoedaPadrao;
property SiglaMoedaPadrao : String read GetSiglaMoedaPadrao;
property IDDefaultCompany : Integer read GetIDDefaultCompany write FIDDefaultCompany;
property TaxInCost : Boolean read GetTaxInCost;
end;
var
DM: TDM;
implementation
{$R *.DFM}
uses
uMsgBox,
uParamFunctions,
uDMGlobal,
Registry,
uMsgConstant,
uDateTimeFunctions,
// Sistema
uSisSelPerfilDlg,
uSisUsuarioFch,
uSisEmpresaFch,
uSisMoedaFch,
uSisSenha,
uSisPessoaFch,
uSisMunicipio,
uFrmServerInfo,
uModuleConfig,
uSystemObj,
uEncryptFunctions,
uOperationSystem,
// Financeiro
uFinLancamentoTipoFch,
uFinQuitacaoMeioFch,
uFinContaCorrenteFch,
uFinDocumentoTipoFch,
uFinCentroCustoFch,
uFinCentroCustoTBrw,
uFinLancamentoTipoTBrw,
uFinBancoAgenciaFch,
uFinBancoFch,
uFinDesdobramentoTipoFch;
function TDM.GetNextID(Const sTabela: String): LongInt;
begin
with spGetNextID do
begin
Parameters.ParamByName('@Tabela').Value := sTabela;
ExecProc;
Result := Parameters.ParamByName('@NovoCodigo').Value;
end;
end;
procedure TDM.SetError(ErrorType: Integer; sSource, sError: String);
begin
if not Assigned(FHandleError.Connection) then
FHandleError.Connection := DBADOConnection;
FHandleError.ErrorDetected(DM.GetNextID(MR_APPHISTORY_ID),
ErrorType,
SisSenha.IDUsuario,
sSource,
sError,
FormatDateTime('mm/dd/yyyy', Now));
end;
procedure TDM.DMCreate(Sender: TObject);
var
//Client StatUp Variables
iMinOfUse : Integer;
sPW, sUser, sDBAlias, sServer, sResult : String;
FrmServrInfo : TFrmServerInfo;
buildInfo: String;
begin
TFrmMsgConstant.Create(Self);
FrmServrInfo := TFrmServerInfo.Create(self);
fSystem := TOMSystem.Create;
sResult := FrmServrInfo.Start('5', False);
sServer := ParseParam(sResult, '#SRV#');
sDBAlias := ParseParam(sResult, '#DB#');
sUser := ParseParam(sResult, '#USER#');
sPW := ParseParam(sResult, '#PW#');
//Colocation test
{ sServer := '192.168.100.100';
sDBAlias := 'ApresentationDB';
sUser := 'checkcustomer';
sPW := '7740';
}
// Default ConnectionString used by the application (SQL Server)
DBADOConnection.ConnectionString := '';
//DBADOConnection.ConnectionString := SetConnectionStr(sUser, sPw, SDBAlias, sServer);
DBADOConnection.ConnectionString := SetConnectionStrNoNETLIB(sUser, sPw, SDBAlias, sServer);
try
DBADOConnection.Open;
FrmServrInfo.Free;
except
MsgBox(MSG_CRT_NO_PARAM_SERVER, vbOKOnly + vbInformation);
//Inicio o frm de Srvr Information
FrmServrInfo.Start('4', True);
FrmServrInfo.Free;
Application.Terminate;
raise;
end;
slProperty := TStringList.Create;
FHandleError := THandleError.Create;
{ with quFreeSQL do
begin
if Active then
Close;
SQL.Text := 'SELECT Nome FROM Sis_Registro';
Open;
Application.Title := Fields[0].AsString;
Close;
end;}
if not ModuleStart then
begin
MsgBox(MSG_CRT_NO_MODEL_INFORMTION, vbCritical + vbOKOnly);
Abort;
end;
//validate license key
if ((fSystem.StartMode <> SYS_MODULE_TRIAL) and (not fSystem.ValidLicense)) then
begin
MsgBox(MSG_CRT_ERROR_INVALID_KEY, vbCritical + vbOKOnly);
Abort;
end;
if (fSystem.StartMode = SYS_MODULE_TRIAL) then
begin
with TRegistry.Create do
begin
try
if ( getOS(buildInfo) = osW7 ) then
RootKey:= HKEY_CURRENT_USER
else
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('SOFTWARE\Applenet\CurrentVersions', True);
if not ValueExists('TrialCount') then
begin
MsgBox(MSG_CRT_NO_VALID_TRIAL_INFO, vbOKOnly + vbCritical);
Application.Terminate;
end;
iMinOfUse:= StrToInt(DecodeServerInfo(ReadString('TrialCount'), 'Count', CIPHER_TEXT_STEALING, FMT_UU));
if iMinOfUse > TRIAL_LIMIT then
begin
MsgBox(MSG_INF_ACCOUNT_EXPIRED, vbOKOnly + vbInformation);
Application.Terminate;
end
else
MsgBox(MSG_INF_PART1_USE_MR+ IntToStr(TRIAL_LIMIT - iMinOfUse) + MSG_INF_PART2_USE_MR,
vbOKOnly + vbInformation);
CloseKey;
finally
Free;
end;
end;
end;
// Seta os parametros do cliente
with TRegistry.Create do
begin
if ( getOS(buildInfo) = osW7 ) then
RootKey:= HKEY_CURRENT_USER
else
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('SOFTWARE\Applenet\OfficeManager', True);
if not ValueExists('DefaultLanguage') then
WriteInteger('DefaultLanguage', 1);
if not ValueExists('LangPath') then
WriteString('LangPath', ExtractFilePath(ParamStr(0)) + LANG_DIRECTORY);
if not ValueExists('DefaultDecimalSeparator') then
WriteString('DefaultDecimalSeparator', '.');
if not ValueExists('DefaultThousandSeparator') then
WriteString('DefaultThousandSeparator', ',');
if not ValueExists('DefaultDateFormat') then
WriteString('DefaultDateFormat', 'mm/dd/yyyy');
DMGlobal.IDLanguage := ReadInteger('DefaultLanguage');
DMGlobal.LangFilesPath := ReadString('LangPath');
DecimalSeparator := ReadString('DefaultDecimalSeparator')[1];
ThousandSeparator := ReadString('DefaultThousandSeparator')[1];
ShortDateFormat := ReadString('DefaultDateFormat');
Free;
end;
ChangeLocalSetings(DMGlobal.IDLanguage);
with quSrvParam do
begin
if Active then
Close;
Parameters.ParamByName('IDParam').Value := 66;
Open;
FTaxInCost := (quSrvParamSrvValue.AsString = 'True');
Close;
end;
inherited;
FIDMoedaPadrao := -1;
end;
procedure TDM.CreateLancSituacao;
begin
SitAberto := GetConst('LancamentoSituacao_Aberto');
SitParteQuitado := getConst('LancamentoSituacao_ParteQuitado');
SitQuitado := getConst('LancamentoSituacao_Quitado');
SitJuridico := getConst('LancamentoSituacao_Juridico');
SitCancelado := getConst('LancamentoSituacao_Cancelado');
end;
function TDM.NewQuery: TADOQuery;
begin
Result := TADOQuery.Create(self);
Result.Connection := DM.DBADOConnection;
end;
procedure TDM.DMDestroy(Sender: TObject);
begin
inherited;
slProperty.Free;
FHandleError.Free;
FreeAndNil(fSystem);
end;
procedure TDM.PropertyValuesRefresh;
begin
slProperty.Clear;
end;
function TDM.GetPropertyValues(MProperty: String): TStringList;
var
p: integer;
begin
// Testo se jŠ li no banco esta propriedade
p := slProperty.IndexOf(MProperty);
if p = -1 then
begin
// Tenho que montar este string list
slProperty.Add(MProperty);
p := slProperty.IndexOf(MProperty);
slProperty.Objects[p] := TStringList.Create;
with quFreeSQL do
begin
Close;
SQL.Text := 'SELECT PropertyValue ' +
'FROM Sis_PropertyDomain ' +
'WHERE Property = ' + #39 + MProperty + #39 + ' ' +
'ORDER BY PropertyValue';
Open;
while not EOF do
begin
TStringList(slProperty.Objects[p]).Add(FieldByName('PropertyValue').AsString);
Next;
end;
Close;
end;
end;
Result := TStringList(slProperty.Objects[p]);
end;
procedure TDM.InitMoedaPadrao;
begin
if FIDMoedaPadrao = -1 then
begin
with quFreeSQL do
begin
if Active then
Close;
SQL.Text := 'SELECT IDMoeda, IDMoedaCotacao, Moeda, Sigla FROM Sis_Moeda Where MoedaPadrao = 1';
Open;
FIDMoedaPadrao := Fields[0].AsInteger;
FIDMoedaCotacaoPadrao := Fields[1].AsInteger;
FMoedaPadrao := Fields[2].AsString;
FSiglaMoedaPadrao := Fields[3].AsString;
Close;
end;
end;
end;
Function TDM.GetIDCentroCustoPadrao: Integer;
begin
if Application.Title = 'Sistema Integrado Nuance Tecidos' then
Result := -1
else
Result := 2;
end;
function TDM.GetIDDefaultCompany : Integer;
begin
Result := FIDDefaultCompany;
end;
Function TDM.GetIDMoedaPadrao : Integer;
begin
InitMoedaPadrao;
Result := FIDMoedaPadrao;
end;
Function TDM.GetIDMoedaCotacaoPadrao : Integer;
begin
InitMoedaPadrao;
Result := FIDMoedaCotacaoPadrao;
end;
Function TDM.GetMoedaPadrao : String;
begin
InitMoedaPadrao;
Result := FMoedaPadrao;
end;
Function TDM.GetSiglaMoedaPadrao : String;
begin
InitMoedaPadrao;
Result := FSiglaMoedaPadrao;
end;
function TDM.RunSQL(RunSQL: String): Boolean;
begin
with quFreeSQL do
begin
Close;
SQL.Text := RunSQL;
try
ExecSQL;
Result := True;
except
Result := False;
end;
end;
end;
function TDM.RunSQLEx(RunSQL: String): Integer;
begin
with quFreeSQL do
begin
Close;
SQL.Text := RunSQL;
ExecSQL;
end;
end;
function TDM.quMoedaClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
begin
inherited;
with TSisMoedaFch.Create(Self) do
begin
Result := Start(ClickedButton, Sender, False, PosID1, PosID2, '', '', nil);
Free;
end;
end;
function TDM.quQuitacaoMeioClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
begin
inherited;
with TFinQuitacaoMeioFch.Create(Self) do
begin
Result := Start(ClickedButton, Sender, False, PosID1, PosID2, '', '', nil);
Free;
end;
end;
function TDM.quContaCorrenteClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
begin
inherited;
with TFinContaCorrenteFch.Create(Self) do
begin
Result := Start(ClickedButton, Sender, False, PosID1, PosID2, '', '', nil);
Free;
end;
end;
function TDM.quBancoClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
begin
inherited;
with TFinBancoFch.Create(Self) do
begin
Result := Start(ClickedButton, Sender, False, PosID1, PosID2, '', '', nil);
Free;
end;
end;
function TDM.quBancoAgenciaClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
begin
inherited;
with TFinBancoAgenciaFch.Create(Self) do
begin
Result := Start(ClickedButton, Sender, False, PosID1, PosID2, '', '', nil);
Free;
end;
end;
function TDM.quPessoaClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
begin
inherited;
with TSisPessoaFch.Create(Self) do
begin
if (ClickedButton = btInc) and (quPessoa.FilterFields.IndexOf('IDTipoPessoa') <> -1) then
Param := Param + 'IDTipoPessoa=' +
quPessoa.FilterValues.Strings[quPessoa.FilterFields.IndexOf('IDTipoPessoa')]+';';
Result := Start(ClickedButton, Sender, False, PosID1, PosID2, '', '', nil);
Free;
end;
end;
function TDM.quEmpresaClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
begin
inherited;
with TSisEmpresaFch.Create(Self) do
begin
Result := Start(ClickedButton, Sender, False, PosID1, PosID2, '', '', nil);
Free;
end;
end;
function TDM.quLancamentoTipoClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
begin
inherited;
with TFinLancamentoTipoFch.Create(Self) do
begin
Result := Start(ClickedButton, Sender, False, PosID1, PosID2, '', '', nil);
Free;
end;
end;
function TDM.quCentroCustoClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
begin
inherited;
if ClickedButton = btInc then
begin
with TFinCentroCustoTBrw.Create(Self) do;
end
else
begin
with TFinCentroCustoFch.Create(Self) do
begin
Result := Start(ClickedButton, Sender, False, PosID1, PosID2, '', '', nil);
Free;
end;
end;
end;
function TDM.quDocumentoTipoClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
begin
inherited;
with TFinDocumentoTipoFch.Create(Self) do
begin
Result := Start(ClickedButton, Sender, False, PosID1, PosID2, '', '', nil);
Free;
end;
end;
function TDM.quDesdobramentoTipoClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
begin
inherited;
with TFinDesdobramentoTipoFch.Create(Self) do
begin
Result := Start(ClickedButton, Sender, False, PosID1, PosID2, '', '', nil);
Free;
end;
end;
function TDM.quUsuarioClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
begin
inherited;
with TSisUsuarioFch.Create(Self) do
begin
Result := Start(ClickedButton, Sender, False, PosID1, PosID2, '', '', nil);
Free;
end;
end;
function TDM.GetPaymentMediaType(IDMeioPag: Integer): Integer;
begin
Result := StrToInt(DescCodigo(['IDMeioPag'], [IntToStr(IDMeioPag)], 'MeioPag', 'Tipo'));
end;
function TDM.GetTaxInCost: Boolean;
begin
Result := FTaxInCost;
end;
function TDM.quLookUpMunicipioClickButton(Sender: TPowerADOQuery;
ClickedButton: TBtnCommandType; var PosID1, PosID2: String): Boolean;
begin
inherited;
with TSisMunicipio.Create(Self) do
begin
Result := Start(ClickedButton, Sender, False, PosID1, PosID2, '', '', nil);
Free;
end;
end;
end.
|
program MyChat;
uses SwinGame, sgTypes, SysUtils;
procedure LoadResources();
begin
LoadFontNamed('InputFont', 'arial.ttf', 14);
LoadFontNamed('DialogFont', 'arial.ttf', 14);
end;
procedure DisplayDialog(const msg: String; x,y: Integer);
var
msgWidth, promptWidth, msgHeight: Integer;
width, height: Integer;
outputFont: Font;
prompt: String = 'Press enter to continue...';
begin
outputFont := FontNamed('DialogFont');
msgWidth := TextWidth(outputFont, msg);
promptWidth := TextWidth(outputFont, prompt);
msgHeight := TextHeight(outputFont, msg);
if msgWidth > promptWidth then
width := msgWidth + 20 //10px left, right
else
width := promptWidth + 20;
height := msgHeight * 2 + 30; // 10px above, between + below
FillRectangle(ColorWhite, x, y, width, height);
DrawRectangle(ColorBlack, x, y, width, height);
DrawText(msg, ColorBlack, outputFont, x + 10, y + 10);
DrawText(prompt, ColorBlack, outputFont, x + 10, y + 20 + msgHeight);
RefreshScreen();
repeat
ProcessEvents();
until KeyTyped(VK_RETURN) or WindowCloseRequested();
end;
function ReadString(const prompt: String; x, y: Integer): String;
var
promptHeight: Integer;
inputAreaWidth, inputAreaHeight: Integer;
inputFont: Font;
begin
inputFont := FontNamed('InputFont');
promptHeight := TextHeight(inputFont, prompt);
inputAreaHeight := promptHeight * 2 + 30; // 10px above, between, below
inputAreaWidth := TextWidth(inputFont, StringOfChar('M',30)) + 20; //10px left, right
StartReadingText(ColorBlack, 30, inputFont, x + 10, y + promptHeight + 20);
while ReadingText() and not WindowCloseRequested() do
begin
ProcessEvents();
FillRectangle(ColorWhite, x, y, inputAreaWidth, inputAreaHeight);
DrawRectangle(ColorBlack, x, y, inputAreaWidth, inputAreaHeight);
DrawRectangle(ColorBlack, x + 8, y + promptHeight + 18, inputAreaWidth - 16, promptHeight + 4);
DrawText(prompt, ColorBlack, inputFont, x + 10, y + 10);
RefreshScreen();
end;
result := TextReadAsASCII();
end;
function ReadInteger(const prompt: String; x, y: Integer): Integer;
var
line: String;
num: Integer;
begin
line := ReadString(prompt, x, y);
while not WindowCloseRequested() and not TryStrToInt(line, num) do
begin
DisplayDialog('Please enter a whole number.', x, y);
line := ReadString(prompt, x, y);
end;
result := num;
end;
function ReadIntegerRange(const prompt: String; min, max, x, y: Integer): Integer;
var
errorMsg: String;
begin
result := ReadInteger(prompt, x, y);
while not WindowCloseRequested() and ((result < min) or (result > max)) do
begin
errorMsg := 'Please enter a number between ' + IntToStr(min) +
' and ' + IntToStr(max);
DisplayDialog(errorMsg, x, y);
result := ReadInteger(prompt, x, y);
end;
end;
procedure Main();
var
answer: String;
i: Integer;
begin
OpenGraphicsWindow('My Chat', 600, 600);
LoadDefaultColors();
LoadResources();
ClearScreen(ColorWhite);
answer := ReadString('Do you want to be a server?', 100, 100);
if answer = 'yes' then
begin
if CreateServer('MyChat', 50000) = nil then
begin
DisplayDialog('Server failed to start.', 100, 100);
exit;
end;
end
else
begin
if OpenConnection('ToServer', ReadString('Enter host address.', 100, 100), 50000) = nil then
begin
DisplayDialog('Unable to connect to that server.', 100, 100);
exit;
end;
SendMessageTo('Hello Server', 'ToServer');
end;
repeat
ProcessEvents();
CheckNetworkActivity();
ClearScreen(ColorWhite);
while HasMessages() do
begin
if answer = 'yes' then
begin
WriteLn(ReadMessageData('MyChat'));
end;
end;
RefreshScreen(60);
until WindowCloseRequested();
end;
begin
Main();
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.