text stringlengths 14 6.51M |
|---|
unit frm_InputHelper;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs;
type
TfrmInputHelper = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
private
{ Private declarations }
FEnableEx, FSizeChange, FActiveEx, FVisibleEx: Boolean;
FCompStr, FBeforText, FAfterText: string;
FBorderColor: TColor;
procedure UpdateView;
procedure SetActiveEx(const Value: Boolean);
procedure WndProc(var Message: TMessage); override;
public
{ Public declarations }
/// <summary> 输入法是否需要重新调整显示位置 </summary>
function ResetImeCompRect(var AImePosition: TPoint): Boolean;
function GetCandiText(const AIndex: Integer): string;
procedure SetCompositionString(const S: string);
procedure SetCaretString(const ABeforText, AAfterText: string);
procedure CompWndMove(const AHandle: THandle; const ACaretX, ACaretY: Integer);
procedure ShowEx;
procedure CloseEx;
property SizeChange: Boolean read FSizeChange;
property EnableEx: Boolean read FEnableEx write FEnableEx;
property ActiveEx: Boolean read FActiveEx write SetActiveEx;
property VisibleEx: Boolean read FVisibleEx;
end;
var
frmInputHelper: TfrmInputHelper;
implementation
{$R *.dfm}
procedure TfrmInputHelper.CloseEx;
begin
ShowWindow(Handle, SW_HIDE);
FVisibleEx := False;
end;
procedure TfrmInputHelper.CompWndMove(const AHandle: THandle; const ACaretX,
ACaretY: Integer);
var
vPt: TPoint;
begin
vPt.X := ACaretX;
vPt.Y := ACaretY;
Windows.ClientToScreen(AHandle, vPt);
Left := vPt.X + 2;
Top := vPt.Y + 4;
if FCompStr <> '' then // 有知识
ShowEx;
end;
procedure TfrmInputHelper.FormCreate(Sender: TObject);
begin
Self.FormStyle := fsStayOnTop;
Self.DoubleBuffered := True;
FSizeChange := False;
FEnableEx := False;
FActiveEx := False;
FVisibleEx := False;
FBorderColor := $00D2C5B5;
end;
procedure TfrmInputHelper.FormPaint(Sender: TObject);
var
vRect: TRect;
vText: string;
begin
if not FActiveEx then
Canvas.Brush.Color := $00FFFEFE
else
Canvas.Brush.Color := clBtnFace;
vRect := ClientRect;
Canvas.Pen.Color := FBorderColor;
Canvas.Rectangle(vRect);
if FCompStr <> '' then
vText := '1.第1项 2.第2项 3.第3项 4.第4项 5.第5项'
else
vText := '你好,我正在学习相关知识^_^';
InflateRect(vRect, -5, -5);
Canvas.TextRect(vRect, vText, [tfVerticalCenter, tfSingleLine]);
end;
function TfrmInputHelper.GetCandiText(const AIndex: Integer): string;
begin
Result := '第' + IntToStr(AIndex + 1) + '项';
end;
function TfrmInputHelper.ResetImeCompRect(var AImePosition: TPoint): Boolean;
begin
Result := False;
if True then // 有知识
begin
AImePosition.Y := AImePosition.Y + Height + 2; // 原输入法下移
{CompWndMove(AHandle, ACaretX, ACaretY);
vPt.X := ACaretX;
vPt.Y := ACaretY;
ClientToScreen(AHandle, vPt);
Show(vPt.X + 2, vPt.Y + 4);}
Result := True;
end;
end;
procedure TfrmInputHelper.SetActiveEx(const Value: Boolean);
begin
if FActiveEx <> Value then
begin
FActiveEx := Value;
UpdateView;
end;
end;
procedure TfrmInputHelper.SetCaretString(const ABeforText, AAfterText: string);
begin
FBeforText := ABeforText;
FAfterText := AAfterText;
UpdateView;
end;
procedure TfrmInputHelper.SetCompositionString(const S: string);
begin
FSizeChange := False;
if FCompStr <> S then
begin
FCompStr := S;
{ TODO : 新的输入,重新匹配知识词条 }
if FCompStr <> '' then // 有知识
begin
if not FVisibleEx then
ShowEx
else
UpdateView;
end
else // 无知识
CloseEx;
end;
end;
procedure TfrmInputHelper.ShowEx;
begin
FActiveEx := False;
if not FVisibleEx then
begin
ShowWindow(Handle, SW_SHOWNOACTIVATE);
FVisibleEx := True;
end;
end;
procedure TfrmInputHelper.UpdateView;
begin
if (Self.FVisibleEx) then
InvalidateRect(Handle, ClientRect, False);
end;
procedure TfrmInputHelper.WndProc(var Message: TMessage);
begin
if Message.Msg = WM_MOUSEACTIVATE then
begin
Message.Result := MA_NOACTIVATE;
Exit;
end
else
if Message.Msg = WM_NCACTIVATE then
begin
if (Message.WParam and $FFFF) <> WA_INACTIVE then
begin
if Message.LParam = 0 then
SetActiveWindow(Message.LParam)
else
SetActiveWindow(0);
end;
end;
inherited WndProc(Message);
end;
end.
|
unit Entity;
{$mode delphi}
interface
uses
Types, SysUtils, Graphics, ExtCtrls, Contnrs;
type
TOrientation = (up, down, left, right);
TRealPoint = record
X, Y: Real;
end;
TEntity = class
protected
PaintBox: TPaintBox;
EntList: TFPObjectList;
procedure DrawLine(x1, y1, x2, y2: Real);
procedure DrawRectangle(x1, y1, x2, y2: Real);
procedure DrawFillRect(x1, y1, x2, y2: Real);
procedure DrawEllipse(x1, y1, x2, y2: Real);
function RotatePoint(x, y: Real): TRealPoint;
function TransformPoint(x, y: Real): TPoint;
function GetTopLeft: TRealPoint;
function GetBottomRight: TRealPoint;
public
Orientation: TOrientation;
X, Y, Width, Height: Real;
MaxSpeed, Speed: Real;
Delete: Boolean;
constructor Create;
procedure LinkEntList(var l: TFPObjectList);
procedure Paint; virtual;
procedure LinkPaintBox(var PaintBox: TPaintBox);
function Think: Boolean; virtual;
procedure Touch(e: TEntity); virtual;
procedure Click; virtual;
property TopLeft: TRealPoint read GetTopLeft;
property BottomRight: TRealPoint read GetBottomRight;
end;
implementation
constructor TEntity.Create;
begin
self.x := 0; self.y := 0;
self.width := 0; self.height := 0;
self.MaxSpeed := 0; self.Speed := 0;
self.orientation := up;
self.Delete := false;
end;
procedure TEntity.LinkEntList;
begin
self.EntList := l;
end;
procedure TEntity.LinkPaintBox;
begin
self.PaintBox := PaintBox;
end;
function TEntity.GetTopLeft;
begin
if self.orientation in [up, down] then
begin
Result.x := self.x - 1/2 * self.width;
Result.y := self.y - 1/2 * self.height;
end
else
begin
Result.x := self.x - 1/2 * self.height;
Result.y := self.y - 1/2 * self.width;
end;
end;
function TEntity.GetBottomRight;
begin
if self.orientation in [up, down] then
begin
Result.x := self.x + 1/2 * self.width;
Result.y := self.y + 1/2 * self.height;
end
else
begin
Result.x := self.x + 1/2 * self.height;
Result.y := self.y + 1/2 * self.width;
end;
end;
function TEntity.RotatePoint;
var
phi, xn, yn: Real;
begin
case self.orientation of
up: phi := 0;
left: phi := 3/2 * Pi;
down: phi := Pi;
right: phi := 1/2 * Pi;
end;
xn := x * cos(phi) - y * sin(phi);
yn := x * sin(phi) + y * cos(phi);
if self.orientation in [up, down] then
begin
xn := self.x + 1/2 * xn * self.width;
yn := self.y + 1/2 * yn * self.height;
end
else
begin
xn := self.x + 1/2 * xn * self.height;
yn := self.y + 1/2 * yn * self.width;
end;
Result.X := xn;
Result.Y := yn;
end;
function TEntity.TransformPoint;
var
p: TRealPoint;
begin
p := self.RotatePoint(X, Y);
Result := Point(Round(p.X * self.PaintBox.Width),
Round(p.Y * self.PaintBox.Height));
end;
procedure TEntity.DrawLine;
var
p1, p2: TPoint;
begin
p1 := self.TransformPoint(x1, y1);
p2 := self.TransformPoint(x2, y2);
with self.PaintBox.Canvas do
begin
MoveTo(p1);
LineTo(p2);
end;
end;
procedure TEntity.DrawRectangle;
var
p1, p2: TPoint;
begin
p1 := self.TransformPoint(x1, y1);
p2 := self.TransformPoint(x2, y2);
self.PaintBox.Canvas.Rectangle(p1.x, p1.y, p2.x, p2.y);
end;
procedure TEntity.DrawFillRect;
var
p1, p2: TPoint;
begin
p1 := self.TransformPoint(x1, y1);
p2 := self.TransformPoint(x2, y2);
self.PaintBox.Canvas.FillRect(p1.x, p1.y, p2.x, p2.y);
end;
procedure TEntity.DrawEllipse;
var
p1, p2: TPoint;
begin
p1 := self.TransformPoint(x1, y1);
p2 := self.TransformPoint(x2, y2);
self.PaintBox.Canvas.Ellipse(p1.x, p1.y, p2.x, p2.y);
end;
function TEntity.Think;
begin
Result := true;
end;
procedure TEntity.Paint;
begin
{ nothing }
end;
procedure TEntity.Touch;
begin
{ nothing }
end;
procedure TEntity.Click;
begin
{ nothing }
end;
end.
|
unit Data.User.Preferences;
interface
uses
System.SysUtils,
System.Classes;
type
IPreferences = interface
['{46F1A60D-634F-4F0F-AB8B-6A13FBE15A14}']
function GetFavourable(const AKeyword: String): Boolean;
function GetUnfavourable(const AKeyword: String): Boolean;
property Favourable[const AKeyword: String]: Boolean read GetFavourable;
property Unfavourable[const AKeywords: String]: Boolean read GetUnfavourable;
function GetAllPreferences: TStringList;
end;
implementation
end.
|
unit MeshSmoothSBGAMESDraft;
// This is the first type of mesh smooth made for this program. It works with
// manifold meshes that are regular (or as regular as possible) and all its edges
// should be in the same size. In short, it is a terrible way to smooth meshes
// and it is here just for comparison purposes. It works similarly as Taubin's
// Smooth. However, it is very quick and using a good filter with an almost
// regular mesh may make the results look good with a single interaction.
interface
uses MeshProcessingBase, Mesh, BasicMathsTypes, BasicDataTypes, NeighborDetector, LOD;
{$INCLUDE source/Global_Conditionals.inc}
type
TMeshSmoothSBGAMES2010Draft = class (TMeshProcessingBase)
protected
procedure MeshSmoothOperation(var _Vertices: TAVector3f; _NumVertices: integer; const _NeighborDetector : TNeighborDetector; const _VertexEquivalences: auint32);
procedure DoMeshProcessing(var _Mesh: TMesh); override;
public
DistanceFunction: TDistanceFunc;
constructor Create(var _LOD: TLOD); override;
end;
implementation
uses MeshPluginBase, NeighborhoodDataPlugin, GLConstants, Math, DistanceFormulas;
constructor TMeshSmoothSBGAMES2010Draft.Create(var _LOD: TLOD);
begin
inherited Create(_LOD);
DistanceFunction := GetLinearDistance;
end;
procedure TMeshSmoothSBGAMES2010Draft.DoMeshProcessing(var _Mesh: TMesh);
var
NeighborDetector : TNeighborDetector;
NeighborhoodPlugin : PMeshPluginBase;
NumVertices: integer;
VertexEquivalences: auint32;
begin
NeighborhoodPlugin := _Mesh.GetPlugin(C_MPL_NEIGHBOOR);
if NeighborhoodPlugin <> nil then
begin
NeighborDetector := TNeighborhoodDataPlugin(NeighborhoodPlugin^).VertexNeighbors;
NumVertices := TNeighborhoodDataPlugin(NeighborhoodPlugin^).InitialVertexCount;
VertexEquivalences := TNeighborhoodDataPlugin(NeighborhoodPlugin^).VertexEquivalences;
end
else
begin
NeighborDetector := TNeighborDetector.Create;
NeighborDetector.BuildUpData(_Mesh.Geometry,High(_Mesh.Vertices)+1);
NumVertices := High(_Mesh.Vertices)+1;
VertexEquivalences := nil;
end;
MeshSmoothOperation(_Mesh.Vertices,NumVertices,NeighborDetector,VertexEquivalences);
// Free memory
if NeighborhoodPlugin = nil then
begin
NeighborDetector.Free;
end;
_Mesh.ForceRefresh;
end;
procedure TMeshSmoothSBGAMES2010Draft.MeshSmoothOperation(var _Vertices: TAVector3f; _NumVertices: integer; const _NeighborDetector : TNeighborDetector; const _VertexEquivalences: auint32);
var
HitCounter: single;
OriginalVertexes: TAVector3f;
v,v1 : integer;
begin
SetLength(OriginalVertexes,High(_Vertices)+1);
BackupVector3f(_Vertices,OriginalVertexes);
// Sum up vertices with its neighbours, using the desired distance formula.
for v := Low(_Vertices) to (_NumVertices-1) do
begin
_Vertices[v].X := 0;
_Vertices[v].Y := 0;
_Vertices[v].Z := 0;
HitCounter := 0;
v1 := _NeighborDetector.GetNeighborFromID(v);
while v1 <> -1 do
begin
_Vertices[v].X := _Vertices[v].X + (OriginalVertexes[v1].X - OriginalVertexes[v].X);
_Vertices[v].Y := _Vertices[v].Y + (OriginalVertexes[v1].Y - OriginalVertexes[v].Y);
_Vertices[v].Z := _Vertices[v].Z + (OriginalVertexes[v1].Z - OriginalVertexes[v].Z);
HitCounter := HitCounter + 1;
v1 := _NeighborDetector.GetNextNeighbor;
end;
// Finally, we do an average for all vertices.
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Mesh Value (' + FloatToStr(_Vertices[v].X) + ', ' + FloatToStr(_Vertices[v].Y) + ', ' +FloatToStr(_Vertices[v].Z) + ') with ' + FloatToStr(HitCounter) + ' neighbours. Expected frequencies: (' + FloatToStr(_Vertices[v].X / HitCounter) + ', ' + FloatToStr(_Vertices[v].Y / HitCounter) + ', ' + FloatToStr(_Vertices[v].Z / HitCounter) + ')');
{$endif}
if HitCounter > 0 then
begin
_Vertices[v].X := OriginalVertexes[v].X + DistanceFunction((_Vertices[v].X) / HitCounter);
_Vertices[v].Y := OriginalVertexes[v].Y + DistanceFunction((_Vertices[v].Y) / HitCounter);
_Vertices[v].Z := OriginalVertexes[v].Z + DistanceFunction((_Vertices[v].Z) / HitCounter);
end
else
begin
_Vertices[v].X := OriginalVertexes[v].X;
_Vertices[v].Y := OriginalVertexes[v].Y;
_Vertices[v].Z := OriginalVertexes[v].Z;
end;
end;
v := _NumVertices;
while v <= High(_Vertices) do
begin
v1 := GetEquivalentVertex(v,_NumVertices,_VertexEquivalences);
_Vertices[v].X := _Vertices[v1].X;
_Vertices[v].Y := _Vertices[v1].Y;
_Vertices[v].Z := _Vertices[v1].Z;
inc(v);
end;
// Free memory
SetLength(OriginalVertexes,0);
end;
end.
|
{$I CetusOptions.inc}
unit ctsMemoryPools;
interface
uses
ctsTypesDef,
ctsBaseInterfaces,
ctsBaseClasses;
type
//& 轻型内存池,空闲内存没有大小限制。
TctsMiniMemoryPool = class(TctsNamedClass, IctsMemoryPool)
private
FBlockSize: LongWord;
FBlockStack: Pointer;
FNodeQuantity: LongWord;
FNodeSize: LongWord;
FNodeStack: Pointer;
protected
procedure GrowStack;
public
constructor Create; overload;
constructor Create(const ANodeSize: LongWord; const ANodeQuantity: LongWord = ctsDefaultNodeQuantity); overload;
destructor Destroy; override;
procedure Delete(ANode: Pointer);
function New: Pointer;
function NewClear: Pointer;
end;
implementation
type
PPoolNode = ^TPoolNode;
TPoolNode = record
Link: PPoolNode;
end;
constructor TctsMiniMemoryPool.Create;
begin
inherited Create;
Create(SizeOf(Pointer));
end;
constructor TctsMiniMemoryPool.Create(const ANodeSize: LongWord; const ANodeQuantity: LongWord = ctsDefaultNodeQuantity);
begin
inherited Create;
FNodeSize := ANodeSize;
FNodeQuantity := ANodeQuantity;
FBlockSize := ANodeQuantity * ANodeSize + SizeOf(Pointer);
end;
destructor TctsMiniMemoryPool.Destroy;
var
P: Pointer;
begin
while (FBlockStack <> nil) do
begin
P := PPoolNode(FBlockStack)^.Link;
FreeMem(FBlockStack, FBlockSize);
FBlockStack := P;
end;
inherited Destroy;
end;
procedure TctsMiniMemoryPool.Delete(ANode: Pointer);
begin
if ANode <> nil then
begin
{$IFDEF DEBUG}
FillChar(ANode^, FNodeSize, ctsDebugSign);
{$ENDIF}
PPoolNode(ANode)^.Link := FNodeStack;
FNodeStack := ANode;
end;
end;
procedure TctsMiniMemoryPool.GrowStack;
var
NewBlock: PAnsiChar;
Temp: Pointer;
I: LongInt;
begin
GetMem(NewBlock, FBlockSize);
PPoolNode(NewBlock)^.Link := FBlockStack;
FBlockStack := NewBlock;
Inc(NewBlock, SizeOf(Pointer));
Temp := FNodeStack;
for I := 1 to FNodeQuantity do
begin
PPoolNode(NewBlock)^.Link := Temp;
Temp := NewBlock;
Inc(NewBlock, FNodeSize);
end;
FNodeStack := Temp;
end;
function TctsMiniMemoryPool.New: Pointer;
begin
if (FNodeStack = nil) then
GrowStack;
Result := FNodeStack;
FNodeStack := PPoolNode(Result)^.Link;
end;
function TctsMiniMemoryPool.NewClear: Pointer;
begin
if (FNodeStack = nil) then
GrowStack;
Result := FNodeStack;
FNodeStack := PPoolNode(Result)^.Link;
FillChar(Result^, FNodeSize, 0);
end;
end.
|
{:
GLSL Shader Component Demo<p>
A demo that shows how to use the TGLSLShader component.
Version history:
30/03/07 - DaStr - Cleaned up "uses" section
20/03/07 - DaStr - Initial version
}
unit umainform;
interface
uses
// VCL
SysUtils, Classes, Controls, Forms, ExtCtrls, StdCtrls,
// GLScene
GLTexture, GLCadencer, GLViewer, GLScene, GLObjects,
GLGraph, VectorLists, VectorTypes, VectorGeometry, GLSLShader,
GLGeomObjects, GLVectorFileObjects, GLSimpleNavigation, GLCustomShader,
GLCrossPlatform, GLMaterial, GLCoordinates, BaseClasses,
// FileFormats
GLFileMD2, GLFileMS3D, GLFile3DS;
type
{ TGLSLTestForm }
TGLSLTestForm = class(TForm)
Scene: TGLScene;
Viewer: TGLSceneViewer;
Cadencer: TGLCadencer;
Camera: TGLCamera;
Light: TGLLightSource;
LightCube: TGLDummyCube;
GLSphere1: TGLSphere;
GLXYZGrid1: TGLXYZGrid;
GLArrowLine1: TGLArrowLine;
Panel1: TPanel;
LightMovingCheckBox: TCheckBox;
GUICube: TGLDummyCube;
WorldCube: TGLDummyCube;
Fighter: TGLActor;
Teapot: TGLActor;
Sphere_big: TGLActor;
Sphere_little: TGLActor;
MaterialLibrary: TGLMaterialLibrary;
ShadeEnabledCheckBox: TCheckBox;
TurnPitchrollCheckBox: TCheckBox;
GLSLShader: TGLSLShader;
GLSimpleNavigation1: TGLSimpleNavigation;
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure CadencerProgress(Sender: TObject; const deltaTime, newTime: double);
procedure LightCubeProgress(Sender: TObject; const deltaTime, newTime: double);
procedure ShadeEnabledCheckBoxClick(Sender: TObject);
procedure GLSLShaderApply(Shader: TGLCustomGLSLShader);
procedure GLSLShaderInitialize(Shader: TGLCustomGLSLShader);
procedure GLSLShaderUnApply(Shader: TGLCustomGLSLShader;
var ThereAreMorePasses: boolean);
private
{ Private declarations }
public
{ Public declarations }
end;
var
GLSLTestForm: TGLSLTestForm;
implementation
{$R *.lfm}
uses
FileUtil;
procedure TGLSLTestForm.FormCreate(Sender: TObject);
var
path: UTF8String;
p: integer;
begin
path := ExtractFilePath(ParamStrUTF8(0));
p := Pos('DemosLCL', path);
Delete(path, p + 5, Length(path));
path := IncludeTrailingPathDelimiter(path) + 'media';
SetCurrentDirUTF8(path);
// First load models.
Fighter.LoadFromFile('waste.md2'); //Fighter
Fighter.SwitchToAnimation(0, True);
Fighter.AnimationMode := aamLoop;
Fighter.Scale.Scale(3);
Teapot.LoadFromFile('Teapot.3ds'); //Teapot (no texture coordinates)
Teapot.Scale.Scale(0.8);
Sphere_big.LoadFromFile('Sphere_big.3ds'); //Sphere_big
Sphere_big.Scale.Scale(70);
Sphere_little.LoadFromFile('Sphere_little.3ds'); //Sphere_little
Sphere_little.Scale.Scale(4);
// Then load textures.
MaterialLibrary.LibMaterialByName('Earth').Material.Texture.Image.LoadFromFile(
'Earth.jpg');
// Shader.
GLSLShader.Enabled := True;
end;
procedure TGLSLTestForm.FormClose(Sender: TObject; var CloseAction: TCloseAction
);
begin
Cadencer.Enabled := False;
end;
procedure TGLSLTestForm.ShadeEnabledCheckBoxClick(Sender: TObject);
begin
GLSLShader.Enabled := ShadeEnabledCheckBox.Checked;
end;
procedure TGLSLTestForm.GLSLShaderApply(Shader: TGLCustomGLSLShader);
begin
with Shader do
begin
Param['DiffuseColor'].AsVector4f := VectorMake(1, 1, 1, 1);
Param['AmbientColor'].AsVector4f := VectorMake(0.2, 0.2, 0.2, 1);
Param['LightIntensity'].AsVector1f := 1;
Param['MainTexture'].AsTexture2D[0] :=
MaterialLibrary.LibMaterialByName('Earth').Material.Texture;
end;
end;
procedure TGLSLTestForm.GLSLShaderInitialize(Shader: TGLCustomGLSLShader);
begin
with Shader do
begin
// Nothing.
end;
end;
procedure TGLSLTestForm.GLSLShaderUnApply(Shader: TGLCustomGLSLShader;
var ThereAreMorePasses: boolean);
begin
with Shader do
begin
// Nothing.
end;
end;
procedure TGLSLTestForm.CadencerProgress(Sender: TObject;
const deltaTime, newTime: double);
begin
Viewer.Invalidate;
if TurnPitchrollCheckBox.Checked then
begin
Sphere_big.Pitch(40 * deltaTime);
Sphere_big.Turn(40 * deltaTime);
Sphere_little.Roll(40 * deltaTime);
end;
end;
procedure TGLSLTestForm.LightCubeProgress(Sender: TObject;
const deltaTime, newTime: double);
begin
if LightMovingCheckBox.Checked then
LightCube.MoveObjectAround(Camera.TargetObject, sin(NewTime) *
deltaTime * 10, deltaTime * 20);
end;
end.
|
unit Q_Sectors;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Q_Utils, misc_utils, Level, MultiSelection, Buttons;
type
TFindSectors = class(TForm)
Label1: TLabel;
CBID: TComboBox;
EBID: TEdit;
LBName: TLabel;
CBName: TComboBox;
EBName: TEdit;
Label3: TLabel;
CBFlags: TComboBox;
EBFlags: TEdit;
Label4: TLabel;
CBPalette: TComboBox;
EBPalette: TEdit;
Label5: TLabel;
CBFOverlay_TX: TComboBox;
EBFOverlay_TX: TEdit;
Label7: TLabel;
CBAmbient: TComboBox;
EBAmbient: TEdit;
GroupBox1: TGroupBox;
RBAdd: TRadioButton;
RBSubtract: TRadioButton;
RBFocus: TRadioButton;
BNFind: TButton;
BNCancel: TButton;
CBSelOnly: TCheckBox;
BNPalette: TButton;
VBNFOverlay_TX: TButton;
BNFlags: TButton;
Label2: TLabel;
CBCMap: TComboBox;
EBCMap: TEdit;
BNCMap: TButton;
Label8: TLabel;
CBFriction: TComboBox;
EBFriction: TEdit;
Label9: TLabel;
CBGravity: TComboBox;
EBGravity: TEdit;
Label10: TLabel;
CBElasticity: TComboBox;
EBElasticity: TEdit;
Label11: TLabel;
CBVel_X: TComboBox;
EBVel_X: TEdit;
Label12: TLabel;
CBVel_Y: TComboBox;
EBVel_Y: TEdit;
Label13: TLabel;
CBVel_Z: TComboBox;
EBVel_Z: TEdit;
Label14: TLabel;
CBVAdjoin: TComboBox;
EBVAdjoin: TEdit;
CBFSound: TComboBox;
BNFSound: TButton;
EBFSound: TEdit;
Label15: TLabel;
Label16: TLabel;
CBFloor_Y: TComboBox;
EBFloor_Y: TEdit;
Label17: TLabel;
CBFloor_TX: TComboBox;
EBFloor_TX: TEdit;
BNFloor_TX: TButton;
Label18: TLabel;
CBCeiling_TX: TComboBox;
EBCeiling_TX: TEdit;
BNCeiling_TX: TButton;
Label19: TLabel;
CBCeiling_Y: TComboBox;
EBCeiling_Y: TEdit;
Label20: TLabel;
CBCOverlay_TX: TComboBox;
EBCOverlay_TX: TEdit;
BNCOverlay_TX: TButton;
Label6: TLabel;
CBLayer: TComboBox;
EBLayer: TEdit;
SBHelp: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure BNPaletteClick(Sender: TObject);
procedure BNCMapClick(Sender: TObject);
procedure BNFSoundClick(Sender: TObject);
procedure BNFloor_TXClick(Sender: TObject);
procedure BNCeiling_TXClick(Sender: TObject);
procedure VBNFOverlay_TXClick(Sender: TObject);
procedure BNCOverlay_TXClick(Sender: TObject);
procedure BNFlagsClick(Sender: TObject);
procedure SBHelpClick(Sender: TObject);
private
{ Private declarations }
fi:TSectorFindInfo;
public
{ Public declarations }
MapWindow:TForm;
Function Find:Boolean;
Function FindNext(curSC:integer):boolean;
end;
var
FindSectors: TFindSectors;
implementation
uses ResourcePicker, FlagEditor, Mapper;
{$R *.DFM}
procedure TFindSectors.FormCreate(Sender: TObject);
begin
ClientWidth:=Label15.Left+BNFlags.Left+BNFlags.Width;
ClientHeight:=Label1.Top+BNFind.Top+BNFind.Height;
fi:=TSectorFindInfo.Create;
TQueryField.CreateHex(CBID,EBID,fi.HexID);
TQueryField.CreateStr(CBName,EBName,fi.Name);
TQueryField.CreateInt(CBAmbient,EBAmbient,fi.Ambient);
TQueryField.CreateStr(CBPalette,EBPalette,fi.Palette);
TQueryField.CreateStr(CBCmap,EBCmap,fi.ColorMap);
TQueryField.CreateDouble(CBFriction,EBFriction,fi.Friction);
TQueryField.CreateDouble(CBGravity,EBGravity,fi.Gravity);
TQueryField.CreateDouble(CBElasticity,EBElasticity,fi.Elasticity);
TQueryField.CreateStr(CBFSound,EBFSound,fi.Floor_sound);
TQueryField.CreateDouble(CBFloor_Y,EBFloor_Y,fi.Floor_Y);
TQueryField.CreateDouble(CBCeiling_Y,EBCeiling_Y,fi.Ceiling_Y);
TQueryField.CreateStr(CBFloor_TX,EBFloor_TX,fi.Floor_TX);
TQueryField.CreateStr(CBCeiling_TX,EBCeiling_TX,fi.Ceiling_TX);
TQueryField.CreateStr(CBFOverlay_TX,EBFOverlay_TX,fi.F_Overlay_TX);
TQueryField.CreateStr(CBCOverlay_TX,EBCOverlay_TX,fi.C_Overlay_TX);
TQueryField.CreateFlags(CBFlags,EBFlags,fi.Flags);
TQueryField.CreateInt(CBLayer,EBLayer,fi.Layer);
TQueryField.CreateDouble(CBVel_X,EBVel_X,fi.Velocity_X);
TQueryField.CreateDouble(CBVel_Y,EBVel_Y,fi.Velocity_Y);
TQueryField.CreateDouble(CBVel_Z,EBVel_Z,fi.Velocity_Z);
TQueryField.CreateInt(CBVAdjoin,EBVAdjoin,fi.VAdjoin);
end;
procedure TFindSectors.BNPaletteClick(Sender: TObject);
begin
EBPalette.Text:=ResPicker.PickPalette(EBPalette.Text);
end;
procedure TFindSectors.BNCMapClick(Sender: TObject);
begin
EBCMap.Text:=ResPicker.PickPalette(EBCMap.Text);
end;
procedure TFindSectors.BNFSoundClick(Sender: TObject);
begin
EBFSound.Text:=ResPicker.PickFloorSound(EBFSound.Text);
end;
procedure TFindSectors.BNFloor_TXClick(Sender: TObject);
begin
EBFloor_TX.Text:=ResPicker.PickTexture(EBFloor_TX.Text);
end;
procedure TFindSectors.BNCeiling_TXClick(Sender: TObject);
begin
EBCeiling_TX.Text:=ResPicker.PickTexture(EBCeiling_TX.Text);
end;
procedure TFindSectors.VBNFOverlay_TXClick(Sender: TObject);
begin
EBFOverlay_TX.Text:=ResPicker.PickTexture(EBFOverlay_TX.Text);
end;
procedure TFindSectors.BNCOverlay_TXClick(Sender: TObject);
begin
EBCOverlay_TX.Text:=ResPicker.PickTexture(EBCOverlay_TX.Text);
end;
procedure TFindSectors.BNFlagsClick(Sender: TObject);
var F:Longint;
begin
ValDword(EBFlags.Text,f);
f:=FlagEdit.EditSectorFlags(f);
EBFlags.Text:=DwordToStr(f);
end;
Function TFindSectors.Find;
var Lev:TLevel;
nSc,s:Integer;
Ms:TMultiSelection;
begin
Result:=false;
Lev:=TMapWindow(MapWindow).Level;
ms:=TMapWindow(MapWindow).SCMultiSel;
if ShowModal<>mrOK then exit;
if RBAdd.Checked then
begin
s:=FindNextSector(Lev,-1,fi);
While s<>-1 do
begin
if ms.FindSector(s)=-1 then ms.AddSector(s);
s:=FindNextSector(Lev,s,fi);
Result:=true;
end;
end;
if RBSubtract.Checked then
begin
s:=FindNextSector(Lev,-1,fi);
While s<>-1 do
begin
nSc:=ms.FindSector(s);
if nSc<>-1 then ms.Delete(nSc);
s:=FindNextSector(Lev,s,fi);
Result:=true;
end;
end;
if RBFocus.Checked then
begin
s:=FindNextSector(Lev,-1,fi);
if s<>-1 then
begin TMapWindow(MapWindow).Goto_Sector(s); Result:=true; end;
end;
if not Result then ShowMessage('No hits!');
end;
Function TFindSectors.FindNext(curSC:Integer):Boolean;
var s:Integer;Lev:TLevel;
begin
Lev:=TMapWindow(MapWindow).Level;
s:=FindNextSector(Lev,CurSC,fi);
if s<>-1 then
begin
TMapWindow(MapWindow).Goto_Sector(s);
Result:=true;
end;
Result:=s<>-1;
if not Result then ShowMessage('No more hits!');
end;
procedure TFindSectors.SBHelpClick(Sender: TObject);
begin
Application.HelpJump('Hlp_Find_Sectors');
end;
end.
|
unit ufrmDialogMerchandiseGroup;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmMasterDialog, System.Actions,
Vcl.ActnList, ufraFooterDialog3Button, Vcl.ExtCtrls, uModBarang, uInterface,
Vcl.StdCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit,
cxDBLookupEdit, cxDBExtLookupComboBox, uModSuplier;
type
TfrmDialogMerchandiseGroup = class(TfrmMasterDialog, ICRUDAble)
lbKode: TLabel;
edtCode: TEdit;
edtName: TEdit;
lbNama: TLabel;
cxLookupMerchan: TcxExtLookupComboBox;
lbDivision: TLabel;
procedure actDeleteExecute(Sender: TObject);
procedure actSaveExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FModMerchandiseGroup: TModMerchandiseGroup;
function GetModMerchandiseGroup: TModMerchandiseGroup;
function ValidateData: Boolean;
{ Private declarations }
public
procedure LoadData(AID: String);
procedure SaveData;
property ModMerchandiseGroup: TModMerchandiseGroup read GetModMerchandiseGroup
write FModMerchandiseGroup;
{ Public declarations }
end;
var
frmDialogMerchandiseGroup: TfrmDialogMerchandiseGroup;
implementation
uses
uAppUtils, uConstanta, uDMClient, uDXUtils;
{$R *.dfm}
procedure TfrmDialogMerchandiseGroup.actDeleteExecute(Sender: TObject);
begin
inherited;
if not TAppUtils.Confirm(CONF_VALIDATE_FOR_DELETE) then exit;
Try
DMCLient.CrudClient.DeleteFromDB(ModMerchandiseGroup);
TAppUtils.Information(CONF_DELETE_SUCCESSFULLY);
Self.ModalResult := mrOk;
Self.Close;
except
TAppUtils.Error(ER_DELETE_FAILED);
raise;
End;
end;
procedure TfrmDialogMerchandiseGroup.actSaveExecute(Sender: TObject);
begin
inherited;
if not ValidateData then exit;
SaveData;
Self.ModalResult := mrOk;
end;
procedure TfrmDialogMerchandiseGroup.FormCreate(Sender: TObject);
begin
inherited;
cxLookupMerchan.LoadFromDS(DMClient.DSProviderClient.Merchandise_GetDSLookup,
'REF$MERCHANDISE_ID','MERCHAN_NAME' ,['REF$MERCHANDISE_ID'], Self);
Self.AssignKeyDownEvent;
end;
function TfrmDialogMerchandiseGroup.GetModMerchandiseGroup:
TModMerchandiseGroup;
begin
if not Assigned(FModMerchandiseGroup) then
FModMerchandiseGroup := TModMerchandiseGroup.Create;
Result := FModMerchandiseGroup;
end;
procedure TfrmDialogMerchandiseGroup.LoadData(AID: String);
begin
if Assigned(FModMerchandiseGroup) then FreeAndNil(FModMerchandiseGroup);
FModMerchandiseGroup := DMClient.CrudClient.Retrieve(TModMerchandiseGroup.ClassName, aID) as TModMerchandiseGroup;
edtCode.Text := ModMerchandiseGroup.MERCHANGRUP_CODE;
edtName.Text := ModMerchandiseGroup.MERCHANGRUP_NAME;
cxLookupMerchan.EditValue := ModMerchandiseGroup.Merchandise.ID;
end;
procedure TfrmDialogMerchandiseGroup.SaveData;
begin
ModMerchandiseGroup.MERCHANGRUP_CODE := edtCode.Text;
ModMerchandiseGroup.MERCHANGRUP_NAME := edtName.Text;
ModMerchandiseGroup.Merchandise := TModMerchandise.CreateID(cxLookupMerchan.EditValue);
Try
ModMerchandiseGroup.ID := DMClient.CrudClient.SaveToDBID(ModMerchandiseGroup);
TAppUtils.Information(CONF_ADD_SUCCESSFULLY);
except
TAppUtils.Error(ER_INSERT_FAILED);
raise;
End;
end;
function TfrmDialogMerchandiseGroup.ValidateData: Boolean;
begin
Result := False;
if VarIsNull(cxLookupMerchan.EditValue) then
begin
TAppUtils.Error('Merchandise wajib dipilih');
exit;
end;
if edtCode.Text = '' then
begin
TAppUtils.Error('Kode tidak boleh kosong');
exit;
end;
if edtName.Text = '' then
begin
TAppUtils.Error('Nama tidak boleh kosong');
exit;
end;
Result := True;
end;
end.
|
unit MyCat.BackEnd.Mysql.CrossSocket.Handler;
interface
uses
System.Generics.Collections, MyCat.Net.CrossSocket.Base, System.SysUtils,
MyCat.BackEnd.Mysql.CrossSocket.Handler.Generics.HeartBeatConnection,
MyCat.BackEnd, MyCat.BackEnd.Mysql.CrossSocket.Handler.ResponseHandler;
type
/// **
// * heartbeat check for mysql connections
// *
// * @author wuzhih
// *
// */
TConnectionHeartBeatHandler = class(TObject, IResponseHandler)
private
FAllConnections: THeartBeatConnectionHashMap;
public
constructor Create;
procedure DoHeartBeat(Connection: IBackEndConnection; SQL: string);
end;
// public class ConnectionHeartBeatHandler implements ResponseHandler {
//
// public void doHeartBeat(BackendConnection conn, String sql) {
// }
//
// /**
// * remove timeout connections
// */
// public void abandTimeOuttedConns() {
// if (allCons.isEmpty()) {
// return;
// }
// Collection<BackendConnection> abandCons = new LinkedList<BackendConnection>();
// long curTime = System.currentTimeMillis();
// Iterator<Entry<Long, HeartBeatCon>> itors = allCons.entrySet()
// .iterator();
// while (itors.hasNext()) {
// HeartBeatCon hbCon = itors.next().getValue();
// if (hbCon.timeOutTimestamp < curTime) {
// abandCons.add(hbCon.conn);
// itors.remove();
// }
// }
//
// if (!abandCons.isEmpty()) {
// for (BackendConnection con : abandCons) {
// try {
// // if(con.isBorrowed())
// con.close("heartbeat timeout ");
// } catch (Exception e) {
// LOGGER.warn("close err:" + e);
// }
// }
// }
//
// }
//
// @Override
// public void connectionAcquired(BackendConnection conn) {
// // not called
// }
//
// @Override
// public void connectionError(Throwable e, BackendConnection conn) {
// // not called
//
// }
//
// @Override
// public void errorResponse(byte[] data, BackendConnection conn) {
// removeFinished(conn);
// ErrorPacket err = new ErrorPacket();
// err.read(data);
// LOGGER.warn("errorResponse " + err.errno + " "
// + new String(err.message));
// conn.release();
//
// }
//
// @Override
// public void okResponse(byte[] ok, BackendConnection conn) {
// boolean executeResponse = conn.syncAndExcute();
// if (executeResponse) {
// removeFinished(conn);
// conn.release();
// }
//
// }
//
// @Override
// public void rowResponse(byte[] row, BackendConnection conn) {
// }
//
// @Override
// public void rowEofResponse(byte[] eof, BackendConnection conn) {
// removeFinished(conn);
// conn.release();
// }
//
// private void executeException(BackendConnection c, Throwable e) {
// removeFinished(c);
// LOGGER.warn("executeException ", e);
// c.close("heatbeat exception:" + e);
//
// }
//
// private void removeFinished(BackendConnection con) {
// Long id = ((BackendConnection) con).getId();
// this.allCons.remove(id);
// }
//
// @Override
// public void writeQueueAvailable() {
//
// }
//
// @Override
// public void connectionClose(BackendConnection conn, String reason) {
// removeFinished(conn);
// LOGGER.warn("connection closed " + conn + " reason:" + reason);
// }
//
// @Override
// public void fieldEofResponse(byte[] header, List<byte[]> fields,
// byte[] eof, BackendConnection conn) {
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("received field eof from " + conn);
// }
// }
//
// }
//
implementation
uses
MyCat.Util.Logger;
{ TConnectionHeartBeatHandler }
constructor TConnectionHeartBeatHandler.Create;
begin
FAllConnections := THeartBeatConnectionHashMap.Create;
end;
procedure TConnectionHeartBeatHandler.DoHeartBeat
(Connection: IBackEndConnection; SQL: string);
begin
AppendLog('do heartbeat for con ' + Connection.PeerAddr);
try
// HeartBeatCon hbCon = new HeartBeatCon(conn);
if FAllConnections.Find(Connection.UID) = FAllConnections.ItEnd then
begin
FAllConnections.Insert(Connection.UID,
THeartBeatConnection.Create(Connection));
Connection.SetResponseHandler(this);
Connection.query(SQL);
end;
except
on E: Exception do
begin
executeException(conn, E);
end;
end;
end;
end.
|
{: Basic terrain rendering demo.<p>
This demo showcases the TerrainRenderer, some of the SkyDome features
and bits of 3D sound 'cause I got carried over ;)<br>
The terrain HeightData is provided by a TGLBitmapHDS (HDS stands for
"Height Data Source"), and displayed by a TGLTerrainRenderer.<p>
The base terrain renderer uses a hybrid ROAM/brute-force approach to
rendering terrain, by requesting height data tiles, then rendering them
using either triangle strips (for those below "QualityDistance") or ROAM
tessellation.<br>
Note that if the terrain is wrapping in this sample (to reduce the required
datasets size), the engine is *not* aware of it and does not exploit this
fact in any way: it considers just an infinite terrain.<p>
Controls:<ul>
<li>Direction keys move the came nora (shift to speedup)
<li>PageUp/PageDown move the camera up and down
<li>Orient the camera freely by holding down the left button
<li>Toggle wireframe mode with 'w'
<li>Increase/decrease the viewing distance with '+'/'-'.
<li>Increase/decrease CLOD precision with '*' and '/'.
<li>Increase/decrease QualityDistance with '9' and '8'.
<li>'n' turns on 'night' mode, 'd' turns back to 'day' mode.
<li>Toggle star twinkle with 't' (night mode only)
<li>'l' turns on/off the lens flares
</ul><p>
When increasing the range, or moving after having increased the range you
may notice a one-time slowdown, this originates in the base height data
being duplicated to create the illusion of an "infinite" terrain (at max
range the visible area covers 1024x1024 height samples, and with tiles of
size 16 or less, this is a lot of tiles to prepare).<p>
Misc. note: since the whole viewer is fully repainted at each frame,
it was possible to set roNoColorBufferClear in the Viewer.Buffer.ContextOptions,
which allows to gain a few more frames per second (try unsetting it).
}
unit unit1;
interface
{þ$I GLScene.inc}
uses
SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
GLScene, GLTerrainRenderer, GLObjects, GLHeightData, GLColor,
ExtCtrls, GLCadencer, GLTexture, GLHUDObjects, GLBitmapFont,
GLSkydome, GLViewer, GLSound, GLSMBASS, VectorGeometry, GLLensFlare,
GLCrossPlatform, GLMaterial, GLCoordinates, GLState, GLFileMP3;
type
TForm1 = class(TForm)
GLSceneViewer1: TGLSceneViewer;
GLBitmapHDS1: TGLBitmapHDS;
GLScene1: TGLScene;
GLCamera1: TGLCamera;
DummyCube1: TGLDummyCube;
TerrainRenderer1: TGLTerrainRenderer;
Timer1: TTimer;
GLCadencer1: TGLCadencer;
GLMaterialLibrary1: TGLMaterialLibrary;
BitmapFont1: TGLBitmapFont;
HUDText1: TGLHUDText;
SkyDome1: TGLSkyDome;
SPMoon: TGLSprite;
SPSun: TGLSprite;
DCSound: TGLDummyCube;
GLSMBASS1: TGLSMBASS;
TISound: TTimer;
GLSoundLibrary: TGLSoundLibrary;
GLLensFlare: TGLLensFlare;
GLDummyCube1: TGLDummyCube;
InitialRenderPoint: TGLRenderPoint;
procedure GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure Timer1Timer(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure FormCreate(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure TISoundTimer(Sender: TObject);
private
{ Déclarations privées }
public
{ Déclarations publiques }
mx, my : Integer;
fullScreen : Boolean;
FCamHeight : Single;
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
uses GLKeyboard, FileUtil, LCLType;
procedure TForm1.FormCreate(Sender: TObject);
var
path: UTF8String;
p: Integer;
begin
path := ExtractFilePath(ParamStrUTF8(0));
p := Pos('DemosLCL', path);
Delete(path, p+5, Length(path));
path := IncludeTrailingPathDelimiter(path) + IncludeTrailingPathDelimiter('media');
SetCurrentDirUTF8(path);
// 8 MB height data cache
// Note this is the data size in terms of elevation samples, it does not
// take into account all the data required/allocated by the renderer
GLBitmapHDS1.MaxPoolSize:=8*1024*1024;
// specify height map data
GLBitmapHDS1.Picture.LoadFromFile('terrain.bmp');
// load the texture maps
GLMaterialLibrary1.Materials[0].Material.Texture.Image.LoadFromFile('snow512.jpg');
GLMaterialLibrary1.Materials[1].Material.Texture.Image.LoadFromFile('detailmap.jpg');
SPMoon.Material.Texture.Image.LoadFromFile('moon.bmp');
SPSun.Material.Texture.Image.LoadFromFile('flare1.bmp');
// apply texture map scale (our heightmap size is 256)
TerrainRenderer1.TilesPerTexture:=256/TerrainRenderer1.TileSize;
// load Bitmap Font
BitmapFont1.Glyphs.LoadFromFile('darkgold_font.bmp');
// load and setup sound samples
with GLSoundLibrary.Samples do begin
Add.LoadFromFile('ChillyWind.mp3');
Add.LoadFromFile('howl.mp3');
end;
// Could've been done at design time, but then it hurts the eyes ;)
GLSceneViewer1.Buffer.BackgroundColor:=clWhite;
// Move camera starting point to an interesting hand-picked location
DummyCube1.Position.X:=570;
DummyCube1.Position.Z:=-385;
DummyCube1.Turn(90);
// Initial camera height offset (controled with pageUp/pageDown)
FCamHeight:=10;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
var
speed : Single;
begin
// handle keypresses
if IsKeyDown(VK_SHIFT) then
speed:=5*deltaTime
else speed:=deltaTime;
with GLCamera1.Position do begin
if IsKeyDown(VK_UP) then
DummyCube1.Translate(Z*speed, 0, -X*speed);
if IsKeyDown(VK_DOWN) then
DummyCube1.Translate(-Z*speed, 0, X*speed);
if IsKeyDown(VK_LEFT) then
DummyCube1.Translate(-X*speed, 0, -Z*speed);
if IsKeyDown(VK_RIGHT) then
DummyCube1.Translate(X*speed, 0, Z*speed);
if IsKeyDown(VK_PRIOR) then
FCamHeight:=FCamHeight+10*speed;
if IsKeyDown(VK_NEXT) then
FCamHeight:=FCamHeight-10*speed;
if IsKeyDown(VK_ESCAPE) then Close;
end;
// don't drop through terrain!
with DummyCube1.Position do
Y:=TerrainRenderer1.InterpolatedHeight(AsVector)+FCamHeight;
end;
// Standard mouse rotation & FPS code below
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
mx:=x;
my:=y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if ssLeft in Shift then begin
GLCamera1.MoveAroundTarget((my-y)*0.5, (mx-x)*0.5);
mx:=x;
my:=y;
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
HUDText1.Text:=Format('%.1f FPS - %d',
[GLSceneViewer1.FramesPerSecond, TerrainRenderer1.LastTriangleCount]);
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
case Key of
'w', 'W' : with GLMaterialLibrary1.Materials[0].Material do begin
if PolygonMode=pmLines then
PolygonMode:=pmFill
else PolygonMode:=pmLines;
end;
'+' : if GLCamera1.DepthOfView<2000 then begin
GLCamera1.DepthOfView:=GLCamera1.DepthOfView*1.2;
with GLSceneViewer1.Buffer.FogEnvironment do begin
FogEnd:=FogEnd*1.2;
FogStart:=FogStart*1.2;
end;
end;
'-' : if GLCamera1.DepthOfView>300 then begin
GLCamera1.DepthOfView:=GLCamera1.DepthOfView/1.2;
with GLSceneViewer1.Buffer.FogEnvironment do begin
FogEnd:=FogEnd/1.2;
FogStart:=FogStart/1.2;
end;
end;
'*' : with TerrainRenderer1 do
if CLODPrecision>20 then CLODPrecision:=Round(CLODPrecision*0.8);
'/' : with TerrainRenderer1 do
if CLODPrecision<1000 then CLODPrecision:=Round(CLODPrecision*1.2);
'8' : with TerrainRenderer1 do
if QualityDistance>40 then QualityDistance:=Round(QualityDistance*0.8);
'9' : with TerrainRenderer1 do
if QualityDistance<1000 then QualityDistance:=Round(QualityDistance*1.2);
'n', 'N' : with SkyDome1 do if Stars.Count=0 then begin
// turn on 'night' mode
Bands[1].StopColor.AsWinColor:=RGB(0, 0, 16);
Bands[1].StartColor.AsWinColor:=RGB(0, 0, 8);
Bands[0].StopColor.AsWinColor:=RGB(0, 0, 8);
Bands[0].StartColor.AsWinColor:=RGB(0, 0, 0);
with Stars do begin
AddRandomStars(700, clWhite, True); // many white stars
AddRandomStars(100, RGB(255, 200, 200), True); // some redish ones
AddRandomStars(100, RGB(200, 200, 255), True); // some blueish ones
AddRandomStars(100, RGB(255, 255, 200), True); // some yellowish ones
end;
GLSceneViewer1.Buffer.BackgroundColor:=clBlack;
with GLSceneViewer1.Buffer.FogEnvironment do begin
FogColor.AsWinColor:=clBlack;
FogStart:=-FogStart; // Fog is used to make things darker
end;
SPMoon.Visible:=True;
SPSun.Visible:=False;
GLLensFlare.Visible:=False;
end;
'd', 'D' : with SkyDome1 do if Stars.Count>0 then begin
// turn on 'day' mode
Bands[1].StopColor.Color:=clrNavy;
Bands[1].StartColor.Color:=clrBlue;
Bands[0].StopColor.Color:=clrBlue;
Bands[0].StartColor.Color:=clrWhite;
Stars.Clear;
GLSceneViewer1.Buffer.BackgroundColor:=clWhite;
with GLSceneViewer1.Buffer.FogEnvironment do begin
FogColor.AsWinColor:=clWhite;
FogStart:=-FogStart;
end;
GLSceneViewer1.Buffer.FogEnvironment.FogStart:=0;
SPMoon.Visible:=False;
SPSun.Visible:=True;
end;
't' : with SkyDome1 do begin
if sdoTwinkle in Options then
Options:=Options-[sdoTwinkle]
else Options:=Options+[sdoTwinkle];
end;
'l' : with GLLensFlare do Visible:=(not Visible) and SPSun.Visible;
end;
Key:=#0;
end;
procedure TForm1.TISoundTimer(Sender: TObject);
var
wolfPos : TVector;
c, s : Single;
begin
if not GLSMBASS1.Active then Exit;
if SkyDome1.Stars.Count=0 then begin
// wind blows around camera
with GetOrCreateSoundEmitter(GLCamera1) do begin
Source.SoundLibrary:=GLSoundLibrary;
Source.SoundName:=GLSoundLibrary.Samples[0].Name;
Source.Volume:=Random*0.5+0.5;
Playing:=True;
end;
end else begin
// wolf howl at some distance, at ground level
wolfPos:=GLCamera1.AbsolutePosition;
SinCos(Random*c2PI, 100+Random(1000), s, c);
wolfPos[0]:=wolfPos[0]+c;
wolfPos[2]:=wolfPos[2]+s;
wolfPos[1]:=TerrainRenderer1.InterpolatedHeight(wolfPos);
DCSound.Position.AsVector:=wolfPos;
with GetOrCreateSoundEmitter(DCSound) do begin
Source.SoundLibrary:=GLSoundLibrary;
Source.SoundName:=GLSoundLibrary.Samples[1].Name;
Source.MinDistance:=100;
Source.MaxDistance:=4000;
Playing:=True;
end;
end;
TISound.Enabled:=False;
TISound.Interval:=10000+Random(10000);
TISound.Enabled:=True;
end;
// Test Code for InterpolatedHeight, use as a Button1's click event
{
procedure TForm1.Button1Click(Sender: TObject);
var
x, y : Integer;
sph : TGLSphere;
begin
for x:=-5 to 5 do begin
for y:=-5 to 5 do begin
sph:=TGLSphere(GLScene1.Objects.AddNewChild(TGLSphere));
sph.Position.X:=DummyCube1.Position.X+X*2;
sph.Position.Z:=DummyCube1.Position.Z+Y*2;
sph.Position.Y:=TerrainRenderer1.InterpolatedHeight(sph.Position.AsVector);
sph.Radius:=0.5;
end;
end;
end; }
end.
|
unit LrProfiles;
interface
{$WARN SYMBOL_PLATFORM OFF}
uses
SysUtils, Classes, LrPersistComponent;
type
TLrProfiles = class;
TLrProfileIdent = string;
//
TLrProfile = class(TCollectionItem)
private
FIdent: TLrProfileIdent;
FName: string;
FProfiles: TLrProfiles;
protected
function GetName: string;
function RandomIdent: TLrProfileIdent;
procedure GuaranteeUniqueIdent;
public
constructor Create(inCollection: TCollection); override;
procedure AssignProfile(inProfile: TLrProfile); virtual;
property Profiles: TLrProfiles read FProfiles;
published
property Ident: TLrProfileIdent read FIdent write FIdent;
property Name: string read GetName write FName;
end;
//
TLrProfileClass = class of TLrProfile;
//
TLrProfiles = class(TOwnedCollection)
protected
function GetProfiles(inIndex: Integer): TLrProfile;
procedure SetProfiles(inIndex: Integer; const Value: TLrProfile);
public
constructor Create(AOwner: TPersistent; ItemClass: TLrProfileClass);
function AddProfile: TLrProfile;
function FindProfile(const inIdent: TLrProfileIdent): TLrProfile;
public
property Profiles[inIndex: Integer]: TLrProfile read GetProfiles
write SetProfiles; default;
end;
//
ELrProfileException = class(Exception)
end;
//
TLrProfileMgr = class(TLrPersistComponent)
private
FProfiles: TLrProfiles;
FDefaultIdent: string;
protected
function GetCount: Integer;
function GetDefaultIdent: string;
function GetDefaultProfile: TLrProfile;
procedure InitDefaultProfile;
procedure SetProfiles(const Value: TLrProfiles);
public
constructor Create(ItemClass: TLrProfileClass;
const inFilename: string = ''); reintroduce;
destructor Destroy; override;
function GetProfileByIdent(const inIdent: TLrProfileIdent): TLrProfile;
function GetProfileByName(const inName: string): TLrProfile;
procedure ProfileNamesToStrings(inStrings: TStrings);
procedure RemoveProfile(inProfile: TLrProfile);
public
property Count: Integer read GetCount;
property DefaultProfile: TLrProfile read GetDefaultProfile;
published
property DefaultIdent: string read GetDefaultIdent
write FDefaultIdent;
property Profiles: TLrProfiles read FProfiles
write SetProfiles;
end;
implementation
uses
StrUtils;
{ TLrProfile }
constructor TLrProfile.Create(inCollection: TCollection);
begin
inherited;
FProfiles := TLrProfiles(inCollection);
GuaranteeUniqueIdent;
end;
function TLrProfile.RandomIdent: TLrProfileIdent;
begin
Result := IntToHex(Random($FFFF), 4);
end;
procedure TLrProfile.GuaranteeUniqueIdent;
var
id: TLrProfileIdent;
begin
if Collection <> nil then
begin
Ident := '';
repeat
id := RandomIdent;
until (Profiles.FindProfile(id) = nil);
Ident := id;
end;
end;
procedure TLrProfile.AssignProfile(inProfile: TLrProfile);
begin
Ident := inProfile.FIdent;
Name := inProfile.FName;
end;
function TLrProfile.GetName: string;
begin
Result := FName;
if Result = '' then
Result := '(untitled)';
end;
{ TLrProfiles }
constructor TLrProfiles.Create(AOwner: TPersistent; ItemClass: TLrProfileClass);
begin
inherited Create(AOwner, ItemClass);
end;
function TLrProfiles.FindProfile(const inIdent: TLrProfileIdent): TLrProfile;
var
i: Integer;
begin
for i := 0 to Count - 1 do
begin
Result := Profiles[i];
if (Result.Ident = inIdent) then
exit;
end;
Result := nil;
end;
function TLrProfiles.AddProfile: TLrProfile;
begin
Result := TLrProfile(Add);
end;
function TLrProfiles.GetProfiles(inIndex: Integer): TLrProfile;
begin
Result := TLrProfile(Items[inIndex]);
end;
procedure TLrProfiles.SetProfiles(inIndex: Integer; const Value: TLrProfile);
begin
Items[inIndex].Assign(Value);
end;
{ TLrProfileMgr }
constructor TLrProfileMgr.Create(ItemClass: TLrProfileClass;
const inFilename: string);
begin
inherited Create(nil);
FProfiles := TLrProfiles.Create(Self, ItemClass);
LoadFromFile(inFilename);
end;
destructor TLrProfileMgr.Destroy;
begin
Save;
Profiles.Free;
inherited;
end;
procedure TLrProfileMgr.InitDefaultProfile;
begin
if (Profiles.Count > 0) then
DefaultIdent := Profiles[0].Ident;
end;
function TLrProfileMgr.GetDefaultIdent: TLrProfileIdent;
begin
if (FDefaultIdent = '') then
InitDefaultProfile;
Result := FDefaultIdent;
end;
function TLrProfileMgr.GetDefaultProfile: TLrProfile;
begin
Result := GetProfileByIdent(DefaultIdent);
end;
procedure TLrProfileMgr.SetProfiles(const Value: TLrProfiles);
begin
FProfiles.Assign(Value);
end;
procedure TLrProfileMgr.ProfileNamesToStrings(inStrings: TStrings);
var
i: Integer;
begin
for i := 0 to Profiles.Count - 1 do
inStrings.Add(Profiles[i].Name);
end;
function TLrProfileMgr.GetProfileByIdent(const inIdent: string): TLrProfile;
var
i: Integer;
begin
for i := 0 to Profiles.Count - 1 do
begin
Result := Profiles[i];
if Result.Ident = inIdent then
exit;
end;
raise ELrProfileException.Create('ProfileByIdent: Bad Ident');
end;
function TLrProfileMgr.GetProfileByName(const inName: string): TLrProfile;
var
i: Integer;
begin
for i := 0 to Profiles.Count - 1 do
begin
Result := Profiles[i];
if Result.Name = inName then
exit;
end;
raise ELrProfileException.Create('ProfileByName: Bad Name');
end;
procedure TLrProfileMgr.RemoveProfile(inProfile: TLrProfile);
begin
if (inProfile.Collection = Profiles) then
begin
if (FDefaultIdent = inProfile.Ident) then
DefaultIdent := '';
Profiles.Delete(inProfile.Index);
end;
end;
function TLrProfileMgr.GetCount: Integer;
begin
Result := Profiles.Count;
end;
end.
|
unit SendToVendorView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit,
cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox,
dxExEdtr, dxEdLib, Buttons, dxCntner, dxEditor, StdCtrls, ExtCtrls,
cxLookAndFeelPainters, cxButtons, DbClient;
type
TfrmSendToVendorView = class(TForm)
Panel5: TPanel;
Label1: TLabel;
Label2: TLabel;
Label19: TLabel;
Label32: TLabel;
noteLabel: TLabel;
lbDefect: TLabel;
serial: TdxEdit;
sendToVendor: TSpeedButton;
note: TdxMemo;
itemModel: TdxEdit;
dxEdit3: TdxEdit;
Label3: TLabel;
Label4: TLabel;
cancel: TcxButton;
defectTypeList: TcxComboBox;
vendorList: TcxComboBox;
Label6: TLabel;
Label7: TLabel;
procedure sendToVendorClick(Sender: TObject);
procedure cancelClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
itemRefund: TClientDataset;
vendorCds: TClientDataset;
defectTypeCds: TClientDataset;
cdsToApply: TClientDataset;
procedure showFormLikeModalForm();
procedure PrepareData();
procedure openModel(arg_idModel: Integer);
procedure setModel(arg_model: String);
function openVendorList(arg_idModel: Integer): Boolean;
procedure loadVendorList();
function openDefectTypeList(): Boolean;
procedure loadDefectTypeList();
procedure closeForm();
procedure validateScreen();
procedure setDataToApply();
procedure applySendToVendor();
public
{ Public declarations }
function startView(arg_itemRefund: TClientDataset): Boolean;
end;
var
frmSendToVendorView: TfrmSendToVendorView;
implementation
uses uDM;
{$R *.dfm}
{ TfrmSendToVendorView }
procedure TfrmSendToVendorView.closeForm;
begin
//close;
end;
procedure TfrmSendToVendorView.openModel(arg_idModel: Integer);
begin
itemRefund := dm.searchModel(arg_idModel);
end;
procedure TfrmSendToVendorView.loadDefectTypeList;
begin
defectTypeList.Clear();
while ( not defectTypeCds.Eof ) do begin
defectTypeList.Properties.Items.add(defectTypeCds.fieldByName('DefectType').AsString);
defectTypeCds.Next;
end;
end;
procedure TfrmSendToVendorView.loadVendorList;
begin
vendorList.Clear;
while ( not vendorCds.Eof ) do begin
vendorlist.Properties.Items.Add(vendorCds.fieldByName('Fornecedor').AsString);
vendorCds.Next;
end;
end;
function TfrmSendToVendorView.openDefectTypeList: Boolean;
begin
defectTypeCds := dm.searchDefectType();
end;
function TfrmSendToVendorView.openVendorList(
arg_IdModel: Integer): Boolean;
begin
vendorCds := dm.searchVendor();
end;
procedure TfrmSendToVendorView.showFormLikeModalForm;
begin
showModal;
end;
function TfrmSendToVendorView.startView(arg_itemRefund: TClientDataset): Boolean;
begin
// Antonio June 24, 2013
itemRefund := arg_itemRefund;
// Antonio June 21, 2013
setModel(itemRefund.fieldByName('Model').value);
openVendorList(itemRefund.fieldByName('ModelID').Value);
loadVendorList();
openDefectTypeList();
loadDefectTypeList();
showFormLikeModalForm();
end;
procedure TfrmSendToVendorView.sendToVendorClick(Sender: TObject);
begin
validateScreen();
PrepareData();
applySendToVendor();
close;
end;
procedure TfrmSendToVendorView.applySendToVendor;
begin
try
//dm.returnToVendor(cdsToApply); save to Sal_ItemRepair
dm.insertRepair(cdsToApply); // save to Repair
application.MessageBox('Sent to vendor successfull !', 'Send To Vendor', mb_OK + MB_ICONEXCLAMATION);
sendToVendor.Enabled := false;
except on e: Exception do
raise Exception.Create('Error to apply to vendor: ' + e.message);
end;
end;
procedure TfrmSendToVendorView.setModel(arg_model: String);
begin
itemModel.Text := arg_model;
end;
procedure TfrmSendToVendorView.cancelClick(Sender: TObject);
begin
closeForm;
end;
procedure TfrmSendToVendorView.FormShow(Sender: TObject);
begin
vendorList.setfocus;
end;
procedure TfrmSendToVendorView.setDataToApply;
begin
vendorCds.Locate('Fornecedor', vendorList.Text, []);
cdsToApply.FieldByName('IDFornecedor').Value := vendorCds.fieldByName('IdFornecedor').Value;
cdsToApply.fieldByname('Fase').Value := 'Send to Vendor';
cdsToApply.fieldByName('SentDate').value := now;
cdsToApply.fieldByName('IdModel').value := itemRefund.fieldByName('ModelID').Value;
cdsToApply.fieldByName('IdStore').Value := itemRefund.fieldByName('StoreID').value;
cdsToApply.fieldByname('qty').value := itemRefund.fieldByName('qty').value;
cdsToApply.FieldByName('TipoRepair').Value := 0;
cdsToApply.FieldByName('SerialNumber').Value := serial.Text;
defectTypeCds.Locate('DefectType', defectTypeList.Text, []);
cdsToApply.fieldByname('IdDefectType').Value := defectTypeCds.fieldByname('IdDefectType').Value;
cdsToApply.fieldByName('IdUserSent').Value := dm.fUser.ID;
cdsToApply.fieldByName('Tipo').value := 2;
end;
procedure TfrmSendToVendorView.validateScreen;
begin
if ( trim(vendorList.Text) = '' ) then
raise Exception.Create('Select a vendor.');
if ( trim(defectTypeList.Text) = '' ) then
raise Exception.Create('Select a defect type.');
end;
procedure TfrmSendToVendorView.PrepareData;
begin
//cdsToApply := dm.getSaleItemRepair(cdsToApply);
cdsToApply := dm.getRepairEmptyRecord;
cdsToApply.Insert();
setDataToApply();
end;
procedure TfrmSendToVendorView.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
// freeAndNil(itemRefund);
freeAndNil(vendorCds);
freeAndNil(defectTypeCds);
freeAndNil(cdsToApply);
end;
end.
|
Unit SetSymPathForm;
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,
Vcl.Menus;
Type
TSetSymPathFrm = Class (TForm)
MainPanel: TPanel;
StornoButton: TButton;
OkButton: TButton;
SymListView: TListView;
SymPopupMenu: TPopupMenu;
AddMenuItem: TMenuItem;
EditMenuItem: TMenuItem;
DeleteMenuItem: TMenuItem;
procedure StornoButtonClick(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
procedure OnSymPopupMenuClick(Sender: TObject);
Private
FCancelled : Boolean;
FSymPath : WideString;
Function ListItemToSymPath(AItem:TListItem):WideString;
Procedure SymPathToListItem(ASymPath:WideString; AItem:TListItem);
Public
Constructor Create(AOwner:TComponent; ASymPath:WideString); Reintroduce;
Property Cancelled : Boolean Read FCancelled;
Property SymPath : WideString Read FSymPath;
end;
Implementation
Uses
AddEditSymServerForm;
Constructor TSetSymPathFrm.Create(AOwner:TComponent; ASymPath:WideString);
begin
FCancelled := True;
FSymPath := ASymPath;
Inherited Create(AOwner);
end;
{$R *.DFM}
Function TSetSymPathFrm.ListItemToSymPath(AItem:TListItem):WideString;
begin
If AItem.SubItems[0] <> '' Then
Result := Format('srv*%s*%s', [AItem.Caption, AItem.SubItems[0]])
Else Result := AItem.Caption;
end;
Procedure TSetSymPathFrm.SymPathToListItem(ASymPath:WideString; AItem:TListItem);
Var
starIndex : Integer;
begin
If Pos(WideString('srv*'), ASymPath) = 1 Then
Delete(ASymPath, 1, Length('srv*'));
starIndex := Pos(WideString('*'), ASymPath);
If starIndex > 0 Then
begin
AItem.Caption := Copy(ASymPath, 1, starIndex - 1);
AItem.SubItems[0] := Copy(ASymPath, starIndex + 1, Length(ASymPath) - starIndex - 1);
end
Else AItem.Caption := ASymPath;
end;
Procedure TSetSymPathFrm.OkButtonClick(Sender: TObject);
Var
L : TListItem;
onePart : WideString;
begin
FSymPath := '';
For L In SymListView.Items Do
begin
onePart := ListItemToSymPath(L);
If FSymPath <> '' Then
FSymPath := FSymPath + ';';
FSymPath := FSymPath + onePart;
end;
FCancelled := False;
Close;
end;
Procedure TSetSymPathFrm.OnSymPopupMenuClick(Sender: TObject);
Var
L : TListItem;
sp : WideString;
begin
L := SymListView.Selected;
If Sender = SymPopupMenu Then
begin
EditMenuItem.Enabled := Assigned(L);
DeleteMenuItem.Enabled := Assigned(L);
end
Else If (Sender = AddMenuItem) Or
(Sender = EditMenuItem) Then
begin
sp := '';
If Sender = EditMenuItem Then
sp := ListItemToSymPath(L)
Else L := Nil;
With TAddEditSymServerFrm.Create(Application, sp) Do
begin
ShowModal;
If Not Cancelled Then
begin
sp := OneSymPath;
If Not Assigned(L) Then
begin
L := SymListView.Items.Add;
L.SubItems.Add('');
end;
SymPathToListItem(sp, L);
end;
Free;
end;
end
Else If Sender = DeleteMenuItem Then
L.Delete;
end;
Procedure TSetSymPathFrm.StornoButtonClick(Sender: TObject);
begin
Close;
end;
End.
|
unit uClassicDivider;
{$I ..\Include\IntXLib.inc}
interface
uses
uDividerBase,
uDigitHelper,
uDigitOpHelper,
uXBits,
uEnums,
uConstants,
uUtils,
uIntXLibTypes;
type
/// <summary>
/// Divider using "classic" algorithm.
/// </summary>
TClassicDivider = class sealed(TDividerBase)
public
/// <summary>
/// Divides two big integers.
/// Also modifies <paramref name="digits1" /> and <paramref name="length1"/> (it will contain remainder).
/// </summary>
/// <param name="digits1">First big integer digits.</param>
/// <param name="digitsBuffer1">Buffer for first big integer digits. May also contain remainder. Can be null - in this case it's created if necessary.</param>
/// <param name="length1">First big integer length.</param>
/// <param name="digits2">Second big integer digits.</param>
/// <param name="digitsBuffer2">Buffer for second big integer digits. Only temporarily used. Can be null - in this case it's created if necessary.</param>
/// <param name="length2">Second big integer length.</param>
/// <param name="digitsRes">Resulting big integer digits.</param>
/// <param name="resultFlags">Which operation results to return.</param>
/// <param name="cmpResult">Big integers comparison result (pass -2 if omitted).</param>
/// <returns>Resulting big integer length.</returns>
function DivMod(digits1: TIntXLibUInt32Array;
digitsBuffer1: TIntXLibUInt32Array; var length1: UInt32;
digits2: TIntXLibUInt32Array; digitsBuffer2: TIntXLibUInt32Array;
length2: UInt32; digitsRes: TIntXLibUInt32Array;
resultFlags: TDivModResultFlags; cmpResult: integer): UInt32;
overload; override;
/// <summary>
/// Divides two big integers.
/// Also modifies <paramref name="digitsPtr1" /> and <paramref name="length1"/> (it will contain remainder).
/// </summary>
/// <param name="digitsPtr1">First big integer digits.</param>
/// <param name="digitsBufferPtr1">Buffer for first big integer digits. May also contain remainder.</param>
/// <param name="length1">First big integer length.</param>
/// <param name="digitsPtr2">Second big integer digits.</param>
/// <param name="digitsBufferPtr2">Buffer for second big integer digits. Only temporarily used.</param>
/// <param name="length2">Second big integer length.</param>
/// <param name="digitsResPtr">Resulting big integer digits.</param>
/// <param name="resultFlags">Which operation results to return.</param>
/// <param name="cmpResult">Big integers comparison result (pass -2 if omitted).</param>
/// <returns>Resulting big integer length.</returns>
function DivMod(digitsPtr1: PCardinal; digitsBufferPtr1: PCardinal;
var length1: UInt32; digitsPtr2: PCardinal; digitsBufferPtr2: PCardinal;
length2: UInt32; digitsResPtr: PCardinal; resultFlags: TDivModResultFlags;
cmpResult: integer): UInt32; overload; override;
end;
implementation
function TClassicDivider.DivMod(digits1: TIntXLibUInt32Array;
digitsBuffer1: TIntXLibUInt32Array; var length1: UInt32;
digits2: TIntXLibUInt32Array; digitsBuffer2: TIntXLibUInt32Array;
length2: UInt32; digitsRes: TIntXLibUInt32Array;
resultFlags: TDivModResultFlags; cmpResult: integer): UInt32;
var
digitsPtr1, digitsBufferPtr1, digitsPtr2, digitsBufferPtr2, digitsResPtr,
tempA: PCardinal;
begin
// Create some buffers if necessary
if (digitsBuffer1 = Nil) then
begin
SetLength(digitsBuffer1, length1 + 1);
end;
if (digitsBuffer2 = Nil) then
begin
SetLength(digitsBuffer2, length2);
end;
digitsPtr1 := @digits1[0];
digitsBufferPtr1 := @digitsBuffer1[0];
digitsPtr2 := @digits2[0];
digitsBufferPtr2 := @digitsBuffer2[0];
if digitsRes <> Nil then
digitsResPtr := @digitsRes[0]
else
digitsResPtr := @digits1[0];
if (digitsResPtr = digitsPtr1) then
tempA := Nil
else
begin
tempA := digitsResPtr;
end;
Result := DivMod(digitsPtr1, digitsBufferPtr1, length1, digitsPtr2,
digitsBufferPtr2, length2, tempA, resultFlags, cmpResult);
end;
function TClassicDivider.DivMod(digitsPtr1: PCardinal;
digitsBufferPtr1: PCardinal; var length1: UInt32; digitsPtr2: PCardinal;
digitsBufferPtr2: PCardinal; length2: UInt32; digitsResPtr: PCardinal;
resultFlags: TDivModResultFlags; cmpResult: integer): UInt32;
var
resultLength, divRes, lastDigit2, preLastDigit2, maxLength, i, iLen2, j,
ji: UInt32;
divNeeded, modNeeded, isMaxLength: Boolean;
shift1, rightShift1: integer;
longDigit, divEst, modEst, mulRes: UInt64;
k, t, tempAsr: Int64;
begin
// Call base (for special cases)
resultLength := inherited DivMod(digitsPtr1, digitsBufferPtr1, length1,
digitsPtr2, digitsBufferPtr2, length2, digitsResPtr, resultFlags,
cmpResult);
if (resultLength <> TConstants.MaxUInt32Value) then
begin
Result := resultLength;
Exit;
end;
divNeeded := (Ord(resultFlags) and Ord(TDivModResultFlags.dmrfDiv)) <> 0;
modNeeded := (Ord(resultFlags) and Ord(TDivModResultFlags.dmrfMod)) <> 0;
//
// Prepare digitsBufferPtr1 and digitsBufferPtr2
//
shift1 := 31 - TBits.Msb(digitsPtr2[length2 - 1]);
if (shift1 = 0) then
begin
// We don't need to shift - just copy
TDigitHelper.DigitsBlockCopy(digitsPtr1, digitsBufferPtr1, length1);
// We also don't need to shift second digits
digitsBufferPtr2 := digitsPtr2;
end
else
begin
rightShift1 := TConstants.DigitBitCount - shift1;
// We do need to shift here - so copy with shift - suppose we have enough storage for this operation
length1 := TDigitOpHelper.ShiftRight(digitsPtr1, length1,
digitsBufferPtr1 + 1, rightShift1, True) + UInt32(1);
// Second digits also must be shifted
TDigitOpHelper.ShiftRight(digitsPtr2, length2, digitsBufferPtr2 + 1,
rightShift1, True);
end;
//
// Division main algorithm implementation
//
// Some digits2 cached digits
lastDigit2 := digitsBufferPtr2[length2 - 1];
preLastDigit2 := digitsBufferPtr2[length2 - 2];
// Main divide loop
maxLength := length1 - length2;
i := maxLength;
iLen2 := length1;
while i <= (maxLength) do
begin
isMaxLength := iLen2 = length1;
// Calculate estimates
if (isMaxLength) then
begin
longDigit := digitsBufferPtr1[iLen2 - 1];
end
else
begin
longDigit := UInt64(digitsBufferPtr1[iLen2])
shl TConstants.DigitBitCount or digitsBufferPtr1[iLen2 - 1];
end;
divEst := longDigit div lastDigit2;
modEst := longDigit - divEst * lastDigit2;
// Check estimate (maybe correct it)
while True do
begin
if ((divEst = TConstants.BitCountStepOf2) or
(divEst * preLastDigit2 > ((modEst shl TConstants.DigitBitCount) +
digitsBufferPtr1[iLen2 - 2]))) then
begin
Dec(divEst);
modEst := modEst + lastDigit2;
if (modEst < TConstants.BitCountStepOf2) then
continue;
end;
break;
end;
divRes := UInt32(divEst);
// Multiply and subtract
k := 0;
j := 0;
ji := i;
while j < (length2) do
begin
mulRes := UInt64(divRes) * digitsBufferPtr2[j];
t := digitsBufferPtr1[ji] - k - Int64(mulRes and $FFFFFFFF);
digitsBufferPtr1[ji] := UInt32(t);
// http://galfar.vevb.net/wp/2009/shift-right-delphi-vs-c/
// 'SHR' treats its first operand as unsigned value even though it is a
// variable of signed type whereas '>>' takes the sign bit into account.
// Since 't' is an Int64 (meaning it can hold -ve numbers (signed type), we are going
// to do an arithmetic shift right to handle such instances.
{ k := Int64(mulRes shr TConstants.DigitBitCount) -
(t shr TConstants.DigitBitCount); } // <== produces different result
k := Int64(mulRes shr TConstants.DigitBitCount);
tempAsr := TUtils.Asr64(t, TConstants.DigitBitCount);
k := UInt32(k - tempAsr);
Inc(j);
Inc(ji);
end;
if (not isMaxLength) then
begin
t := digitsBufferPtr1[iLen2] - k;
digitsBufferPtr1[iLen2] := UInt32(t);
end
else
begin
t := -k;
end;
// Correct result if subtracted too much
if (t < 0) then
begin
Dec(divRes);
k := 0;
j := 0;
ji := i;
while j < (length2) do
begin
t := Int64(digitsBufferPtr1[ji]) + digitsBufferPtr2[j] + k;
digitsBufferPtr1[ji] := UInt32(t);
// http://galfar.vevb.net/wp/2009/shift-right-delphi-vs-c/
// 'SHR' treats its first operand as unsigned value even though it is a
// variable of signed type whereas '>>' takes the sign bit into account.
// Since 't' is an Int64 (meaning it can hold -ve numbers (signed type), we are going
// to do an arithmetic shift right to handle such instances.
// k := t shr TConstants.DigitBitCount; <== produces different result
k := TUtils.Asr64(t, TConstants.DigitBitCount);
Inc(j);
Inc(ji);
end;
if (not isMaxLength) then
begin
digitsBufferPtr1[iLen2] := UInt32(k + digitsBufferPtr1[iLen2]);
end;
end;
// Maybe save div result
if (divNeeded) then
begin
digitsResPtr[i] := divRes;
end;
Dec(i);
Dec(iLen2);
end;
if (modNeeded) then
begin
// First set correct mod length
length1 := TDigitHelper.GetRealDigitsLength(digitsBufferPtr1, length2);
// Next maybe shift result back to the right
if ((shift1 <> 0) and (length1 <> 0)) then
begin
length1 := TDigitOpHelper.ShiftRight(digitsBufferPtr1, length1,
digitsBufferPtr1, shift1, false);
end;
end;
// Finally return length
if not divNeeded then
begin
Result := 0;
Exit;
end
else
begin
if digitsResPtr[maxLength] = 0 then
begin
Result := maxLength;
Exit;
end
else
begin
Inc(maxLength);
Result := maxLength;
Exit;
end;
end;
end;
end.
|
unit AST.Delphi.SysOperators;
interface
uses AST.Delphi.Classes, AST.Delphi.Contexts;
type
TSysOperator = class(TIDOperator)
protected
constructor CreateAsIntOp; reintroduce;
end;
TSysTypeCast = class(TSysOperator)
public
constructor CreateInternal(ResultType: TIDType); reintroduce;
function Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean; overload; virtual;
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; overload; virtual;
function Match(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDExpression; virtual;
end;
TSysOpImplicit = class(TSysTypeCast)
end;
TSysOpExplisit = class(TSysTypeCast)
end;
TSysOpBinary = class(TSysOperator)
function Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression; virtual; abstract;
end;
///////////////////////////////////////////////////////////////////////////////////////////
/// ANY TYPE CAST
///////////////////////////////////////////////////////////////////////////////////////////
TSysTypeCast_IsOrdinal = class(TSysTypeCast)
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
///////////////////////////////////////////////////////////////////////////////////////////
/// IMPLICIT
///////////////////////////////////////////////////////////////////////////////////////////
{implicit String -> AnsiString}
TSysImplicitStringToAnsiString = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
end;
{implicit Class -> Class}
TSysImplicitClassToClass = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{implicit String -> PChar}
TSysImplicitStringToPChar = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
end;
{implicit String <- PChar}
TSysImplicitStringFromPChar = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
end;
{implicit String -> TGUID}
TSysImplicitStringToGUID = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
end;
{implicit ShortString <- Any}
TSysImplicitShortStringFromAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{implicit AnsiString <- Any}
TSysImplicitAnsiStringFromAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{implicit String <- Any}
TSysImplicitStringFromAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{implicit AnsiString -> String}
TSysImplicitAnsiStringToString = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
end;
{implicit Char -> String}
TSysImplicitCharToString = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
end;
{implicit Char -> AnsiString}
TSysImplicitCharToAnsiString = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
end;
{implicit Char -> AnsiChar}
TSysImplicitCharToAnsiChar = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
end;
{implicit AnsiChar -> AnsiString}
TSysImplicitAnsiCharToAnsiString = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
end;
{implicit AnsiChar -> String}
TSysImplicitAnsiCharToString = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
end;
{implicit AnsiChar -> WideChar}
TSysImplicitAnsiCharToWideChar = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
end;
{implicit MetaClass -> TGUID}
TSysImplicitMetaClassToGUID = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
end;
{implicit Closure -> TMethod}
TSysImplicitClosureToTMethod = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
end;
{implicit Variant <- Any}
TSysImplicitVariantFromAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
end;
{implicit Variant -> Any}
TSysImplicitVariantToAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
end;
{implicit Untyped <- Any}
TSysImplicitUntypedFromAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean; override;
end;
{implicit Array -> Any}
TSysImplicitArrayToAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{implicit Array <- Any}
TSysImplicitArrayFromAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
end;
{implicit Pointer -> Any}
TSysImplicitPointerToAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{implicit Pointer <- Any}
TSysImplicitPointerFromAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{implicit Range <- Any}
TSysImplicitRangeFromAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{implicit Range -> Any}
TSysImplicitRangeToAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{implicit Set <- Any}
TSysImplicitSetFromAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
function Match(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDExpression; override;
end;
{implicit nil -> Any}
TSysImplicitNullPtrToAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{implicit TVarRec -> Any}
TSysImplicitTVarRecToAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{implicit TVarRec <- Any}
TSysImplicitTVarRecFromAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{implicit TVarRec <- Any}
TSysImplicitSysVarFromAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
end;
///////////////////////////////////////////////////////////////////////////////////////////
/// EXPLICIT
///////////////////////////////////////////////////////////////////////////////////////////
{explicit Enum -> Any}
TSysExplicitEnumToAny = class(TSysOpExplisit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{explicit Enum <- Any}
TSysExplicitEnumFromAny = class(TSysOpExplisit)
public
function Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean; override;
end;
{explicit TProc <- Any}
TSysExplicitTProcFromAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration; override;
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{explicit Class <- Any}
TSysExplicitClassFromAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{explicit Interface <- Any}
TSysExplicitInterfaceFromAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{explicit Class of -> Any}
TSysExplicitClassOfToAny = class(TSysOpImplicit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{explicit Class of <- Any}
TSysExplicitClassOfFromAny = class(TSysOpExplisit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{explicit AnsiString <- Any}
TSysExplicitAnsiStringFromAny = class(TSysOpExplisit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
function Match(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDExpression; override;
end;
{explicit String <- Any}
TSysExplicitStringFromAny = class(TSysOpExplisit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{explicit Pointer -> Any}
TSysExplictPointerToAny = class(TSysOpExplisit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{explicit Pointer <- Any}
TSysExplictPointerFromAny = class(TSysOpExplisit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{explicit Untyped Ref -> Any}
TSysExplicitUntypedRefToAny = class(TSysOpExplisit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{explicit Untyped -> Any}
TSysExplicitUntypedToAny = class(TSysOpExplisit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{explicit Char -> Any}
TSysExplicitCharToAny = class(TSysOpExplisit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{explicit Range <- Any}
TSysExplicitRangeFromAny = class(TSysOpExplisit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{explicit Record <- Any}
TSysExplicitRecordFromAny = class(TSysOpExplisit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{explicit Record -> Any}
TSysExplicitRecordToAny = class(TSysOpExplisit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{explicit StaticArray -> Any}
TSysExplicitStaticArrayToAny = class(TSysOpExplisit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{explicit DynArray -> Any}
TSysExplicitDynArrayToAny = class(TSysOpExplisit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{explicit Variant -> Any}
TSysExplicitVariantToAny = class(TSysOpExplisit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
{explicit Variant <- Any}
TSysExplicitVariantFromAny = class(TSysOpExplisit)
public
function Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean; override;
end;
///////////////////////////////////////////////////////////////////////////////////////////
/// BINARY
///////////////////////////////////////////////////////////////////////////////////////////
{operator Ordinal IN Set}
TSysOrdinalInSet = class(TSysOpBinary)
public
function Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression; override;
end;
{operator ptr IntDiv int}
TSys_Ptr_IntDiv_Int = class(TSysOpBinary)
public
function Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression; override;
end;
{operator ptr IntDiv int}
TSys_StaticArray_Add = class(TSysOpBinary)
public
function Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression; override;
end;
{operator Set + Set}
TSys_Add_Set = class(TSysOpBinary)
public
function Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression; override;
end;
{operator Set - Set}
TSys_Subtract_Set = class(TSysOpBinary)
public
function Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression; override;
end;
{operator Set * Set}
TSys_Multiply_Set = class(TSysOpBinary)
public
function Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression; override;
end;
{operator [...] = [...]}
TSys_Equal_DynArray = class(TSysOpBinary)
public
function Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression; override;
end;
{operator any = nullptr}
TSys_Equal_NullPtr = class(TSysOpBinary)
public
function Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression; override;
end;
{operator any = nullptr}
TSys_NotEqual_NullPtr = class(TSysOpBinary)
public
function Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression; override;
end;
implementation
uses AST.Delphi.DataTypes,
AST.Parser.Utils,
AST.Delphi.Parser,
AST.Delphi.Errors,
AST.Pascal.Parser,
AST.Delphi.System;
{ TSysOperator }
constructor TSysOperator.CreateAsIntOp;
begin
CreateFromPool;
ItemType := itSysOperator;
end;
{ TSysTypeCast }
function TSysTypeCast.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
if Check(SContext, Src.DataType, Dst) then
Result := Dst
else
Result := nil;
end;
function TSysTypeCast.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := False;
end;
constructor TSysTypeCast.CreateInternal(ResultType: TIDType);
begin
CreateFromPool;
ItemType := itSysOperator;
Self.DataType := ResultType;
end;
function TSysTypeCast.Match(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDExpression;
begin
if Check(SContext, Src, Dst) <> nil then
Result := TIDCastExpression.Create(Src, Dst)
else
Result := nil;
end;
{ TSysImplicitStringToAnsiString }
function TSysImplicitStringToAnsiString.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
if Src.IsConstant then
begin
if IsAnsiString(Src.AsStrConst.Value) then
Exit(Dst);
end;
Result := nil;
end;
{ TSysImplicitAnsiStringToString }
function TSysImplicitAnsiStringToString.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
Result := Self;
end;
{ TSysImplicitCharToString }
function TSysImplicitCharToString.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
if Src.IsConstant then
Exit(SYSUnit._UnicodeString)
else
Result := Self;
end;
{ TSysImplicitCharToAnsiString }
function TSysImplicitCharToAnsiString.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
if Src.IsConstant then
Exit(SYSUnit._AnsiString)
else
Result := Self;
end;
{ TSysImplicitCharToAnsiChar }
function TSysImplicitCharToAnsiChar.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
if Src.IsConstant then
Exit(SYSUnit._AnsiChar)
else
Result := Self;
end;
{ TSysImplicitAnsiCharToAnsiString }
function TSysImplicitAnsiCharToAnsiString.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
Result := Dst;
end;
{ TSysImplicitAnsiCharToString }
function TSysImplicitAnsiCharToString.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
Result := nil;
end;
{ TSysImplicitAnsiCharToWideChar }
function TSysImplicitAnsiCharToWideChar.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
Result := Dst;
end;
{ TSysImplicitMetaClassToGUID }
function TSysImplicitMetaClassToGUID.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
if Src.AsType.DataTypeID <> dtInterface then
TASTDelphiErrors.INTF_TYPE_REQUIRED(Src);
Result := Dst;
end;
{ TSysImplicitStringToGUID }
function TSysImplicitStringToGUID.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
var
GUID: TGUID;
begin
if Src.IsConstant then
begin
if TryStrToGUID(Src.AsStrConst.Value, GUID) then
begin
Exit(Src.Declaration); // tmp
end;
end;
Result := nil;
end;
{ TSysImplicitClosureToTMethod }
function TSysImplicitClosureToTMethod.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
Result := nil;
end;
{ TSysImplicitVariantFromAny }
function TSysImplicitVariantFromAny.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
if Src.DataTypeID in [dtInt8, dtInt16, dtInt32, dtInt64, dtUInt8, dtUInt16, dtUInt32, dtUInt64, dtBoolean,
dtFloat32, dtFloat64, dtFloat80, dtCurrency, dtNativeInt, dtNativeUInt, dtChar, dtAnsiChar,
dtString, dtWideString, dtAnsiString] then
Result := Self
else
Result := nil;
end;
{ TSysImplicitVariantToAny }
function TSysImplicitVariantToAny.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
if Dst.DataTypeID in [dtInt8, dtInt16, dtInt32, dtInt64, dtUInt8, dtUInt16, dtUInt32, dtUInt64, dtBoolean,
dtFloat32, dtFloat64, dtNativeInt, dtNativeUInt, dtChar, dtAnsiChar,
dtString, dtAnsiString, dtVariant] then
Result := Self
else
Result := nil;
end;
{ TSysExplicitEnumFromAny }
function TSysExplicitEnumFromAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := Src.IsOrdinal;
end;
{ TSysExplicitTProcFromAny }
function TSysExplicitTProcFromAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := (Src.DataTypeID = dtProcType) or
(
(Src.DataTypeID = dtPointer) and (Dst as TIDProcType).IsStatic
);
end;
function TSysExplicitTProcFromAny.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
var LDstProcType := Dst as TIDProcType;
if Src.ItemType = itProcedure then
begin
var LSrcProc := Src.AsProcedure;
repeat
if TASTDelphiUnit.StrictMatchProcSingnatures(LSrcProc.ExplicitParams,
LDstProcType.Params,
LSrcProc.ResultType,
LDstProcType.ResultType) then
Exit(Dst);
LSrcProc := LSrcProc.PrevOverload;
until not Assigned(LSrcProc);
end else
if Src.DataTypeID = dtProcType then
begin
var LSrcProcType := Src.DataType as TIDProcType;
if TASTDelphiUnit.StrictMatchProcSingnatures(LSrcProcType.Params,
LDstProcType.Params,
LSrcProcType.ResultType,
LDstProcType.ResultType) then
Exit(Dst);
end else
begin
if (Src.DataTypeID = dtPointer) and LDstProcType.IsStatic then
Exit(Dst);
end;
Result := nil;
end;
{ TSysExplicitEnumToAny }
function TSysExplicitEnumToAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := Dst.IsOrdinal;
end;
{ TSysImplicitStringToPChar }
function TSysImplicitStringToPChar.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
Result := Dst;
end;
{ TSysImplicitUntypedFromAny }
function TSysImplicitUntypedFromAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := True;
end;
{ TIDOpExplicitClassOfToPointer }
function TSysExplicitClassOfToAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := Dst.DataTypeID in [dtClassOf, dtPointer];
end;
{ TSysImplicitPointerToAny }
function TSysImplicitPointerToAny.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
if Dst.DataTypeID in [dtPointer, dtPAnsiChar, dtPWideChar, dtClassOf] then
Result := Dst
else
Result := nil;
end;
function TSysImplicitPointerToAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := (Dst.DataTypeID = dtPointer);
end;
{ TSysExplicitClassOfFromAny }
function TSysExplicitClassOfFromAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := Dst.DataTypeID in [dtPointer, dtNativeInt, dtNativeUInt];
end;
{ TSysImplicitArrayToAny }
function TSysImplicitArrayToAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
var
SrcElType, DstElType: TIDType;
begin
SrcElType := TIDArray(Src).ElementDataType;
if Dst is TIDArray then
begin
DstElType := TIDArray(Dst).ElementDataType;
Result := ((Dst.DataTypeID = dtOpenArray) and SameTypes(SrcElType, DstElType)) or
(SrcElType.IsGeneric and DstElType.IsGeneric);
end else begin
Result :=
((Dst = SYSUnit._PAnsiChar) and (SrcElType = SYSUnit._AnsiChar)) or
((Dst = SYSUnit._PWideChar) and (SrcElType = SYSUnit._WideChar));
end;
end;
{ TSysImplicitArrayFromAny }
function TSysImplicitArrayFromAny.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
if Src.IsDynArrayConst then
Result := TASTDelphiUnit.CheckConstDynArrayImplicit(SContext, Src, Dst)
else
Result := nil;
end;
{ TSysExplictPointerFromAny }
function TSysExplictPointerFromAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := Src.IsOrdinal or (Src.DataTypeID in [dtPointer, dtClass, dtInterface, dtWideString, dtString, dtAnsiString, dtDynArray]);
if (Src.DataTypeID = dtRecord) and (Src.DataSize = 4) then // todo: platform
Result := True;
end;
{ TSysExplicitAnsiStringFromAny }
function TSysExplicitAnsiStringFromAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := (SYSUnit._PAnsiChar = Src) or
(Src.DataTypeID in [dtPointer, dtUntypedRef]);
end;
function TSysExplicitAnsiStringFromAny.Match(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDExpression;
begin
if Src.IsConstant and Src.DataType.IsOrdinal then
Result := Src
else
Result := inherited;
end;
{ TSysExplicitStringFromAny }
function TSysExplicitStringFromAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := (Src.DataTypeID in [dtAnsiString, dtPointer, dtUntypedRef, dtPAnsiChar, dtPWideChar]) or
(
(Src.DataTypeID = dtStaticArray) and
(
(TIDArray(Src).ElementDataType.DataTypeID = dtChar) or
(TIDArray(Src).ElementDataType.DataTypeID = dtAnsiChar)
)
);
end;
{ TSysExplictPointerToAny }
function TSysExplictPointerToAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := Dst.IsOrdinal or (Dst.DataTypeID in [dtPointer,
dtPAnsiChar,
dtPWideChar,
dtProcType,
dtRecord,
dtClass,
dtInterface,
dtDynArray,
dtAnsiString,
dtString,
dtWideString]);
end;
{ TSysOrdinalInSet }
function TSysOrdinalInSet.Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression;
begin
if (Right.Declaration is TIDDynArrayConstant) or (Right.DataTypeID = dtSet) then
begin
Result := SYSUnit._TrueExpression; // tmp
end else
Result := nil;
end;
{ TSysImplicitStringFromPChar }
function TSysImplicitStringFromPChar.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
Result := Src.DataType;
end;
{ TSys_Ptr_IntDiv_Int }
function TSys_Ptr_IntDiv_Int.Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression;
begin
if Left.DataTypeID = dtPointer then
Result := SYSUnit._ZeroIntExpression // tmp
else
Result := nil;
end;
{ TSysExplicitUntypedRefToAny }
function TSysExplicitUntypedRefToAny.Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean;
begin
// does Delphi support explicit cast to any type?
Result := True;// Dst.IsOrdinal or (Dst.DataTypeID in [dtPointer, dtStaticArray, dtClass, dtInterface, dtString, dtWideString]);
end;
{ TSysExplicitUntypedToAny }
function TSysExplicitUntypedToAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := Dst.DataSize = Src.DataSize;
end;
{ TSysExplicitCharToAny }
function TSysExplicitCharToAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := True;
end;
{ TSys_CharArray_Add_Int }
function TSys_StaticArray_Add.Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression;
begin
if (Left.DataTypeID = dtStaticArray) and (Right.DataType.IsInteger) then
begin
var ADT := TIDArray(Left.DataType);
if ADT.ElementDataType = SYSUnit._WideChar then
begin
Result := TIDExpression.Create(GetTMPVar(SYSUnit._WideChar.DefaultReference));
Exit;
end;
if ADT.ElementDataType = SYSUnit._AnsiChar then
begin
Result := TIDExpression.Create(GetTMPVar(SYSUnit._AnsiChar.DefaultReference));
Exit;
end;
end;
Result := nil;
end;
{ TSysImplicitAnsiStringFromAny }
function TSysImplicitAnsiStringFromAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := (Src.DataTypeID = dtStaticArray) and
(TIDArray(Src).ElementDataType.DataTypeID in [dtAnsiChar]);
end;
{ TSysImplicitShortStringFromAny }
function TSysImplicitShortStringFromAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := (Src.DataTypeID = dtStaticArray) and
(TIDArray(Src).ElementDataType.DataTypeID in [dtAnsiChar]);
end;
{ TSysImplicitStringFromAny }
function TSysImplicitStringFromAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := (Src.DataTypeID = dtAnsiString) or
(Src.DataTypeID in [dtPointer, dtPAnsiChar, dtPWideChar]) or
(
(Src.DataTypeID = dtStaticArray) and (TIDArray(Src).ElementDataType.DataTypeID = dtChar)
) or
(
(Src.DataTypeID = dtStaticArray) and
(TIDArray(Src).ElementDataType.DataTypeID in [dtAnsiChar, dtChar])
);
end;
{ TSysImplicitClassToClass }
function TSysImplicitClassToClass.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := TIDClass(Src).IsInheritsForm(TIDClass(Dst));
end;
{ TSysExplicitRangeFromAny }
function TSysExplicitRangeFromAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := Src.IsOrdinal;
end;
{ TSysExplicitRecordFromAny }
function TSysExplicitRecordFromAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := Dst.DataSize = Src.DataSize;
end;
{ TSysImplicitRangeFromAny }
function TSysImplicitRangeFromAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := Src.IsOrdinal;
end;
{ TSysImplicitRangeToAny }
function TSysImplicitRangeToAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := Dst.DataSize >= Src.DataSize;
end;
{ TSysTypeCast_IsOrdinal }
function TSysTypeCast_IsOrdinal.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := Src.IsOrdinal;
end;
{ TSysImplicitSetFromAny }
function TSysImplicitSetFromAny.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
Result := nil;
if Src.IsDynArrayConst then
Result := TASTDelphiUnit.CheckConstDynArrayImplicit(SContext, Src, Dst)
else
if Src.DataTypeId = dtSet then
begin
var DstSetType := TIDSet(Dst);
var SrcSetType := TIDSet(Src.DataType);
if DstSetType.BaseType.ActualDataType = SrcSetType.BaseType.ActualDataType then
Exit(DstSetType);
end;
end;
function TSysImplicitSetFromAny.Match(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDExpression;
begin
Result := nil;
if Src.IsDynArrayConst then
begin
var Implicit := TASTDelphiUnit.CheckConstDynArrayImplicit(SContext, Src, Dst);
if Assigned(Implicit) and (Src.DataTypeID <> dtSet) then
begin
var Decl := TIDSetConstant.CreateAsAnonymous(SContext.Scope, Dst, Src.AsDynArrayConst.Value);
Result := TIDExpression.Create(Decl, Src.TextPosition);
end;
end else
if Src.DataTypeId = dtSet then
Result := Src;
end;
{ TSysImplicitNullPtrToAny }
function TSysImplicitNullPtrToAny.Check(const SContext: TSContext; const Src: TIDType; const Dst: TIDType): Boolean;
begin
Result := Dst.IsReferenced or (Dst.DataTypeID = dtProcType);
end;
{ TSysImplicitPointerFromAny }
function TSysImplicitPointerFromAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := (
((Dst.DataTypeID in [dtPAnsiChar]) and (Src.DataTypeID = dtStaticArray) and (TIDStaticArray(Src).ElementDataType = SYSUnit._AnsiChar)) or
((Dst.DataTypeID in [dtPWideChar]) and (Src.DataTypeID = dtStaticArray) and (TIDStaticArray(Src).ElementDataType = SYSUnit._WideChar))
);
end;
{ TSysExplicitRecordToAny }
function TSysExplicitRecordToAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := Src.DataSize = Dst.DataSize;
end;
{ TSysExplicitStaticArrayToAny }
function TSysExplicitStaticArrayToAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := Src.DataSize = Dst.DataSize;
end;
{ TSysExplicitDynArrayToAny }
function TSysExplicitDynArrayToAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := (Dst.DataTypeID = dtDynArray) and SameTypes(TIDDynArray(Src).ElementDataType,
TIDDynArray(Dst).ElementDataType);
end;
{ TSys_Add_Set }
function TSys_Add_Set.Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression;
begin
// todo:
Result := Left;
end;
{ TSys_Subtract_Set }
function TSys_Subtract_Set.Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression;
begin
// todo:
Result := Left;
end;
{ TSys_Multiply_Set }
function TSys_Multiply_Set.Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression;
begin
// todo:
Result := Left;
end;
{ TSys_Equal_DynArray }
function TSys_Equal_DynArray.Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression;
begin
// todo:
Result := SYSUnit._TrueExpression;
end;
{ TSysImplicitTVarRecToAny }
function TSysImplicitTVarRecToAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
case Dst.DataTypeID of
dtInt8, dtInt16, dtInt32, dtInt64, dtUInt8, dtUInt16, dtUInt32, dtUInt64,
dtNativeInt, dtNativeUInt, dtFloat32, dtFloat64, dtFloat80, dtCurrency, dtBoolean,
dtAnsiChar, dtChar, dtAnsiString, dtString, dtShortString, dtPAnsiChar, dtPWideChar,
dtClass, dtClassOf, dtInterface: Result := True;
else
Result := False;
end;
end;
{ TSysImplicitTVarRecFromAny }
function TSysImplicitTVarRecFromAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
case Src.DataTypeID of
dtInt8, dtInt16, dtInt32, dtInt64, dtUInt8, dtUInt16, dtUInt32, dtUInt64,
dtNativeInt, dtNativeUInt, dtFloat32, dtFloat64, dtFloat80, dtCurrency, dtBoolean,
dtAnsiChar, dtChar, dtAnsiString, dtString, dtShortString, dtPAnsiChar, dtPWideChar,
dtClass, dtClassOf, dtInterface: Result := True;
else
Result := False;
end;
end;
{ TSysImplicitSysVarFromAny }
function TSysImplicitSysVarFromAny.Check(const SContext: TSContext; const Src: TIDExpression; const Dst: TIDType): TIDDeclaration;
begin
var ASysVar := Dst as TIDSysVariativeType;
for var AType in ASysVar.Types do
begin
Result := TASTDelphiUnit(SContext.Module).CheckImplicit(SContext, Src, Dst);
if Assigned(Result) then
Exit;
end;
Result := nil;
end;
{ TSysExplicitClassFromAny }
function TSysExplicitClassFromAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := (Dst.DataTypeID in [dtInt32, dtPointer, dtClass]) or (Src = SysUnit._Untyped);
end;
{ TSysExplicitInterfaceFromAny }
function TSysExplicitInterfaceFromAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := (Dst.DataTypeID in [dtInt32, dtPointer, dtClass]) or (Src = SysUnit._Untyped);
end;
{ TSysExplicitVariantToAny }
function TSysExplicitVariantToAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := Dst.DataTypeID in [dtInt8, dtInt16, dtInt32, dtInt64, dtUInt8, dtUInt16, dtUInt32, dtUInt64, dtBoolean,
dtFloat32, dtFloat64, dtNativeInt, dtNativeUInt, dtChar, dtAnsiChar,
dtString, dtAnsiString, dtWideString, dtVariant];
end;
{ TSysExplicitVariantFromAny }
function TSysExplicitVariantFromAny.Check(const SContext: TSContext; const Src, Dst: TIDType): Boolean;
begin
Result := Src.DataTypeID in [dtPointer, dtUntypedRef];
end;
{ TSys_Equal_NullPtr }
function TSys_Equal_NullPtr.Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression;
begin
// todo:
Result := SYSUnit._TrueExpression;
end;
{ TSys_NotEqual_NullPtr }
function TSys_NotEqual_NullPtr.Match(const SContext: TSContext; const Left, Right: TIDExpression): TIDExpression;
begin
// todo:
Result := SYSUnit._TrueExpression;
end;
end.
|
unit uPropertyInjectionMultiple;
interface
type
TReciepe = class
private
fText: string;
public
property Text: string read fText write fText;
end;
IFoodPreparer = interface
procedure PrepareFood(aReciepe: TReciepe);
end;
TBaker = class(TInterfacedObject, IFoodPreparer)
procedure PrepareFood(aReciepe: TReciepe);
end;
TShortOrderCook = class(TInterfacedObject, IFoodPreparer)
procedure PrepareFood(aReciepe: TReciepe);
end;
TChef = class(TInterfacedObject, IFoodPreparer)
procedure PrepareFood(aReciepe: TReciepe);
end;
TResturant = class
private
fName: string;
public
constructor Create(const aName: string);
procedure PrepareFood(aReciepe: TReciepe; aPreparer: IFoodPreparer);
property Name: string read fName;
end;
implementation
constructor TResturant.Create(const aName: string);
begin
fName := aName;
end;
procedure TResturant.PrepareFood(aReciepe: TReciepe; aPreparer: IFoodPreparer);
begin
aPreparer.PrepareFood(aReciepe);
end;
procedure TBaker.PrepareFood(aReciepe: TReciepe);
begin
WriteLn('Use baking skills to do the following: ' + aReciepe.Text);
end;
procedure TShortOrderCook.PrepareFood(aReciepe: TReciepe);
begin
WriteLn('Use the grill to do the following: ' + aReciepe.Text);
end;
procedure TChef.PrepareFood(aReciepe: TReciepe);
begin
WriteLn('Use the well trained culinary skills to do the following: ' + aReciepe.Text);
end;
end.
|
unit KuttaClass;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, ParseMath;
type
TKutta4 = class
x,y,xn : Real;
Parse : TParseMath;
function f(_x:Real; _y:Real) : Real;
function execute() : String;
public
constructor create;
destructor Destroy; override;
end;
implementation
constructor TKutta4.create;
begin
Parse := TParseMath.create();
Parse.AddVariable('x',0);
Parse.AddVariable('y',0);
end;
destructor TKutta4.Destroy;
begin
Parse.Destroy;
end;
function TKutta4.f(_x : Real; _y : Real) : Real;
begin
Parse.NewValue('x',_x);
Parse.NewValue('y',_y);
Result := Parse.Evaluate();
end;
function TKutta4.execute() : String;
var h, m, k1, k2, k3, k4 : Real;
begin
h := 0.001;
while x<=xn do
begin
k1 := f(x,y);
k2 := f(x+h/2,y+h/2*k1);
k3 := f(x+h/2,y+h/2*k2);
k4 := f(x+h,y+h*k3);
m := (k1+2*k2+2*k3+k4)/6;
y := y + h*m;
x := x + h;
end;
Result := FloatToStr(y);
end;
end.
|
unit o_lpUser;
interface
uses
SysUtils, Classes, Contnrs;
type
Tlp_User = class
private
fKey: Integer;
fHint: string;
fMachine: string;
fId: Integer;
fUser: string;
fIncId: Integer;
fLastUpdate: String;
fSession: string;
public
constructor Create;
destructor Destroy; override;
procedure Init;
property Id : Integer read fId write fId;
property IncId : Integer read fIncId write fIncId;
property Machine : string read fMachine write fMachine;
property Key : Integer read fKey write fKey;
property User : string read fUser write fUser;
property Session : string read fSession write fSession;
property Hint : string read fHint write fHint;
property LastUpdate : String read fLastUpdate write fLastUpdate;
end;
implementation
{ Tlp_User }
constructor Tlp_User.Create;
begin
Init;
end;
destructor Tlp_User.Destroy;
begin
inherited;
end;
procedure Tlp_User.Init;
begin
fKey := 0;
fHint := '';
fMachine := '';
fId := 0;
fUser := '';
fIncId := 0;
fLastUpdate:= '';
fSession := '';
end;
end.
|
unit Unit4;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids,vcl.themes,
vcl.extctrls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Buttons,
Datasnap.DBClient;
Type
TModDbGrid = class(TCustomGrid)
end;
TForm4 = class(TForm)
DBGrid1: TDBGrid;
Button2: TButton;
Button1: TButton;
ClientDataSet1: TClientDataSet;
DataSource1: TDataSource;
Panel1: TPanel;
cbxVclStyles: TComboBox;
Label1: TLabel;
procedure DBGrid1DrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumn;
State: TGridDrawState);
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure cbxVclStylesChange(Sender: TObject);
private
{ Private declarations }
procedure ButtondrawColumnCell(Sender: TObject;Button:Tbutton;
Btncaption:string;Datacol,YourCol: Integer; Column: TColumn;
Grid: TDBGrid; const Rect: TRect; State: TGridDrawState);
public
{ Public declarations }
end;
var
Form4: TForm4;
implementation
{$R *.dfm}
procedure TForm4.Button1Click(Sender: TObject);
begin
showmessage('Edit this row');
end;
procedure TForm4.Button2Click(Sender: TObject);
begin
showmessage('Delete this Information ');
end;
procedure TForm4.cbxVclStylesChange(Sender: TObject);
begin
TStyleManager.SetStyle(cbxVclStyles.Text);
end;
procedure TForm4.DBGrid1DrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumn;
State: TGridDrawState);
const
DeleteName:string = 'Delete';
EditName:string = 'Edit';
var
R,DataRect: TRect;
style: DWORD;
FButtonCol :integer;
FCellDown:TGridCoord;
begin
//Change color if the white space below the grid to same as background
TModDBGrid(sender).FInternalColor:= styleservices.GetStyleColor(scCategoryPanelGroup);
ButtondrawColumnCell(Sender,Button1,'Edit',Datacol,7,Column,dbGrid1,Rect,State);
ButtondrawColumnCell(Sender,Button2,'Delete',Datacol,8,Column,DbGrid1,Rect,State);
end;
procedure TForm4.FormCreate(Sender: TObject);
var
StyleName: string;
begin
for StyleName in TStyleManager.StyleNames do
cbxVclStyles.Items.Add(StyleName);
cbxVclStyles.itemindex:= 1;
//set style
cbxVclStyles.ItemIndex := cbxVclStyles.Items.IndexOf(TStyleManager.ActiveStyle.Name);
// set up the buttons
button1.Parent:= dbgrid1;
button1.Caption:= 'Edit';
button1.ControlStyle:= button1.ControlStyle +[csClickEvents];
button2.Parent:= dbgrid1;
button2.Caption:= 'Delete';
button2.ControlStyle:= button2.ControlStyle +[csClickEvents];
end;
procedure TForm4.Buttondrawcolumncell(Sender: TObject;Button:Tbutton;Btncaption:string;Datacol,YourCol: Integer; Column: TColumn; Grid: TDBGrid; const Rect: TRect; State: TGridDrawState);
var
R,DataRect: TRect;
style: DWORD;
FButtonCol :integer;
FCellDown:TGridCoord;
begin
R := rect;
inflaterect(R,-1,-1);
//Set up Button
if (not (gdFixed in State)) and (DataCol = YourCol) then
begin
if styleservices.Enabled then
TDBGrid(Sender).Canvas.Brush.Color := styleservices.GetStyleColor(scButtonDisabled)
else
TDBGrid(Sender).Canvas.Brush.Color := clbtnface;
style := DFCS_INACTIVE or DFCS_ADJUSTRECT;
// if (FCellDown.X = DataCol) Then
// style := style or DFCS_PUSHED;
DrawFrameControl( grid.Canvas.Handle, r, DFC_BUTTON, style );
TDBGrid(Sender).DefaultDrawColumnCell(R, DataCol, Column, State);
TDBGrid(Sender).Canvas.Brush.Style:= bsclear;
if styleservices.enabled then
TDBGrid(Sender).Canvas.Font.Color := Styleservices.GetStyleFontColor(sfButtonTextdisabled)
else
TDBGrid(Sender).Canvas.Font.Color := clblack;
DrawText(Grid.Canvas.Handle, PChar(BtnCaption), -1, r, DT_CENTER );
TDBGrid(Sender).DefaultDrawColumnCell(R, DataCol, Column, State);
end;
if grid.DataSource.DataSet.RecNo <= grid.DataSource.DataSet.recordcount then
begin
if (not (gdFixed in State)) and (DataCol = YourCol) then
begin
DataRect := TModDbGrid(grid).CellRect((YourCol+1),TModDbGrid(grid).row);
Inflaterect(datarect,-1,-1);
button.Width:= Datarect.Width;
button.left := (DataRect.right - button.width) ;
button.top := DataRect.top ;
button.height := (DataRect.bottom-DataRect.top);
button.visible:= true;
end;
end;
end;
end.
|
unit TimerFrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,ActnList, ExtCtrls,UTimer;
type
TFrmTimer = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Edit1: TEdit;
EditInterval: TEdit;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Déclarations privées }
procedure OnTimer(Sender:TObject);
public
{ Déclarations publiques }
FTimer:TWaitableTime;
constructor create(AOwner:TComponent);override;
destructor Destroy;override;
end;
var
FrmTimer: TFrmTimer;
implementation
{$R *.dfm}
procedure TFrmTimer.Button1Click(Sender: TObject);
begin
FTimer.Intervalle:=strToInt(EditInterval.Text);
//qd on met false il se déclenche après l'intervalle. Pour tester, mettr un très gd intervalle
FTimer.Start(False);
end;
procedure TFrmTimer.Button3Click(Sender: TObject);
begin
FTimer.Intervalle:=strToInt(EditInterval.Text);
FTimer.Start(True);
end;
procedure TFrmTimer.Button2Click(Sender: TObject);
begin
FTimer.Stop;
end;
constructor TFrmTimer.create(AOwner: TComponent);
begin
inherited;
FTimer:=TWaitableTime.Create;
FTimer.OnTimer:=OnTimer;
end;
destructor TFrmTimer.Destroy;
begin
FTimer.Kill;
FTimer.WaitFor;
FTimer.Free;
inherited;
end;
procedure TFrmTimer.OnTimer(Sender: TObject);
begin
Edit1.Text:=IntTostr(FTimer.TickCount);
end;
end.
|
{..............................................................................}
{ Summary Clear Inside - Delete objects within an area defined by user. }
{ Copyright (c) 2003 by Altium Limited }
{..............................................................................}
{..............................................................................}
Begin
ResetParameters;
AddStringParameter('Action','All');
RunProcess('Sch:Deselect');
ResetParameters;
AddStringParameter('Action','InsideArea');
RunProcess('Sch:Select');
ResetParameters;
RunProcess('Sch:Clear');
End.
{..............................................................................}
|
//////////////////////////////////////////////////////////////////////////
// This file is a part of NotLimited.Framework.Common NuGet package.
// You are strongly discouraged from fiddling with it.
// If you do, all hell will break loose and living will envy the dead.
//////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
namespace NotLimited.Framework.Common.Helpers
{
public static class EnumHelper
{
public static T MergeFlags<T>(this IEnumerable<T> source)
{
return (T)Enum.ToObject(typeof(T), source.Sum(x => (int)Convert.ChangeType(x, typeof(int))));
}
public static Dictionary<T, string> GetEnumDictionary<T>()
{
return GetEnumDictionary<T>(typeof(T));
}
public static Dictionary<T, string> GetEnumDictionary<T>(Type enumType)
{
var fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
return (from field in fields
let value = field.GetRawConstantValue()
let description = field.GetDisplayName()
orderby value
select new { Name = description, Value = value })
.ToDictionary(x => (T)x.Value, x => x.Name);
}
public static string GetEnumValueString<T>(this T en)
{
return GetEnumDictionary<T>()[en];
}
}
} |
unit uI2XImg;
interface
uses
Windows,
Classes,
MapStream,
uStrUtil,
Graphics,
SysUtils,
OmniXML,
uDWImage,
uI2XConstants,
uFileDir,
uHashTable,
uI2XPlugin;
//GR32, GR32_Image,
const
UNIT_NAME = 'uI2XImg';
type
TI2XImg = class(TI2XPlugin)
private
Image : TDWImage;
InstructionList : TStringList2;
protected
FParms : THashStringTable;
function ExecuteInstruction( const InstructionString : string ) : boolean; virtual; abstract;
property Parms : THashStringTable read FParms write FParms;
function ParseParmString(const ParmString: string; Parms : THashStringTable): boolean; overload;
function ParseParmString(const ParmString: string): boolean; overload;
function ParmMustExist( const ParmName : string ) : boolean;
public
function GetCapabilities( CapabilitiesList : TStrings ) : integer;
//function ProcessImage( MemoryMapName : pchar; InstructionList : pchar ) : boolean; virtual; overload;
function ProcessImage( const MemoryMapName : string; InstructionList : TStrings ) : boolean; virtual; abstract;
function ProcessImageDLL( MemoryMapName, InstructionList : PChar;
LoadImageFromMemoryMap : boolean = true ) : boolean; virtual;
constructor Create( const GUID, ParmFileName : string ); dynamic;
destructor Destroy; override;
end;
implementation
constructor TI2XImg.Create(const GUID, ParmFileName : string);
begin
inherited Create(GUID, ParmFileName);
Image := TDWImage.Create;
InstructionList := TStringList2.Create;
FParms := THashStringTable.Create;
end;
destructor TI2XImg.Destroy;
begin
FreeAndNil( Image );
FreeAndNil( InstructionList );
FreeAndNil( FParms );
inherited;
End;
function TI2XImg.ParseParmString(const ParmString : string; Parms : THashStringTable ) : boolean;
var
strList : TStringList2;
sParm, sValue : string;
i : integer;
begin
Result := false;
if (Parms = nil) then
Parms := THashStringTable.Create;
try
strList := TStringList2.Create;
strList.fromString( ParmString, IMGPROC_PARM_SEP );
if (strList.Count > 0 ) then begin
for i := 0 to strList.Count - 1 do begin
if ( i > 0 ) then begin
sParm := Split(strList[i], '=', 0);
sValue := Split(strList[i], '=', 1);
Parms.Add( sParm, sValue );
end;
end;
end;
Result := true;
finally
FreeAndNil( strList );
end;
End;
function TI2XImg.GetCapabilities( CapabilitiesList : TStrings ) : integer;
var
xmlNodeList : IXMLNodeList;
i : integer;
begin
CapabilitiesList.Add( 'I2XCFG:' + self.XMLParmFile );
Result := CapabilitiesList.Count;
end;
function TI2XImg.ParmMustExist(const ParmName: string): boolean;
begin
Result := ( self.FParms.ContainsKey( ParmName ) );
if ( not Result ) then
self.ErrorUpdate( 'Required Parm "' + ParmName + '" is missing!', ERROR_PARM_MISSING );
//raise PluginException.Create('Required Parm "' + ParmName + '" is missing!', ERROR_PARM_FILE_INVALID, self );
//raise Exception.Create( 'Required Parm "' + ParmName + '" is missing!');
end;
function TI2XImg.ParseParmString(const ParmString: string): boolean;
begin
Result := self.ParseParmString( ParmString, self.FParms );
end;
function TI2XImg.ProcessImageDLL(MemoryMapName, InstructionList: pchar;
LoadImageFromMemoryMap : boolean): boolean;
var
sMemoryMapName, sInstructionList : string;
slInstList : TStringList2;
begin
try
sMemoryMapName := PChar(MemoryMapName);
sInstructionList := PChar(InstructionList);
slInstList := TStringList2.Create;
slInstList.fromString( sInstructionList );
if ( LoadImageFromMemoryMap ) then
self.FMemoryMapManager.Read( sMemoryMapName, Image );
//Image.LoadFromMemoryMap( sMemoryMapName );
Result := self.ProcessImage( sMemoryMapName, slInstList );
finally
FreeAndNil( slInstList );
end;
end;
END.
|
unit ibSHMessages;
interface
resourcestring
SUnregisterServer = 'Unregister server alias "%s"?';
SUnregisterDatabase = 'Unregister database alias "%s"?';
SDropDatabase = 'Drop database "%s"?';
SDeleteUser = 'Delete user "%s"?';
SDriverIsNotInstalled = 'Driver is not installed';
SServerTestConnectionOK = 'Test connect to server "%s" successfully passed';
SServerTestConnectionNO = 'Test connect to server "%s" not passed (or Services API not found)' + SLineBreak + 'Detail information:' + SLineBreak + '----------------------------' + SLineBreak + '%s';
SDatabaseTestConnectionOK = 'Test connect to database "%s" successfully passed';
SDatabaseTestConnectionNO = 'Test connect to database "%s" not passed' + SLineBreak + 'Detail information:' + SLineBreak + '----------------------------' + SLineBreak + '%s';
SDatabaseConnectNO = 'Can not connect to database "%s"' + SLineBreak + 'Detail information:' + SLineBreak + '----------------------------' + SLineBreak + '%s';
SServerIsNotInterBase = 'Current server is not Firebird/InterBase server. The operation is aborted';
SDatabaseIsNotInterBase = 'Current database is not Firebird/InterBase database or database is not connected. The operation is aborted';
SApplicationNotFound = 'Application "%s" not found';
SNoParametersExpected = '* No parameters expected *';
SDDLStatementInput = 'You are trying to execute DDL statement.'#13#10'Please, use DDL editor for this purpose.'#13#10'Load DDL editor with current statement?';
SReplaceEditorContextWorning = 'Do you realy want to replace existing SQL Editor context by saved?';
SClearEditorContextWorning = 'Clear SQL Editor context?';
SClearDMLHistoryWorning = 'Clear DML History for %s?';
SClearDDLHistoryWorning = 'Clear DDL History for %s?';
SCommitTransaction = 'Commit transaction?';
SCloseResult = 'Close result?';
SRollbackTransaction = 'Rollback transaction?';
STransactionCommited = 'Transaction commited...';
STransactionRolledBack = 'Transaction rolled back...';
STransactionStarted= 'Transaction started (%s)';
SNoExportersRegisted = 'Cannot save data couse of no dataexporters registed.';
SSQLEditorTransactionActive = 'Please, end active transaction to change this property.';
SNotSupported = 'Not supported yet.';
SFileModified = 'File was modified. Save changes?';
STextModified = 'Text was modified. Save changes?';
SDataFetching = 'Fetching data in progress.' + SLineBreak + 'Stop fetch before closing editor.';
SErrorPlanRetrieving = 'Error plan retrieving.';
// SStatisticInserted = '%d record(s) was(were) inserted in %s';
// SStatisticUpdated = '%d record(s) was(were) updated in %s';
// SStatisticDeleted = '%d record(s) was(were) deleted from %s';
// SStatisticIndexedRead = '%d indexed reads from %s';
// SStatisticNonIndexedRead = '%d non-indexed reads from %s';
SStatisticInserted = 'Inserts into %s: %s';
SStatisticUpdated = 'Updates of %s: %s';
SStatisticDeleted = 'Deletes from %s: %s';
SStatisticIndexedRead = 'Indexed reads from %s: %s';
SStatisticNonIndexedRead = 'Non-indexed reads from %s: %s';
SMillisecondsFmt = ' %d ms';
SSecondsFmt = ' %d s';
SMinutesFmt = ' %d min';
SHoursFmt = ' %d h';
SDaysFmt = ' %d days';
SPrepare = 'Prepare';
SExecute = 'Execute';
SFetch = 'Fetch';
SStatistics = 'Statistics';
SOperationsPerTable = 'Operations';
SGarbageStatistics = 'Garbage collection';
SStatisticsSummary = 'Statistics summary';
SQueryTime = 'Time';
SIndexedReads = ' indexed reads';
SNonIndexedReads = ' non-indexed reads';
SUpdates = ' updates';
SDeletes = ' deletes';
SInserts = ' inserts';
SBackouts = ' backouts';
SExpunges = ' expunges';
SPurges = ' purges';
SFileIOError = 'Unable to create/open file: %s!';
//Player captions
SUnknown = 'Unknown';
SDatabases = 'Databases';
SDomains = 'Domains';
STables = 'Tables';
SViews = 'Views';
SProcedures = 'Procedures';
STriggers = 'Triggers';
SGenerators = 'Generators';
SExceptions = 'Exceptions';
SFunctions = 'Functions';
SRoles = 'Roles';
SIndices = 'Indices';
SDML = 'DML';
SStateSQL = 'SQL';
SStateCreate = 'Create';
SStateAlter = 'Alter';
SStateDrop = 'Drop';
SStateRecreate = 'Recreate';
SStateConnect = 'Connect';
SStateReConnect = 'Reconnect';
SStateDisConnect = 'Disconnect';
SStateGrant = 'Grant';
SComment='Comment';
SPlayerContainsDatabaseStats = 'SQL Script contains database manipulations statements'#13#10'and will be executed in additional connection.'#13#10'Continue with new connection?';
SPlayerSuccess = 'SQL Script executed successfuly.';
SPlayerError = 'SQL Script executed with errors.';
SUncommitedChanges = 'There are uncommited changes.'#13#10'Commit them?';
SPlayerTerminated = 'SQL Script terminated by user.';
SPlayerStartedAt = 'SQL Script started at ';
SPlayerTraceModeStartedAt = 'SQL Script Trace Mode started at ';
SPlayerTerminatedAt = 'SQL Script terminated by user at ';
SPlayerTerminatedAtLine = 'SQL Script terminated at Line N %d';
SPlayerSuccessfulyExecutedAt = 'SQL Script successfuly executed at ';
SPlayerExecutedWithErrorsAt = 'SQL Script executed with errors at ';
SPlayerStatementExecutedWithErrorsAt = 'Statement executed with errors at ';
SElapsedTime = 'Elapsed time ';
SRuningScript = 'Running script...';
SParsingScript = 'Parsing script...';
SExtractorTmpBLOBFileUserNotification = '/* BT: The following temporary file with BLOB fields content will be automatically renamed and moved to the current directory after saving script output. */';
//DML Exporter
SLoadingTables = 'Loading Tables...';
implementation
end.
|
{ Modified from
http://free-pascal-general.1045716.n5.nabble.com/lNet-getting-the-local-IP-td3200339.html }
program GetPrimaryIpAddress;
{$mode objfpc}
uses
baseunix,
unixtype,
sockets,
SysUtils;
procedure Get(out AddrOut: string);
const
CN_GDNS_ADDR = '127.0.0.1';
CN_GDNS_PORT = 53;
var
sock: longint;
err: longint;
UnixAddr: TInetSockAddr;
HostAddr: TSockAddr;
len: Integer;
begin
err := 0;
sock := fpsocket(AF_INET, SOCK_DGRAM, 0);
assert(sock <> -1);
// changed because previous properties were deprecated
UnixAddr.sin_family := AF_INET;
UnixAddr.sin_port := htons(CN_GDNS_PORT);
UnixAddr.sin_addr := StrToHostAddr(CN_GDNS_ADDR);
if (fpConnect(sock, @UnixAddr, SizeOf(UnixAddr)) = 0) then
begin
try
len := SizeOf(HostAddr);
if (fpgetsockname(sock, @HostAddr, @len) = 0) then
begin
AddrOut := NetAddrToStr(HostAddr.sin_addr);
end
else
begin
err:=socketError;
end;
finally
if (fpclose(sock) <> 0) then
begin
err := socketError;
end;
end;
end
else
begin
err:=socketError;
end;
if (err <> 0) then
begin
// report error
end;
end;
var
strAddr: string;
begin
Get(strAddr);
WriteLn('ip : ',strAddr);
end.
_________
|
unit StockMinuteDataAccess;
interface
uses
define_dealItem,
BaseDataSet,
QuickList_int,
define_price,
define_stock_quotes;
type
{ 行情分钟线数据访问 }
TRT_StockMinuteData = record
DealItem : PRT_DealItem;
IsDataChangedStatus: Byte;
WeightMode : Byte;
MinuteDealData : TALIntegerList;
FirstDealDate : Word; // 2
LastDealDate : Word; // 2 最后记录交易时间
DataSourceId : integer;
end;
TStockMinuteDataAccess = class(TBaseDataSetAccess)
protected
fStockMinuteData: TRT_StockMinuteData;
function GetFirstDealDate: Word;
procedure SetFirstDealDate(const Value: Word);
function GetLastDealDate: Word;
procedure SetLastDealDate(const Value: Word);
function GetEndDealDate: Word;
procedure SetEndDealDate(const Value: Word);
procedure SetStockItem(AStockItem: PRT_DealItem);
function GetWeightMode: TWeightMode;
procedure SetWeightMode(value: TWeightMode);
function GetRecordItem(AIndex: integer): Pointer; override;
function GetRecordCount: Integer; override;
public
constructor Create(AStockItem: PRT_DealItem; ADataSrcId: integer; AWeightMode: TWeightMode);
destructor Destroy; override;
function FindRecord(ADate: Integer): PRT_Quote_Minute;
function CheckOutRecord(ADate: Word): PRT_Quote_Minute;
function DoGetRecords: integer;
function DoGetStockOpenPrice(AIndex: integer): double;
function DoGetStockClosePrice(AIndex: integer): double;
function DoGetStockHighPrice(AIndex: integer): double;
function DoGetStockLowPrice(AIndex: integer): double;
procedure Sort; override;
procedure Clear; override;
property FirstDealDate: Word read GetFirstDealDate;
property LastDealDate: Word read GetLastDealDate;
property EndDealDate: Word read GetEndDealDate write SetEndDealDate;
property StockItem: PRT_DealItem read fStockMinuteData.DealItem write SetStockItem;
property DataSourceId: integer read fStockMinuteData.DataSourceId write fStockMinuteData.DataSourceId;
property WeightMode: TWeightMode read GetWeightMode write SetWeightMode;
end;
procedure AddDealDayData(ADataAccess: TStockMinuteDataAccess; ATempDealDayData: PRT_Quote_Minute);
implementation
uses
QuickSortList,
SysUtils;
{ TStockMinuteDataAccess }
procedure AddDealDayData(ADataAccess: TStockMinuteDataAccess; ATempDealDayData: PRT_Quote_Minute);
var
tmpAddDealDayData: PRT_Quote_Minute;
// tmpDate: string;
begin
if (nil = ATempDealDayData) then
exit;
if //(ATempDealDayData.DealDate.Value > 0) and
(ATempDealDayData.PriceRange.PriceOpen.Value > 0) and
(ATempDealDayData.PriceRange.PriceClose.Value > 0) and
(ATempDealDayData.DealVolume > 0) and
(ATempDealDayData.DealAmount > 0) then
begin
// tmpDate := FormatDateTime('', ATempDealDayData.DealDateTime.Value);
// if '' <> tmpDate then
// begin
// end;
//tmpAddDealDayData := ADataAccess.CheckOutRecord(ATempDealDayData.DealDate.Value);
tmpAddDealDayData.PriceRange.PriceHigh := ATempDealDayData.PriceRange.PriceHigh;
tmpAddDealDayData.PriceRange.PriceLow := ATempDealDayData.PriceRange.PriceLow;
tmpAddDealDayData.PriceRange.PriceOpen := ATempDealDayData.PriceRange.PriceOpen;
tmpAddDealDayData.PriceRange.PriceClose := ATempDealDayData.PriceRange.PriceClose;
tmpAddDealDayData.DealVolume := ATempDealDayData.DealVolume;
tmpAddDealDayData.DealAmount := ATempDealDayData.DealAmount;
//tmpAddDealDayData.Weight := ATempDealDayData.Weight;
end;
end;
constructor TStockMinuteDataAccess.Create(AStockItem: PRT_DealItem; ADataSrcId: integer; AWeightMode: TWeightMode);
begin
//inherited;
FillChar(fStockMinuteData, SizeOf(fStockMinuteData), 0);
fStockMinuteData.DealItem := AStockItem;
fStockMinuteData.MinuteDealData := TALIntegerList.Create;
fStockMinuteData.MinuteDealData.Clear;
fStockMinuteData.MinuteDealData.Duplicates := QuickSortList.lstDupIgnore;
fStockMinuteData.FirstDealDate := 0; // 2
fStockMinuteData.LastDealDate := 0; // 2 最后记录交易时间
fStockMinuteData.DataSourceId := ADataSrcId;
fStockMinuteData.WeightMode := Byte(AWeightMode);
end;
destructor TStockMinuteDataAccess.Destroy;
begin
Clear;
FreeAndNil(fStockMinuteData.MinuteDealData);
inherited;
end;
procedure TStockMinuteDataAccess.Clear;
var
i: integer;
tmpQuoteDay: PRT_Quote_Minute;
begin
if nil <> fStockMinuteData.MinuteDealData then
begin
for i := fStockMinuteData.MinuteDealData.Count - 1 downto 0 do
begin
tmpQuoteDay := PRT_Quote_Minute(fStockMinuteData.MinuteDealData.Objects[i]);
FreeMem(tmpQuoteDay);
end;
fStockMinuteData.MinuteDealData.Clear;
end;
end;
procedure TStockMinuteDataAccess.SetStockItem(AStockItem: PRT_DealItem);
begin
if nil <> AStockItem then
begin
if fStockMinuteData.DealItem <> AStockItem then
begin
end;
end;
fStockMinuteData.DealItem := AStockItem;
if nil <> fStockMinuteData.DealItem then
begin
end;
end;
function TStockMinuteDataAccess.GetFirstDealDate: Word;
begin
Result := fStockMinuteData.FirstDealDate;
end;
function TStockMinuteDataAccess.GetWeightMode: TWeightMode;
begin
Result := TWeightMode(fStockMinuteData.WeightMode);
end;
procedure TStockMinuteDataAccess.SetWeightMode(value: TWeightMode);
begin
fStockMinuteData.WeightMode := Byte(value);
end;
procedure TStockMinuteDataAccess.SetFirstDealDate(const Value: Word);
begin
fStockMinuteData.FirstDealDate := Value;
end;
function TStockMinuteDataAccess.GetLastDealDate: Word;
begin
Result := fStockMinuteData.LastDealDate;
end;
procedure TStockMinuteDataAccess.SetLastDealDate(const Value: Word);
begin
fStockMinuteData.LastDealDate := Value;
end;
function TStockMinuteDataAccess.GetEndDealDate: Word;
begin
Result := 0;
end;
procedure TStockMinuteDataAccess.SetEndDealDate(const Value: Word);
begin
end;
function TStockMinuteDataAccess.GetRecordCount: Integer;
begin
Result := fStockMinuteData.MinuteDealData.Count;
end;
function TStockMinuteDataAccess.GetRecordItem(AIndex: integer): Pointer;
begin
Result := fStockMinuteData.MinuteDealData.Objects[AIndex];
end;
procedure TStockMinuteDataAccess.Sort;
begin
fStockMinuteData.MinuteDealData.Sort;
end;
function TStockMinuteDataAccess.CheckOutRecord(ADate: Word): PRT_Quote_Minute;
begin
Result := nil;
if ADate < 1 then
exit;
Result := FindRecord(ADate);
if nil = Result then
begin
if fStockMinuteData.FirstDealDate = 0 then
fStockMinuteData.FirstDealDate := ADate;
if fStockMinuteData.FirstDealDate > ADate then
fStockMinuteData.FirstDealDate := ADate;
if fStockMinuteData.LastDealDate < ADate then
fStockMinuteData.LastDealDate := ADate;
Result := System.New(PRT_Quote_Minute);
FillChar(Result^, SizeOf(TRT_Quote_Minute), 0);
//Result.DealDate.Value := ADate;
fStockMinuteData.MinuteDealData.AddObject(ADate, TObject(Result));
end;
end;
function TStockMinuteDataAccess.FindRecord(ADate: Integer): PRT_Quote_Minute;
var
tmpPos: integer;
begin
Result := nil;
tmpPos := fStockMinuteData.MinuteDealData.IndexOf(ADate);
if 0 <= tmpPos then
Result := PRT_Quote_Minute(fStockMinuteData.MinuteDealData.Objects[tmpPos]);
end;
function TStockMinuteDataAccess.DoGetStockOpenPrice(AIndex: integer): double;
begin
Result := PRT_Quote_Minute(RecordItem[AIndex]).PriceRange.PriceOpen.Value;
end;
function TStockMinuteDataAccess.DoGetStockClosePrice(AIndex: integer): double;
begin
Result := PRT_Quote_Minute(RecordItem[AIndex]).PriceRange.PriceClose.Value;
end;
function TStockMinuteDataAccess.DoGetStockHighPrice(AIndex: integer): double;
begin
Result := PRT_Quote_Minute(RecordItem[AIndex]).PriceRange.PriceHigh.Value;
end;
function TStockMinuteDataAccess.DoGetStockLowPrice(AIndex: integer): double;
begin
Result := PRT_Quote_Minute(RecordItem[AIndex]).PriceRange.PriceLow.Value;
end;
function TStockMinuteDataAccess.DoGetRecords: integer;
begin
Result := Self.RecordCount;
end;
end.
|
unit uPermissoesModel;
interface
uses uUsuarioModel;
type
TPermissoesModel = class
private
FAcessoEmprestimo: Boolean;
FCodigo: Integer;
FAcessoUsuario: Boolean;
FAcessoLivro: Boolean;
FAcessoEditora: Boolean;
FAcessoPermissoes: Boolean;
FAcessoAutor: Boolean;
FUsuario: TUsuarioModel;
procedure SetAcessoAutor(const Value: Boolean);
procedure SetAcessoEditora(const Value: Boolean);
procedure SetAcessoEmprestimo(const Value: Boolean);
procedure SetAcessoLivro(const Value: Boolean);
procedure SetAcessoPermissoes(const Value: Boolean);
procedure SetAcessoUsuario(const Value: Boolean);
procedure SetCodigo(const Value: Integer);
procedure SetUsuario(const Value: TUsuarioModel);
public
property Codigo: Integer read FCodigo write SetCodigo;
property Usuario: TUsuarioModel read FUsuario write SetUsuario;
property AcessoUsuario: Boolean read FAcessoUsuario write SetAcessoUsuario;
property AcessoAutor: Boolean read FAcessoAutor write SetAcessoAutor;
property AcessoEditora: Boolean read FAcessoEditora write SetAcessoEditora;
property AcessoLivro: Boolean read FAcessoLivro write SetAcessoLivro;
property AcessoEmprestimo: Boolean read FAcessoEmprestimo write SetAcessoEmprestimo;
property AcessoPermissoes: Boolean read FAcessoPermissoes write SetAcessoPermissoes;
end;
implementation
{ TPermissoesModel }
procedure TPermissoesModel.SetAcessoAutor(const Value: Boolean);
begin
FAcessoAutor := Value;
end;
procedure TPermissoesModel.SetAcessoEditora(const Value: Boolean);
begin
FAcessoEditora := Value;
end;
procedure TPermissoesModel.SetAcessoEmprestimo(const Value: Boolean);
begin
FAcessoEmprestimo := Value;
end;
procedure TPermissoesModel.SetAcessoLivro(const Value: Boolean);
begin
FAcessoLivro := Value;
end;
procedure TPermissoesModel.SetAcessoPermissoes(const Value: Boolean);
begin
FAcessoPermissoes := Value;
end;
procedure TPermissoesModel.SetAcessoUsuario(const Value: Boolean);
begin
FAcessoUsuario := Value;
end;
procedure TPermissoesModel.SetCodigo(const Value: Integer);
begin
FCodigo := Value;
end;
procedure TPermissoesModel.SetUsuario(const Value: TUsuarioModel);
begin
FUsuario := Value;
end;
end.
|
unit uSisPessoaProcuraFrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
uParentAllFrm, ExtCtrls, Db, DBTables, StdCtrls, Buttons,
Grids,uParentDialogFrm,
dxDBGrid, dxCntner, dxTL, dxDBCtrl, ADODB, siComp, siLangRT;
type
TSisPessoaProcuraFrm = class(TParentDialogFrm)
Image1: TImage;
lblTitulo: TLabel;
editProcura: TEdit;
Label2: TLabel;
btProcuraCliente: TBitBtn;
grdResultado: TdxDBGrid;
quResult: TADOQuery;
dsResult: TDataSource;
lblResult: TLabel;
quResultIDPessoa: TIntegerField;
cmbField: TComboBox;
grdResultadoCodigoPessoa: TdxDBGridMaskColumn;
grdResultadoPessoa: TdxDBGridMaskColumn;
quResultCode: TIntegerField;
quResultPessoa: TStringField;
procedure btProcuraClienteClick(Sender: TObject);
procedure dsResultDataChange(Sender: TObject; Field: TField);
procedure grdResultadoDblClick(Sender: TObject);
procedure btOkClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function Start(IDTipoPessoa: Integer): Integer;
end;
implementation
uses uDM;
{$R *.DFM}
function TSisPessoaProcuraFrm.Start(IDTipoPessoa: Integer): Integer;
begin
quResult.Parameters.ParamByName('IDTipoPessoa').Value := IDTipoPessoa;
cmbField.ItemIndex := 0;
lblTitulo.Caption := DM.DescCodigo(['IDTipoPessoa'], [IntToStr(IDTipoPessoa)], 'TipoPessoa', 'TipoPessoa') + ' finder';
if (ShowModal = mrOk) then
result := quResultIDPessoa.AsInteger
else
result := -1;
end;
procedure TSisPessoaProcuraFrm.btProcuraClienteClick(Sender: TObject);
begin
inherited;
with quResult do
begin
if Active then
Close;
Parameters.ParamByName('CampoIndex').Value := cmbField.ItemIndex;
Parameters.ParamByName('Procura').Value := '%' + Trim(editProcura.text) + '%';
Open;
end;
end;
procedure TSisPessoaProcuraFrm.dsResultDataChange(Sender: TObject;
Field: TField);
begin
inherited;
with quResult do
begin
btOk.Enabled := ACTIVE AND (NOT (EOF AND BOF));
lblResult.Caption := IntToStr(RecordCount) + ' Pessoa(s) encontrada(s).';
end;
end;
procedure TSisPessoaProcuraFrm.grdResultadoDblClick(Sender: TObject);
begin
inherited;
if btOk.Enabled then
btOkClick(nil);
end;
procedure TSisPessoaProcuraFrm.btOkClick(Sender: TObject);
begin
inherited;
if quResultIDPessoa.AsString = '' then
ModalResult := mrNone
else
ModalResult := mrOk;
end;
end.
|
unit calculate.test;
interface
uses
calculate,
DUnitX.TestFramework;
type
[TestFixture]
TCalculateTest = class(TObject)
private
calc: TCalculate;
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
// Test with TestCase Attribute to supply parameters.
[Test]
[TestCase('TestA','1,2,3')]
[TestCase('TestB','3,4,7')]
procedure Test(const a: uint32; const b: uint32; r: uint32);
end;
implementation
procedure TCalculateTest.Setup;
begin
calc := TCalculate.Create;
end;
procedure TCalculateTest.TearDown;
begin
calc.DisposeOf;
end;
procedure TCalculateTest.Test(const a: uint32; const b: uint32; r: uint32);
var
v: uint32;
begin
v := calc.calc(a, b);
if v = r then
Assert.Pass('Passou nos testes!')
else
Assert.Fail('Não passou nos testes!');
end;
initialization
TDUnitX.RegisterTestFixture(TCalculateTest);
end.
|
//This unit controls loading the packet_db.txt into memory, and setting up
//procedures for executing packets.
unit Packets;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
Character,
Classes,
Contnrs,
PacketTypes;
(*------------------------------------------------------------------------------
Its a bit complex, but here is a rundown. (June 28th, 2008 - Tsusai)
You have a TPacketDB class. This contains multiple methods of accessing
packet data. The packet data breaks down into the following:
TPacketDB.fCodebase[0->? Array].EAPACKETVER -
TPacketDB.fCodebase[0->? Array].PacketList - List of TPackets. Stores individual packets data
as objects. Owns its list of objects.
TPacketDB.GetLength - Returns length of a packet based on ID and fCodeBase index
TPacketDB.GetPacketInfo - Same as above, but returns a TPacket object.
TPacketDB.GetMapConnectPacket - Finds the proper mapconnect packet
TPacketDB.GetEAPacketVer - Takes the fCodeBase index, and pulls out the EAPacketVer
------------------------------------------------------------------------------*)
type
//The more usual of the zone procedures
TPacketProc = procedure (var AChara : TCharacter; const RecvBuffer : TBuffer; const ReadPts : TReadPts);
//The Tchara, Avoidself packets. About 3 exist
TAvoidSelfPacketProc = procedure (var AChara : TCharacter; const AvoidSelf : boolean = False);
TPackets = class
ID : word; //PacketID
//Length, trying not to conflict with Length() command.
//[2006/03/12] Tsusai - MUST BE INTEGER TYPE! I messed it up using word.
PLength : integer;
Command : string;
ReadPoints : TReadPts;
ExecCommand : TPacketProc; //Regular procedure link
ExecAvoidSelfCommand : TAvoidSelfPacketProc; //avoidself special procedure link
end;
PPackets = ^TPackets;
//Packet List to replace PacketArray.
//Needs some destruction stuffs.
TPacketList = class(TObjectList)
public
procedure Assign(Source : TPacketList);
procedure Add(PacketObject : TPackets);
constructor Create;
end;
TCodebaseData = record
EAPACKETVER : word;
Packets : TPacketList;
end;
TPacketDB = class
private
fCodeBase : array of TCodeBaseData;
public
function GetLength(
ID : Word;
Version : Word = 0
) : LongWord;
procedure GetPacketInfo(
const Packet : word;
const Version : Word;
var ReturnPackets : TPackets
);
procedure GetMapConnectPacket(
const Packet : word;
const PLength : word;
var ReturnVersion : word;
var ReturnPacketInfo : TPackets
);
function GetEAPacketVer(InternalPacketDBVer : word) : word;
function Load : boolean;
procedure Unload;
end;
implementation
uses
SysUtils,
Main,
Globals,
ZoneRecv;
(**)
(**)
(*TPACKETLIST METHODS!!!!!*)
(**)
(**)
//------------------------------------------------------------------------------
//TPacketList.Assign PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Copies contents of one PacketList to another.
//
// Changes -
// June 28th, 2008 - Tsusai - Created.
//
//------------------------------------------------------------------------------
procedure TPacketList.Assign(Source : TPacketList);
var
idx : integer;
PacketObject : TPackets;
begin
if not Assigned(Self) then Self := TPacketList.Create;
Self.Clear;
for idx := 0 to Source.Count - 1 do
begin
PacketObject := TPackets.Create;
PacketObject.ID := TPackets(Source.Items[idx]).ID;
PacketObject.PLength := TPackets(Source.Items[idx]).PLength;
PacketObject.Command := TPackets(Source.Items[idx]).Command;
SetLength(PacketObject.ReadPoints,Length(TPackets(Source.Items[idx]).ReadPoints));
PacketObject.ReadPoints := Copy(TPackets(Source.Items[idx]).ReadPoints,0,Length(PacketObject.ReadPoints));
PacketObject.ExecCommand := TPackets(Source.Items[idx]).ExecCommand;
PacketObject.ExecAvoidSelfCommand := TPackets(Source.Items[idx]).ExecAvoidSelfCommand;
Add(PacketObject);
end;
end;
//------------------------------------------------------------------------------
//TPacketList.Add PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Packet adding/updating procedure
// For all new codelists after the first one, any different packets are
// updated, since each packet ver after the base is an updated diff.
// so packet ver 3 = packet ver 0 + 1 diff, + 2 diff + 3 diff
//
// Changes -
// June 28th, 2008 - Tsusai - Created.
//
//------------------------------------------------------------------------------
procedure TPacketList.Add(PacketObject : TPackets);
var
idx : integer;
begin
//Check for existing to update
for idx := 0 to Count - 1 do
begin
If TPackets(Items[idx]).ID = PacketObject.ID then
begin
TPackets(Items[idx]).ID := PacketObject.ID;
TPackets(Items[idx]).PLength := PacketObject.PLength;
TPackets(Items[idx]).Command := PacketObject.Command;
SetLength(TPackets(Items[idx]).ReadPoints,Length(PacketObject.ReadPoints));
TPackets(Items[idx]).ReadPoints := Copy(PacketObject.ReadPoints,0,Length(PacketObject.ReadPoints));
TPackets(Items[idx]).ExecCommand := PacketObject.ExecCommand;
TPackets(Items[idx]).ExecAvoidSelfCommand := PacketObject.ExecAvoidSelfCommand;
Exit; //Don't need to readd another, since we updated
end;
end;
//Didn't find one to update, add it.
inherited Add(PacketObject);
end;
//------------------------------------------------------------------------------
//TPacketList.Create CONSTRUCTOR
//------------------------------------------------------------------------------
// What it does-
// Sets the list to own its objects
//
// Changes -
// June 28th, 2008 - Tsusai - Created.
//
//------------------------------------------------------------------------------
constructor TPacketList.Create;
begin
inherited;
Self.OwnsObjects := True;
end;
(**)
(**)
(*TPACKETDB METHODS!!!!!*)
(**)
(**)
//------------------------------------------------------------------------------
//TPacketDB.GetLength FUNCTION
//------------------------------------------------------------------------------
// What it does-
// Gets the length of a packet specified by ID for version Version
//
// Changes -
// December 22nd, 2006 - RaX - Created.
// June 8th, 2008 - Tsusai - Updated to use the Packet Object List
// June 28th, 2008 - Tsusai - Moved into TPacketDB as GetLength
//
//------------------------------------------------------------------------------
function TPacketDB.GetLength(ID : Word; Version : Word = 0) : LongWord;
var
Index : Integer;
CodebaseLength : Integer;
begin
Result := 0;
CodebaseLength := fCodebase[Version].Packets.Count;
for Index := 0 to CodebaseLength - 1 do
begin
if TPackets(fCodebase[Version].Packets[Index]).ID = ID then
begin
Result := TPackets(fCodebase[Version].Packets[Index]).PLength;
break;
end;
end;
end;
//------------------------------------------------------------------------------
//TPacketDB.GetPacketInfo PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// This is only executed to find information about a packet for ingame/zone
// packets. If there is data, it returns a a valid object.
// External procedures must check this via if Assigned()
//
// Notes -
// packet - The integer packet id.
// Ver - The version of packets we are going to look at. This is called
// twice, first if we need to look through it with our new client packet,
// and if we can't find it, we need to search through the 0 version aka
// oldschool aka 0628sakexe based.
//
// Changes -
// June 28th, 2008 - Tsusai - Moved to TPacketDB, renamed, and upgraded
//
//------------------------------------------------------------------------------
Procedure TPacketDB.GetPacketInfo(
const Packet : word;
const Version : Word;
var ReturnPackets : TPackets
);
var
Index : Integer;
begin
ReturnPackets := nil; //Shouldn't have anything, and shuts up compiler warning
//about it being unassigned.
//Check packet list based on Version
for Index := 0 to fCodeBase[Version].Packets.Count - 1 do
begin
//With Statement..
with TPackets(fCodeBase[Version].Packets.Items[Index]) do
begin
if (ID = Packet) then
begin
//Ok so we found a matching packet ID, fill the info
ReturnPackets := TPackets.Create;
ReturnPackets.PLength := PLength;
SetLength(ReturnPackets.ReadPoints,Length(ReadPoints));
ReturnPackets.ReadPoints := Copy(ReadPoints,0,Length(ReadPoints));
ReturnPackets.Command := Command;
ReturnPackets.ExecCommand := ExecCommand;
ReturnPackets.ExecAvoidSelfCommand := ExecAvoidSelfCommand;
Break;
end;
end;
end;
end;
//------------------------------------------------------------------------------
//TPacketDB.GetMapConnectPacket PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Digs through all packet codebases, from newest to oldest lookgin for a
// 'wanttoconnect' that matches the ID, and PacketLength given. This routine
// will comb through using TPacketDB.GetPacketInfo until the end. If data is
// found, the TPacket object has data and is sent up to the caller in
// ZoneServer, where if there is no data, then ZoneServer gets no data.
// Obviously this must be checked with an if Assigned().
//
// Changes -
// June 28th, 2008 - Tsusai - Created
//
//------------------------------------------------------------------------------
procedure TPacketDB.GetMapConnectPacket(
const Packet : word;
const PLength : word;
var ReturnVersion : word;
var ReturnPacketInfo : TPackets
);
var
ClientBaseIndex : integer;
begin
for ClientBaseIndex := (Length(fCodeBase) -1) downto 0 do
begin
//Use the other TPacketDB method to find it based on ID and Version.
GetPacketInfo(Packet,ClientBaseIndex,ReturnPacketInfo);
if Assigned(ReturnPacketInfo) then
begin
//Check length and command
if (ReturnPacketInfo.Command = 'wanttoconnection') and (ReturnPacketInfo.PLength = PLength) then
begin
//Found it, set the version and exit
ReturnVersion := ClientBaseIndex;
Exit; //Exit since we found it.
end;
end;
end;
//Didn't find it, so free it. This will cause a unknown client error higher up
ReturnPacketInfo.Free;
end;
//------------------------------------------------------------------------------
//TPacketDB.GetEAPacketVer FUNCTION
//------------------------------------------------------------------------------
// What it does-
// By using our fCodeBase index number, which is usually stored in
// ACharacter.ClientVer, we can pull out the eA packet ver which is specified
// by the packet_db file
//
// Changes -
// June 28th, 2008 - Tsusai - Created
//
//------------------------------------------------------------------------------
function TPacketDB.GetEAPacketVer(InternalPacketDBVer : word) : word;
begin
Result := fCodeBase[InternalPacketDBVer].EAPACKETVER;
end;
(*------------------------------------------------------------------------------
TPacketDB.Load
Basic logic: load packets in a set in CodeBase[] until you see a packet that is
already listed. If so, increment CodeBase[], clone the data, and add/update
TODO:
--
Unknown.
--
Revisions:
--
[2006/01/01] CR - Reindented. Moved creation of "sl" stringlists closer to
first use. Left a note where a reported bug was, but could not figure out a
solution at this time.
[2006/03/10] Tsusai - Moved the Command elseif check to assign procedures to the
database to be called.
[2006/03/10] Tsusai - Renamed ExecSpecialCommand to ExecAvoidSelfCommand.
[2006/03/11] Tsusai - Renamed variables to something less stupid like sl.
changed variable types from integer to word/byte for certain parts of the loops.
Also removed packetID being stored as string, now being stored as a word type.
[2006/04/09] Tsusai - Adjusted expanding of packet array to prevent blank end
packet info.
[2006/09/26] Tsusai - Imported to Helios
January 20th 2007 - Tsusai - Now a function
June 8th 2008 - Tsusai - Overhauled. Introduced a packet object list, to hold
packet objects, instead of another array. Also implemented use of eAthena's
packet_db to help with easy updating.
June 28th, 2008 - Tsusai - Put in TPacketDB
------------------------------------------------------------------------------*)
function TPacketDB.Load : boolean;
Var
sidx : integer;
CBIdx : word;
ReadLoc : byte;
PacketVersion : integer;
packet_db : TStringList;
PacketInfo : TStringList;
PacketData : TPackets;
ReadPtInfo : TStringList;
Begin
Result := FileExists(MainProc.Options.DatabaseDirectory+'/'+'packet_db.txt');
if Result then
begin
PacketVersion := 0;
CBIdx := 0;
//Init the first list
SetLength(fCodebase,CBIdx+1);
fCodebase[CBIdx].EAPACKETVER := PacketVersion;
fCodebase[CBIdx].Packets := TPacketList.Create;
//load the packet_db file
packet_db := TStringList.Create;
packet_db.LoadFromFile(MainProc.Options.DatabaseDirectory+'/'+'packet_db.txt');
PacketInfo := TStringList.Create;
for sidx := 0 to (packet_db.Count -1) do
begin
//Look for packet_ver: sections
if Copy(packet_db.Strings[sidx],1,12) = ('packet_ver: ') then
begin
//Get the packet version # out of eA
PacketVersion := StrToInt(
StringReplace(packet_db.Strings[sidx],'packet_ver: ','',[rfReplaceAll])
);
//skip making a new packet version group if we're already using it (ie. packetver 0)
if PacketVersion = fCodebase[CBIdx].EAPACKETVER then continue;
//if we're hitting our first REAL packet version (ie the Client <> server packets)
//Then we're just going to give it a packetversion number, and add onto it.
//There should be no packetver 0, just whatever the first packetver is, plus
//any random packets like inter before it.
if fCodebase[CBIdx].EAPACKETVER = 0 then
begin
fCodebase[CBIdx].EAPACKETVER := PacketVersion;
Continue;
end;
Inc(CBIdx);
//Init New list
SetLength(fCodebase,CBIdx+1);
fCodebase[CBIdx].EAPACKETVER := PacketVersion;
fCodebase[CBIdx].Packets := TPacketList.Create;
//Copy contents from previous to new list
fCodebase[CBIdx].Packets.Assign(fCodeBase[CBIdx-1].Packets);
//Go to next line, we're done with setup
Continue;
end else if (Copy(packet_db[sidx],1,2) <> '0x') then
begin
Continue; //we are ignoring comments and other crap
end;
//READ THE PACKET DATA (>^.^>)
PacketData := TPackets.Create;
PacketInfo.CommaText := packet_db[sidx];// break up the information by commas
if (PacketInfo.Count >= 2) then
begin
PacketData.ID := StrToIntDef( StringReplace(PacketInfo[0], 'Ox', '$', [rfReplaceAll]),0);
PacketData.PLength := StrToIntDef(PacketInfo[1],0);//Save the packet length
end;
if (PacketInfo.Count = 4) then
begin
PacketData.Command := PacketInfo[2]; //Procedure name to run
//Loading all the procedural read packet locations
ReadPtInfo := TStringList.Create;
ReadPtInfo.Delimiter := ':';
ReadPtInfo.DelimitedText := PacketInfo[3];
SetLength(PacketData.ReadPoints, ReadPtInfo.Count);
for ReadLoc := 0 to (ReadPtInfo.Count -1) do
begin
PacketData.ReadPoints[ReadLoc] := StrToInt(ReadPtInfo[ReadLoc]);
{[2006/01/01] CR - ERangeError reported here at +36 in Rev 582...
don't know if it was a corrupt line in the file, or what the issue is,
at this point. }
end;
ReadPtInfo.Free;
end else begin
PacketData.Command := 'nocommand';
SetLength(PacketData.ReadPoints, 1);
PacketData.ReadPoints[0] := 0;
end;
with PacketData do begin
//Blank out the procedures with dummy ones.
ExecCommand := NoCommand;
ExecAvoidSelfCommand := NoCommand;
//Find the right procedure to assign to the database
if Command = 'loadendack' then begin
ExecCommand := ShowMap;
end else if Command = 'ticksend' then begin
ExecCommand := RecvTick;
end else if Command = 'walktoxy' then begin
ExecCommand := CharacterWalkRequest;
end else if Command = 'actionrequest' then begin
ExecCommand := ActionRequest;
end else if Command = 'globalmessage' then begin
ExecCommand := AreaChat;
end else if Command = 'npcclicked' then begin
ExecCommand := NPCClick;
end else if Command = 'getcharnamerequest' then begin
ExecCommand := GetNameAndID;
end else if Command = 'wis' then begin
ExecCommand := Whisper;
end else if Command = 'gmmessage' then begin
ExecCommand := GMBroadcast;
end else if Command = 'changedir' then begin
ExecCommand := CharaRotation;
end else if Command = 'takeitem' then begin
ExecCommand := TakeItem;
end else if Command = 'dropitem' then begin
ExecCommand := DropItem;
end else if Command = 'useitem' then begin
ExecCommand := ItemUse;
end else if Command = 'equipitem' then begin
ExecCommand := ItemEquip;
end else if Command = 'unequipitem' then begin
ExecCommand := ItemUnequip;
end else if Command = 'restart' then begin
ExecCommand := ReturnToCharacterSelect;
end else if Command = 'npcselectmenu' then begin
ExecCommand := NPCMenu;
end else if Command = 'npcnextclicked' then begin
ExecCommand := NPCNext;
end else if Command = 'statusup' then begin
ExecCommand := StatUP;
end else if Command = 'emotion' then begin
ExecCommand := EmotionCheck;
end else if Command = 'howmanyconnections' then begin
ExecCommand := SlashWho;
{end else if Command = 'npcbuysellselected' then begin
ExecCommand := ClickNPCshop;
end else if Command = 'npcbuylistsend' then begin
ExecCommand := BuyFromNPC;
end else if Command = 'npcselllistsend' then begin
ExecCommand := SellToNPC;
end else if Command = 'gmkick' then begin
ExecCommand := GMRightClickKill;
//Unknown eA block here
end else if Command = 'killall' then begin
ExecCommand := KillAll;
end else if Command = 'wisexin' then begin
ExecCommand := wisexin;
end else if Command = 'wisall' then begin
ExecCommand := wisall;
end else if Command = 'wisexlist' then begin
ExecCommand := wisexlist;}
//end of first unknown eA block
end else if Command = 'createchatroom' then begin
ExecCommand := CreateChatroom;
end else if Command = 'chataddmember' then begin
ExecCommand := JoinChatroom;
end else if Command = 'chatroomstatuschange' then begin
ExecCommand := UpdateChatroom;
end else if Command = 'changechatowner' then begin
ExecCommand := ChatroomOwnerChange;
end else if Command = 'kickfromchat' then begin
ExecCommand := KickFromChatroom;
end else if Command = 'chatleave' then begin
ExecCommand := ChatRoomExit;
{end else if Command = 'traderequest' then begin
ExecCommand := RequestTrade;
end else if Command = 'tradeack' then begin
ExecCommand := TradeRequestAcceptDeny;
end else if Command = 'tradeadditem' then begin
ExecCommand := AddItemToTrade;
end else if Command = 'tradeok' then begin
ExecCommand := TradeAccept;
end else if Command = 'tradecancel' then begin
ExecAvoidSelfCommand := CancelDealings;
end else if Command = 'tradecommit' then begin
ExecCommand := ConfirmTrade;
end else if Command = 'movetokafra' then begin
ExecCommand := AddToStorage;
end else if Command = 'movefromkafra' then begin
ExecCommand := RemoveFromStorage;
end else if Command = 'closekafra' then begin
ExecCommand := CloseStorage;
end else if Command = 'createparty' then begin
ExecCommand := CreateParty;
end else if Command = 'partyinvite' then begin
ExecCommand := InviteToParty;
end else if Command = 'replypartyinvite' then begin
ExecCommand := PartyInviteReply;
end else if Command = 'leaveparty' then begin
ExecCommand := RequestLeaveParty;
end else if Command = 'partychangeoption' then begin
ExecCommand := ChangePartySettings;
end else if Command = 'removepartymember' then begin
ExecCommand := KickPartyMember;
end else if Command = 'partymessage' then begin
ExecCommand := MessageParty;
end else if Command = 'skillup' then begin
ExecCommand := SkillUP;
end else if Command = 'useskilltoid' then begin
ExecCommand := UseSkillOnID;
end else if Command = 'useskilltopos' then begin
if Length(ReadPoints) = 4 then
begin
ExecCommand := UseSkillOnXY;
end;
if Length(ReadPoints) = 5 then
begin
ExecCommand := UseSkillOnXYExtra;
end;}
end else if Command = 'stopattack' then begin
ExecCommand := CancelAttack;{
end else if Command = 'useskillmap' then begin
ExecCommand := UseSkillOnMap;
end else if Command = 'requestmemo' then begin
ExecCommand := SaveMemoRequest;
end else if Command = 'putitemtocart' then begin
ExecCommand := ItemInventoryToCart;
end else if Command = 'getitemfromcart' then begin
ExecCommand := ItemCartToInventory;
end else if Command = 'movefromkafratocart' then begin
ExecCommand := ItemKafraToCart;
end else if Command = 'movetokafrafromcart' then begin
ExecCommand := ItemCartToKafra;
end else if Command = 'removeoption' then begin
ExecCommand := CharaOptionOff;
end else if Command = 'closevending' then begin
ExecAvoidSelfCommand := VenderExit;
end else if Command = 'vendinglistreq' then begin
ExecCommand := VenderItemList;
end else if Command = 'purchasereq' then begin
ExecCommand := BuyFromVender;
end else if Command = 'itemmonster' then begin
ExecCommand := GMSummonItemMob;}
end else if Command = 'mapmove' then begin
ExecCommand := GMMapMove;
end else if Command = 'recall' then begin
ExecCommand := GMRecall;
end else if Command = 'npcamountinput' then begin
ExecCommand := NPCIntegerInput;
{end else if Command = 'npccloseclicked' then begin
ExecCommand := NPCClickClose;
end else if Command = 'gmreqnochat' then begin
ExecCommand := GMRequestNoChat;
end else if Command = 'guildcheckmaster' then begin
ExecCommand := GuildCheckMaster;
end else if Command = 'guildrequestinfo' then begin
ExecCommand := GuildRequestInfoPage;
end else if Command = 'guildrequestemblem' then begin
ExecCommand := GuildRequestEmblem;
end else if Command = 'guildchangeemblem' then begin
ExecCommand := GuildChangeEmblem;
end else if Command = 'guildchangememberposition' then begin
ExecCommand := GuildRequestMemberChange;
end else if Command = 'guildleave' then begin
ExecCommand := GuildCharaLeave;
end else if Command = 'guildexplusion' then begin
ExecCommand := GuildCharaBan;
end else if Command = 'guildbreak' then begin
ExecCommand := GuildDissolve;
end else if Command = 'guildchangepositioninfo' then begin
ExecCommand := GuildChangePositionInfo;
end else if Command = 'createguild' then begin
ExecCommand := CreateGuild;
end else if Command = 'guildinvite' then begin
ExecCommand := GuildInviteChara;
end else if Command = 'guildreplyinvite' then begin
ExecCommand := GuildCharaInviteReply;
end else if Command = 'guildchangenotice' then begin
ExecCommand := GuildSetAnnouncement;
end else if Command = 'guildrequestalliance' then begin
ExecCommand := GuildRequestAlly;
end else if Command = 'guildreplyalliance' then begin
ExecCommand := GuildRequestAllyResponse;
end else if Command = 'itemidentify' then begin
ExecCommand := AppraiseItem;
end else if Command = 'usecard' then begin
ExecCommand := UseCard;
end else if Command = 'insertcard' then begin
ExecCommand := CardMountRequest;
end else if Command = 'guildmessage' then begin
ExecCommand := MessageGuild;
end else if Command = 'guildopposition' then begin
ExecCommand := OpposeGuild;
end else if Command = 'guilddelalliance' then begin
ExecCommand := CancelGuildRelation;}
end else if Command = 'quitgame' then begin
ExecCommand := QuitGame;{
end else if Command = 'producemix' then begin
ExecCommand := CreateItem;
end else if Command = 'useskilltoposinfo' then begin
ExecCommand := UseSkillOnXYExtra;
end else if Command = 'solvecharname' then begin
ExecCommand := SolveCharaName;
end else if Command = 'resetchar' then begin
ExecCommand := GMReset;
end else if Command = 'lgmmessage' then begin
ExecCommand := lgmmessage;
end else if Command = 'gmhide' then begin
ExecCommand := GMHide;
end else if Command = 'catchpet' then begin
ExecCommand := CaptureMonster;
end else if Command = 'petmenu' then begin
ExecCommand := PetMenuAction;
end else if Command = 'changepetname' then begin
ExecCommand := ChangePetName;
end else if Command = 'selectegg' then begin
ExecCommand := SelectPetEgg;
end else if Command = 'sendemotion' then begin
ExecCommand := SendPetEmotion;
end else if Command = 'selectarrow' then begin
ExecCommand := SelectArrow;
end else if Command = 'changecart' then begin
ExecCommand := ChangeCart;
end else if Command = 'openvending' then begin
ExecCommand := OpenVendingShop;}
end else if Command = 'shift' then begin
ExecCommand := GMShiftChar;
{end else if Command = 'summon' then begin
ExecCommand := GMSummonChar;
end else if Command = 'autospell' then begin
ExecCommand := AutoSpellSelect;}
end else if Command = 'npcstringinput' then begin
ExecCommand := NPCStringInput;
{end else if Command = 'gmreqnochatcount' then begin
ExecCommand := GMReqNoChatCount;
end else if Command = 'sndoridori' then begin
ExecCommand := SNDoridori;
end else if Command = 'createparty2' then begin
ExecCommand := CreatParty2;
end else if Command = 'snexplosionspirits' then begin
ExecCommand := SNExplosionSpirits; }
end else if Command = 'friendslistadd' then begin
ExecCommand := RequestToAddFriend;
end else if Command = 'friendslistremove' then begin
ExecCommand := RemoveFriendFromList;
end else if Command = 'friendlistreply' then begin
ExecCommand := RequestToAddFriendResponse;
end else if Command = 'mailwinopen' then begin
ExecCommand := MailWindowSwitch;
end else if Command = 'mailrefresh' then begin
ExecCommand := RequestMailRefresh;
end else if Command = 'mailread' then begin
ExecCommand := ReadMail;
end else if Command = 'maildelete' then begin
ExecCommand := DeleteMail;
end else if Command = 'mailsend' then begin
ExecCommand := RequestSendMail;
end else if Command = 'hotkey' then begin
ExecCommand := SaveHotKey;
end;
end;
//Add data (or update, .Add knows how) to current work list
fCodeBase[CBIdx].Packets.Add(PacketData);
end;
packet_db.Free; //free the stringlist with the text
//PacketInfo.Free; (Can't free, else it'll free the last object in the last list!!!!!! (x.x)'
end else begin
Console.WriteLn('*** '+MainProc.Options.DatabaseDirectory+'/'+'packet_db.txt was not found.');
end;
End; (* Proc TPacketDB.Load
*-----------------------------------------------------------------------------*)
///------------------------------------------------------------------------------
//TPacketDB.Unload PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Unloads the database
//
// Changes -
// June 28th, 2008 - Tsusai - Created
//
//------------------------------------------------------------------------------
procedure TPacketDB.Unload;
var
idx : integer;
begin
for idx := 0 to Length(fCodeBase) - 1 do
begin
//Free lists
fCodeBase[idx].Packets.Free;
end;
//Shut down the array of lists.
SetLength(fCodebase,0);
end;
end.
|
unit CCJS_CheckPickPharmacy;
(****************************************************************************
* © PgkSoft 24.03.2015
* Механизм выбора (пожбора) аптеки для курьерской доставки
* Обработка результатов анализа состояния остатков на аптеке, в
* том числе срокового товара.
* Окончательный выбор (подбор аптеки)
****************************************************************************)
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, ExtCtrls, ComCtrls, ToolWin, ActnList, DB, ADODB,
StdCtrls;
type
TfrmCCJS_CheckPickPharmacy = class(TForm)
statusBar: TStatusBar;
pnlHeader: TPanel;
pnlTool: TPanel;
pnlTool_Show: TPanel;
pnlTool_Bar: TPanel;
pnlControl: TPanel;
pnlControl_Bar: TPanel;
pnlControl_Show: TPanel;
pnlGrid: TPanel;
gMain: TDBGrid;
aList: TActionList;
tlbarControl: TToolBar;
aControl_Close: TAction;
tlbtnControl_Close: TToolButton;
dsCheck: TDataSource;
qrspCheck: TADOStoredProc;
spAutoNumberReserve: TADOStoredProc;
pnlHeader_Pharmacy: TPanel;
aControl_Select: TAction;
tlbtnControl_Select: TToolButton;
tlbarTool: TToolBar;
aTool_SelectItem: TAction;
tlbtnTool_SelectItemReserve: TToolButton;
spSetNumberToReserve: TADOStoredProc;
pnlTool_Fields: TPanel;
aTool_ClearSelectItem: TAction;
spSetPharmacy: TADOStoredProc;
aControl_AddPharmacy: TAction;
pnlTool_Fields_01: TPanel;
pnlTool_Fields_02: TPanel;
lblNumberToReserve: TLabel;
cmbxNumberToReserve: TComboBox;
tlbarTool_Fields: TToolBar;
aTool_Fileds_OK: TAction;
tlbtnTool_Fields_OK: TToolButton;
spCountOtherDistrib: TADOStoredProc;
spAddPharmacy: TADOStoredProc;
spGetPickItemDistributePosCount: TADOStoredProc;
spSumReserve: TADOStoredProc;
procedure FormCreate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure aControl_CloseExecute(Sender: TObject);
procedure gMainDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
procedure dsCheckDataChange(Sender: TObject; Field: TField);
procedure aControl_SelectExecute(Sender: TObject);
procedure aTool_SelectItemExecute(Sender: TObject);
procedure aTool_ClearSelectItemExecute(Sender: TObject);
procedure aControl_AddPharmacyExecute(Sender: TObject);
procedure aTool_Fileds_OKExecute(Sender: TObject);
private
{ Private declarations }
ISign_Activate : integer;
Mode : integer; { Режим работы }
PRN : integer;
BigIdAction : int64; { Уникальный идентификатор процесса }
IDUSER : integer;
ItemCode : integer;
Pharmacy : integer;
NamePharmacy : string;
SIDENT : string;
Order : integer;
ModeReserve : smallint;
procedure ShowGets;
procedure CreateCondition;
procedure ExecCondition;
procedure GridRefresh;
procedure InitStatusBar;
public
{ Public declarations }
procedure SetMode(cFMode : integer);
procedure SetPRN(Param : integer);
procedure SetBigIdAction(IdAction : int64);
procedure SetUSER(Param : integer);
procedure SetItemCode(Param : integer);
procedure SetPharmacy(Param : integer);
procedure SetNamePharmacy(Param : string);
procedure SetOrder(Param : integer);
procedure SetSIDENT(Param : string);
procedure SetModeReserve(Param : smallint);
function GetCountOtherDistrib: integer;
function GetPickItemDistributePosCount(ArtCodeTerm : integer): integer;
function GetSumReserve: integer;
end;
const
{ Режимы работы }
cFCCJS_CheckPP_ArtCode_Distribute = 0; { Для выбранной (текущей) товарной позиции при ее распределении по аптекам }
cFCCJS_CheckPP_ArtCode_Pharmacy = 1; { Для выбранной (текущей) товарной позиции }
cFCCJS_CheckPP_Order_Pharmacy = 2; { Для всех позиций заказа }
var
frmCCJS_CheckPickPharmacy: TfrmCCJS_CheckPickPharmacy;
implementation
uses UTIL, Umain, ExDBGRID, UCCenterJournalNetZkz, CCJS_PickPharmacy;
{$R *.dfm}
procedure TfrmCCJS_CheckPickPharmacy.FormCreate(Sender: TObject);
begin
ISign_Activate := 0;
ModeReserve := 0;
PRN := 0;
Pharmacy := 0;
Order := 0;
IDUSER := 0;
Mode := -1;
end;
procedure TfrmCCJS_CheckPickPharmacy.FormActivate(Sender: TObject);
var
IErr : integer;
SErr : string;
SCaption : string;
begin
if ISign_Activate = 0 then begin
cmbxNumberToReserve.Clear;
{ Заголовок}
SCaption := 'Аптека ' + NamePharmacy;
pnlHeader_Pharmacy.Caption := SCaption;
{ pnlHeader_Pharmacy.Width := TextPixWidth(SCaption, pnlHeader_Pharmacy.Font) + 20; }
{ Иконка формы }
if Mode = cFCCJS_CheckPP_ArtCode_Distribute then begin
pnlTool_Bar.Visible := false;
pnlTool_Fields_01.Visible := true;
pnlTool_Fields_02.Visible := true;
FCCenterJournalNetZkz.imgMain.GetIcon(101,self.Icon);
self.Caption := 'Добавить аптеку';
tlbtnControl_Select.Action := aControl_AddPharmacy;
end
else if Mode = cFCCJS_CheckPP_ArtCode_Pharmacy then begin
pnlTool_Bar.Visible := true;
pnlTool_Fields_01.Visible := false;
pnlTool_Fields_02.Visible := false;
FCCenterJournalNetZkz.imgMain.GetIcon(102,self.Icon);
self.Caption := 'Выбрать аптеку';
tlbtnControl_Select.Action := aControl_Select;
end
else if Mode = cFCCJS_CheckPP_Order_Pharmacy then begin
pnlTool_Bar.Visible := true;
pnlTool_Fields_01.Visible := false;
pnlTool_Fields_02.Visible := false;
FCCenterJournalNetZkz.imgMain.GetIcon(102,self.Icon);
self.Caption := 'Выбрать аптеку для всех позиций заказа';
tlbtnControl_Select.Action := aControl_Select;
end
else begin
pnlTool_Bar.Visible := false;
pnlTool_Fields_01.Visible := false;
pnlTool_Fields_02.Visible := false;
FCCenterJournalNetZkz.imgMain.GetIcon(108,self.Icon);
self.Caption := 'Добавить аптеку';
aControl_Select.Enabled := false;
aControl_AddPharmacy.Enabled := false;
end;
if (Mode = cFCCJS_CheckPP_ArtCode_Pharmacy) or (Mode = cFCCJS_CheckPP_Order_Pharmacy) then begin
statusBar.SimpleText := 'Определяем количество для резервирования...';
{ Автоматическое проставление количества }
IErr := 0;
SErr := '';
try
spAutoNumberReserve.Parameters.ParamValues['@NIdentPharmacy'] := BigIdAction;
spAutoNumberReserve.Parameters.ParamValues['@SIDENT'] := SIDENT;
spAutoNumberReserve.Parameters.ParamValues['@Order'] := Order;
spAutoNumberReserve.Parameters.ParamValues['@IDUser'] := IDUSER;
spAutoNumberReserve.ExecProc;
IErr := spAutoNumberReserve.Parameters.ParamValues['@RETURN_VALUE'];
if IErr <> 0 then begin
SErr := spAutoNumberReserve.Parameters.ParamValues['@SErr'];
ShowMessage('Сбой при определении количества для резервирования.' + chr(10) + SErr);
end;
except
on e:Exception do begin
ShowMessage('Сбой при определении количества для резервирования.' + chr(10) + e.Message);
end;
end;
end
else if (Mode = cFCCJS_CheckPP_ArtCode_Distribute) then begin
end;
ExecCondition;
ISign_Activate := 1;
ShowGets;
end;
end;
procedure TfrmCCJS_CheckPickPharmacy.InitStatusBar;
var
MsgInit : string;
begin
MsgInit := 'АртКод ' + gMain.DataSource.DataSet.FieldByName('NArtCode').AsString;
if gMain.DataSource.DataSet.FieldByName('ISignTerm').AsInteger = 1 then begin
MsgInit := MsgInit + ', ' + 'сроковый АртКод ' + gMain.DataSource.DataSet.FieldByName('NArtCodeTerm').AsString;
end;
statusBar.SimpleText := MsgInit;
end;
procedure TfrmCCJS_CheckPickPharmacy.ShowGets;
var
SCaption : string;
begin
if ISign_Activate = 1 then begin
InitStatusBar;
{ Количество строк }
SCaption := VarToStr(qrspCheck.RecordCount);
pnlTool_Show.Caption := SCaption;
pnlTool_Show.Width := TextPixWidth(SCaption, pnlTool_Show.Font) + 40;
{ Доступ к действиям }
if GetSumReserve = 0 then begin
aControl_Select.Enabled := false;
aControl_AddPharmacy.Enabled := false;
end else begin
aControl_Select.Enabled := true;
aControl_AddPharmacy.Enabled := true;
end;
end;
end;
procedure TfrmCCJS_CheckPickPharmacy.SetMode(cFMode : integer); begin Mode := cFMode; end;
procedure TfrmCCJS_CheckPickPharmacy.SetPRN(Param : integer); begin PRN := Param; end;
procedure TfrmCCJS_CheckPickPharmacy.SetBigIdAction(IdAction : int64); begin BigIdAction := IdAction; end;
procedure TfrmCCJS_CheckPickPharmacy.SetUSER(Param : integer); begin IDUSER := Param; end;
procedure TfrmCCJS_CheckPickPharmacy.SetItemCode(Param : integer); begin ItemCode := Param; end;
procedure TfrmCCJS_CheckPickPharmacy.SetPharmacy(Param : integer); begin Pharmacy := Param; end;
procedure TfrmCCJS_CheckPickPharmacy.SetOrder(Param : integer); begin Order := Param; end;
procedure TfrmCCJS_CheckPickPharmacy.SetSIDENT(Param : string); begin SIDENT := Param; end;
procedure TfrmCCJS_CheckPickPharmacy.SetNamePharmacy(Param : string); begin NamePharmacy := Param; end;
procedure TfrmCCJS_CheckPickPharmacy.SetModeReserve(Param : smallint); begin ModeReserve := Param; end;
function TfrmCCJS_CheckPickPharmacy.GetCountOtherDistrib: integer;
var
CountOtherDistrib : integer;
begin
CountOtherDistrib := 0;
try
spCountOtherDistrib.Parameters.ParamValues['@NIdentPharmacy'] := BigIdAction;
spCountOtherDistrib.Parameters.ParamValues['@NRN'] := gMain.DataSource.DataSet.FieldByName('NRN').AsInteger;
spCountOtherDistrib.ExecProc;
CountOtherDistrib := spCountOtherDistrib.Parameters.ParamValues['@CountOtherDistrib'];
except
on e:Exception do
begin
CountOtherDistrib := 987654321;
ShowMessage('Сбой при расчета количества для резервирования в других позициях'+chr(10)+e.Message);
end;
end;
result := CountOtherDistrib;
end;
function TfrmCCJS_CheckPickPharmacy.GetPickItemDistributePosCount(ArtCodeTerm : integer): integer;
var
PosCount : integer;
begin
PosCount := 0;
try
spGetPickItemDistributePosCount.Parameters.ParamValues['@RN'] := PRN;
spGetPickItemDistributePosCount.Parameters.ParamValues['@IDENT'] := SIDENT;
spGetPickItemDistributePosCount.Parameters.ParamValues['@Pharmacy'] := Pharmacy;
spGetPickItemDistributePosCount.Parameters.ParamValues['@TermArtCode'] := ArtCodeTerm;
spGetPickItemDistributePosCount.ExecProc;
PosCount := spGetPickItemDistributePosCount.Parameters.ParamValues['@Count'];
except
on e:Exception do
begin
ShowMessage('Сбой при определении количества товара, распределенного по аптекам'+chr(10)+e.Message);
end;
end;
result := PosCount;
end;
function TfrmCCJS_CheckPickPharmacy.GetSumReserve: integer;
Var
SumReserve : integer;
begin
SumReserve := 0;
try
spSumReserve.Parameters.ParamValues['@NIdentPharmacy'] := BigIdAction;
spSumReserve.ExecProc;
SumReserve := spSumReserve.Parameters.ParamValues['@SumReserve'];
except
on e:Exception do
begin
ShowMessage('Сбой при расчете суммы количества для резервирования'+chr(10)+e.Message);
end;
end;
result := SumReserve;
end;
procedure TfrmCCJS_CheckPickPharmacy.ExecCondition;
var
RNOrderID: Integer;
begin
if not qrspCheck.IsEmpty then RNOrderID := qrspCheck.FieldByName('NArtCodeTerm').AsInteger else RNOrderID := -1;
if qrspCheck.Active then qrspCheck.Active := false;
CreateCondition;
qrspCheck.Active := true;
qrspCheck.Locate('NArtCodeTerm', RNOrderID, []);
ShowGets;
end;
procedure TfrmCCJS_CheckPickPharmacy.CreateCondition;
begin
qrspCheck.Parameters.ParamValues['@NIdentPharmacy'] := BigIdAction;
qrspCheck.Parameters.ParamValues['@SIDENT'] := SIDENT;
qrspCheck.Parameters.ParamValues['@Order'] := Order;
end;
procedure TfrmCCJS_CheckPickPharmacy.GridRefresh;
var
RN: Integer;
begin
if not qrspCheck.IsEmpty then RN := qrspCheck.FieldByName('NRN').AsInteger else RN := -1;
qrspCheck.Requery;
qrspCheck.Locate('NRN', RN, []);
end;
procedure TfrmCCJS_CheckPickPharmacy.aControl_CloseExecute(Sender: TObject);
begin
self.Close;
end;
procedure TfrmCCJS_CheckPickPharmacy.gMainDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
db : TDBGrid;
NRemn : integer;
NArmour : integer;
NCountItemOrder : integer;
NumberToReserve : integer;
begin
if Sender = nil then Exit;
db := TDBGrid(Sender);
NRemn := db.DataSource.DataSet.FieldByName('NRemn').AsInteger;
NArmour := db.DataSource.DataSet.FieldByName('NArmour').AsInteger;
NCountItemOrder := db.DataSource.DataSet.FieldByName('NCountItemOrder').AsInteger;
NumberToReserve := db.DataSource.DataSet.FieldByName('NumberToReserve').AsInteger;
if (gdSelected in State) then begin
db.Canvas.Font.Style := [fsBold];
end;
if not (gdSelected in State) then begin
{ Сроковый товар }
if db.DataSource.DataSet.FieldByName('ISignTerm').AsInteger = 1 then begin
db.Canvas.Brush.Color := TColor($D3EFFE); { светло-коричневый }
end;
{ Выделение поля для редактирования }
if Column.FieldName = 'NumberToReserve' then begin
{ Подкрашиваются только строки, в которых нужно определить значение }
if (Mode = cFCCJS_CheckPP_ArtCode_Pharmacy) or (Mode = cFCCJS_CheckPP_Order_Pharmacy) then begin
if (
(gMain.DataSource.DataSet.FieldByName('NCountArtCode').AsInteger = 1)
and (gMain.DataSource.DataSet.FieldByName('NEnoughArtCode').AsInteger = 1)
)
or
(
(gMain.DataSource.DataSet.FieldByName('NCountArtCode').AsInteger > 1)
and (gMain.DataSource.DataSet.FieldByName('NEnoughArtCode').AsInteger = 1)
)
or
(gMain.DataSource.DataSet.FieldByName('NEnoughArtCode').AsInteger = 0)
then begin
{}
end else begin
{ Доступны товарные позиции с возможностью выбора по несколькими арткодами и достаточным количеством }
if gMain.DataSource.DataSet.FieldByName('NCountDefinedArtCode').AsInteger = 0
then db.Canvas.Brush.Color := TColor($80FFFF); { светло-желтый };
end;
end
else if (Mode = cFCCJS_CheckPP_ArtCode_Distribute) then begin
db.Canvas.Brush.Color := TColor($80FFFF); { светло-желтый }
end;
end;
if (NRemn - NArmour) < NCountItemOrder then begin
{ не хватает остатков для резервирования }
db.Canvas.Font.Color := TColor(clRed);
end else begin
{ Хватает остатков для резервирования }
if NumberToReserve = 0 then begin
db.Canvas.Font.Color := TColor(clGreen);
end
else if NumberToReserve < NCountItemOrder then begin
db.Canvas.Font.Color := TColor(clBlue);
end;
end;
end;
db.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
procedure TfrmCCJS_CheckPickPharmacy.dsCheckDataChange(Sender: TObject; Field: TField);
var
iCkl : integer;
PickItemDistributeCount : integer;
CountOtherDistrib : integer;
NumberToReserve : integer;
NRemn : integer;
NArmour : integer;
NCountItemOrder : integer;
DistribPosCount : integer;
ArtCodeTerm : integer;
ArtCode : integer;
begin
tlbtnTool_SelectItemReserve.Action := aTool_SelectItem;
pnlTool_Bar.Width := tlbtnTool_SelectItemReserve.Width + 10;
if (not qrspCheck.IsEmpty) then begin
{ Для каждой товарной позиции управление доступом к определению значения NumberToReserve}
if (Mode = cFCCJS_CheckPP_ArtCode_Pharmacy) or (Mode = cFCCJS_CheckPP_Order_Pharmacy) then begin
if (
(gMain.DataSource.DataSet.FieldByName('NCountArtCode').AsInteger = 1)
and (gMain.DataSource.DataSet.FieldByName('NEnoughArtCode').AsInteger = 1)
)
or
(
(gMain.DataSource.DataSet.FieldByName('NCountArtCode').AsInteger > 1)
and (gMain.DataSource.DataSet.FieldByName('NEnoughArtCode').AsInteger = 1)
)
or
(gMain.DataSource.DataSet.FieldByName('NEnoughArtCode').AsInteger = 0)
then begin
aTool_SelectItem.Enabled := false;
aTool_ClearSelectItem.Enabled := false;
end else begin
{ Доступны товарные позиции с возможностью выбора по несколькими арткодами и достаточным количеством }
if gMain.DataSource.DataSet.FieldByName('NCountDefinedArtCode').AsInteger = 0 then begin
aTool_SelectItem.Enabled := true;
aTool_ClearSelectItem.Enabled := false;
end else begin
if gMain.DataSource.DataSet.FieldByName('NumberToReserve').AsInteger = gMain.DataSource.DataSet.FieldByName('NCountItemOrder').AsInteger then begin
tlbtnTool_SelectItemReserve.Action := aTool_ClearSelectItem;
pnlTool_Bar.Width := tlbtnTool_SelectItemReserve.Width + 10;
aTool_SelectItem.Enabled := false;
aTool_ClearSelectItem.Enabled := true;
end else begin
aTool_SelectItem.Enabled := false;
aTool_ClearSelectItem.Enabled := false;
end;
end;
end;
end
else if (Mode = cFCCJS_CheckPP_ArtCode_Distribute) then begin
ArtCode := gMain.DataSource.DataSet.FieldByName('NArtCode').AsInteger;
ArtCodeTerm := gMain.DataSource.DataSet.FieldByName('NArtCodeTerm').AsInteger;
if ArtCode = ArtCodeTerm then ArtCodeTerm := 0;
PickItemDistributeCount := TfrmCCJS_PickPharmacy(Owner).GetPickItemDistributeCount;
CountOtherDistrib := GetCountOtherDistrib;
DistribPosCount := GetPickItemDistributePosCount(ArtCodeTerm);
NRemn := gMain.DataSource.DataSet.FieldByName('NRemn').AsInteger;
NArmour := gMain.DataSource.DataSet.FieldByName('NArmour').AsInteger;
NCountItemOrder := gMain.DataSource.DataSet.FieldByName('NCountItemOrder').AsInteger;
if (NRemn-NArmour-DistribPosCount) > ((NCountItemOrder-PickItemDistributeCount) - CountOtherDistrib)
then NumberToReserve := (NCountItemOrder-PickItemDistributeCount) - CountOtherDistrib
else NumberToReserve := (NRemn-NArmour-DistribPosCount);
if NumberToReserve <= 0 then begin
tlbtnTool_Fields_OK.Enabled := false;
NumberToReserve := 0;
end else tlbtnTool_Fields_OK.Enabled := true;
{ Расчет (автозаполнение) доступного количества для текущей позиции }
cmbxNumberToReserve.Clear;
for iCkl := 0 to NumberToReserve do begin
cmbxNumberToReserve.Items.Add(IntToStr(iCkl));
end;
cmbxNumberToReserve.ItemIndex := cmbxNumberToReserve.Items.Count-1;
end;
end else begin
aTool_SelectItem.Enabled := false;
end;
ShowGets;
end;
procedure TfrmCCJS_CheckPickPharmacy.aControl_SelectExecute(Sender: TObject);
var
IErr : integer;
SErr : string;
begin
if (MessageDLG('Подтвердите выполнение операции.',mtConfirmation,[mbYes,mbNo],0) = mrNo) then exit;
try
spSetPharmacy.Parameters.ParamValues['@NIdentPharmacy'] := BigIdAction;
spSetPharmacy.Parameters.ParamValues['@IDUser'] := IDUSER;
spSetPharmacy.Parameters.ParamValues['@Pharmacy'] := Pharmacy;
spSetPharmacy.Parameters.ParamValues['@SIDENT'] := SIDENT;
spSetPharmacy.Parameters.ParamValues['@Order'] := Order;
spSetPharmacy.ExecProc;
IErr := spSetPharmacy.Parameters.ParamValues['@RETURN_VALUE'];
if IErr <> 0 then begin
SErr := spSetPharmacy.Parameters.ParamValues['@SErr'];
ShowMessage('Сбой при сохранении результатов выбора аптеки.' + chr(10) + SErr);
end;
except
on e:Exception do begin
ShowMessage('Сбой при сохранении результатов выбора аптеки.' + chr(10) + e.Message);
end;
end;
self.Close;
end;
procedure TfrmCCJS_CheckPickPharmacy.aTool_SelectItemExecute(Sender: TObject);
var
IErr : integer;
SErr : string;
begin
if (MessageDLG('Подтвердите выполнение операции.',mtConfirmation,[mbYes,mbNo],0) = mrNo) then exit;
if (Mode = cFCCJS_CheckPP_ArtCode_Pharmacy) or (Mode = cFCCJS_CheckPP_Order_Pharmacy) then begin
try
spSetNumberToReserve.Parameters.ParamValues['@RN'] := gMain.DataSource.DataSet.FieldByName('NRN').AsInteger;
spSetNumberToReserve.Parameters.ParamValues['@NumberToReserve'] := gMain.DataSource.DataSet.FieldByName('NCountItemOrder').AsInteger;
spSetNumberToReserve.Parameters.ParamValues['@IDUser'] := IDUSER;
spSetNumberToReserve.ExecProc;
IErr := spSetNumberToReserve.Parameters.ParamValues['@RETURN_VALUE'];
if IErr <> 0 then begin
SErr := spSetNumberToReserve.Parameters.ParamValues['@SErr'];
ShowMessage('Сбой при определении количества для резервирования.' + chr(10) + SErr);
end;
except
on e:Exception do begin
ShowMessage('Сбой при определении количества для резервирования.' + chr(10) + e.Message);
end;
end;
end;
GridRefresh;
end;
procedure TfrmCCJS_CheckPickPharmacy.aTool_ClearSelectItemExecute(Sender: TObject);
var
IErr : integer;
SErr : string;
begin
if (MessageDLG('Подтвердите выполнение операции.',mtConfirmation,[mbYes,mbNo],0) = mrNo) then exit;
if (Mode = cFCCJS_CheckPP_ArtCode_Pharmacy) or (Mode = cFCCJS_CheckPP_Order_Pharmacy) then begin
try
spSetNumberToReserve.Parameters.ParamValues['@RN'] := gMain.DataSource.DataSet.FieldByName('NRN').AsInteger;
spSetNumberToReserve.Parameters.ParamValues['@NumberToReserve'] := 0;
spSetNumberToReserve.Parameters.ParamValues['@IDUser'] := IDUSER;
spSetNumberToReserve.ExecProc;
IErr := spSetNumberToReserve.Parameters.ParamValues['@RETURN_VALUE'];
if IErr <> 0 then begin
SErr := spSetNumberToReserve.Parameters.ParamValues['@SErr'];
ShowMessage('Сбой при определении количества для резервирования.' + chr(10) + SErr);
end;
except
on e:Exception do begin
ShowMessage('Сбой при определении количества для резервирования.' + chr(10) + e.Message);
end;
end;
end;
GridRefresh;
end;
procedure TfrmCCJS_CheckPickPharmacy.aControl_AddPharmacyExecute(Sender: TObject);
var
IErr : integer;
SErr : string;
begin
if (MessageDLG('Подтвердите выполнение операции.',mtConfirmation,[mbYes,mbNo],0) = mrNo) then exit;
try
spAddPharmacy.Parameters.ParamValues['@NIdentPharmacy'] := BigIdAction;
spAddPharmacy.Parameters.ParamValues['@PRN'] := PRN;
spAddPharmacy.Parameters.ParamValues['@ISignModeReserve'] := ModeReserve;
spAddPharmacy.Parameters.ParamValues['@IDUser'] := IDUSER;
spAddPharmacy.Parameters.ParamValues['@Pharmacy'] := Pharmacy;
spAddPharmacy.Parameters.ParamValues['@SIDENT'] := SIDENT;
spAddPharmacy.Parameters.ParamValues['@Order'] := Order;
spAddPharmacy.ExecProc;
IErr := spAddPharmacy.Parameters.ParamValues['@RETURN_VALUE'];
if IErr <> 0 then begin
SErr := spAddPharmacy.Parameters.ParamValues['@SErr'];
ShowMessage('Сбой при сохранении результатов выбора аптеки.' + chr(10) + SErr);
end;
except
on e:Exception do begin
ShowMessage('Сбой при сохранении результатов выбора аптеки.' + chr(10) + e.Message);
end;
end;
self.Close;
end;
procedure TfrmCCJS_CheckPickPharmacy.aTool_Fileds_OKExecute(Sender: TObject);
var
IErr : integer;
SErr : string;
begin
if (MessageDLG('Подтвердите выполнение операции.',mtConfirmation,[mbYes,mbNo],0) = mrNo) then exit;
try
spSetNumberToReserve.Parameters.ParamValues['@RN'] := gMain.DataSource.DataSet.FieldByName('NRN').AsInteger;
spSetNumberToReserve.Parameters.ParamValues['@NumberToReserve'] := cmbxNumberToReserve.ItemIndex;
spSetNumberToReserve.Parameters.ParamValues['@IDUser'] := IDUSER;
spSetNumberToReserve.ExecProc;
IErr := spSetNumberToReserve.Parameters.ParamValues['@RETURN_VALUE'];
if IErr <> 0 then begin
SErr := spSetNumberToReserve.Parameters.ParamValues['@SErr'];
ShowMessage('Сбой при определении количества для резервирования.' + chr(10) + SErr);
end;
except
on e:Exception do begin
ShowMessage('Сбой при определении количества для резервирования.' + chr(10) + e.Message);
end;
end;
GridRefresh;
ShowGets;
end;
end.
|
unit search;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TfrmSearch = class(TForm)
Label1: TLabel;
Label2: TLabel;
edtAnomaly: TEdit;
edtSystem: TEdit;
Button1: TButton;
Button2: TButton;
Button3: TButton;
procedure Button3Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
anomCode: String;
systemCode: String;
public
{ Public declarations }
function findAnom(): Boolean;
function findSystem(): Boolean;
end;
var
frmSearch: TfrmSearch;
implementation
{$R *.dfm}
uses anomInfo, data, systemInfo;
procedure TfrmSearch.Button1Click(Sender: TObject);
begin
anomCode := edtAnomaly.Text;
if length(anomCode) < 7 then
showMessage('Please enter the correct Anomaly code.')
else if findAnom then
begin
frmAnomInfo := TfrmAnomInfo.Create(self);
frmAnomInfo.Show;
close;
end
else
showMessage('The Anomaly Code you have entered has not been saved in the database.');
end;
procedure TfrmSearch.Button2Click(Sender: TObject);
begin
SystemCode := edtSystem.Text;
if length(systemCode) < 3 then
showMessage('Please enter the correct System code.')
else if findSystem then
begin
frmSystemInfo := TfrmSystemInfo.Create(self);
frmSystemInfo.Show;
close;
end
else
showMessage('The System Code you have entered has not been saved in the database.');
end;
procedure TfrmSearch.Button3Click(Sender: TObject);
begin
close;
end;
function TfrmSearch.findAnom: Boolean;
begin
Database.qAnomaly.Active := false;
Database.qAnomaly.Parameters.ParamByName('value').Value := anomCode;
Database.qAnomaly.Active := true;
if Database.qAnomaly.IsEmpty then
result := false
else
result := true;
end;
function TfrmSearch.findSystem: Boolean;
begin
Database.qSystem.Active := false;
Database.qSystem.Parameters.ParamByName('value').Value := systemCode;
Database.qSystem.Active := true;
if Database.qSystem.IsEmpty then
result := false
else
result := true;
end;
end.
|
//------------------------------------------------------------------------------
//Map UNIT
//------------------------------------------------------------------------------
// What it does -
// Our Map class, holds everything to do with our map object.
//
// Changes -
// October 30th, 2006 - RaX - Created.
// [2007/03/28] CR - Cleaned up uses clauses, using Icarus as a guide.
// [2007/04/23] Tsusai - Added lua
// [2007/04/28] Tsusai - Removed lua
//
//------------------------------------------------------------------------------
unit Map;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{RTL/VCL}
Types,
Classes,
contnrs,
{Project}
EventList,
MapTypes,
{3rd Party}
List32
;
type
//------------------------------------------------------------------------------
//TMap CLASS
//------------------------------------------------------------------------------
TMap = class(TObject)
protected
Path : String;
SlotList : TIntList32;
NextID : LongWord;
procedure LoadNpc;
procedure LoadMob;
function LoadFromStream(
AStream : TStream
):Boolean;
procedure StepCleanupSlotList;
public
ID : LongWord;
Name : String;
Cell : TGraph;
Size : TPoint;
Flags : TFlags;
State : TMapMode;
EventList : TEventList;
MobList : TObjectList;
ItemList : TIntList32;
NPCList : TIntList32;
ChatroomList : TIntList32;
Constructor Create;
Destructor Destroy;override;
Function IsBlocked(
const
APoint : TPoint;
AGraph : TGraph = NIL
) : Boolean;
function LoadFromFile(
const
PmsFile : String
) : Boolean;
procedure Load;
Procedure Unload;
Function PointInRange(const APoint : TPoint) : Boolean;
function RandomCell: TPoint;
function SafeLoad: Boolean;
function NewObjectID:LongWord;
procedure DisposeObjectID(const ID:LongWord);
end;
//------------------------------------------------------------------------------
implementation
uses
{RTL/VCL}
SysUtils,
Math,
WinLinux,
{Project}
Globals,
Main,
NPC,
Mob
{3rd Party}
;
//------------------------------------------------------------------------------
//TMap.Create()
//------------------------------------------------------------------------------
// What it does -
// Builds our TMap Object.
//
// Changes -
// October 30th, 2006 - RaX - Created.
//------------------------------------------------------------------------------
Constructor TMap.Create();
begin
inherited;
State := UNLOADED;
//Set Size to 0
Size.X := 0;
Size.Y := 0;
EventList := TEventList.Create(TRUE);
//We own mob objects here!
MobList := TObjectList.Create(TRUE);
ItemList := TIntList32.Create;
{Don't own the objects please.. Delphi's TObjectList never actually owns}
NPCList := TIntList32.Create;
SlotList := TIntList32.Create;
NextID := 1;
ChatroomList := TIntList32.Create;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//TMap.Destroy()
//------------------------------------------------------------------------------
// What it does -
// Destroys our TMap Object.
//
// Changes -
// October 30th, 2006 - RaX - Created.
//------------------------------------------------------------------------------
Destructor TMap.Destroy();
begin
if State = LOADED then
begin
Unload;
end;
EventList.Free;
MobList.Free;
ItemList.Free;
NPCList.Free;
SlotList.Free;
ChatroomList.Free;
inherited;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//IsBlocked() FUNCTION
//------------------------------------------------------------------------------
// What it does -
// It figures out if a specified cell is blocked.
//
// Changes -
// November 1st, 2006 - Tsusai - Created.
//------------------------------------------------------------------------------
function TMap.IsBlocked(const APoint : TPoint; AGraph : TGraph = NIL) : boolean;
begin
if NOT Assigned(AGraph) then
begin
AGraph := Cell;
end;
//Assume it is not.
Result := false;
if (AGraph[APoint.X][APoint.Y].Attribute in [1,5]) OR
(AGraph[APoint.X][APoint.Y].ObstructionCount > 0 ) then
begin
Result := True;
end;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//LoadFromStream FUNCTION
//------------------------------------------------------------------------------
// What it does -
// Load Map data from Stream
//
// Changes -
// [2008/12/07] Aeomin - Created
//------------------------------------------------------------------------------
function TMap.LoadFromStream(
AStream : TStream
):Boolean;
Var
AByte : Byte;
MapTag : array[1..MAX_PMS_HEADER_LENGTH] of Char;
begin
Result := TRUE;
AStream.Read(MapTag[1], MAX_PMS_HEADER_LENGTH);
if (MapTag <> 'PrometheusMap') then //Check type
begin
Console.WriteLn('The Map :' + Path + ' is not a Prometheus Map.');
Result := FALSE;
end
else
begin
AStream.Read(AByte,1); //Check version.
if (AByte <> 1) then
begin
Console.WriteLn('The Map :' + Path + ' failed the version check.');
Result := FALSE;
end
else
begin
AStream.Read(Size.X, 4);
AStream.Read(Size.Y, 4);
//check size.
if NOT (InRange(Size.X, 0, 511) AND InRange(Size.Y, 0, 511)) then
begin
Console.WriteLn('The Map :' + Path + '''s size is out of range.');
Result := FALSE;
end;
end;
end;
end;{LoadFromStream}
//------------------------------------------------------------------------------
(*- Function ------------------------------------------------------------------*
TMap.LoadFromFile()
--------------------------------------------------------------------------------
Overview:
----------------------------------------
Loads a map from a .pms file.
Modelled after Borland's TStrings.LoadFromFile.
----------------------------------------
Revisions:
----------------------------------------
January 22nd, 2007 - RaX - Created.
January 25th, 2007 - Tsusai - Removed complicated path name code, replaced
with ExtractFileNameMod (WinLinux)
[2007/03/24] CR - Parameter made constant (optimization).
Renamed Parameter "Path" to "PmsFile" to avoid ambiguity with TMap.Path
It's a more appropriate name than "Path" in the first place! :)
Surrounded TMemoryStream with a try-finally to protect the resource.
Fixed major logic flaws -- Result is NOT handled like C/C++'s "return"
keyword. Thus, we NEED to use if-then-else branching, not just sequential
if-thens. Malformed/hand-mangled maps could cause fatal errors with the old
code flow, because it couldn't avoid continuing on instead of bailing early.
*-----------------------------------------------------------------------------*)
Function TMap.LoadFromFile(
const
PmsFile : String
) : Boolean;
Var
MapFile : TMemoryStream;
Begin
MapFile := TMemoryStream.Create;
try
MapFile.LoadFromFile(PmsFile);
Path := PmsFile;
Result := LoadFromStream(MapFile);
finally
MapFile.Free; //finally, free the memory stream.
end;
End;//LoadFromFile
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Load() FUNCTION
//------------------------------------------------------------------------------
// What it does -
// Loads a map's cells from a .pms file.
//
// Changes -
// January 25th, 2007 - RaX - Created.
// [2007/04/23] Tsusai - Added lua setup and execution
// [2007/04/28] Tsusai - Removed lua
//------------------------------------------------------------------------------
Procedure TMap.Load;
Var
MapFile : TMemoryStream;
XIndex : Integer;
YIndex : Integer;
Begin
State := LOADING;
MapFile := TMemoryStream.Create;
MapFile.LoadFromFile(Path);
MainProc.ZoneServer.Database.Map.LoadFlags(Flags, Name);
MapFile.Seek(22,0);//skip other non-cell information
//Load Cell Information
SetLength(Cell, Size.X, Size.Y);
for YIndex := 0 to Size.Y - 1 do begin
for XIndex := 0 to Size.X - 1 do begin
MapFile.Read(Cell[XIndex][YIndex].Attribute,1);
Cell[XIndex][YIndex].Position := Point(XIndex, YIndex);
Cell[XIndex][YIndex].ObstructionCount := 0;
Cell[XIndex][YIndex].Beings := TIntList32.Create;
Cell[XIndex][YIndex].Items := TIntList32.Create;
end;
end;
State := LOADED;
LoadNpc;
LoadMob;
MainProc.ZoneServer.Database.Items.FillMapGround(Self);
MapFile.Free;//finally, free the memory stream.
End;//Load
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//LoadNPC PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Extracted from Load
//
// Changes -
// [2008/12/07] Aeomin - Created
//------------------------------------------------------------------------------
procedure TMap.LoadNpc;
var
ObjIndex : Integer;
AnNPC : TNPC;
begin
//Enable all npcs on this map.
for ObjIndex := 0 to NPCList.Count -1 do
begin
AnNPC := TNPC(NPCList.Objects[ObjIndex]);
if PointInRange(AnNPC.Position) then
begin
// We don't want add npc outside of map..
AnNPC.MapInfo := Self;
Cell[AnNPC.Position.X][AnNPC.Position.Y].Beings.AddObject(AnNPC.ID, AnNPC);
AnNPC.Enabled := True;
end;
end;
end;{LoadNPC}
//------------------------------------------------------------------------------
procedure TMap.LoadMob;
var
ObjIndex : Integer;
AMob : TMob;
begin
//Add mobs that is already in list
for ObjIndex := 0 to MobList.Count -1 do
begin
AMob := TMob(MobList[ObjIndex]);
AMob.ID := NewObjectID;
AMob.Initiate;
end;
end;
//------------------------------------------------------------------------------
//Unload() FUNCTION
//------------------------------------------------------------------------------
// What it does -
// Unloads a map's cells and flags.
//
// Changes -
// January 25th, 2007 - RaX - Created.
//------------------------------------------------------------------------------
Procedure TMap.Unload;
var
XIndex : Integer;
YIndex : Integer;
Begin
if State = LOADED then
begin
//Free up each Cell.
for XIndex := 0 to Size.X - 1 do
begin
for YIndex := 0 to Size.Y - 1 do
begin
Cell[XIndex][YIndex].Beings.Free;
Cell[XIndex][YIndex].Items.Free;
end;
end;
SetLength(Cell, 0, 0);
State := UNLOADED;
end;
End;//Unload
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//RandomCell FUNCTION
//------------------------------------------------------------------------------
// What it does -
// Random a walkable cell
//
// Changes -
// [2007/08/13] Aeomin - Created.
//------------------------------------------------------------------------------
function TMap.RandomCell: TPoint;
var
LoopTrials : Byte;
LoopOk : Boolean;
idxX : Word;
idxY : Word;
begin
LoopTrials := 0;
LoopOk := False;
while LoopTrials < 20 do
begin
//Random one!
Result.X := Random(Size.X -1);
Result.Y := Random(Size.Y -1);
if IsBlocked(Result) then
Inc(LoopTrials)
else begin
LoopOk := True;
Break;
end;
end;
//We just tried 10 times, if still cant find one..
if not LoopOK then
begin
for idxX := 0 to Size.X - 1 do
begin
if LoopOK then
Break;
for idxY := 0 to Size.Y - 1 do
begin
//Then just get one that works..
Result.X := idxX;
Result.Y := idxY;
if not IsBlocked(Result) then
begin
LoopOk := True;
Break;
end;
end;
end;
end;
//Really.. i can't help anymore...
if not LoopOk then
begin
Result.X := 0;
Result.Y := 0;
end;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//SafeLoad FUNCTION
//------------------------------------------------------------------------------
// What it does -
// Check and load map, return false of failed.
//
// Changes -
// [2007/08/14] Aeomin - Created.
//------------------------------------------------------------------------------
function TMap.SafeLoad: Boolean;
var
LoopTries : Byte;
begin
Result := False;
case State of
UNLOADED: begin
// Just load it
Load;
if State = LOADED then
begin
Result := True;
end;
end;
LOADING: begin
//We can't do anything but wait...
LoopTries := 0;
while LoopTries <= 10 do
begin
if State = LOADED then
begin
Result := True;
Break;
end;
Sleep(1000);
end;
end;
LOADED: begin
//Simple!
Result := True;
end;
end;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//PointInRange FUNCTION
//------------------------------------------------------------------------------
// What it does -
// Checks to see if a point is inside the range of the map.
//
// Changes -
// [2008/01/02] RaX - Created
//------------------------------------------------------------------------------
Function TMap.PointInRange(const APoint : TPoint) : Boolean;
begin
if (APoint.X < Size.X) AND
(APoint.Y < Size.Y) AND
(APoint.X > -1) AND
(APoint.Y > -1) then
begin
Result := TRUE;
end else
begin
Result := FALSE;
end;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//NewObjectID PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Generate a "GUID"
// result is > 0; fail if return 0
//
// Changes -
// [2008/12/08] Aeomin - Created.
//------------------------------------------------------------------------------
function TMap.NewObjectID:LongWord;
begin
{Result := 0; }
if SlotList.Count = 0 then
begin
Result := NextID;
Inc(NextID);
end else
begin
Result := SlotList[0];
end;
StepCleanupSlotList;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//DisposeObjectID PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Delete an object id
//
// Changes -
// [2008/12/09] Aeomin - Created.
//------------------------------------------------------------------------------
procedure TMap.DisposeObjectID(const ID:LongWord);
begin
if SlotList.IndexOf(ID) = -1 then
begin
SlotList.Add(ID);
StepCleanupSlotList;
end;
end;{DisposeObjectID}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//StepCleanupSlotList PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Sometimes slot list just too much items..
//
// Changes -
// [2008/12/09] Aeomin - Created.
//------------------------------------------------------------------------------
procedure TMap.StepCleanupSlotList;
begin
if SlotList.Count > 0 then
begin
if (SlotList[SlotList.Count-1]+1) = NextID then
begin
SlotList.Delete(SlotList.Count-1);
Dec(NextID);
end;
end;
end;{StepCleanupSlotList}
//------------------------------------------------------------------------------
end.
|
unit NewFrontiers.Validation;
interface
uses
Classes;
type
IValidator = interface(IInterface)
/// <summary>
/// Basisinterface für alle Validator
/// </summary>
function validate(aString: string): boolean;
end;
/// <summary>
/// Basisklasse für alle Validator
/// </summary>
TValidator = class(TInterfacedObject, IValidator)
protected
_lastError: string;
public
function validate(aString: string): boolean; virtual; abstract;
function getLastError: string;
end;
implementation
{ TValidator }
function TValidator.getLastError: string;
begin
result := _lastError;
end;
end.
|
namespace ComplexNumbers;
interface
type
Complex = public class
private
property Size: Double read Real*Imaginary;
protected
public
constructor; empty;
constructor (aReal, aImaginary: Double);
property Real: Double;
property Imaginary: Double;
method ToString: String; override;
class operator Add(aOperand1: Complex; aOperand2: Complex): Complex;
class operator Subtract(aOperand1: Complex; aOperand2: Complex): Complex;
class operator Multiply(aOperand1: Complex; aOperand2: Complex): Complex;
class operator Divide(aOperand1: Complex; aOperand2: Complex): Complex;
class operator Equal(aOperand1: Complex; aOperand2: Complex): Boolean;
class operator Less(aOperand1: Complex; aOperand2: Complex): Boolean;
class operator LessOrEqual(aOperand1: Complex; aOperand2: Complex): Boolean;
class operator Greater(aOperand1: Complex; aOperand2: Complex): Boolean;
class operator GreaterOrEqual(aOperand1: Complex; aOperand2: Complex): Boolean;
class operator Minus(aOperand: Complex): Complex;
class operator Plus(aOperand: Complex) : Complex;
class operator Explicit(aValue: Complex): Double;
class operator Implicit(aValue: Double): Complex;
class operator Implicit(aValue: Int32): Complex;
end;
implementation
constructor Complex(aReal, aImaginary: Double);
begin
Real := aReal;
Imaginary := aImaginary;
end;
class operator Complex.Add(aOperand1 : Complex; aOperand2 : Complex) : Complex;
begin
result := new Complex(aOperand1.Real+aOperand2.Real, aOperand1.Imaginary+aOperand2.Imaginary);
end;
class operator Complex.Subtract(aOperand1 : Complex; aOperand2 : Complex) : Complex;
begin
result := new Complex(aOperand1.Real-aOperand2.Real, aOperand1.Imaginary-aOperand2.Imaginary);
end;
class operator Complex.Multiply(aOperand1 : Complex; aOperand2 : Complex) : Complex;
var
lReal, lImaginary: Double;
begin
//
// (a + ib)(c + id) = (ac - bd) + i(bc + ad)
//
lReal := aOperand1.Real*aOperand2.Real - aOperand1.Imaginary*aOperand2.Imaginary;
lImaginary := aOperand1.Imaginary*aOperand2.Real + aOperand1.Real*aOperand2.Imaginary;
result := new Complex(lReal, lImaginary);
end;
class operator Complex.Divide(aOperand1 : Complex; aOperand2 : Complex) : Complex;
var
lReal, lImaginary, lDivisor: Double;
begin
//
// (a + ib)(c + id) = (ac + bd)/(c�+d�) + i(bc - ad)/(c�+d�)
//
lDivisor := (aOperand2.Real*aOperand2.Real + aOperand2.Imaginary*aOperand2.Imaginary);
lReal := (aOperand1.Real*aOperand2.Real + aOperand1.Imaginary*aOperand2.Imaginary) / lDivisor;
lImaginary := (aOperand1.Imaginary*aOperand2.Real - aOperand1.Real*aOperand2.Imaginary) / lDivisor;
result := new Complex(lReal, lImaginary);
end;
{ Unary Operators }
class operator Complex.Minus(aOperand: Complex): Complex;
begin
result := new Complex(-aOperand.Real, -aOperand.Imaginary);
end;
class operator Complex.Plus(aOperand: Complex) : Complex;
begin
result := aOperand;
end;
{ Comparison operators }
class operator Complex.Equal(aOperand1 : Complex; aOperand2 : Complex): boolean;
begin
result := (aOperand1.Real = aOperand2.Real) and (aOperand1.Imaginary = aOperand2.Imaginary);
end;
class operator Complex.Less(aOperand1: Complex; aOperand2: Complex): boolean;
begin
result := aOperand1.Size < aOperand2.Size;
end;
class operator Complex.LessOrEqual(aOperand1: Complex; aOperand2: Complex): boolean;
begin
result := aOperand1.Size <= aOperand2.Size;
end;
class operator Complex.Greater(aOperand1: Complex; aOperand2: Complex): boolean;
begin
result := aOperand1.Size > aOperand2.Size;
end;
class operator Complex.GreaterOrEqual(aOperand1: Complex; aOperand2: Complex): boolean;
begin
result := aOperand1.Size >= aOperand2.Size;
end;
{ Cast Operators }
class operator Complex.Explicit(aValue: Complex): Double;
begin
result := aValue.Real;
end;
class operator Complex.Implicit(aValue: Double): Complex;
begin
result := new Complex(aValue, 0)
end;
class operator Complex.Implicit(aValue: Int32): Complex;
begin
result := new Complex(aValue, 0)
end;
method Complex.ToString: string;
begin
if (Real = 0) and (Imaginary = 0) then
result := '0'//'.ToString
else if (Imaginary = 0) then
result := Real.ToString
else if (Real = 0) then
result := Imaginary.ToString+'i'
else if (Imaginary < 0) then
result := Real.ToString+Imaginary.ToString+'i'
else
result := Real.ToString+'+'+Imaginary.ToString+'i';
end;
end. |
unit adamsbdfG;
{ Lsoda differential equation solver Delphied. H M Sauro Dec 1996
Original Pascal translation by Joao Pedro Monij-Barreto and Ronny Shuster.
Original FORTRAN (version march30, 1987) to C translation by
From tam@dragonfly.wri.com Wed Apr 24 01:35:52 1991
Return-Path: <tam>
Date: Wed, 24 Apr 91 03:35:24 CDT
From: tam@dragonfly.wri.com
To: whitbeck@wheeler.wrc.unr.edu
Subject: lsoda.c
Cc: augenbau@sparc0.brc.uconn.edu
I'm told by Steve Nichols at Georgia Tech that you are interested in
a stiff integrator. Here's a translation of the fortran code LSODA.
Please note that there is no comment. The interface is the same as the FORTRAN
code and I believe the documentation in LSODA will suffice.
As usual, a free software comes with no guarantee.
Hon Wah Tam
Wolfram Research, Inc.
tam@wri.com
I have done some additions to lsoda.c . These were mainly to fill the
gap of some features that were available in the fortran code and were
missing in the C version.
Changes are: all messages printed by lsoda routines will start with
a '\n' (instead of ending with one); xsetf() was added so that user
can control printing of messages by lsoda. xsetf should be called before
calling lsoda: xsetf(0) switches printing off xsetf(1) swithces printing
on (default) this implies one new global variable prfl (print flag).
xsetf(0) will stop *any* printing by lsoda functions.
Turning printing off means losing valuable information but will not scramble
your stderr output ;-) This function is part of the original FORTRAN version.
xsetf() and intdy() are now callable from outside the library as assumed
in the FORTRAN version; created lsoda.h that should be included in blocks
calling functions in lsoda's library. iwork5 can now have an extra value:
0 - no extra printing (default), 1 - print data on each method switch,
-> 2 - print useful information at *each* stoda step (one lsoda call
has performs many stoda calls) and also data on each method switch
note that a xsetf(0) call will prevent any printing even if iwork5 > 0;
hu, tn were made available as extern variables.
eMail: INTERNET: prm@aber.ac.uk
Pedro Mendes, Dept. of Biological Sciences, University College of Wales,
Aberystwyth, Dyfed, SY23 3DA, United Kingdom.
Further minor changes: 10 June 1992 by H Sauro and Pedro Mendes }
{ This version in a Delphi compatible object by H M Sauro Dec 1996 }
{ -------------------------------------------------------------------------- }
{ Quick usage instructions:
1. Create Lsoda object specifying dimension of problem
2. Initialise rtol and atol arrays (error tolerances, relative and absolute)
3. Initialise t and tout (t = initial val, tout = requested solution point)
4. Set itol to 4
5. Set itask to 1, indicating normal computation
6. Set istart to 1, indicating first call to lsoda
7. Set iopt = 0 for no optional inputs
8. jt = 2 for internal evaluation of jacobian
9. Call Setfcn (fcn) to install your dydt routine
10. Call lsoda (y, t, tout) to perfom one iteration }
{ See lsoda.doc for further details of interface. There may be further changes to
this source in the future. The object interface is not neat enough yet, but it
does work, see included example. Also xome works needs to be done to the body }
{ Note on TVector. TVector implements a dynamic array type of doubles. Use
v := TVector.Create (10) to create 10 element array. Access data via v[i].
v.size returns number of elements in vector. See vector.pas for more details }
{ Note on TMat. TMat is a simple matrix object type which serves a similar role
to TVector except of course TMatrix is a 2D version }
{ LsodaMat includes two routines for doing LU decomposition and backward-
substitution, painfully translated from FORTRAN code, couldn't use my own coz'
I think LSODA requires particular structure to LU result. These routines use a
TVectori type (included with vector.pas) which simply handles dynamics arrays of
integers }
{ Note to FORTRAN coders: please stop playing 'neat' tricks with arrays, it make
translating decent algorithms written in FORTRAN a hellish experience! }
interface
{$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF}
uses SysUtils,
util1,stmVec1, stmKLMat, LsodaMatG;
type
ELsodaException = class (Exception);
{ This is the type for the dydt function }
fcnProc = procedure (t : double; y, dydt : TVector) of object;
TErrorType = (eNone, eDerivative, eBuildAlphaBeta, eChiSqr, eDelta,
eNormalisation, eMatrixInversion, ePoorConvergence);
vector13 = array [1..13] of double; { Used in declaring pc in cfode }
{mat1314 = array [1..13,1..14] of double;
mat134 = array [1..13,1..4] of double;
vec14 = array[1..14] of double;
vec6 = array[1..6] of double;
mat12ne = array[1..13] of TVector;}
TLsoda = class (TObject)
private
neq : integer; { # of first-order odes }
tn, h, hu, tsw, tolsf : double;
nje, nfe, prfl, nq, nqu, meth, mused, nst, imxer : integer;
{ static variables for lsoda() }
ccmax, el0, hmin, hmxi, rc, pdnorm : double;
illin, init, mxstep, mxhnil, nhnil, ntrep,
nslast, nyh, ierpj, iersl, jcur, jstart, kflag, l,
miter, maxord, maxcor, msbp, mxncf, n,
ixpr, jtyp, mxordn, mxords : integer;
{ non-static variable for prja(), solsy() }
{ static variables for stoda() }
conit, crate, hold, rmax,pdest, pdlast, ratio: double;
elco, tesco : TMat;
ialth, ipup, lmax, meo, nslp, icount, irflag : integer;
cm1, cm2, el : TVector;
{ static variables for various vectors and the Jacobian. }
yh : array[1..13] of TVector;
wm : TMat;
perm : TVector; { Permuation vector for LU decomp }
ewt, savf, acor : TVector;
sqrteta : double; { sqrt (ETA) }
Frtol, Fatol : TVector;
Fitol, Fitask, Fistate, Fiopt, Fjt, Fiwork5, Fiwork6 : integer;
Fiwork7, Fiwork8, Fiwork9 : integer;
Frwork1, Frwork5, Frwork6, Frwork7 : double;
FDerivatives : fcnProc;
procedure terminate(var istate: integer );
procedure terminate2 (var y : TVector; var t : double);
procedure successreturn(var y : TVector;var t : double;
itask, ihit : integer; tcrit : double; var istate : integer);
procedure ewset(itol : integer; rtol, atol, ycur : TVector);
procedure prja (neq : integer; var y : TVector);
procedure corfailure(var told, rh : double; var ncf, corflag : integer);
procedure solsy(var y : TVector);
procedure methodswitch( dsm, pnorm: double; var pdh, rh: double);
procedure endstoda;
procedure orderswitch (var rhup : double; dsm : double; var pdh, rh : double;
var orderflag : integer);
procedure resetcoeff;
procedure correction (neq : integer; var y : TVector; var corflag : integer;
pnorm : double; var del, delp, told : double;
var ncf : integer; var rh : double; var m : integer);
procedure intdy (t : double; k : integer; var dky : TVector; var iflag : integer);
procedure cfode(meth : integer);
procedure scaleh (var rh, pdh : double);
procedure stoda (var neq : integer; var y : TVector);
procedure DummyFcn (t : double; y, dydt :TVector);
public
property NbEq:integer read neq;
constructor Create (n : integer); virtual;
destructor destroy; override;
procedure Setfcn (fcn : fcnProc);
{ y = array of initial values of variables. t = initial value of
independent variable, tout, value of t when output is required.
On output, y holds new values of variables and t updated to tout }
procedure Execute (var y : TVector; var t, tout : double);
function Getrtol (i : integer) : double;
procedure Setrtol (i : integer; d : double);
function Getatol (i : integer) : double;
procedure Setatol (i : integer; d : double);
property rtol[i : Integer] : double read Getrtol write Setrtol;
property atol[i : Integer] : double read Getatol write Setatol;
property itol : integer read Fitol write Fitol;
property itask : integer read Fitask write Fitask;
property istate : integer read Fistate write Fistate;
property iopt : integer read Fiopt write Fiopt;
property jt : integer read Fjt write Fjt;
property iwork5 : integer read Fiwork5 write Fiwork5;
property iwork6 : integer read Fiwork6 write Fiwork6;
property iwork7 : integer read Fiwork7 write Fiwork7;
property iwork8 : integer read Fiwork8 write Fiwork8;
property iwork9 : integer read Fiwork9 write Fiwork9;
property rwork1 : double read Frwork1 write Frwork1;
property rwork5 : double read Frwork5 write Frwork5;
property rwork6 : double read Frwork6 write Frwork6;
property rwork7 : double read Frwork7 write Frwork7;
end;
{ ------------------------------------------------------------------------- }
implementation
const
ETA = 2.2204460492503131e-16;
mord : array[1..2] of integer = (12, 5) ;
sm1 : array[0..12] of double = ( 0., 0.5, 0.575, 0.55, 0.45, 0.35, 0.25,
0.2, 0.15, 0.1, 0.075, 0.05, 0.025 );
{ Excecuted if fitting function not assigned by user }
procedure TLsoda.DummyFcn (t : double; y, dydt :TVector);
begin
raise ELsodaException.Create ('No function assigned to evaluate dydts (Use Setfcn)!');
end;
{ Create a Lsoda object with n differential equations }
constructor TLsoda.Create (n : integer);
var i : integer;
begin
neq := n;
el := TVector.Create (g_double,1,14);
elco := TMat.Create (g_double,13, 14);
tesco := TMat.Create (g_double,13, 4);
cm1 := TVector.Create (g_double,1,13);
cm2 := TVector.Create (g_double,1,6);
for i := 1 to 13 do yh[i] := TVector.Create (g_double,1,13);
wm := TMat.Create (g_double,neq, neq);
perm := TVector.Create (g_longint,1,neq);
ewt := TVector.Create (g_double,1,13);
savf := TVector.Create (g_double,1,13);
acor := TVector.Create (g_double,1,13);
Frtol := TVector.Create (g_double,1,neq);
Fatol := TVector.Create (g_double,1,neq);
FDerivatives := DummyFcn; { Install the default fcn handler, in case user forgets }
end;
destructor TLsoda.destroy;
var i : integer;
begin
el.free; elco.free;
tesco.free; cm1.free; cm2.free;
for i := 1 to 13 do yh[i].free;
wm.free; perm.free; ewt.free; savf.free; acor.free;
Frtol.free; Fatol.free;
end;
procedure TLsoda.Setfcn (fcn : fcnProc);
begin
FDerivatives := fcn;
end;
{**************************************************************}
function max(a, b : double) : double;
begin
if(a>b) then max:=a
else max:=b;
end;
{**************************************************************}
function min(a, b : double) : double;
begin
if(a>b) then min:=b
else min:=a;
end;
{**************************************************************}
function maxi(a, b : integer) : integer;
begin
if(a>b) then maxi:=a
else maxi:=b;
end;
{**************************************************************}
function mini(a, b : integer) : integer;
begin
if(a>b) then mini:=b
else mini:=a;
end;
{**************************************************************}
function pow(a : double; x : double) : double;
begin
if a=0 then pow := 0 else pow := exp(x*ln(abs(a)))*abs(a)/a;
end;
function TLsoda.Getrtol (i : integer) : double;
begin
result := Frtol[i];
end;
procedure TLsoda.Setrtol (i : integer; d : double);
begin
Frtol[i] := d;
end;
function TLsoda.Getatol (i : integer) : double;
begin
result := Fatol[i];
end;
procedure TLsoda.Setatol (i : integer; d : double);
begin
Fatol[i] := d;
end;
{**************************************************************}
{ Terminate lsoda due to illegal input. }
procedure TLsoda.terminate(var istate: integer );
begin
if ( illin = 5 ) then
begin
writeln('lsoda -- repeated occurrence of illegal input');
writeln(' run aborted.. apparent infinite loop');
end
else
begin
illin:=illin+1;
istate := -3;
end;
end; { end terminate }
{**************************************************************}
{ Terminate lsoda due to various error conditions. }
procedure TLsoda.terminate2 (var y : TVector; var t : double);
var i: integer;
begin
for i := 1 to n do y[i] := yh[1][i];
t := tn;
illin := 0;
end; { end terminate2 }
{**************************************************************}
{ The following block handles all successful returns from lsoda.
If itask != 1, y is loaded from yh and t is set accordingly.
*Istate is set to 2, the illegal input counter is zeroed, and the
optional outputs are loaded into the work arrays before returning.}
procedure TLsoda.successreturn(var y: TVector;var t:double;
itask, ihit:integer;
tcrit :double;
var istate:integer );
var i: integer;
begin
for i := 1 to n do y[i] := yh[1][i];
t := tn;
if (itask = 4) or (itask = 5) then
if (ihit = 0) then
t := tcrit;
istate := 2;
illin := 0;
end; { end successreturn }
{**************************************************************}
procedure TLsoda.ewset(itol : integer; rtol, atol, ycur : TVector);
var i: integer;
begin
case itol of
1 : for i := 1 to n do
ewt[i] := rtol[1] * abs( ycur[i] ) + atol[1];
2 : for i := 1 to n do
ewt[i] := rtol[1] * abs( ycur[i] ) + atol[i];
3 : for i := 1 to n do
ewt[i] := rtol[i] * abs( ycur[i] ) + atol[1];
4 : for i := 1 to n do
ewt[i] := rtol[i] * abs( ycur[i] ) + atol[i];
end;
end; { end ewset }
{**************************************************************}
function vmnorm(v, w : TVector) : double;
{ This function routine computes the weighted max-norm
of the vector of length n contained in the array v, with weights
contained in the array w of length n.
vmnorm = max( i = 1, ..., n ) fabs( v[i] ) * w[i]. }
var i, n : integer;
begin
result := 0.; n := v.Icount;
for i := 1 to n do result := max(result, abs(v[i]) * w[i]);
end; { end vmnorm }
{**************************************************************}
function fnorm(a : TMat; w : TVector) : double;
{ This subroutine computes the norm of a full n by n matrix,
stored in the array a, that is consistent with the weighted max-norm
on vectors, with weights stored in the array w.
fnorm = max(i=1,...,n) ( w[i] * sum(j=1,...,n) fabs( a[i][j] ) / w[j] ) }
var
i, j, n : integer;
sum : double;
begin
result := 0.; n := a.rowCount;
for i := 1 to n do
begin
sum := 0.;
for j := 1 to n do
sum := sum + (abs(a[i,j]) / w[j]);
result := max(result, sum * w[i]);
end;
end; { end fnorm }
{**************************************************************}
procedure TLsoda.prja (neq : integer; var y : TVector);
var i, j : integer;
fac, hl0, r, r0, yj : double;
ier : byte;
{ prja is called by stoda to compute and process the matrix
P = I - h * el[1] * J, where J is an approximation to the Jacobian.
Here J is computed by finite differencing.
J, scaled by -h * el[1], is stored in wm. Then the norm of J ( the
matrix norm consistent with the weighted max-norm on vectors given
by vmnorm ) is computed, and J is overwritten by P. P is then
subjected to LU decomposition in preparation for later solution
of linear systems with p as coefficient matrix. This is done
by LUfactor if miter = 2, and by dgbfa if miter = 5. }
begin
nje := nje + 1;
ierpj := 0;
jcur := 1;
hl0 := h * el0;
{ If miter = 2, make n calls to f to approximate J. }
if miter <> 2 then
begin
if prfl = 1 then writeln('prja -- miter != 2');
exit;
end;
if miter = 2 then
begin
fac := vmnorm(savf, ewt);
r0 := 1000. * abs(h) * ETA * n * fac;
if r0 = 0. then
r0 := 1.;
for j := 1 to n do
begin
yj := y[j];
r := max(sqrteta * abs( yj ), r0 / ewt[j]);
y[j] := y[j] + r;
fac := -hl0 / r;
FDerivatives (tn, y, acor);
for i := 1 to n do
wm[i,j] := (acor[i] - savf[i]) * fac;
y[j] := yj;
end;
nfe := nfe + n;
{ Compute norm of Jacobian }
pdnorm := fnorm(wm, ewt ) / abs( hl0 );
{ Add identity matrix. }
for i := 1 to n do wm[i,i] := wm[i,i]+1.;
{ Do LU decomposition on P.}
LUfactor (wm, perm);
end;
end; { end prja }
{**************************************************************}
procedure TLsoda.corfailure(var told, rh : double; var ncf, corflag : integer);
var j, i1, i : integer;
begin
ncf:= ncf+1;
rmax := 2.;
tn := told;
for j := nq downto 1 do
for i1 := j to nq do
for i := 1 to n do
yh[i1][i] := yh[i1][i] - yh[i1+1][i];
if (abs(h) <= hmin * 1.00001) or (ncf = mxncf ) then
begin
corflag := 2;
exit;
end;
corflag := 1;
rh := 0.25;
ipup := miter;
end; { end corfailure }
{**************************************************************}
procedure TLsoda.solsy(var y : TVector);
{ This routine manages the solution of the linear system arising from
a chord iteration. It is called if miter != 0.
If miter is 2, it calls dgesl to accomplish this.
If miter is 5, it calls dgbsl.
y = the right-hand side vector on input, and the solution vector
on output. }
var ier : byte;
begin
iersl := 0;
if miter <> 2 then
begin
if ( prfl=1 ) then writeln('solsy -- miter != 2');
exit;
end;
if miter = 2 then LUsolve (wm, perm, y);
end; { end solsy }
{**************************************************************}
procedure TLsoda.methodswitch( dsm, pnorm: double; var pdh, rh: double);
var
lm1, lm1p1, lm2, lm2p1, nqm1, nqm2 : integer;
rh1, rh2, rh1it, exm2, dm2, exm1, dm1, alpha, exsm : double;
{ We are current using an Adams method. Consider switching to bdf.
If the current order is greater than 5, assume the problem is
not stiff, and skip this section.
If the Lipschitz constant and error estimate are not polluted
by roundoff, perform the usual test.
Otherwise, switch to the bdf methods if the last step was
restricted to insure stability ( irflag = 1 ), and stay with Adams
method if not. When switching to bdf with polluted error estimates,
in the absence of other information, double the step size.
When the estimates are ok, we make the usual test by computing
the step size we could have (ideally) used on this step,
with the current (Adams) method, and also that for the bdf.
If nq > mxords, we consider changing to order mxords on switching.
Compare the two step sizes to decide whether to switch.
The step size advantage must be at least ratio = 5 to switch.}
begin
if meth = 1 then
begin
if nq > 5 then exit;
if (dsm <= ( 100. * pnorm * ETA )) or (pdest = 0. ) then
begin
if irflag = 0 then exit;
rh2 := 2.;
nqm2 := mini(nq, mxords );
end
else
begin
exsm := 1. / l;
rh1 := 1. / ( 1.2 * pow( dsm, exsm ) + 0.0000012 );
rh1it := 2. * rh1;
pdh := pdlast * abs( h );
if (pdh * rh1) > 0.00001 then rh1it := sm1[nq] / pdh;
rh1 := min(rh1, rh1it);
if nq > mxords then
begin
nqm2 := mxords;
lm2 := mxords + 1;
exm2 := 1. / lm2;
lm2p1 := lm2 + 1;
dm2 := vmnorm(yh[lm2p1], ewt ) / cm2[mxords];
rh2 := 1. / ( 1.2 * pow( dm2, exm2 ) + 0.0000012 );
end
else
begin
dm2 := dsm * ( cm1[nq] / cm2[nq] );
rh2 := 1. / ( 1.2 * pow( dm2, exsm ) + 0.0000012 );
nqm2 := nq;
end;
if rh2 < ratio * rh1 then exit;
end;
{ The method switch test passed. Reset relevant quantities for bdf. }
rh := rh2;
icount := 20;
meth := 2;
miter := jtyp;
pdlast := 0.;
nq := nqm2;
l := nq + 1;
exit;
end; { end if ( meth == 1 ) }
{ We are currently using a bdf method, considering switching to Adams.
Compute the step size we could have (ideally) used on this step,
with the current (bdf) method, and also that for the Adams.
If nq > mxordn, we consider changing to order mxordn on switching.
Compare the two step sizes to decide whether to switch.
The step size advantage must be at least 5/ratio = 1 to switch.
If the step size for Adams would be so small as to cause
roundoff pollution, we stay with bdf. }
exsm := 1. / l;
if mxordn < nq then
begin
nqm1 := mxordn;
lm1 := mxordn + 1;
exm1 := 1. / lm1;
lm1p1 := lm1 + 1;
dm1 := vmnorm(yh[lm1p1], ewt ) / cm1[mxordn];
rh1 := 1. / ( 1.2 * pow( dm1, exm1 ) + 0.0000012 );
end
else
begin
dm1 := dsm * ( cm2[nq] / cm1[nq] );
rh1 := 1. / ( 1.2 * pow( dm1, exsm ) + 0.0000012 );
nqm1 := nq;
exm1 := exsm;
end;
rh1it := 2. * rh1;
pdh := pdnorm * abs( h );
if ( pdh * rh1 ) > 0.00001 then rh1it := sm1[nqm1] / pdh;
rh1 := min( rh1, rh1it );
rh2 := 1. / ( 1.2 * pow( dsm, exsm ) + 0.0000012 );
if (( rh1 * ratio ) < ( 5. * rh2 )) then exit;
alpha := max( 0.001, rh1 );
dm1 := dm1 * pow( alpha, exm1 );
if (dm1 <= 1000. * ETA * pnorm) then exit;
{ The switch test passed. Reset relevant quantities for Adams. }
rh := rh1;
icount := 20;
meth := 1;
miter := 0;
pdlast := 0.;
nq := nqm1;
l := nq + 1;
end; { end methodswitch }
{**************************************************************}
{ This routine returns from stoda to lsoda. Hence freevectors() is
not executed. }
procedure TLsoda.endstoda;
var
r : double;
i : integer;
begin
r := 1. / tesco[nqu,2];
for i := 1 to n do
acor[i] := acor[i] * r;
hold := h;
jstart := 1;
end; { end endstoda }
{**************************************************************}
procedure TLsoda.orderswitch( var rhup: double;
dsm: double;
var pdh, rh: double;
var orderflag: integer);
{ Regardless of the success or failure of the step, factors
rhdn, rhsm, and rhup are computed, by which h could be multiplied
at order nq - 1, order nq, or order nq + 1, respectively.
In the case of a failure, rhup = 0. to avoid an order increase.
The largest of these is determined and the new order chosen
accordingly. If the order is to be increased, we compute one
additional scaled derivative.
orderflag = 0 : no change in h or nq,
1 : change in h but not nq,
2 : change in both h and nq. }
var
newq, i: integer;
exsm, rhdn, rhsm, ddn, exdn, r: double;
begin
orderflag := 0;
exsm := 1. / l;
rhsm := 1. / ( 1.2 * pow( dsm, exsm ) + 0.0000012 );
rhdn := 0.;
if nq <> 1 then
begin
ddn := vmnorm(yh[l], ewt ) / tesco[nq,1];
exdn := 1. / nq;
rhdn := 1. / ( 1.3 * pow( ddn, exdn ) + 0.0000013 );
end;
{ If meth = 1, limit rh accordinfg to the stability region also. }
if meth = 1 then
begin
pdh := max( abs( h ) * pdlast, 0.000001 );
if l < lmax then
rhup := min( rhup, sm1[l] / pdh );
rhsm := min( rhsm, sm1[nq] / pdh );
if nq > 1 then
rhdn := min( rhdn, sm1[nq-1] / pdh );
pdest := 0.;
end;
if rhsm >= rhup then
begin
if rhsm >= rhdn then
begin
newq := nq;
rh := rhsm;
end
else
begin
newq := nq - 1;
rh := rhdn;
if (kflag < 0) AND (rh > 1.0) then
rh := 1.;
end;
end
else
begin
if ( rhup <= rhdn ) then
begin
newq := nq - 1;
rh := rhdn;
if ( kflag < 0) AND (rh > 1. ) then
rh := 1.;
end
else
begin
rh := rhup;
if ( rh >= 1.1 ) then
begin
r := el[l] / l;
nq := l;
l := nq + 1;
for i := 1 to n do
yh[l][i] := acor[i] * r;
orderflag := 2;
exit;
end
else
begin
ialth := 3;
exit;
end;
end;
end;
{ If meth = 1 and h is restricted by stability, bypass 10 percent test. }
if meth = 1 then
begin
if (( rh * pdh * 1.00001 ) < sm1[newq]) then
if (kflag = 0) AND (rh < 1.1) then
begin
ialth := 3;
exit;
end;
end
else
begin
if (kflag = 0) AND (rh < 1.1 ) then
begin
ialth := 3;
exit;
end;
end;
if kflag <= -2 then
rh := min( rh, 0.2 );
{ If there is a change of order, reset nq, l, and the coefficients.
In any case h is reset according to rh and the yh array is rescaled.
Then exit or redo the step. }
if (newq = nq) then
begin
orderflag := 1;
exit;
end;
nq := newq;
l := nq + 1;
orderflag := 2;
end; { end orderswitch }
{**************************************************************}
procedure TLsoda.resetcoeff;
{ The el vector and related constants are reset
whenever the order nq is changed, or at the start of the problem. }
var i : integer;
begin
for i := 1 to l do el[i] := elco[nq,i];
rc := rc * el[1] / el0;
el0 := el[1];
conit := 0.5 / ( nq + 2 );
end; { end resetcoeff }
{**************************************************************}
procedure TLsoda.correction( neq:integer;
var y:TVector;
var corflag:integer;
pnorm: double;
var del, delp, told: double;
var ncf: integer;
var rh: double;
var m: integer);
{ *corflag = 0 : corrector converged,
1 : step size to be reduced, redo prediction,
2 : corrector cannot converge, failure flag. }
var
i: integer;
rm, rate, dcon: double;
{ Up to maxcor corrector iterations are taken. A convergence test is
made on the r.m.s. norm of each correction, weighted by the error
weight vector ewt. The sum of the corrections is accumulated in the
vector acor[i]. The yh array is not altered in the corrector loop. }
begin
m := 0;
corflag := 0;
rate := 0.;
del := 0.;
for i := 1 to n do
y[i] := yh[1][i];
FDerivatives (tn, y, savf);
nfe := nfe + 1;
{ If indicated, the matrix P = I - h * el[1] * J is reevaluated and
preprocessed before starting the corrector iteration. ipup is set
to 0 as an indicator that this has been done. }
while ( 1=1 ) do
begin
if ( m = 0 ) then
begin
if ( ipup > 0 ) then
begin
prja( neq, y);
ipup := 0;
rc := 1.;
nslp := nst;
crate := 0.7;
if ( ierpj <> 0 ) then
begin
corfailure( told, rh, ncf, corflag );
exit;
end;
end;
for i := 1 to n do
acor[i] := 0.;
end; { end if ( *m == 0 ) }
if ( miter = 0 ) then
begin
{ In case of functional iteration, update y directly from
the result of the last function evaluation. }
for i := 1 to n do
begin
savf[i] := h * savf[i] - yh[2][i];
y[i] := savf[i] - acor[i];
end;
del := vmnorm(y, ewt );
for i := 1 to n do
begin
y[i] := yh[1][i] + el[1] * savf[i];
acor[i] := savf[i];
end;
end { end functional iteration }
{ In the case of the chord method, compute the corrector error,
and solve the linear system with that as right-hand side and
P as coefficient matrix. }
else
begin
for i := 1 to n do
y[i] := h * savf[i] - ( yh[2][i] + acor[i] );
solsy( y );
del := vmnorm(y, ewt );
for i := 1 to n do
begin
acor[i] := acor[i] + y[i];
y[i] := yh[1][i] + el[1] * acor[i];
end;
end; { end chord method }
{ Test for convergence. If *m > 0, an estimate of the convergence
rate constant is stored in crate, and this is used in the test.
We first check for a change of iterates that is the size of
roundoff error. If this occurs, the iteration has converged, and a
new rate estimate is not formed.
In all other cases, force at least two iterations to estimate a
local Lipschitz constant estimate for Adams method.
On convergence, form pdest = local maximum Lipschitz constant
estimate. pdlast is the most recent nonzero estimate. }
if ( del <= 100. * pnorm * ETA ) then exit;
if ( m <> 0) OR (meth <> 1 ) then
begin
if ( m <> 0 ) then
begin
rm := 1024.0;
if ( del <= ( 1024. * delp ) ) then
rm := del / delp;
rate := max( rate, rm );
crate := max( 0.2 * crate, rm );
end;
dcon := del * min( 1., 1.5 * crate ) / ( tesco[nq,2] * conit );
if ( dcon <= 1. ) then
begin
pdest := max( pdest, rate / abs( h * el[1] ) );
if ( pdest <> 0. ) then
pdlast := pdest;
exit;
end;
end;
{ The corrector iteration failed to converge.
If miter != 0 and the Jacobian is out of date, prja is called for
the next try. Otherwise the yh array is retracted to its values
before prediction, and h is reduced, if possible. If h cannot be
reduced or mxncf failures have occured, exit with corflag = 2. }
m:=m+1;
if ( m = maxcor) OR (( m >= 2) AND (del > 2. * delp )) then
begin
if ( miter = 0) OR (jcur = 1 ) then
begin
corfailure( told, rh, ncf, corflag );
exit;
end;
ipup := miter;
{ Restart corrector if Jacobian is recomputed. }
m := 0;
rate := 0.;
del := 0.;
for i := 1 to n do y[i] := yh[1][i];
FDerivatives (tn, y, savf);
nfe := nfe + 1;
end
{ Iterate corrector. }
else
begin
delp := del;
FDerivatives (tn, y, savf);
nfe := nfe + 1;
end;
end; { end while }
end; { end correction }
{**************************************************************}
procedure TLsoda.intdy (t : double; k : integer; var dky : TVector; var iflag : integer);
{ intdy computes interpolated values of the k-th derivative of the
dependent variable vector y, and stores it in dky. This routine
is called within the package with k = 0 and *t = tout, but may
also be called by the user for any k up to the current order.
( See detailed instructions in the usage documentation. )
The computed values in dky are gotten by interpolation using the
Nordsieck history array yh. This array corresponds uniquely to a
vector-valued polynomial of degree nqcur or less, and dky is set
to the k-th derivative of this polynomial at t.
The formula for dky is
q
dky[i] = sum c[k][j] * ( t - tn )^(j-k) * h^(-j) * yh[j+1][i]
j=k
where c[k][j] = j*(j-1)*...*(j-k+1), q = nqcur, tn = tcur, h = hcur.
The quantities nq = nqcur, l = nq+1, n = neq, tn, and h are declared
static globally. The above sum is done in reverse order.
*iflag is returned negative if either k or t is out of bounds. }
var
i, ic, j, jj, jp1: integer;
c, r, s, tp: double;
begin
iflag := 0;
if ( k < 0) OR (k > nq ) then
begin
if ( prfl=1 ) then
writeln('intdy -- k = ',k,' illegal');
iflag := -1;
exit;
end;
tp := tn - hu - 100. * ETA * ( tn + hu );
if ( ( t - tp ) * ( t - tn ) > 0. ) then
begin
if ( prfl=1 ) then
begin
writeln('intdy -- t = ',t,' illegal');
writeln(' t not in interval tcur - hu to tcur');
end;
iflag := -2;
exit;
end;
s := ( t - tn ) / h;
ic := 1;
for jj := l - k to nq do
ic := ic * jj;
c := ic;
for i := 1 to n do
dky[i] := c * yh[l][i];
for j := nq - 1 downto k do
begin
jp1 := j + 1;
ic := 1;
for jj := jp1 - k to j do
ic := ic * jj;
c := ic;
for i := 1 to n do
dky[i] := c * yh[jp1][i] + s * dky[i];
end;
if ( k = 0 ) then exit;
r := pow( h, -k );
for i := 1 to n do
dky[i] := dky[i] * r;
end; { end intdy }
{**************************************************************}
procedure TLsoda.cfode(meth : integer);
var
i, nq, nqm1, nqp1: integer;
agamq, fnq, fnqm1, pint, ragq,rqfac, rq1fac, tsign, xpin : double;
pc : vector13;
{ cfode is called by the integrator routine to set coefficients
needed there. The coefficients for the current method, as
given by the value of meth, are set for all orders and saved.
The maximum order assumed here is 12 if meth = 1 and 5 if meth = 2.
( A smaller value of the maximum order is also allowed. )
cfode is called once at the beginning of the problem, and
is not called again unless and until meth is changed.
The elco array contains the basic method coefficients.
The coefficients el[i], 1 < i < nq+1, for the method of
order nq are stored in elco[nq][i]. They are given by a generating
polynomial, i.e.,
l(x) = el[1] + el[2]*x + ... + el[nq+1]*x^nq.
For the implicit Adams method, l(x) is given by
dl/dx = (x+1)*(x+2)*...*(x+nq-1)/factorial(nq-1), l(-1) = 0.
For the bdf methods, l(x) is given by
l(x) = (x+1)*(x+2)*...*(x+nq)/k,
where k = factorial(nq)*(1+1/2+...+1/nq).
The tesco array contains test constants used for the
local error test and the selection of step size and/or order.
At order nq, tesco[nq][k] is used for the selection of step
size at order nq-1 if k = 1, at order nq if k = 2, and at order
nq+1 if k = 3. }
begin
if (meth = 1) then
begin
elco[1,1] := 1.;
elco[1,2] := 1.;
tesco[1,1] := 0.;
tesco[1,2] := 2.;
tesco[2,1] := 1.;
tesco[12,3] := 0.;
pc[1] := 1.;
rqfac := 1.;
for nq := 2 to 12 do
begin
{ The pc array will contain the coefficients of the polynomial
p(x) = (x+1)*(x+2)*...*(x+nq-1).
Initially, p(x) = 1. }
rq1fac := rqfac;
rqfac := rqfac / nq;
nqm1 := nq - 1;
fnqm1 := nqm1;
nqp1 := nq + 1;
{ Form coefficients of p(x)*(x+nq-1). }
pc[nq] := 0.;
for i := nq downto 2 do
pc[i] := pc[i-1] + fnqm1 * pc[i];
pc[1] := fnqm1 * pc[1];
{ Compute integral, -1 to 0, of p(x) and x*p(x). }
pint := pc[1];
xpin := pc[1] / 2.;
tsign := 1.;
for i := 2 to nq do
begin
tsign := -tsign;
pint := pint + tsign * pc[i] / i;
xpin := xpin + tsign * pc[i] / ( i + 1 );
end;
{ Store coefficients in elco and tesco. }
elco[nq,1] := pint * rq1fac;
elco[nq,2] := 1.;
for i := 2 to nq do
elco[nq,i+1] := rq1fac * pc[i] / i;
agamq := rqfac * xpin;
ragq := 1. / agamq;
tesco[nq,2] := ragq;
if (nq < 12) then
tesco[nqp1,1] := ragq * rqfac / nqp1;
tesco[nqm1,3] := ragq;
end; { end for }
exit;
end; { end if meth == 1 }
{ meth = 2. }
pc[1] := 1.;
rq1fac := 1.;
{ The pc array will contain the coefficients of the polynomial
p(x) = (x+1)*(x+2)*...*(x+nq).
Initially, p(x) = 1. }
for nq := 1 to 5 do
begin
fnq := nq;
nqp1 := nq + 1;
{ Form coefficients of p(x)*(x+nq). }
pc[nqp1] := 0.;
for i := nq + 1 downto 2 do
pc[i] := pc[i-1] + fnq * pc[i];
pc[1] := pc[1]*fnq;
{ Store coefficients in elco and tesco. }
for i := 1 to nqp1 do
elco[nq,i] := pc[i] / pc[2];
elco[nq,2] := 1.;
tesco[nq,1] := rq1fac;
tesco[nq,2] := nqp1 / elco[nq,1];
tesco[nq,3] := ( nq + 2 ) / elco[nq,1];
rq1fac := rq1fac/fnq;
end;
end; { end cfode }
{**************************************************************}
procedure TLsoda.scaleh( var rh, pdh: double );
var
r: double;
j, i: integer;
{ If h is being changed, the h ratio rh is checked against
rmax, hmin, and hmxi, and the yh array is rescaled. ialth is set to
l = nq + 1 to prevent a change of h for that many steps, unless
forced by a convergence or error test failure. }
begin
rh := min( rh, rmax );
rh := rh / max( 1., abs( h ) * hmxi * rh );
{ If meth = 1, also restrict the new step size by the stability region.
If this reduces h, set irflag to 1 so that if there are roundoff
problems later, we can assume that is the cause of the trouble.}
if ( meth = 1 ) then
begin
irflag := 0;
pdh := max( abs( h ) * pdlast, 0.000001 );
if ( ( rh * pdh * 1.00001 ) >= sm1[nq] ) then
begin
rh := sm1[nq] / pdh;
irflag := 1;
end;
end;
r := 1.;
for j := 2 to l do
begin
r := r * rh;
for i := 1 to n do
yh[j][i] := yh[j][i] * r;
end;
h := h * rh;
rc := rc * rh;
ialth := l;
end; { end scaleh }
{**************************************************************}
procedure TLsoda.stoda(var neq : integer; var y : TVector);
var
corflag, orderflag,i, i1, j, jb, m, ncf: integer;
del, delp, dsm, dup, exup, r, rh, rhup, told, pdh, pnorm: double;
{ stoda performs one step of the integration of an initial value
problem for a system of ordinary differential equations.
Note.. stoda is independent of the value of the iteration method
indicator miter, when this is != 0, and hence is independent
of the type of chord method used, or the Jacobian structure.
Communication with stoda is done with the following variables:
jstart = an integer used for input only, with the following
values and meanings:
0 perform the first step,
> 0 take a new step continuing from the last,
-1 take the next step with a new value of h,
n, meth, miter, and/or matrix parameters.
-2 take the next step with a new value of h,
but with other inputs unchanged.
kflag = a completion code with the following meanings:
0 the step was successful,
-1 the requested error could not be achieved,
-2 corrector convergence could not be achieved,
-3 fatal error in prja or solsy.
miter = corrector iteration method:
0 functional iteration,
>0 a chord method corresponding to jacobian type jt. }
begin
kflag := 0;
told := tn;
ncf := 0;
ierpj := 0;
iersl := 0;
jcur := 0;
delp := 0.;
{ On the first call, the order is set to 1, and other variables are
initialized. rmax is the maximum ratio by which h can be increased
in a single step. It is initially 1.e4 to compensate for the small
initial h, but then is normally equal to 10. If a filure occurs
(in corrector convergence or error test), rmax is set at 2 for
the next increase.
cfode is called to get the needed coefficients for both methods. }
if ( jstart = 0 ) then
begin
lmax := maxord + 1;
nq := 1;
l := 2;
ialth := 2;
rmax := 10000.;
rc := 0.;
el0 := 1.;
crate := 0.7;
hold := h;
nslp := 0;
ipup := miter;
{ Initialize switching parameters. meth = 1 is assumed initially. }
icount := 20;
irflag := 0;
pdest := 0.;
pdlast := 0.;
ratio := 5.;
cfode( 2 );
for i := 1 to 5 do
cm2[i] := tesco[i,2] * elco[i,i+1];
cfode( 1 );
for i := 1 to 12 do
cm1[i] := tesco[i,2] * elco[i,i+1];
resetcoeff;
end; { end if ( jstart == 0 ) }
{ The following block handles preliminaries needed when jstart = -1.
ipup is set to miter to force a matrix update.
If an order increase is about to be considered ( ialth = 1 ),
ialth is reset to 2 to postpone consideration one more step.
If the caller has changed meth, cfode is called to reset
the coefficients of the method.
If h is to be changed, yh must be rescaled.
If h or meth is being changed, ialth is reset to l = nq + 1
to prevent further changes in h for that many steps. }
if ( jstart = -1 ) then
begin
ipup := miter;
lmax := maxord + 1;
if ( ialth = 1 ) then
ialth := 2;
if ( meth <> mused ) then
begin
cfode( meth );
ialth := l;
resetcoeff;
end;
if ( h <> hold ) then
begin
rh := h / hold;
h := hold;
scaleh( rh, pdh );
end;
end; { if ( jstart == -1 ) }
if ( jstart = -2 ) then
begin
if ( h <> hold ) then
begin
rh := h / hold;
h := hold;
scaleh( rh, pdh );
end;
end; { if ( jstart == -2 ) }
{ Prediction.
This section computes the predicted values by effectively
multiplying the yh array by the pascal triangle matrix.
rc is the ratio of new to old values of the coefficient h * el[1].
When rc differs from 1 by more than ccmax, ipup is set to miter
to force pjac to be called, if a jacobian is involved.
In any case, prja is called at least every msbp steps. }
while (1=1 ) do
begin
repeat
if ( abs( rc - 1. ) > ccmax ) then
ipup := miter;
if ( nst >= nslp + msbp ) then
ipup := miter;
tn := tn+h;
for j := nq downto 1 do
for i1 := j to nq do
begin
for i := 1 to n do
yh[i1][i] := yh[i1][i]+yh[i1+1][i];
end;
pnorm := vmnorm(yh[1], ewt );
correction( neq, y, corflag, pnorm, del, delp, told, ncf,rh, m );
if ( corflag = 1 ) then
begin
rh := max( rh, hmin / abs( h ) );
scaleh( rh, pdh );
end;
if ( corflag = 2 ) then
begin
kflag := -2;
hold := h;
jstart := 1;
exit;
end;
until (corflag=0); { end inner while ( corrector loop ) }
{ The corrector has converged. jcur is set to 0
to signal that the Jacobian involved may need updating later.
The local error test is done now. }
jcur := 0;
if ( m = 0 ) then
dsm := del / tesco[nq,2];
if ( m > 0 ) then
dsm := vmnorm(acor, ewt ) / tesco[nq,2];
if ( dsm <= 1. ) then
begin
{ After a successful step, update the yh array.
Decrease icount by 1, and if it is -1, consider switching methods.
If a method switch is made, reset various parameters,
rescale the yh array, and exit. If there is no switch,
consider changing h if ialth = 1. Otherwise decrease ialth by 1.
If ialth is then 1 and nq < maxord, then acor is saved for
use in a possible order increase on the next step.
If a change in h is considered, an increase or decrease in order
by one is considered also. A change in h is made only if it is by
a factor of at least 1.1. If not, ialth is set to 3 to prevent
testing for that many steps. }
kflag := 0;
nst:=nst+1;
hu := h;
nqu := nq;
mused := meth;
for j := 1 to l do
begin
r := el[j];
for i := 1 to n do
yh[j][i] := yh[j][i] + r * acor[i];
end;
icount:=icount-1;
if ( icount < 0 ) then
begin
methodswitch( dsm, pnorm, pdh, rh );
if ( meth <> mused ) then
begin
rh := max( rh, hmin / abs( h ) );
scaleh( rh, pdh );
rmax := 10.;
endstoda;
exit;
end;
end;
{ No method switch is being made. Do the usual step/order selection. }
ialth:=ialth-1;
if ( ialth = 0 ) then
begin
rhup := 0.;
if ( l <> lmax ) then
begin
for i := 1 to n do
savf[i] := acor[i] - yh[lmax][i];
dup := vmnorm(savf, ewt ) / tesco[nq,3];
exup := 1. / ( l + 1 );
rhup := 1. / ( 1.4 * pow( dup, exup ) + 0.0000014 );
end;
orderswitch( rhup, dsm, pdh, rh, orderflag );
{ No change in h or nq. }
if ( orderflag = 0 ) then
begin
endstoda;
exit;
end;
{ h is changed, but not nq. }
if ( orderflag = 1 ) then
begin
rh := max( rh, hmin / abs( h ) );
scaleh( rh, pdh );
rmax := 10.;
endstoda;
exit;
end;
{ both nq and h are changed. }
if ( orderflag = 2 ) then
begin
resetcoeff;
rh := max( rh, hmin / abs( h ) );
scaleh( rh, pdh );
rmax := 10.;
endstoda;
exit;
end;
end; { end if ( ialth == 0 ) }
if ( ialth > 1) OR (l = lmax ) then
begin
endstoda;
exit;
end;
for i := 1 to n do
yh[lmax][i] := acor[i];
endstoda;
exit;
end { end if ( dsm <= 1. ) }
{ The error test failed. kflag keeps track of multiple failures.
Restore tn and the yh array to their previous values, and prepare
to try the step again. Compute the optimum step size for this or
one lower. After 2 or more failures, h is forced to decrease
by a factor of 0.2 or less. }
else
begin
kflag:=kflag-1;
tn := told;
for j := nq downto 1 do
for i1 := j to nq do
begin
for i := 1 to n do
yh[i1][i] := yh[i1][i]-yh[i1+1][i];
end;
rmax := 2.;
if ( abs( h ) <= hmin * 1.00001 ) then
begin
kflag := -1;
hold := h;
jstart := 1;
exit;
end;
if ( kflag > -3 ) then
begin
rhup := 0.;
orderswitch( rhup, dsm, pdh, rh, orderflag );
if ( orderflag = 1) OR (orderflag = 0 ) then
begin
if ( orderflag = 0 ) then
rh := min( rh, 0.2 );
rh := max( rh, hmin / abs( h ) );
scaleh( rh, pdh );
end;
if ( orderflag = 2 ) then
begin
resetcoeff;
rh := max( rh, hmin / abs( h ) );
scaleh( rh, pdh );
end;
end { if ( kflag > -3 ) }
{ Control reaches this section if 3 or more failures have occurred.
If 10 failures have occurred, exit with kflag = -1.
It is assumed that the derivatives that have accumulated in the
yh array have errors of the wrong order. Hence the first
derivative is recomputed, and the order is set to 1. Then
h is reduced by a factor of 10, and the step is retried,
until it succeeds or h reaches hmin. }
else
begin
if ( kflag = -10 ) then
begin
kflag := -1;
hold := h;
jstart := 1;
exit;
end
else
begin
rh := 0.1;
rh := max( hmin / abs( h ) , rh );
h := h * rh;
for i := 1 to n do y[i] := yh[1][i];
FDerivatives (tn, y, savf);
nfe:=nfe+1;
for i := 1 to n do
yh[2][i] := h * savf[i];
ipup := miter;
ialth := 5;
if ( nq <> 1 ) then
begin
nq := 1;
l := 2;
resetcoeff;
end;
end;
end; { end else -- kflag <= -3 }
end; { end error failure handling }
end; { end outer while }
end; { end stoda }
{**************************************************************}
procedure TLsoda.Execute (var y : TVector; var t, tout : double);
{ If the user does not supply any of these values, the calling program
should initialize those untouched working variables to zero.
ml = iwork1
mu = iwork2
ixpr = iwork5
mxstep = iwork6
mxhnil = iwork7
mxordn = iwork8
mxords = iwork9
tcrit = rwork1
h0 = rwork5
hmax = rwork6
hmin = rwork7 }
var
mxstp0, mxhnl0,i, i1, i2, iflag, kgo, lf0, lenyh, ihit: integer;
atoli, ayi, big, ewti, h0, hmax, hmx, rh, rtoli,
tcrit, tdist, tnext, tol, tp, size, sum, w0: double;
begin
mxstp0 := 500;
mxhnl0 := 10;
{ Block a.
This code block is executed on every call.
It tests *istate and itask for legality and branches appropriately.
If *istate > 1 but the flag init shows that initialization has not
yet been done, an error return occurs.
If *istate = 1 and tout = t, return immediately. }
if (istate=1) then
begin
illin:=0; init:=0; ntrep:=0; ixpr:=0;
end;
if ( istate < 1) OR (istate > 3 ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- illegal istate =',istate );
terminate( Fistate );
exit;
end;
if ( itask < 1) OR (itask > 5 ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- illegal itask =',itask );
terminate( Fistate );
exit;
end;
if ( init = 0) AND (( istate = 2) OR (istate = 3 ) ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- istate > 1 but lsoda not initialized');
terminate( Fistate );
exit;
end;
if (istate = 1 ) then
begin
init := 0;
if ( tout = t ) then
begin
ntrep:=ntrep+1;
if ( ntrep < 5 ) then exit;
if ( prfl=1 ) then
begin
writeln('lsoda -- repeated calls with istate = 1 and tout = t');
writeln(' run aborted.. apparent infinite loop');
end;
exit;
end;
end;
{ Block b.
The next code block is executed for the initial call ( *istate = 1 ),
or for a continuation call with parameter changes ( *istate = 3 ).
It contains checking of all inputs and various initializations.
First check legality of the non-optional inputs neq, itol, iopt,
jt, ml, and mu. }
if ( istate = 1) OR (istate = 3 ) then
begin
ntrep := 0;
if ( neq <= 0 ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- neq =',neq,' is less than 1');
terminate( Fistate );
exit;
end;
if ( istate = 3) AND (neq > n ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- istate = 3 and neq increased');
terminate( Fistate );
exit;
end;
n := neq;
if ( itol < 1) OR (itol > 4 ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- itol = ',itol,' illegal');
terminate( Fistate );
exit;
end;
if ( iopt < 0) OR (iopt > 1 ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- iopt = ',iopt,' illegal');
terminate( Fistate );
exit;
end;
if ( jt = 3) OR (jt < 1) OR (jt > 5 ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- jt = ',jt,' illegal');
terminate( Fistate );
exit;
end;
jtyp := jt;
{ Next process and check the optional inputs. }
{ Default options. }
if ( iopt = 0 ) then
begin
ixpr := 0;
mxstep := mxstp0;
mxhnil := mxhnl0;
hmxi := 0.;
hmin := 0.;
if ( istate = 1 ) then
begin
h0 := 0.;
mxordn := mord[1];
mxords := mord[2];
end;
end { end if ( iopt == 0 ) }
{ Optional inputs. }
else { if ( iopt = 1 ) }
begin
ixpr := iwork5;
if ( ixpr < 0) OR (ixpr > 2 ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- ixpr = ',ixpr,' is illegal');
terminate( Fistate );
exit;
end;
mxstep := iwork6;
if ( mxstep < 0 ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- mxstep < 0');
terminate( Fistate );
exit;
end;
if ( mxstep = 0 ) then
mxstep := mxstp0;
mxhnil := iwork7;
if ( mxhnil < 0 ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- mxhnil < 0');
terminate( Fistate );
exit;
end;
if ( istate = 1 ) then
begin
h0 := rwork5;
mxordn := iwork8;
if ( mxordn < 0 ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- mxordn = ',mxordn,' is less than 0');
terminate( Fistate );
exit;
end;
if ( mxordn = 0 ) then
mxordn := 100;
mxordn := mini( mxordn, mord[1] );
mxords := iwork9;
if ( mxords < 0 ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- mxords = ',mxords,' is less than 0');
terminate( Fistate );
exit;
end;
if ( mxords = 0 ) then
mxords := 100;
mxords := mini( mxords, mord[2] );
if ( ( tout - t ) * h0 < 0. ) then
begin
if ( prfl=1 ) then
begin
writeln('lsoda -- tout = ',tout,' behind t = ',t);
writeln(' integration direction is given by ',h0);
end;
terminate( Fistate );
exit;
end;
end; { end if ( *istate == 1 ) }
hmax := rwork6;
if ( hmax < 0. ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- hmax < 0.');
terminate( Fistate );
exit;
end;
hmxi := 0.;
if ( hmax > 0 ) then
hmxi := 1. / hmax;
hmin := rwork7;
if ( hmin < 0. ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- hmin < 0.');
terminate( Fistate );
exit;
end;
end; { end else } { end iopt = 1 }
end; { end if ( *istate == 1 || *istate == 3 ) }
{ If *istate = 1, meth is initialized to 1. }
if ( istate = 1 ) then
begin
{ If memory were not freed, *istate = 3 need not reallocate memory.
Hence this section is not executed by *istate = 3. }
sqrteta := Sqrt( ETA );
meth := 1;
nyh := n;
lenyh := 1 + maxi( mxordn, mxords );
end;
{ Check rtol and atol for legality. }
if ( istate = 1) OR (istate = 3 ) then
begin
rtoli := rtol[1];
atoli := atol[1];
for i := 1 to n do
begin
if ( itol >= 3 ) then
rtoli := rtol[i];
if ( itol = 2) OR (itol = 4 ) then
atoli := atol[i];
if ( rtoli < 0. ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- rtol = ',rtoli,' is less than 0.');
terminate( Fistate );
exit;
end;
if ( atoli < 0. ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- atol = ',atoli,' is less than 0.');
terminate( Fistate );
exit;
end;
end; { end for }
end; { end if ( *istate == 1 || *istate == 3 ) }
{ If *istate = 3, set flag to signal parameter changes to stoda. }
if ( istate = 3 ) then
jstart := -1;
{ Block c.
The next block is for the initial call only ( *istate = 1 ).
It contains all remaining initializations, the initial call to f,
and the calculation of the initial step size.
The error weights in ewt are inverted after being loaded. }
if ( istate = 1 ) then
begin
tn := t;
tsw := t;
maxord := mxordn;
if ( itask = 4) OR (itask = 5 ) then
begin
tcrit := rwork1;
if ( ( tcrit - tout ) * ( tout - t ) < 0. ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- itask = 4 or 5 and tcrit behind tout');
terminate( Fistate );
exit;
end;
if ( h0 <> 0) AND (( t + h0 - tcrit ) * h0 > 0. ) then
h0 := tcrit - t;
end;
jstart := 0;
nhnil := 0;
nst := 0;
nje := 0;
nslast := 0;
hu := 0.;
nqu := 0;
mused := 0;
miter := 0;
ccmax := 0.3;
maxcor := 3;
msbp := 20;
mxncf := 10;
{ Initial call to fonction }
FDerivatives (t, y, yh[2]);
nfe := 1;
{ Load the initial value vector in yh.}
for i := 1 to n do
yh[1][i] := y[i];
{ Load and invert the ewt array. ( h is temporarily set to 1. ) }
nq := 1;
h := 1.;
ewset( Fitol, Frtol, Fatol, y );
for i := 1 to n do
begin
if ( ewt[i] <= 0. ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- ewt[',i,'] = ',ewt[i],' <= 0.');
terminate2( y, t);
exit;
end;
ewt[i] := 1. / ewt[i];
end;
{ The coding below computes the step size, h0, to be attempted on the
first step, unless the user has supplied a value for this.
First check that tout - *t differs significantly from zero.
A scalar tolerance quantity tol is computed, as max(rtol[i])
if this is positive, or max(atol[i]/fabs(y[i])) otherwise, adjusted
so as to be between 100*ETA and 0.001.
Then the computed value h0 is given by
h0^(-2) = 1. / ( tol * w0^2 ) + tol * ( norm(f) )^2
where w0 = max( fabs(*t), fabs(tout) ),
f = the initial value of the vector f(t,y), and
norm() = the weighted vector norm used throughout, given by
the vmnorm function routine, and weighted by the
tolerances initially loaded into the ewt array.
The sign of h0 is inferred from the initial values of tout and *t.
fabs(h0) is made < fabs(tout-*t) in any case. }
if ( h0 = 0. ) then
begin
tdist := abs( tout - t );
w0 := max( abs( t ), abs( tout ) );
if ( tdist < 2. * ETA * w0 ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- tout too close to t to start integration');
terminate( Fistate );
exit;
end;
tol := rtol[1];
if ( itol > 2 ) then
begin
for i := 2 to n do
tol := max( tol, rtol[i] );
end;
if ( tol <= 0. ) then
begin
atoli := atol[1];
for i := 1 to n do
begin
if ( itol = 2) OR (itol = 4 ) then
atoli := atol[i];
ayi := abs( y[i] );
if ( ayi <> 0. ) then
tol := max( tol, atoli / ayi );
end;
end;
tol := max( tol, 100. * ETA );
tol := min( tol, 0.001 );
sum := vmnorm(yh[2], ewt );
sum := 1. / ( tol * w0 * w0 ) + tol * sum * sum;
h0 := 1. / sqrt( sum );
h0 := min( h0, tdist );
if(tout-t < 0) then h0:=-h0;
end; { end if ( h0 == 0. ) }
{ Adjust h0 if necessary to meet hmax bound. }
rh := abs( h0 ) * hmxi;
if ( rh > 1. ) then
h0 := h0/rh;
{ Load h with h0 and scale yh[2] by h0. }
h := h0;
for i := 1 to n do
yh[2][i] := yh[2][i]*h0;
end; { if ( *istate == 1 ) }
{ Block d.
The next code block is for continuation calls only ( *istate = 2 or 3 )
and is to check stop conditions before taking a step. }
if ( istate = 2) OR (istate = 3 ) then
begin
nslast := nst;
case itask of
1 :
begin
if ( ( tn - tout ) * h >= 0. ) then
begin
intdy( tout, 0, y, iflag );
if ( iflag <> 0 ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- trouble from intdy, itask = ',itask,', tout = ',tout);
terminate( Fistate );
exit;
end;
t := tout;
istate := 2;
illin := 0;
exit;
end;
end;
2 :
begin end;
3 :
begin
tp := tn - hu * ( 1. + 100. * ETA );
if ( ( tp - tout ) * h > 0. ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- itask = ',itask,' and tout behind tcur - hu');
terminate( Fistate );
exit;
end;
if ( ( tn - tout ) * h >= 0. ) then
begin
successreturn( y, t, itask, ihit, tcrit, Fistate );
exit;
end;
end;
4 :
begin
tcrit := rwork1;
if ( ( tn - tcrit ) * h > 0. ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- itask = 4 or 5 and tcrit behind tcur');
terminate( Fistate );
exit;
end;
if ( ( tcrit - tout ) * h < 0. ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- itask = 4 or 5 and tcrit behind tout');
terminate( Fistate );
exit;
end;
if ( ( tn - tout ) * h >= 0. ) then
begin
intdy( tout, 0, y, iflag );
if ( iflag <> 0 ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- trouble from intdy, itask = ',itask,', tout = ',tout);
terminate( Fistate );
exit;
end;
t := tout;
istate := 2;
illin := 0;
exit;
end;
end;
5 :
begin
if ( itask = 5 ) then
begin
tcrit := rwork1;
if ( ( tn - tcrit ) * h > 0. ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- itask = 4 or 5 and tcrit behind tcur');
terminate( Fistate );
exit;
end;
end;
hmx := abs( tn ) + abs( h );
if (abs( tn - tcrit ) <= ( 100. * ETA * hmx )) then ihit:=1
else ihit:=0;
if ( ihit=1 ) then
begin
t := tcrit;
successreturn( y, t, itask, ihit, tcrit, Fistate );
exit;
end;
tnext := tn + h * ( 1. + 4. * ETA );
if ( ( tnext - tcrit ) * h > 0. ) then
begin
h := ( tcrit - tn ) * ( 1. - 4. * ETA );
if ( istate = 2 ) then jstart := -2;
end;
end;
end; { end switch }
end; { end if ( *istate == 2 || *istate == 3 ) }
{ Block e.
The next block is normally executed for all calls and contains
the call to the one-step core integrator stoda.
This is a looping point for the integration steps.
First check for too many steps being taken, update ewt ( if not at
start of problem). Check for too much accuracy being requested, and
check for h below the roundoff level in *t. }
while (1=1 ) do
begin
if ( istate <> 1) OR (nst <> 0 ) then
begin
if ( ( nst - nslast ) >= mxstep ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- ',mxstep,' steps taken before reaching tout');
istate := -1;
terminate2( y, t );
exit;
end;
ewset( Fitol, Frtol, Fatol, yh[1] );
for i := 1 to n do
begin
if ( ewt[i] <= 0. ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- ewt[',i,'] = ',ewt[i],' <= 0.');
istate := -6;
terminate2( y, t );
exit;
end;
ewt[i] := 1. / ewt[i];
end;
end;
tolsf := ETA * vmnorm(yh[1], ewt );
if ( tolsf > 0.01 ) then
begin
tolsf := tolsf * 200.;
if ( nst = 0 ) then
begin
if ( prfl=1 ) then
begin
writeln('lsoda -- at start of problem, too much accuracy');
writeln(' requested for precision of machine,');
writeln(' suggested scaling factor = ',tolsf);
end;
terminate( Fistate );
exit;
end;
if ( prfl=1 ) then
begin
writeln('lsoda -- at t = ',t,', too much accuracy requested');
writeln(' for precision of machine, suggested');
writeln(' scaling factor = ',tolsf );
end;
istate := -2;
terminate2( y, t );
exit;
end;
if ( ( tn + h ) = tn ) then
begin
nhnil:=nhnil+1;
if ( nhnil <= mxhnil ) then
begin
if ( prfl=1 ) then
begin
writeln('lsoda -- warning..internal t = ',tn,' and h = ',h,' are');
writeln(' such that in the machine, t + h = t on the next step');
writeln(' solver will continue anyway.');
end;
if ( nhnil = mxhnil ) AND (prfl=1 ) then
begin
writeln('lsoda -- above warning has been issued ',nhnil,' times,');
writeln(' it will not be issued again for this problem');
end;
end;
end;
{ Call stoda }
stoda( neq, y);
{ Print extra information }
if ( ixpr = 2 ) AND (prfl=1 ) then
begin
writeln('meth= ',meth,', order= ',nq,', nfe= ',nfe,', nje= ',nje);
writeln('t= ',tn,', h= ',h,', nst= ',nst);
end;
if ( kflag = 0 ) then
begin
{ Block f.
The following block handles the case of a successful return from the
core integrator ( kflag = 0 ).
If a method switch was just made, record tsw, reset maxord,
set jstart to -1 to signal stoda to complete the switch,
and do extra printing of data if ixpr != 0.
Then, in any case, check for stop conditions. }
init := 1;
if ( meth <> mused ) then
begin
tsw := tn;
maxord := mxordn;
if ( meth = 2 ) then
maxord := mxords;
jstart := -1;
if ( ixpr=1) AND (prfl=1 ) then
begin
if ( meth = 2 ) then
writeln('lsoda -- a switch to the stiff method has occurred');
if ( meth = 1 ) then
writeln('lsoda -- a switch to the nonstiff method has occurred');
writeln(' at t = ',tn,', tentative step size h = ',h,', step nst = ',nst);
end;
end; { end if ( meth != mused ) }
{ itask = 1.
If tout has been reached, interpolate. }
if ( itask = 1 ) then
begin
if ( ( tn - tout ) * h >= 0. ) then
begin
intdy( tout, 0, y, iflag );
t := tout;
istate := 2;
illin := 0;
exit;
end;
end;
{ itask = 2. }
if ( itask = 2 ) then
begin
successreturn( y, t, itask, ihit, tcrit, Fistate );
exit;
end;
{ itask = 3.
Jump to exit if tout was reached. }
if ( itask = 3 ) then
begin
if ( ( tn - tout ) * h >= 0. ) then
begin
successreturn( y, t, itask, ihit, tcrit, Fistate );
exit;
end;
end;
{ itask = 4.
See if tout or tcrit was reached. Adjust h if necessary. }
if ( itask = 4 ) then
begin
if ( ( tn - tout ) * h >= 0. ) then
begin
intdy( tout, 0, y, iflag );
t := tout;
istate := 2;
illin := 0;
exit;
end
else
begin
hmx := abs( tn ) + abs( h );
if(abs( tn - tcrit ) <= ( 100. * ETA * hmx )) then ihit:=1
else ihit:=0;
if ( ihit=1 ) then
begin
successreturn( y, t, itask, ihit, tcrit, Fistate );
exit;
end;
tnext := tn + h * ( 1. + 4. * ETA );
if ( ( tnext - tcrit ) * h < 0. ) then
begin
h := ( tcrit - tn ) * ( 1. - 4. * ETA );
jstart := -2;
end;
end;
end; { end if ( itask == 4 ) }
{ itask = 5.
See if tcrit was reached and jump to exit. }
if ( itask = 5 ) then
begin
hmx := abs( tn ) + abs( h );
if (abs( tn - tcrit ) <= ( 100. * ETA * hmx )) then ihit:=1
else ihit:=0;
successreturn( y, t, itask, ihit, tcrit, Fistate );
exit;
end;
end; { end if ( kflag == 0 ) }
{ kflag = -1, error test failed repeatedly or with fabs(h) = hmin.
kflag = -2, convergence failed repeatedly or with fabs(h) = hmin. }
if ( kflag = -1) OR (kflag = -2 ) then
begin
if ( prfl=1 ) then
writeln('lsoda -- at t = ',tn,' and step size h = ',h,', the');
if ( kflag = -1 ) then
begin
if ( prfl=1 ) then
begin
writeln(' error test failed repeatedly or');
writeln(' with abs(h) = hmin');
end;
istate := -4;
end;
if ( kflag = -2 ) then
begin
if ( prfl=1 ) then
begin
writeln(' corrector convergence failed repeatedly or');
writeln(' with abs(h) = hmin');
end;
istate := -5;
end;
big := 0.;
imxer := 1;
for i := 1 to n do
begin
size := abs( acor[i] ) * ewt[i];
if ( big < size ) then
begin
big := size;
imxer := i;
end;
end;
terminate2( y, t );
exit;
end; { end if ( kflag == -1 || kflag == -2 ) }
end; { end while }
end; { end lsoda }
{**************************************************************}
end. { of unit lsoda }
|
unit ExtSeek2;
{-
********************************************************************************
******* XLSReadWriteII V3.00 *******
******* *******
******* Copyright(C) 1999,2006 Lars Arvidsson, Axolot Data *******
******* *******
******* email: components@axolot.com *******
******* URL: http://www.axolot.com *******
********************************************************************************
** Users of the XLSReadWriteII component must accept the following **
** disclaimer of warranty: **
** **
** XLSReadWriteII is supplied as is. The author disclaims all warranties, **
** expressedor implied, including, without limitation, the warranties of **
** merchantability and of fitness for any purpose. The author assumes no **
** liability for damages, direct or consequential, which may result from the **
** use of XLSReadWriteII. **
********************************************************************************
}
{$B-}
{$H+}
{$R-}
{$I XLSRWII2.inc}
interface
uses Classes, SysUtils, BIFFRecsII2, XLSUtils2, XLSStream2, SST2, XLSFonts2;
type
//* Performs a fast seek for a cell value in an Excel file. TExternalSeek is much
//* faster for reading a single value in a file than TXLSReadWriteII2. It shall
//* however only be used for reading single cells. It is not possible to change
//* a cell value with TExternalSeek.
TExternalSeek = class(TObject)
private
FSSTPos,FExtSSTPos: integer;
FFilename: WideString;
PBuf: PByteArray;
FHeader: TBIFFHeader;
FVersion: TExcelVersion;
FStream: TXLSStream;
FValue: TFormulaValue;
FSST: TSST2;
function CheckCell(Col,Row: word): boolean;
public
constructor Create;
destructor Destroy; override;
//* Seeks the file.
//* Seek the file given by Filename for the sheet SheetIndex and the cell
//* at Col and Row. Returns True if a cell was found at the location.
function Seek(SheetIndex,Col,Row: integer): boolean;
//* The name of the file to be seeked.
property Filename: WideString read FFilename write FFilename;
//* The value of the cell, if it was found.
property Value: TFormulaValue read FValue;
end;
implementation
constructor TExternalSeek.Create;
begin
FVersion := xvExcel97;
FSST := TSST2.Create(Nil);
end;
function TExternalSeek.CheckCell(Col,Row: word): boolean;
function GetFormulaStr(V: double): WideString;
begin
case TByte8Array(V)[0] of
0: begin
FStream.ReadHeader(FHeader);
if FHeader.RecID = $0207 then begin
FStream.Read(PBuf^,FHeader.Length);
Result := ByteStrToWideString(PBuf,PRecSTRING(PBuf).Len);
end;
end;
1: if TByte8Array(V)[2] = 0 then
Result := 'False'
else
Result := 'True';
2: Result := ErrorCodeToText(TByte8Array(V)[2]);
end;
end;
begin
Result := False;
case FHeader.RecID of
BIFFRECID_LABEL:
if (PRecLABEL(PBuf).Col = Col) and (PRecLABEL(PBuf).Row = Row) then begin
FVSetString(FValue,ByteStrToWideString(@PRecLABEL(PBuf).Data,PRecLABEL(PBuf).Len));
Result := True;
end;
BIFFRECID_LABELSST:
if (PRecLABELSST(PBuf).Col = Col) and (PRecLABELSST(PBuf).Row = Row) then begin
if FExtSSTPos > 0 then
FVSetString(FValue,FSST.StrSeek(FStream,FExtSSTPos,PRecLABELSST(PBuf).SSTIndex))
else begin
FStream.Seek(FSSTPos,soFromBeginning);
FStream.ReadHeader(FHeader);
FSST.Read(FStream,FHeader.Length,False);
FVSetString(FValue,FSST.ItemsByIndex[PRecLABELSST(PBuf).SSTIndex]);
end;
Result := True;
end;
BIFFRECID_MULRK:
begin
if (Col >= PRecMULRK(PBuf).Col1) and (Col <= (PRecMULRK(PBuf).Col1 + ((FHeader.Length - 6) div 6 - 1))) and (Row = PRecMULRK(PBuf).Row) then begin
FVSetFloat(FValue,DecodeRK(PRecMULRK(PBuf).RKs[Col - PRecMULRK(PBuf).Col1].Value));
Result := True;
end;
end;
BIFFRECID_NUMBER:
if (PRecNUMBER(PBuf).Col = Col) and (PRecNUMBER(PBuf).Row = Row) then begin
FVSetFloat(FValue,PRecNUMBER(PBuf).Value);
Result := True;
end;
BIFFRECID_RK,$027E:
if (PRecRK(PBuf).Col = Col) and (PRecRK(PBuf).Row = Row) then begin
FVSetFloat(FValue,DecodeRK(PRecRK(PBuf).Value));
Result := True;
end;
BIFFRECID_RSTRING:
if (PRecRSTRING(PBuf).Col = Col) and (PRecRSTRING(PBuf).Row = Row) then begin
FVSetString(FValue,ByteStrToWideString(@PRecRSTRING(PBuf).Data,PRecRSTRING(PBuf).Len));
Result := True;
end;
BIFFRECID_FORMULA:
if (PRecFORMULA(PBuf).Col = Col) and (PRecFORMULA(PBuf).Row = Row) then begin
if (TByte8Array(PRecFORMULA(PBuf).Value)[6] = $FF) and (TByte8Array(PRecFORMULA(PBuf).Value)[7] = $FF) then
FVSetString(FValue,GetFormulaStr(PRecFORMULA(PBuf).Value))
else
FVSetFloat(FValue,PRecFORMULA(PBuf).Value);
Result := True;
end;
$0206,$0406:
if (PRecFORMULA3(PBuf).Col = Col) and (PRecFORMULA3(PBuf).Row = Row) then begin
if (TByte8Array(PRecFORMULA3(PBuf).Value)[6] = $FF) and (TByte8Array(PRecFORMULA3(PBuf).Value)[7] = $FF) then
FVSetString(FValue,GetFormulaStr(PRecFORMULA3(PBuf).Value))
else
FVSetFloat(FValue,PRecFORMULA3(PBuf).Value);
Result := True;
end;
end;
end;
function TExternalSeek.Seek(SheetIndex,Col,Row: integer): boolean;
type
TIntArray = array[0..High(integer) div 4 - 1] of integer;
PIntArray = ^TIntArray;
TSmallIntArray = array[0..High(smallint) div 2 - 1] of smallint;
PSmallIntArray = ^TSmallIntArray;
var
Pos,DbCellPos,Offs: integer;
R1,R2,DBCellCount,RowCount: integer;
DbCellOffsets: PIntArray;
CellOffsets: PSmallIntArray;
function NoneIndexSearch: boolean;
begin
Result := False;
while True do begin
Pos := FStream.ReadHeader(FHeader);
if (FHeader.RecID = BIFFRECID_EOF) or (Pos <= 0) then
Exit;
if (FHeader.RecID = BIFFRECID_LABEL) or
(FHeader.RecID = BIFFRECID_LABELSST) or
(FHeader.RecID = BIFFRECID_MULRK) or
(FHeader.RecID = BIFFRECID_NUMBER) or
(FHeader.RecID = BIFFRECID_RK) or (FHeader.RecID = $027E) or
(FHeader.RecID = BIFFRECID_RSTRING) or
(FHeader.RecID = BIFFRECID_FORMULA) or (FHeader.RecID = $0206) or (FHeader.RecID = $0406) then begin
FStream.Read(PBuf^,FHeader.Length);
Result := CheckCell(Col,Row);
if Result then
Exit;
end
else
FStream.Seek(FHeader.Length,soFromCurrent);
end;
end;
function OleSearch: boolean;
var
i,j: integer;
begin
FSSTPos := -1;
FExtSSTPos := -1;
Result := False;
j := 0;
while True do begin
Pos := FStream.ReadHeader(FHeader);
if Pos <= 0 then
Exit;
if (FHeader.RecID = BIFFRECID_BOUNDSHEET) and (SheetIndex >= 0) then begin
Dec(SheetIndex);
if SheetIndex < 0 then begin
FStream.Read(PBuf^,FHeader.Length);
if FVersion < xvExcel97 then with PRecBOUNDSHEET7(PBuf)^ do
j := BOFPos
else with PRecBOUNDSHEET8(PBuf)^ do
j := BOFPos;
// ???
if (FVersion < xvExcel97) {or (FSST <> Nil)} then
Break;
end
else
FStream.Seek(FHeader.Length,soFromCurrent);
end
else if FHeader.RecID = BIFFRECID_SST then begin
FSSTPos := FStream.Pos - SizeOf(TBIFFHeader);
FStream.Seek(FHeader.Length,soFromCurrent);
end
else if FHeader.RecID = BIFFRECID_EXTSST then begin
FExtSSTPos := FStream.Pos - SizeOf(TBIFFHeader);
FStream.Seek(FHeader.Length,soFromCurrent);
end
else if FHeader.RecID = BIFFRECID_EOF then
Break
else
FStream.Seek(FHeader.Length,soFromCurrent);
end;
if SheetIndex >= 0 then
raise Exception.Create('Can not find the sheet');
FStream.Seek(j,soFromBeginning);
FStream.Read(FHeader,SizeOf(TBIFFHeader));
if (FHeader.RecID and $FF) <> BIFFRECID_BOF then
raise Exception.Create('File has no data');
FStream.Seek(FHeader.Length,soFromCurrent);
FStream.Read(FHeader,SizeOf(TBIFFHeader));
FStream.Read(PBuf^,FHeader.Length);
if FHeader.RecID <> BIFFRECID_INDEX then begin
Result := NoneIndexSearch;
Exit;
end;
if FVersion < xvExcel97 then with PRecINDEX7(PBuf)^ do begin
R1 := Row1;
R2 := Row2 - 1;
DBCellCount := (FHeader.Length - (Integer(@PRecINDEX7(PBuf).Offsets[0]) - Integer(PBuf))) div 4;
end
else with PRecINDEX8(PBuf)^ do begin
R1 := Row1;
R2 := Row2 - 1;
DBCellCount := (FHeader.Length - (Integer(@PRecINDEX8(PBuf).Offsets[0]) - Integer(PBuf))) div 4;
end;
if (Row >= R1) and (Row <= R2) then begin
GetMem(DbCellOffsets,DBCellCount * 4);
try
if FVersion < xvExcel97 then
Move(PRecINDEX7(PBuf).Offsets[0],DbCellOffsets^,DBCellCount * 4)
else
Move(PRecINDEX8(PBuf).Offsets[0],DbCellOffsets^,DBCellCount * 4);
for i := 0 to DBCellCount - 1 do begin
FStream.Seek(DbCellOffsets[i],soFromBeginning);
FStream.Read(FHeader,SizeOf(TBIFFHeader));
if FHeader.RecID <> BIFFRECID_DBCELL then
raise Exception.Create('DBCELL record is missing');
FStream.Read(PBuf^,FHeader.Length);
RowCount := (FHeader.Length - 4) div 2;
GetMem(CellOffsets,RowCount * 2);
Move(PRecDBCELL(PBuf).Offsets[0],CellOffsets^,RowCount * 2);
try
Offs := 0;
DbCellPos := FStream.Seek(0,soFromCurrent);
DbCellPos := DbCellPos - (FHeader.Length + 4);
FStream.Seek(DbCellPos - PRecDBCELL(PBuf).RowOffset,soFromBeginning);
for j := 0 to RowCount - 1 do begin
FStream.Read(FHeader,SizeOf(TBIFFHeader));
if FHeader.RecID <> BIFFRECID_ROW then
raise Exception.Create('ROW record is missing');
FStream.Read(PBuf^,FHeader.Length);
if Offs <= 0 then
Offs := FStream.Pos;
Offs := Offs + CellOffsets[j];
if (PRecROW(PBuf).Row = Row) and (Col >= PRecROW(PBuf).Col1) and (Col <= (PRecROW(PBuf).Col2 - 1)) then begin
FStream.Seek(Offs,soFromBeginning);
repeat
FStream.Read(FHeader,SizeOf(TBIFFHeader));
Pos := FStream.Read(PBuf^,FHeader.Length);
if CheckCell(Col,Row) then begin
Result := True;
Exit;
end;
until ((FHeader.RecID in [BIFFRECID_DBCELL,BIFFRECID_EOF]) or (Pos <= 0));
Exit;
end;
end;
finally
FreeMem(CellOffsets);
end;
end;
finally
FreeMem(DbCellOffsets);
end;
end;
end;
function FileSearch: boolean;
var
i: integer;
begin
Result := False;
PBuf := AllocMem(MAXRECSZ_97);
try
i := 0;
repeat
FStream.Read(FHeader,SizeOf(TBIFFHeader));
FStream.Read(PBuf^,FHeader.Length);
Inc(i);
until ((FHeader.RecID = BIFFRECID_INDEX) or (i > 10));
if i > 0 then begin
Result := NoneIndexSearch;
Exit;
end;
if FVersion < xvExcel97 then with PRecINDEX7(PBuf)^ do begin
R1 := Row1;
R2 := Row2 - 1;
DBCellCount := (FHeader.Length - (Integer(@PRecINDEX7(PBuf).Offsets[0]) - Integer(PBuf))) div 4;
end
else with PRecINDEX8(PBuf)^ do begin
R1 := Row1;
R2 := Row2 - 1;
DBCellCount := (FHeader.Length - (Integer(@PRecINDEX8(PBuf).Offsets[0]) - Integer(PBuf))) div 4;
end;
// ATTN: I am not sure this is the moste efficiant way to search.
// There seem to be no DBCELL records (or anyhing similar).
// I have no ducumentation on records prior to Excel 5.
if (Row >= R1) and (Row <= R2) then begin
GetMem(DbCellOffsets,DBCellCount * 4);
try
if FVersion < xvExcel97 then
Move(PRecINDEX7(PBuf).Offsets[0],DbCellOffsets^,DBCellCount * 4)
else
Move(PRecINDEX8(PBuf).Offsets[0],DbCellOffsets^,DBCellCount * 4);
for i := 0 to DBCellCount - 1 do begin
FStream.Seek(DbCellOffsets[i],soFromBeginning);
repeat
FStream.Read(FHeader,SizeOf(TBIFFHeader));
FStream.Read(PBuf^,FHeader.Length);
if FHeader.RecID = BIFFRECID_ROW then begin
if (PRecROW(PBuf).Row = Row) and (Col >= PRecROW(PBuf).Col1) and (Col <= (PRecROW(PBuf).Col2 - 1)) then begin
repeat
FStream.Read(FHeader,SizeOf(TBIFFHeader));
FStream.Seek(FHeader.Length,soFromCurrent);
until (FHeader.RecID <> BIFFRECID_ROW);
repeat
FStream.Read(FHeader,SizeOf(TBIFFHeader));
Pos := FStream.Read(PBuf^,FHeader.Length);
if CheckCell(Col,Row) then begin
Result := True;
Exit;
end;
until ((FHeader.RecID in [BIFFRECID_DBCELL,BIFFRECID_EOF]) or (Pos <= 0));
Exit;
end;
end;
until (FHeader.RecID <> BIFFRECID_ROW);
end;
finally
FreeMem(DbCellOffsets);
end;
end;
finally
FreeMem(PBuf);
end;
end;
begin
FStream := TXLSStream.Create(Nil);
try
FVersion := FStream.OpenStorageRead(FFilename);
GetMem(PBuf,MAXRECSZ_97);
try
if FVersion < xvExcel50 then
Result := FileSearch
else
Result := OleSearch;
finally
FreeMem(PBuf);
FSST.Clear;
end
finally
FStream.CloseStorage;
end;
end;
destructor TExternalSeek.Destroy;
begin
FSST.Free;
inherited;
end;
end.
|
unit uNalogReestr;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,uNalogReestrDM, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxClasses,
cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, ExtCtrls,IBase, StdCtrls, Buttons, frxDesgn,
frxClass, frxDBSet,ZMessages, frxExportXLS, ZProc;
type
TNalogReestrForm = class(TForm)
ToolPanel: TPanel;
MainGridDBTableView1: TcxGridDBTableView;
MainGridLevel1: TcxGridLevel;
MainGrid: TcxGrid;
MainGridDBTableView1DATE_REG: TcxGridDBColumn;
MainGridDBTableView1YEAR_SET: TcxGridDBColumn;
MainGridDBTableView1COUNT: TcxGridDBColumn;
ShowReportBtn: TBitBtn;
GroupBtn: TBitBtn;
ExitBtn: TBitBtn;
ReportDataSet: TfrxDBDataset;
Designer: TfrxDesigner;
Report: TfrxReport;
DeleteBtn: TBitBtn;
frxXLSExport1: TfrxXLSExport;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ShowReportBtnClick(Sender: TObject);
procedure ExitBtnClick(Sender: TObject);
procedure GroupBtnClick(Sender: TObject);
procedure DeleteBtnClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function ShowNalogReCountReestr(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE):
Variant;stdcall;
exports ShowNalogReCountReestr;
var
NalogReestrForm: TNalogReestrForm;
implementation
{$R *.dfm}
function ShowNalogReCountReestr(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE):Variant;
var
form:TNalogReestrForm;
begin
NalogReestrDM:=TNalogReestrDM.Create(AOwner);
NalogReestrDM.MainDatabase.Handle:=DB_HANDLE;
NalogReestrDM.MainDatabase.Connected:=True;
form:=TNalogReestrForm.Create(AOWner);
NalogReestrDM.ReestrDataSet.CloseOpen(True);
form.Show;
Result:=null;
end;
procedure TNalogReestrForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
NalogReestrDM.Free;
Action:=caFree;
end;
procedure TNalogReestrForm.ShowReportBtnClick(Sender: TObject);
begin
NalogReestrDM.PrintDataSet.ParamByName('ID_REESTR').Value:=
NalogReestrDM.ReestrDataSet['ID_REESTR'];
NalogReestrDM.PrintDataSet.CloseOpen(True);
Report.LoadFromFile('Reports\Zarplata\NalogReestrList.fr3');
Report.Variables['YEAR_SET']:=
QuotedStr(IntToStr(NalogReestrDM.ReestrDataSet['YEAR_SET']));
Report.Variables['DATE_VIDAN']:=
QuotedStr(DateToStr(NalogReestrDM.ReestrDataSet['DATE_REG']));
if zDesignReport then Report.DesignReport
else Report.ShowReport;
end;
procedure TNalogReestrForm.ExitBtnClick(Sender: TObject);
begin
Close;
end;
procedure TNalogReestrForm.GroupBtnClick(Sender: TObject);
begin
with NalogReestrDM do
begin
WriteTransaction.StartTransaction;
FillCurrentProc.ParamByName('ID_REESTR').Value:=ReestrDataSet['ID_REESTR'];
try
FillCurrentProc.ExecProc;
WriteTransaction.Commit;
except on E:Exception
do
begin
ShowMessage(E.Message);
WriteTransaction.Rollback;
end;
end;
end;
ShowMessage('Дані додані до поточних операцій!');
end;
procedure TNalogReestrForm.DeleteBtnClick(Sender: TObject);
begin
if (ZShowMessage('Вилучити',
'Ви справді бажаєете вилучити цей реєстр?',
mtConfirmation,[mbOk,MbCancel])=mrOk) then
begin
NalogReestrDm.DeleteReestrSP.ParamByName('ID_REESTR').Value:=
NalogReestrDM.ReestrDataSet['ID_REESTR'];
NalogReestrDm.WriteTransaction.StartTransaction;
try
NalogReestrDm.DeleteReestrSP.ExecProc;
NalogReestrDM.WriteTransaction.Commit;
except on E:Exception
do
begin
ZShowMessage('Помилка!',E.Message,mtError,[mbOk]);
NalogReestrDM.WriteTransaction.Rollback;
end;
end;
NalogReestrDm.ReestrDataSet.CloseOpen(True);
end;
end;
end.
|
unit Shredder;
// Description: File/Disk Free Space Shredder (overwriter)
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
SDUGeneral, SDUProgressDlg,
FileList_U,
SDUClasses;
type
TShredDetails = array [0..2] of byte;
TShredBlock = array of byte;
TShredFreeSpaceBlock = array of byte;
TShredFreeSpaceBlockObj = class
public
BLANK_FREESPACE_BLOCK: TShredFreeSpaceBlock;
end;
TShredResult = (
srSuccess = 1,
srError = -1,
srUserCancel = -2
);
TShredMethod = (
smZeros,
smOnes,
smPseudorandom,
smRCMP,
smUSDOD_E,
smUSDOD_ECE,
smGutmann
);
resourcestring
SHREDMETHOD_ZEROS = 'Zeros';
SHREDMETHOD_ONES = 'Ones';
SHREDMETHOD_PSEUDORANDOM_DATA = 'Pseudorandom data';
SHREDMETHOD_RCMP = 'RCMP (DSX)';
SHREDMETHOD_DOD_E = 'US DoD 5220.22-M (E)';
SHREDMETHOD_DOD_ECE = 'US DoD 5220.22-M (ECE)';
SHREDMETHOD_GUTMANN = 'Gutmann (35 pass)';
const
TShredMethodTitle: array [TShredMethod] of Pointer = (
@SHREDMETHOD_ZEROS,
@SHREDMETHOD_ONES,
@SHREDMETHOD_PSEUDORANDOM_DATA,
@SHREDMETHOD_RCMP,
@SHREDMETHOD_DOD_E,
@SHREDMETHOD_DOD_ECE,
@SHREDMETHOD_GUTMANN
);
// Number of each passes for each type.
// -ve number indicates user specified ("IntPasses" property)
TShredMethodPasses: array [TShredMethod] of integer = (
-1,
-1,
-1,
3,
3,
7,
35
);
type
// The array passed in is zero-indexed; populate elements zero to "bytesRequired"
TGenerateOverwriteDataEvent = procedure (Sender: TObject; passNumber: integer; bytesRequired: cardinal; var generatedOK: boolean; var outputBlock: TShredBlock) of object;
TNotifyStartingFileOverwritePass = procedure (Sender: TObject; itemName: string; passNumber: integer; totalPasses: integer) of object;
TCheckForUserCancel = procedure (Sender: TObject; var userCancelled: boolean) of object;
TShredder = class(TComponent)
private
FFileDirUseInt: boolean;
FFreeUseInt: boolean;
FExtFileExe: AnsiString;
FExtDirExe: AnsiString;
FExtFreeSpaceExe: AnsiString;
FExtShredFilesThenDir: boolean;
FIntSegmentOffset: ULONGLONG;
FIntSegmentLength: ULONGLONG;
FIntMethod: TShredMethod;
FIntPasses: integer;
FIntFreeSpcFileSize: integer;
FIntFreeSpcSmartFileSize: boolean;
FIntFreeSpcFileCreationBlkSize: integer;
FIntFileBufferSize: integer;
FOnOverwriteDataReq: TGenerateOverwriteDataEvent;
FOnStartingFileOverwritePass: TNotifyStartingFileOverwritePass;
FOnCheckForUserCancel: TCheckForUserCancel;
FLastIntShredResult: TShredResult;
function ShredDir(dirname: string; silent: boolean): TShredResult;
function InternalShredFile(
filename : string;
quickShred: boolean;
silent: boolean;
silentProgressDlg: TSDUProgressDialog;
leaveFile: boolean = FALSE
): TShredResult;
function DeleteFileOrDir(itemname: string): TShredResult;
function BytesPerCluster(filename: string): DWORD;
function GetRandomDataBlock(passNum: integer; var outputBlock: TShredBlock): boolean;
procedure GetBlockZeros(var outputBlock: TShredBlock);
procedure GetBlockOnes(var outputBlock: TShredBlock);
procedure GetBlockPRNG(var outputBlock: TShredBlock);
procedure GetBlockRCMP(passNum: integer; var outputBlock: TShredBlock);
procedure GetBlockDOD(passNum: integer; var outputBlock: TShredBlock);
procedure GetBlockGutmann(passNum: integer; var outputBlock: TShredBlock);
function GetGutmannChars(passNum: integer): TShredDetails;
function SetGutmannDetails(nOne: integer; nTwo: integer; nThree: integer): TShredDetails;
function CreateEmptyFile(filename: string; size: int64; blankArray: TShredFreeSpaceBlockObj; progressDlg: TSDUProgressDialog): TShredResult;
function GetTempFilename(driveDir: string; serialNo: integer): string;
function WipeFileSlacksInDir(dirName: string; progressDlg: TSDUProgressDialog; problemFiles: TStringList): TShredResult;
function CountFiles(dirName: string): integer;
function GenerateRndDotFilename(path: string; origFilename: string): string;
protected
function IsDevice(filename: string): boolean;
function DeviceDrive(filename: string): char;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
// Call this to shred all free space on the specified drive
// Note: Does *not* wipe file slack - OverwriteAllFileSlacks(...) should be
// called before this function, if needed
function OverwriteDriveFreeSpace(driveLetter: DriveLetterChar; silent: boolean = FALSE): TShredResult;
// Call this to a specific file's slack space
function OverwriteFileSlack(filename: string): boolean;
// Call this to wipe all file slack on the specified drive
function OverwriteAllFileSlacks(driveLetter: Ansichar; silent: boolean = FALSE): TShredResult;
// You probably don't want to call this one - call
// OverwriteDriveFreeSpace(...) instead
function DestroyDevice(itemname: string; quickShred: boolean; silent: boolean = FALSE): TShredResult;
// Destroy the specified file or directory
// Note that, with the internal shredder at any rate, calling WipeFileSlack
// is not needed before calling this procedure
function DestroyFileOrDir(itemname: string; quickShred: boolean; silent: boolean = FALSE; leaveFile: boolean = FALSE): TShredResult;
// Destroy the specified registry key
procedure DestroyRegKey(key: string);
published
// Set this to TRUE to use the internal shredder when shredding
// files/directories. Set to FALSE to use a 3rd party executable
property FileDirUseInt: boolean read FFileDirUseInt write FFileDirUseInt default TRUE;
// Set this to TRUE to use the internal shredder when shredding
// free space. Set to FALSE to use a 3rd party executable
property FreeUseInt: boolean read FFreeUseInt write FFreeUseInt default TRUE;
// Command to be used when using a 3rd party executable to shred files
property ExtFileExe: Ansistring read FExtFileExe write FExtFileExe;
// Command to be used when using a 3rd party executable to shred directories
property ExtDirExe: Ansistring read FExtDirExe write FExtDirExe;
// Command to be used when using a 3rd party executable to free space
property ExtFreeSpaceExe: Ansistring read FExtFreeSpaceExe write FExtFreeSpaceExe;
// When shredding directories, and using a 3rd party executable to do so,
// if all the files and subdirs within the directory to be destroyed must
// be destroyed before the directory, this must be set to TRUE.
property ExtShredFilesThenDir: boolean read FExtShredFilesThenDir write FExtShredFilesThenDir default FALSE;
// If "quickShred" is set to TRUE on any of the Destroy...(...) calls,
// then only the FIntSegmentLength bytes of files, starting from offset
// FIntSegmentOffset will be overwritten before they are deleted
property IntSegmentOffset: ULONGLONG read FIntSegmentOffset write FIntSegmentOffset default 0;
property IntSegmentLength: ULONGLONG read FIntSegmentLength write FIntSegmentLength default BYTES_IN_MEGABYTE; // 1MB
// Method of shredding to be used.
// Note: If OnOverwriteDataReq is set, this is ignored (user specified
// block generator)
property IntMethod: TShredMethod read FIntMethod write FIntMethod default smPseudorandom;
// If IntMethod refers to an overwrite method with a user specified number
// of passes, this should be set to the required number of passes
property IntPasses: integer read FIntPasses write FIntPasses default 1;
// If this parameter is set, this event will be called to populate the
// buffer with pseudorandom data before writing.
// IntMethod will be IGNORED if this is set
// IF SET, THE METHOD THAT THIS IS SET TO MUST POPULATE THE BUFFER IT IS
// SUPPLIED WITH
property OnOverwriteDataReq: TGenerateOverwriteDataEvent read FOnOverwriteDataReq write FOnOverwriteDataReq default nil;
// If this parameter is set, this event will be called whenever a file is
// being overwritten, and it's starting a new pass
property OnStartingFileOverwritePass: TNotifyStartingFileOverwritePass read FOnStartingFileOverwritePass write FOnStartingFileOverwritePass default nil;
// If this parameter is set, this event will be called regularly to see if
// the use has cancelled via some event method
property OnCheckForUserCancel: TCheckForUserCancel read FOnCheckForUserCancel write FOnCheckForUserCancel default nil;
// When shredding free space on a drive, the temp files that are created
// and then overwritten should be of this size
property IntFreeSpcFileSize: integer read FIntFreeSpcFileSize write FIntFreeSpcFileSize default (50 * BYTES_IN_MEGABYTE); // 50MB
// (Used in conjunction with IntFreeSpcFileSize)
// If this is TRUE, then:
// f10 := The amount of free space is computed, and divided by 10
// fmax := max(5MB, f10)
// If fmax is less than IntFreeSpcFileSize, then fmax will be used
// If fmax is more than IntFreeSpcFileSize, then IntFreeSpcFileSize
// will be used
// This means that if progress is being shown to the user, they'll always
// get at least 10 "blocks" on the progress bar, making the application
// appear more responsive; to actually be doing something
property IntFreeSpcSmartFileSize: boolean read FIntFreeSpcSmartFileSize write FIntFreeSpcSmartFileSize default TRUE;
// When shredding free space on a drive, the temp files that are created
// are made by repeatedly writing this blocksize amount of data until the
// file reaches FIntFreeSpcFileSize, or the write fails (at which point,
// the temp files are overwritten using the normal IntFileBufferSize as
// with overwriting any other file)
property IntFreeSpcFileCreationBlkSize: integer read FIntFreeSpcFileCreationBlkSize write FIntFreeSpcFileCreationBlkSize default BYTES_IN_MEGABYTE; // 1MB
// When shredding files, blocks of data which are of this buffer length are
// written to the file to be destroyed until the whole file is overwritten
property IntFileBufferSize: integer read FIntFileBufferSize write FIntFileBufferSize default BYTES_IN_MEGABYTE; // 1MB
property LastIntShredResult: TShredResult read FLastIntShredResult write FLastIntShredResult;
end;
function ShredMethodTitle(shredMethod: TShredMethod): string;
procedure Overwrite(var x: AnsiString); overload;
procedure Overwrite(var x: TStream); overload;
// Not clear why this next one is needed; descends from TStream, but Delphi
// can't match it when this when a TSDUMemoryStream is passed to the TStream
// version...
procedure Overwrite(var x: TSDUMemoryStream); overload;
procedure Overwrite(var x: TStringList); overload;
procedure OverwriteAndFree(var x: TStream); overload;
// Not clear why this next one is needed; descends from TStream, but Delphi
// can't match it when this when a TSDUMemoryStream is passed to the TStream
// version...
procedure OverwriteAndFree(var x: TSDUMemoryStream); overload;
procedure OverwriteAndFree(var x: TStringList); overload;
procedure Register;
implementation
uses
Math,
SDUi18n,
SDUFileIterator_U, SDUDirIterator_U,
lcDialogs,
Registry;
type
// Exceptions... These should *all* be handled internally
EShredderError = Exception;
EShredderErrorUserCancel = EShredderError;
const
OVERWRITE_FREESPACE_TMP_DIR = '~STUfree';
resourcestring
USER_CANCELLED = 'User cancelled';
procedure Register;
begin
RegisterComponents('SDeanSecurity', [TShredder]);
end;
function ShredMethodTitle(shredMethod: TShredMethod): string;
begin
Result := LoadResString(TShredMethodTitle[shredMethod]);
end;
procedure Overwrite(var x: AnsiString);
begin
x := StringOfChar(Ansichar(#0), length(x));
end;
procedure Overwrite(var x: TStream);
var
i: integer;
tmpByte: byte;
begin
if (x <> nil) then
begin
x.Position := 0;
for i:=0 to (x.Size - 1) do
begin
tmpByte := random(256);
x.Write(tmpByte, sizeof(tmpByte));
end;
end;
end;
procedure Overwrite(var x: TSDUMemoryStream);
var
i: integer;
tmpByte: byte;
begin
if (x <> nil) then
begin
x.Position := 0;
for i:=0 to (x.Size - 1) do
begin
tmpByte := random(256);
x.Write(tmpByte, sizeof(tmpByte));
end;
end;
end;
procedure Overwrite(var x: TStringList);
var
i: integer;
begin
if (x <> nil) then
begin
for i:=0 to (x.count - 1) do
begin
x[i] := StringOfChar(#0, length(x[i]));
end;
end;
end;
procedure OverwriteAndFree(var x: TSDUMemoryStream);
begin
if (x <> nil) then
begin
Overwrite(x);
x.Free();
x := nil;
end;
end;
procedure OverwriteAndFree(var x: TStream);
begin
if (x <> nil) then
begin
Overwrite(x);
x.Free();
x := nil;
end;
end;
procedure OverwriteAndFree(var x: TStringList);
begin
if (x <> nil) then
begin
Overwrite(x);
x.Free();
x := nil;
end;
end;
constructor TShredder.Create(AOwner: TComponent);
begin
inherited;
FFileDirUseInt:= TRUE;
FFreeUseInt:= TRUE;
FExtFileExe:= '';
FExtDirExe:= '';
FExtFreeSpaceExe:= '';
FExtShredFilesThenDir:= FALSE;
FIntSegmentOffset:= 0;
FIntSegmentLength:= BYTES_IN_MEGABYTE; // First MB by default
FIntMethod:= smPseudorandom;
FIntPasses:= 1;
FIntFreeSpcFileSize:= (50 * BYTES_IN_MEGABYTE); // 50MB by default
FIntFreeSpcSmartFileSize:= TRUE;
FIntFreeSpcFileCreationBlkSize:= BYTES_IN_MEGABYTE; // 1MB by default
FIntFileBufferSize:= BYTES_IN_MEGABYTE; // 1MB by default
end;
destructor TShredder.Destroy();
begin
inherited;
end;
// Returns #0 on failure
function TShredder.DeviceDrive(filename: string): char;
var
retval: char;
begin
retval := #0;
if IsDevice(filename) then
begin
retval := filename[5];
end;
Result := retval;
end;
function TShredder.IsDevice(filename: string): boolean;
begin
Result := (Pos('\\.\', filename) > 0);
end;
// Destroy a given drive.
// !!! WARNING !!!!
// This will overwrite the ENTIRE DRIVE
// !USE WITH EXTREME CAUTION!
// You probably want to call OverwriteDriveFreeSpace(...) - NOT THIS!
// itemname - The drive to be destroyed e.g. "\\.\Z:"
// quickShred - ignored if not using internal shredding, otherwise if set to
// FALSE then delete whole file; setting it to TRUE will only
// delete the first n bytes
// Note: Use LastIntShredResult to determine if user cancelled, or there was a
// failure in the shredding
function TShredder.DestroyDevice(itemname: string; quickShred: boolean; silent: boolean = FALSE): TShredResult;
begin
result := srError;
if IsDevice(itemname) then
begin
result := InternalShredFile(itemname, quickShred, silent, nil, TRUE);
end;
end;
// Destroy a given file/dir, using the method specified in the INI file
// NOTE: When destroying dirs, QUICKSHRED IS ALWAYS FALSE - set in the dir
// shredding procedure
// itemname - The file/dir to be destroyed
// quickShred - Ignored if not using internal shredding, otherwise if set to
// FALSE then delete whole file; setting it to TRUE will only
// delete the first n bytes
// leaveFile - Ignored if not using internal shredding AND "itemname" refers to
// a file (NOT dir - not yet implemented with this). Set to TRUE to
// prevent the final deletion of the file. FALSE to go ahead with
// the final delete
function TShredder.DestroyFileOrDir(itemname: string; quickShred: boolean; silent: boolean = FALSE; leaveFile: boolean = FALSE): TShredResult;
var
{$IFDEF MSWINDOWS}
fileAttributes : integer;
{$ENDIF}
shredderCommandLine : AnsiString;
retval: TShredResult;
begin
// Remove any hidden, system or readonly file attrib
{$IFDEF MSWINDOWS}
{$WARNINGS OFF} // Useless warning about platform - we're already protecting
// against that!
fileAttributes := FileGetAttr(itemname);
fileAttributes := fileAttributes AND not(faReadOnly);
fileAttributes := fileAttributes AND not(faHidden);
fileAttributes := fileAttributes AND not(faSysFile);
FileSetAttr(itemname, fileAttributes);
{$WARNINGS ON}
{$ENDIF}
{$IFDEF LINUX}
xxx - to be implemented: remove any readonly attribute from the file
{$ENDIF}
if (fileAttributes AND faDirectory)<>0 then
begin
retval := ShredDir(itemname, silent);
end
else
begin
itemname := SDUConvertLFNToSFN(itemname);
if FFileDirUseInt then
begin
retval := InternalShredFile(itemname, quickShred, silent, nil, leaveFile);
end
else
begin
shredderCommandLine := format(FExtFileExe, [itemname]); { TODO 1 -otdk -cinvestigate : what happens if unicode filename? }
WinExec(PAnsiChar(shredderCommandLine), SW_MINIMIZE);
// Assume success
retval := srSuccess;
end;
end;
Result := retval;
end;
// Attempt to get the number of bytes/cluster on the drive the specified file is
// stored on
// Returns: The number of bytes per sector; or "1" if this cannot be
// determined (e.g. the filename is a UNC)
function TShredder.BytesPerCluster(filename: string): DWORD;
var
driveColon: string;
retVal: DWORD;
dwSectorsPerCluster: DWORD;
dwBytesPerSector: DWORD;
dwNumberOfFreeClusters: DWORD;
dwTotalNumberOfClusters: DWORD;
begin
// Attempt to get the number of bytes/sector
retVal := 1;
if (
(Pos(':\', filename) = 2) or
(Pos(':/', filename) = 2)
) then
begin
driveColon := filename[1]+':\';
if GetDiskFreeSpace(
PChar(driveColon), // address of root path
dwSectorsPerCluster, // address of sectors per cluster
dwBytesPerSector, // address of bytes per sector
dwNumberOfFreeClusters, // address of number of free clusters
dwTotalNumberOfClusters // address of total number of clusters
) then
begin
retVal := (dwBytesPerSector * dwSectorsPerCluster);
end;
end;
Result := retVal;
end;
// leaveFile - Set to TRUE to just leave the file after shredding; don't
// delete it (default = FALSE). (Used when shredding files created
// during drive freespace overwriting; the files must remain)
// silentProgressDlg - If silent is set to TRUE, then this may *optionally* be
// set to a progress dialog. This progress dialog will
// *only* be used for checking to see if the user's
// cancelled the operation
// Returns: TShredResult
function TShredder.InternalShredFile(
filename: string;
quickShred: boolean;
silent: boolean;
silentProgressDlg: TSDUProgressDialog;
leaveFile: boolean = FALSE
): TShredResult;
var
fileHandle : THandle;
i: integer;
blankingBytes: TShredBlock;
bytesToShredLo: DWORD;
bytesToShredHi: DWORD;
bytesWritten: DWORD;
numPasses: integer;
progressDlg: TSDUProgressDialog;
bpc: DWORD;
bpcMod: DWORD;
tmpDWORD: DWORD;
bytesLeftToWrite: int64;
failure: boolean;
userCancel: boolean;
retVal: TShredResult;
bytesToWriteNow: DWORD;
gotSize: boolean;
drive: char;
partInfo: TSDUPartitionInfo;
tmpUint64: ULONGLONG;
useShredMethodTitle: string;
tmpInt64: int64;
eventUserCancel: boolean;
startOffsetLo: DWORD;
startOffsetHi: DWORD;
begin
failure := FALSE;
userCancel := FALSE;
eventUserCancel := FALSE;
bpc:= BytesPerCluster(filename);
// Determine number of passes...
numPasses := TShredMethodPasses[IntMethod];
if (numPasses < 0) then
begin
numPasses := FIntPasses;
end;
progressDlg:= TSDUProgressDialog.create(nil);
try
progressDlg.ShowTimeRemaining := TRUE;
try // Exception handler for EShredderErrorUserCancel
if not(silent) then
begin
progressDlg.Show();
end;
// Nuke any file attributes (e.g. readonly)
{$IFDEF MSWINDOWS}
{$WARN SYMBOL_PLATFORM OFF} // Useless warning about platform - we're already
// protecting against that!
FileSetAttr(filename, 0);
{$WARN SYMBOL_PLATFORM ON}
{$ENDIF}
{$IFDEF LINUX}
xxx - to be implemented: strip off any readonly attribute from the file
{$ENDIF}
gotSize := FALSE;
bytesToShredHi := 0;
bytesToShredLo := 0;
if IsDevice(filename) then
begin
drive := DeviceDrive(filename);
gotSize := SDUGetPartitionInfo(drive, partInfo);
if gotSize then
begin
tmpUint64 := (partInfo.PartitionLength shr 32);
bytesToShredHi := tmpUint64 and $00000000FFFFFFFF;
bytesToShredLo := partInfo.PartitionLength and $00000000FFFFFFFF;
end;
end;
fileHandle := CreateFile(PChar(filename),
GENERIC_READ or GENERIC_WRITE,
0,
nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL or FILE_FLAG_WRITE_THROUGH,
0);
if (fileHandle = INVALID_HANDLE_VALUE) then
begin
failure := TRUE;
end
else
begin
try
// Identify the size of the file being overwritten...
if not(IsDevice(filename)) then
begin
bytesToShredLo := GetFileSize(fileHandle, @bytesToShredHi);
gotSize := not( (bytesToShredLo = $FFFFFFFF) AND (GetLastError()<>NO_ERROR) );
end;
// Check that the GetFileSize call was successful...
if gotSize then
begin
// Adjust to increase up to the nearest bytes per sector boundry
// Note: This makes the reasonable assumption that ($FFFFFFFF + 1)
// will always be a multiple of "bpc"; so we don't need to
// bother involving the high DWORD of the file's size in this
// calculation
bpcMod := (bytesToShredLo mod bpc);
if (bpcMod>0) then
begin
tmpDWORD := bytesToShredLo + (bpc - bpcMod);
// In case that causes an overflow...
if (bytesToShredLo > tmpDWORD) then
begin
inc(bytesToShredHi);
end;
bytesToShredLo := tmpDWORD;
end;
// Sanity check - we can only handle files less than 2^63 bytes long
// tmpInt64 used to prevent Delphi effectivly casting to DWORD
tmpInt64 := bytesToShredHi;
bytesLeftToWrite := (tmpInt64 shl 32) + bytesToShredLo;
if (bytesLeftToWrite < 0) then
begin
// Do nothing - retVal defaults to error
end
else
begin
startOffsetLo := 0;
startOffsetHi := 0;
if quickShred then
begin
startOffsetLo := (IntSegmentOffset AND $FFFFFFFF);
startOffsetHi := (IntSegmentOffset shr 32);
bytesLeftToWrite := bytesLeftToWrite - IntSegmentOffset;
// Note: Cast to int64 to ensure that no problems with truncation
bytesLeftToWrite := min(bytesLeftToWrite, int64(IntSegmentLength));
bytesToShredHi := (bytesLeftToWrite shr 32);
bytesToShredLo := (bytesLeftToWrite AND $FFFFFFFF);
end;
progressDlg.i64Min := 0;
progressDlg.i64Max := bytesLeftToWrite;
for i:=1 to numPasses do
begin
// Let user know what's going on...
useShredMethodTitle := ShredMethodTitle(IntMethod);
if assigned(FOnOverwriteDataReq) then
begin
useShredMethodTitle := _('Custom');
end;
progressDlg.Caption := SDUParamSubstitute(
_('Shredding (%1 pass %2/%3) %4'),
[useShredMethodTitle, i, numPasses, filename]
);
progressDlg.i64Position := 0;
if assigned(OnStartingFileOverwritePass) then
begin
OnStartingFileOverwritePass(self, filename, i, numPasses);
end;
// Has user cancelled?
Application.ProcessMessages();
if progressDlg.Cancel then
begin
raise EShredderErrorUserCancel.Create(USER_CANCELLED);
end;
if (silentProgressDlg <> nil) then
begin
if silentProgressDlg.Cancel then
begin
raise EShredderErrorUserCancel.Create(USER_CANCELLED);
end;
end;
if assigned(FOnCheckForUserCancel) then
begin
FOnCheckForUserCancel(self, eventUserCancel);
if eventUserCancel then
begin
raise EShredderErrorUserCancel.Create(USER_CANCELLED);
end;
end;
// Reset the file ptr
SetFilePointer(
fileHandle,
startOffsetLo,
@startOffsetHi,
FILE_BEGIN
);
// Reset the total number of bytes to be written...
// tmpInt64 used to prevent Delphi effectivly casting to DWORD
tmpInt64 := bytesToShredHi;
bytesLeftToWrite := (tmpInt64 shl 32) + bytesToShredLo;
// Fill a block with random garbage
SetLength(blankingBytes, FIntFileBufferSize);
if not(assigned(FOnOverwriteDataReq)) then
begin
failure := not(GetRandomDataBlock(i, blankingBytes));
end;
while (
(bytesLeftToWrite > 0) AND
not(failure)
) do
begin
progressDlg.i64Position := (progressDlg.i64Max - bytesLeftToWrite);
// Has user cancelled?
Application.ProcessMessages();
if progressDlg.Cancel then
begin
raise EShredderErrorUserCancel.Create(USER_CANCELLED);
end;
if (silentProgressDlg <> nil) then
begin
if silentProgressDlg.Cancel then
begin
raise EShredderErrorUserCancel.Create(USER_CANCELLED);
end;
end;
if assigned(FOnCheckForUserCancel) then
begin
FOnCheckForUserCancel(self, eventUserCancel);
if eventUserCancel then
begin
raise EShredderErrorUserCancel.Create(USER_CANCELLED);
end;
end;
// Generate new data if user supplied routine...
if (assigned(FOnOverwriteDataReq)) then
begin
failure := not(GetRandomDataBlock(i, blankingBytes));
end;
// Note: Cast to int64 to ensure no problems
bytesToWriteNow := (min(bytesLeftToWrite, int64(FIntFileBufferSize)) AND $FFFFFFFF);
failure := failure or not(WriteFile(fileHandle, blankingBytes[0], bytesToWriteNow, bytesWritten, nil));
dec(bytesLeftToWrite, bytesWritten);
// Ensure that the buffer is flushed to disk (even through disk caching
// software) [from Borland FAQ]
// xxx - this line commented out - prevents process from exiting?! It remains
// visible in task manager, and can't be killed?!
// FlushFileBuffers(fileHandle);
end;
if (failure) then
begin
// Get out of loop...
break;
end;
end; // for i:=1 to numPasses do
end; // ELSE PART - if (bytesLeftToWrite < 0) then
end; // if not( (fileLengthLo = $FFFFFFFF) AND (GetLastError()<>NO_ERROR) ) then
finally
// xxx - this line commented out - prevents process from exiting?! It remains
// visible in task manager, and can't be killed?!
// FlushFileBuffers(fileHandle);
CloseHandle(fileHandle);
end;
end; // ELSE PART - if (fileHandle = INVALID_HANDLE_VALUE) then
except
on EShredderErrorUserCancel do
begin
// Ensure flag set
userCancel := TRUE;
end;
end;
finally
progressDlg.Free();
end;
// Clean up file?
if not(leaveFile) then
begin
DeleteFileOrDir(filename);
end;
// Determine return value...
if (failure) then
begin
retVal := srError;
end
else if (userCancel) then
begin
retVal := srUserCancel;
end
else
begin
// Everything OK...
retVal := srSuccess;
end;
FLastIntShredResult := retval;
Result := retVal;
end;
// Simple rename a file/dir and then delete it.
function TShredder.DeleteFileOrDir(itemname: string): TShredResult;
const
// This should be enough to overwrite any LFN directory entries (about 255 chars long)
MASSIVE_FILENAME = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaa';
var
j: integer;
deleteFilename: string;
testRenameFilename: string;
fileAttributes: integer;
largeFilename: string;
fileHandle : THandle;
tmpFsp: string;
zero: DWORD;
fileIterator: TSDUFileIterator;
currFile: string;
retval: TShredResult;
begin
retval := srError;
zero := 0; // Obviously!
try
tmpFsp := GenerateRndDotFilename(ExtractFilePath(itemname), ExtractFileName(itemname));
tmpFsp := ExtractFilePath(itemname)+tmpFsp;
if tmpFsp<>'' then
begin
if RenameFile(itemname, tmpFsp) then
begin
itemname := tmpFsp;
end;
end;
deleteFilename := itemname;
if (Win32Platform=VER_PLATFORM_WIN32_NT) then
begin
for j:=ord('a') to ord('z') do
begin
testRenameFilename := ExtractFilePath(itemname) + chr(j)+'.';
if not(fileexists(testRenameFilename)) then
begin
deleteFilename := testRenameFilename;
break;
end;
end;
largeFilename := ExtractFilePath(itemname) + MASSIVE_FILENAME;
if length(largeFilename)>MAX_PATH then
begin
Delete(largeFilename, MAX_PATH-1, length(largeFilename)-MAX_PATH+1);
end;
if RenameFile(itemname, largeFilename) then
begin
if not(RenameFile(largeFilename, deleteFilename)) then
begin
deleteFilename := largeFilename;
end;
end
else
begin
deleteFilename := itemname;
end;;
end;
{$IFDEF MSWINDOWS}
{$WARN SYMBOL_PLATFORM OFF} // Useless warning about platform - we're already
// protecting against that!
fileAttributes := FileGetAttr(deleteFilename);
if (fileAttributes AND faDirectory)=0 then
{$WARN SYMBOL_PLATFORM ON}
{$ENDIF}
{$IFDEF LINUX}
xxx - to be implemented: test if it's *not* a directory
{$ENDIF}
begin
// Truncate the file to 0 bytes and set it's date/time to some junk
fileHandle := CreateFile(PChar(deleteFilename),
GENERIC_READ or GENERIC_WRITE,
0,
nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL or FILE_FLAG_WRITE_THROUGH,
0);
SetFilePointer(fileHandle, 0, @zero, FILE_BEGIN);
SetEndOfFile(fileHandle);
SDUSetAllFileTimes(fileHandle, DateTimeToFileDate(encodedate(1980, 1, 1)));
CloseHandle(fileHandle);
if DeleteFile(deleteFilename) then
begin
retval := srSuccess;
end;
end
else
begin
// Delete all files and dirs beneath the directory
fileIterator := TSDUFileIterator.Create(nil);
try
fileIterator.Directory := deleteFilename;
fileIterator.RecurseSubDirs := FALSE; // We handle recursion
fileIterator.IncludeDirNames := TRUE;
fileIterator.OmitStartDirPrefix := FALSE;
fileIterator.Reset();
currFile := fileIterator.Next();
retval := srSuccess;
while (currFile<>'') do
begin
retval := DeleteFileOrDir(currFile);
if (retval <> srSuccess) then
begin
break;
end;
currFile := fileIterator.Next();
end;
finally
fileIterator.Free();
end;
if (retval = srSuccess) then
begin
// Finally, remove the dir itsself...
if RemoveDir(deleteFilename) then
begin
retval := srSuccess;
end;
end;
end;
except
begin
// Nothing (i.e. ignore all exceptions, e.g. can't open file)
retval := srError;
end;
end;
Result := retval;
end;
function TShredder.GetRandomDataBlock(passNum: integer; var outputBlock: TShredBlock): boolean;
var
allOK: boolean;
begin
allOK := TRUE;
if assigned(FOnOverwriteDataReq) then
begin
FOnOverwriteDataReq(self, passNum, (high(outputBlock)-low(outputBlock)), allOK, outputBlock);
end
else
begin
case IntMethod of
smZeros:
begin
GetBlockZeros(outputBlock);
end;
smOnes:
begin
GetBlockOnes(outputBlock);
end;
smPseudorandom:
begin
GetBlockPRNG(outputBlock);
end;
smRCMP:
begin
GetBlockRCMP(passNum, outputBlock);
end;
smUSDOD_E:
begin
GetBlockDOD(passNum, outputBlock);
end;
smUSDOD_ECE:
begin
GetBlockDOD(passNum, outputBlock);
end;
smGutmann:
begin
GetBlockGutmann(passNum, outputBlock);
end;
end;
end;
Result := allOK;
end;
procedure TShredder.GetBlockZeros(var outputBlock: TShredBlock);
var
i: integer;
begin
for i:=low(outputBlock) to high(outputBlock) do
begin
outputBlock[i] := 0;
end;
end;
procedure TShredder.GetBlockOnes(var outputBlock: TShredBlock);
var
i: integer;
begin
for i:=low(outputBlock) to high(outputBlock) do
begin
outputBlock[i] := $FF;
end;
end;
procedure TShredder.GetBlockPRNG(var outputBlock: TShredBlock);
var
i: integer;
begin
for i:=low(outputBlock) to high(outputBlock) do
begin
outputBlock[i] := random(256);
end;
end;
procedure TShredder.GetBlockRCMP(passNum: integer; var outputBlock: TShredBlock);
const
DSX_VERSION_ID = 1.40;
var
i: integer;
strBlock: string;
timeStamp: TDateTime;
year: WORD;
month: WORD;
day: WORD;
hour: WORD;
min: WORD;
sec: WORD;
msec: WORD;
begin
if (passNum = 1) then
begin
// 0x00
for i:=low(outputBlock) to high(outputBlock) do
begin
outputBlock[i] := $00;
end;
end
else if (passNum = 2) then
begin
// 0xFF
for i:=low(outputBlock) to high(outputBlock) do
begin
outputBlock[i] := $FF;
end;
end
else if (passNum = 3) then
begin
// Text with version ID and date/timestamp
timeStamp := now;
DecodeDate(timeStamp, year, month, day);
DecodeTime(timeStamp, hour, min, sec, msec);
strBlock := Format(
'%f%.4d%.2d%.2d%.2d%.2d%.2d',
[
DSX_VERSION_ID,
year,
month,
day,
hour,
min,
sec
]
);
for i:=low(outputBlock) to high(outputBlock) do
begin
outputBlock[i] := ord(strBlock[ ((i mod length(strBlock)) + 1) ]);
end;
end;
end;
procedure TShredder.GetBlockDOD(passNum: integer; var outputBlock: TShredBlock);
var
i: integer;
begin
if (
(passNum = 1) or
(passNum = 5)
) then
begin
// Any character...
for i:=low(outputBlock) to high(outputBlock) do
begin
outputBlock[i] := $00;
end;
end
else if (
(passNum = 2) or
(passNum = 6)
) then
begin
// Character's complement...
for i:=low(outputBlock) to high(outputBlock) do
begin
outputBlock[i] := $FF;
end;
end
else if (
(passNum = 3) or
(passNum = 7)
) then
begin
// Random...
GetBlockPRNG(outputBlock);
end
else if (passNum = 4) then
begin
// Single character...
for i:=low(outputBlock) to high(outputBlock) do
begin
outputBlock[i] := $7F;
end;
end;
end;
procedure TShredder.GetBlockGutmann(passNum: integer; var outputBlock: TShredBlock);
var
i: integer;
passDetails: TShredDetails;
begin
if (passNum<5) OR (passNum>31) then
begin
GetBlockPRNG(outputBlock);
end
else
begin
passDetails := GetGutmannChars(passNum);
for i:=low(outputBlock) to high(outputBlock) do
begin
outputBlock[i] := passDetails[i mod 3];
end;
end;
end;
function TShredder.GetGutmannChars(passNum: integer): TShredDetails;
begin
case passnum of
5: Result := SetGutmannDetails($55, $55, $55);
6: Result := SetGutmannDetails($aa, $aa, $aa);
7: Result := SetGutmannDetails($92, $49, $24);
8: Result := SetGutmannDetails($49, $24, $92);
9: Result := SetGutmannDetails($24, $92, $49);
10: Result := SetGutmannDetails($00, $00, $00);
11: Result := SetGutmannDetails($11, $11, $11);
12: Result := SetGutmannDetails($22, $22, $22);
13: Result := SetGutmannDetails($33, $33, $33);
14: Result := SetGutmannDetails($44, $44, $44);
15: Result := SetGutmannDetails($55, $55, $55);
16: Result := SetGutmannDetails($66, $66, $66);
17: Result := SetGutmannDetails($77, $77, $77);
18: Result := SetGutmannDetails($88, $88, $88);
19: Result := SetGutmannDetails($99, $99, $99);
20: Result := SetGutmannDetails($aa, $aa, $aa);
21: Result := SetGutmannDetails($bb, $bb, $bb);
22: Result := SetGutmannDetails($cc, $cc, $cc);
23: Result := SetGutmannDetails($dd, $dd, $dd);
24: Result := SetGutmannDetails($ee, $ee, $ee);
25: Result := SetGutmannDetails($ff, $ff, $ff);
26: Result := SetGutmannDetails($92, $49, $24);
27: Result := SetGutmannDetails($49, $24, $92);
28: Result := SetGutmannDetails($24, $92, $49);
29: Result := SetGutmannDetails($6d, $b6, $db);
30: Result := SetGutmannDetails($b6, $db, $6d);
31: Result := SetGutmannDetails($db, $6d, $b6);
end;
end;
function TShredder.SetGutmannDetails(nOne: integer; nTwo: integer; nThree: integer): TShredDetails;
begin
Result[0] := nOne;
Result[1] := nTwo;
Result[2] := nThree;
end;
// Returns: TShredResult
function TShredder.OverwriteDriveFreeSpace(driveLetter: DriveLetterChar; silent: boolean): TShredResult;
const
FIVE_MB = (5 * BYTES_IN_MEGABYTE);
var
drive: DriveLetterString;
tempDriveDir: string;
freeSpace: int64;
fileNumber: integer;
currFilename: string;
blankArray: TShredFreeSpaceBlockObj;
i: integer;
lastFilename: string;
shredderCommandLine: Ansistring;
progressDlg: TSDUProgressDialog;
diskNumber: integer;
userCancel: boolean;
failure: boolean;
retVal: TShredResult;
createOK: TShredResult;
internalShredOK: TShredResult;
useTmpFileSize: int64;
prevCursor: TCursor;
eventUserCancel: boolean;
begin
userCancel := FALSE;
failure := FALSE;
eventUserCancel := FALSE;
if not(FFreeUseInt) then
begin
shredderCommandLine := format(FExtFreeSpaceExe, [driveLetter]); // no data loss in converting to ansi - as driveLetter is ansichar
if (WinExec(PAnsiChar(shredderCommandLine), SW_RESTORE))<31 then
begin
failure := TRUE;
SDUMessageDlg(_('Error running external (3rd party) free space shredder'),
mtError,
[mbOK],
0);
end;
end
else
begin
progressDlg := TSDUProgressDialog.Create(nil);
try
progressDlg.ShowTimeRemaining := TRUE;
blankArray := TShredFreeSpaceBlockObj.Create();
try
SetLength(blankArray.BLANK_FREESPACE_BLOCK, FIntFreeSpcFileCreationBlkSize);
for i:=0 to FIntFreeSpcFileCreationBlkSize-1 do
begin
blankArray.BLANK_FREESPACE_BLOCK[i] := 0;
end;
// Create a subdir
drive := uppercase(driveLetter);
driveLetter := drive[1];
tempDriveDir := driveLetter + ':\'+OVERWRITE_FREESPACE_TMP_DIR+inttostr(random(10000))+'.tmp';
diskNumber := ord(drive[1])-ord('A')+1;
CreateDir(tempDriveDir);
fileNumber := 0;
// While there is FIntFreeSpcFileSize (or smart) bytes diskspace
// left, create a file FIntFreeSpcFileSize (or smart) big
freeSpace := DiskFree(diskNumber);
progressDlg.Caption := SDUParamSubstitute(_('Shredding free space on drive %1:'), [driveLetter]);
progressDlg.i64Max := freeSpace;
progressDlg.i64Min := 0;
progressDlg.i64Position := 0;
prevCursor := Screen.Cursor;
if not(silent) then
begin
Screen.Cursor := crAppStart;
progressDlg.Show();
end;
try // Finally (mouse cursor revert)
try // Except (EShredderErrorUserCancel)
try // Finally
if FIntFreeSpcSmartFileSize then
begin
useTmpFileSize:= max((freeSpace div 10), FIVE_MB);
if (useTmpFileSize >= int64(FIntFreeSpcFileSize)) then
begin
useTmpFileSize := FIntFreeSpcFileSize;
end;
end
else
begin
useTmpFileSize:= FIntFreeSpcFileSize;
end;
// This is > and not >= so that the last file to be created (outside this
// loop) isn't zero bytes long
while (freeSpace>useTmpFileSize) do
begin
inc(fileNumber);
currFilename := GetTempFilename(tempDriveDir, fileNumber);
createOK := CreateEmptyFile(currFilename, useTmpFileSize, blankArray, progressDlg);
if (createOK = srUserCancel) then
begin
raise EShredderErrorUserCancel.Create(USER_CANCELLED);
end
else if (createOK = srError) then
begin
failure := TRUE;
// Quit loop...
break;
end;
if assigned(FOnCheckForUserCancel) then
begin
FOnCheckForUserCancel(self, eventUserCancel);
if eventUserCancel then
begin
raise EShredderErrorUserCancel.Create(USER_CANCELLED);
end;
end;
// Shred the file, but _don't_ _delete_ _it_
// Note that this will overwrite any slack space at the end of the file
internalShredOK := InternalShredFile(currFilename, FALSE, TRUE, progressDlg, TRUE);
if (internalShredOK = srUserCancel) then
begin
raise EShredderErrorUserCancel.Create(USER_CANCELLED);
end
else if (internalShredOK = srError) then
begin
failure := TRUE;
// Quit loop...
break;
end;
if assigned(FOnCheckForUserCancel) then
begin
FOnCheckForUserCancel(self, eventUserCancel);
if eventUserCancel then
begin
raise EShredderErrorUserCancel.Create(USER_CANCELLED);
end;
end;
freeSpace := DiskFree(diskNumber);
progressDlg.i64InversePosition := freeSpace;
// Check for user cancel...
Application.ProcessMessages();
if progressDlg.Cancel then
begin
raise EShredderErrorUserCancel.Create(USER_CANCELLED);
end;
if assigned(FOnCheckForUserCancel) then
begin
FOnCheckForUserCancel(self, eventUserCancel);
if eventUserCancel then
begin
raise EShredderErrorUserCancel.Create(USER_CANCELLED);
end;
end;
end; // while (freeSpace>useTmpFileSize) do
// Create a file with the remaining disk bytes
if not(failure) then
begin
lastFilename := GetTempFilename(tempDriveDir, fileNumber+1);
createOK := CreateEmptyFile(lastFilename, freeSpace, blankArray, progressDlg);
if (createOK = srUserCancel) then
begin
raise EShredderErrorUserCancel.Create(USER_CANCELLED);
end
else if (createOK = srError) then
begin
failure := TRUE;
end;
if assigned(FOnCheckForUserCancel) then
begin
FOnCheckForUserCancel(self, eventUserCancel);
if eventUserCancel then
begin
raise EShredderErrorUserCancel.Create(USER_CANCELLED);
end;
end;
end; // if not(failure) then
// Shred the last file
if not(failure) then
begin
internalShredOK := InternalShredFile(lastFilename, FALSE, TRUE, progressDlg, TRUE);
// Note that this will overwrite any slack space at the end of the file
if (internalShredOK = srUserCancel) then
begin
raise EShredderErrorUserCancel.Create(USER_CANCELLED);
end
else if (internalShredOK = srError) then
begin
failure := TRUE;
end;
if assigned(FOnCheckForUserCancel) then
begin
FOnCheckForUserCancel(self, eventUserCancel);
if eventUserCancel then
begin
raise EShredderErrorUserCancel.Create(USER_CANCELLED);
end;
end;
end; // if not(failure) then
finally
// Remove any files that were created, together with the dir
DeleteFileOrDir(tempDriveDir);
end;
except
on EShredderErrorUserCancel do
begin
// Ensure flag set
userCancel := TRUE;
end;
end;
finally
// Revert the mouse pointer, if we were showing overwrite
// progress...
if not(silent) then
begin
Screen.Cursor := prevCursor;
end;
end;
finally
blankArray.Free();
end;
finally
progressDlg.Free();
end;
end; // use internal free space shredder
// Determine return value...
if (failure) then
begin
retVal := srError;
end
else if (userCancel) then
begin
retVal := srUserCancel;
end
else
begin
// Everything OK...
retVal := srSuccess;
end;
Result := retVal;
end;
// progressDlg - This may *optionally* be
// set to a progress dialog. This progress dialog will
// *only* be used for checking to see if the user's
// cancelled the operation
function TShredder.CreateEmptyFile(filename: string; size: int64; blankArray: TShredFreeSpaceBlockObj; progressDlg: TSDUProgressDialog): TShredResult;
var
retVal: TShredResult;
userCancel: boolean;
failure: boolean;
fileHandle : THandle;
bytesWritten: DWORD;
bytesInBlock: DWORD;
totalBytesWritten: int64;
eventUserCancel: boolean;
begin
failure := FALSE;
userCancel := FALSE;
eventUserCancel := FALSE;
fileHandle := CreateFile(PChar(filename),
GENERIC_READ or GENERIC_WRITE,
0,
nil,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL or FILE_FLAG_WRITE_THROUGH,
0);
if (fileHandle = INVALID_HANDLE_VALUE) then
begin
failure := TRUE;
end
else
begin
try
// Fill out the file to the required size
totalBytesWritten := 0;
// Set bytesWritten to bootstrap loop
bytesWritten := 1;
while ( (totalBytesWritten<size) and (bytesWritten>0) )do
begin
bytesInBlock := min((size-totalBytesWritten), FIntFreeSpcFileCreationBlkSize);
WriteFile(fileHandle, blankArray.BLANK_FREESPACE_BLOCK[0], bytesInBlock, bytesWritten, nil);
inc(totalBytesWritten, bytesWritten);
// Has user cancelled?
Application.ProcessMessages();
if (progressDlg <> nil) then
begin
if progressDlg.Cancel then
begin
raise EShredderErrorUserCancel.Create(USER_CANCELLED);
end;
end;
if assigned(FOnCheckForUserCancel) then
begin
FOnCheckForUserCancel(self, eventUserCancel);
if eventUserCancel then
begin
raise EShredderErrorUserCancel.Create(USER_CANCELLED);
end;
end;
end;
// Ensure that the buffer is flushed to disk (even through disk caching
// software) [from Borland FAQ]
// xxx - this line commented out - prevents process from exiting?! It remains
// visible in task manager, and can't be killed?!
// FlushFileBuffers(fileHandle);
finally
CloseHandle(fileHandle);
end;
end; // ELSE PART - if (fileHandle = INVALID_HANDLE_VALUE) then
// Determine return value...
if (failure) then
begin
retVal := srError;
end
else if (userCancel) then
begin
retVal := srUserCancel;
end
else
begin
// Everything OK...
retVal := srSuccess;
end;
Result := retVal;
end;
function TShredder.GetTempFilename(driveDir: string; serialNo: integer): string;
begin
Result := driveDir + '\~STUtmp.'+inttostr(serialNo);
end;
function TShredder.OverwriteAllFileSlacks(driveLetter: Ansichar; silent: boolean): TShredResult;
var
progressDlg: TSDUProgressDialog;
rootDir: string;
problemFiles: TStringList;
reportDlg: TFileList_F;
drive: Ansistring;
begin
drive := uppercase(driveLetter);
driveLetter := drive[1];
progressDlg := TSDUProgressDialog.Create(nil);
problemFiles:= TStringList.create();
try
rootDir:= driveLetter+':\';
progressDlg.ShowTimeRemaining := TRUE;
progressDlg.Caption := SDUParamSubstitute(_('Shredding file slack on drive %1:'), [driveLetter]);
progressDlg.i64Max := CountFiles(rootDir);
progressDlg.i64Min := 0;
progressDlg.i64Position := 0;
if not(silent) then
begin
progressDlg.Show();
end;
Result := WipeFileSlacksInDir(rootDir, progressDlg, problemFiles);
if not(silent) AND (problemFiles.count>0) then
begin
reportDlg := TFileList_F.Create(nil);
try
reportDlg.lbFiles.visible := TRUE;
reportDlg.lblTitle.caption := _('The following files could not have their slack space shredded:');
reportDlg.lbFiles.items.assign(problemFiles);
reportDlg.showmodal;
finally
reportDlg.Free();
end;
end;
finally
problemFiles.Free();
progressDlg.Free();
end;
end;
// Perform file slack shredding on all files in specified dir
function TShredder.WipeFileSlacksInDir(dirName: string; progressDlg: TSDUProgressDialog; problemFiles: TStringList): TShredResult;
var
slackFile: string;
fileIterator: TSDUFileIterator;
currFile: string;
retval: TShredResult;
eventUserCancel: boolean;
begin
retval := srSuccess;
eventUserCancel := FALSE;
fileIterator := TSDUFileIterator.Create(nil);
try
fileIterator.Directory := dirName;
fileIterator.RecurseSubDirs := TRUE;
fileIterator.IncludeDirNames := FALSE;
fileIterator.OmitStartDirPrefix := FALSE;
fileIterator.Reset();
currFile := fileIterator.Next();
while (currFile<>'') do
begin
slackFile := SDUConvertLFNToSFN(currFile);
if not(OverwriteFileSlack(slackFile)) then
begin
problemFiles.add(slackFile);
end;
progressDlg.i64IncPosition();
if ProgressDlg.Cancel then
begin
retval := srUserCancel;
break;
end;
if assigned(FOnCheckForUserCancel) then
begin
FOnCheckForUserCancel(self, eventUserCancel);
if eventUserCancel then
begin
retval := srUserCancel;
break;
end;
end;
currFile := fileIterator.Next();
end;
finally
fileIterator.Free();
end;
Result := retval;
end;
function TShredder.OverwriteFileSlack(filename: string): boolean;
var
fileHandle: THandle;
fileLengthLo: DWORD;
fileLengthHi: DWORD;
numPasses: integer;
i: integer;
blankingBytes: TShredBlock;
bytesWritten: DWORD;
fileDateStamps: integer;
fileAttributes : integer;
retVal: boolean;
slackSize: DWORD;
writeFailed: boolean;
bpc: DWORD;
bpcMod: DWORD;
begin
// Record any file attributes and remove any hidden, system or readonly file
// attribs in order to put them back later
{$IFDEF MSWINDOWS}
{$WARN SYMBOL_PLATFORM OFF} // Useless warning about platform - we're already
// protecting against that!
fileAttributes := FileGetAttr(filename);
// If got attributes OK, continue...
retVal := (fileAttributes <> -1);
if (fileAttributes <> -1) then
{$WARN SYMBOL_PLATFORM ON}
{$ENDIF}
{$IFDEF LINUX}
xxx - to be implemented: get all file attributes
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
{$WARN SYMBOL_PLATFORM OFF} // Useless warning about platform - we're already
// protecting against that!
if (FileSetAttr(filename, faArchive) = 0) then
{$WARN SYMBOL_PLATFORM ON}
{$ENDIF}
{$IFDEF LINUX}
xxx - to be implemented: set file attributes to ensure that we can
{$ENDIF}
begin
fileHandle := CreateFile(PChar(filename),
GENERIC_READ or GENERIC_WRITE,
0,
nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL or FILE_FLAG_WRITE_THROUGH,
0);
if (fileHandle<>INVALID_HANDLE_VALUE) then
begin
// Get the date/timestamps before we start changing the file...
fileDateStamps := FileGetDate(fileHandle);
fileLengthLo := GetFileSize(fileHandle, @fileLengthHi);
// Check that the GetFileSize call was successful...
if not( (fileLengthLo = $FFFFFFFF) AND (GetLastError()<>NO_ERROR) ) then
begin
bpc := BytesPerCluster(filename);
// If the bytes per sector was reported as "1", as assume that it
// couldn't be determined, and assume a much larger sector size
if (bpc=1) then
begin
bpc := (128 * BYTES_IN_KILOBYTE); // 128K - In practice, it's likely to be much less than this
end;
// Reserve block for random garbage
SetLength(blankingBytes, bpc);
// Determine the amount of slack space beyond the file to fill the
// sector
// Note: This makes the reasonable assumption that ($FFFFFFFF + 1)
// will always be a multiple of "bpc"; so we don't need to
// bother involving the high DWORD of the file's size in this
// calculation
slackSize := 0;
bpcMod := (fileLengthLo mod bpc);
if (bpcMod>0) then
begin
slackSize := (bpc - bpcMod);
end;
// Determine the number of passes...
numPasses := TShredMethodPasses[IntMethod];
if (numPasses < 0) then
begin
numPasses := FIntPasses;
end;
// ...and finally, perform the slack space wipe
writeFailed := FALSE;
for i:=1 to numPasses do
begin
// Fill a block with random garbage
if not(GetRandomDataBlock(i, blankingBytes)) then
begin
writeFailed := TRUE;
break;
end;
// Set the file pointer to the end of the file
SetFilePointer(fileHandle, fileLengthLo, @fileLengthHi, FILE_BEGIN);
// Write from there, pass data (e.g. a block of pseudorandom data)
WriteFile(fileHandle, blankingBytes[0], slackSize, bytesWritten, nil);
if (bytesWritten<>slackSize) then
begin
writeFailed := TRUE;
break;
end;
// Ensure that the buffer is flushed to disk (even through disk caching
// software) [from Borland FAQ]
// xxx - this line commented out - prevents process from exiting?! It remains
// visible in task manager, and can't be killed?!
// FlushFileBuffers(fileHandle);
end; // for each pass
// Truncate the file back down to the correct length
SetFilePointer(fileHandle, fileLengthLo, @fileLengthHi, FILE_BEGIN);
SetEndOfFile(fileHandle);
retVal := not(writeFailed);
end;
// Reset the date/timestamps
{$WARN SYMBOL_PLATFORM OFF} // Don't care that this is platform specific - if anyone needs this under Kylix, let me know though!
FileSetDate(fileHandle, fileDateStamps);
{$WARN SYMBOL_PLATFORM ON}
// Flush and close
// xxx - this line commented out - prevents process from exiting?! It remains
// visible in task manager, and can't be killed?!
// FlushFileBuffers(fileHandle);
CloseHandle(fileHandle);
end; // if (fileHandle<>INVALID_HANDLE_VALUE) then
// Reset the file attributes
{$IFDEF MSWINDOWS}
{$WARN SYMBOL_PLATFORM OFF} // Useless warning about platform - we're already
// protecting against that!
FileSetAttr(filename, fileAttributes);
{$WARN SYMBOL_PLATFORM ON}
{$ENDIF}
{$IFDEF LINUX}
xxx - to be implemented: reset file attributes to those stored previously
{$ENDIF}
end; // if (FileSetAttr(filename, faArchive) = 0) then
end; // if (fileAttributes <> -1) then
Result := retVal;
end;
// Perform dir shredding, using the method specified in the INI file
// filename - the file to be destroyed
function TShredder.ShredDir(dirname: string; silent: boolean): TShredResult;
var
dirToDestroy: string;
shredderCommandLine: Ansistring;
fileIterator: TSDUFileIterator;
dirIterator: TSDUDirIterator;
currFile: string;
currDir: string;
retval: TShredResult;
begin
retval := srSuccess;
if (not(FFileDirUseInt)) AND
(not(FExtShredFilesThenDir)) AND
(FExtDirExe<>'') then
begin
// i.e. we using an external shredder which doesn't need all files to be
// removed before it can be used
dirname := SDUConvertLFNToSFN(dirname);
shredderCommandLine := format(FExtDirExe, [dirname]);{ TODO 1 -otdk -cinvestigate : what happens if unicode dirname? }
winexec(PAnsiChar(shredderCommandLine), SW_MINIMIZE);
end
else
begin
// Shred all files in the current directory
fileIterator := TSDUFileIterator.Create(nil);
try
fileIterator.Directory := dirname;
fileIterator.RecurseSubDirs := TRUE;
fileIterator.IncludeDirNames := FALSE;
fileIterator.OmitStartDirPrefix := FALSE;
fileIterator.Reset();
currFile := fileIterator.Next();
while (currFile<>'') do
begin
retval := DestroyFileOrDir(
currFile,
FALSE,
silent
);
if (retval <> srSuccess) then
begin
break;
end;
currFile := fileIterator.Next();
end;
finally
fileIterator.Free();
end;
if (retval = srSuccess) then
begin
dirIterator := TSDUDirIterator.Create(nil);
try
dirIterator.Directory := dirName;
dirIterator.ReverseFormat := TRUE;
dirIterator.IncludeStartDir := TRUE;
dirIterator.Reset();
// Now do the dir structure
currDir := dirIterator.Next();
while currDir<>'' do
begin
// And finally, remove the current dir...
// if external shredder handles dirs, use it
// else pass the dirname to the internal shredder for shredding
if (not(FFileDirUseInt)) AND
(FExtDirExe<>'') then
begin
// i.e. we using an external shredder which doesn't need all files to be
// removed before it can be used
dirToDestroy := SDUConvertLFNToSFN(currDir);
shredderCommandLine := format(FExtDirExe, [dirToDestroy]); { TODO 1 -otdk -cinvestigate : what happens if unicode filename? }
WinExec(PAnsiChar(shredderCommandLine), SW_MINIMIZE);
end
else
begin
// Fallback to simply removing the dir using internal method
retval := DeleteFileOrDir(currDir);
end;
currDir := dirIterator.Next();
end;
finally
dirIterator.Free();
end;
end;
end; // External shredder not being used/needs files deleted first
Result := retval;
end;
procedure TShredder.DestroyRegKey(key: string);
var
registry: TRegistry;
NTsubkeys: TStrings;
keyValues: TStrings;
valueInfo: TRegDataInfo;
rootStr: string;
i: integer;
j: integer;
buffer: array of byte;
begin
registry := TRegistry.create();
try
registry.LazyWrite := FALSE;
if Pos('HKCR\', key)=1 then
begin
registry.RootKey := HKEY_CLASSES_ROOT;
end
else if Pos('HKCU\', key)=1 then
begin
registry.RootKey := HKEY_CURRENT_USER;
end
else if Pos('HKLM\', key)=1 then
begin
registry.RootKey := HKEY_LOCAL_MACHINE;
end
else if ( (Pos('HKU \', key)=1) or (Pos('HKU\', key)=1) ) then
begin
registry.RootKey := HKEY_USERS;
end
else if Pos('HKCC\', key)=1 then
begin
registry.RootKey := HKEY_CURRENT_CONFIG;
end
else if Pos('HKDD\', key)=1 then
begin
registry.RootKey := HKEY_DYN_DATA;
end;
rootStr := Copy(key, 1, 5);
Delete(key, 1, 5);
if (Win32Platform=VER_PLATFORM_WIN32_NT) then
begin
NTsubkeys:=TStringList.Create();
try
if registry.OpenKey(key, FALSE) then
begin
if registry.HasSubkeys() then
begin
registry.GetKeyNames(NTsubkeys);
end;
keyValues := TStringList.Create();
try
registry.GetValueNames(keyValues);
for i:=0 to (keyValues.count-1) do
begin
registry.GetDataInfo(keyValues[i], valueInfo);
case valueInfo.RegData of
rdString:
begin
registry.WriteString(keyValues[i],
Format('%-'+inttostr(valueInfo.DataSize-1)+'.'+inttostr(valueInfo.DataSize-1)+'s', ['']));
end;
rdExpandString:
begin
registry.WriteExpandString(keyValues[i],
Format('%-'+inttostr(valueInfo.DataSize-1)+'.'+inttostr(valueInfo.DataSize-1)+'s', ['']));
end;
rdInteger:
begin
registry.WriteInteger(keyValues[i], 0);
end;
rdBinary:
begin
setlength(buffer, valueInfo.DataSize);
for j:=0 to (valueInfo.DataSize-1) do
begin
buffer[j] := $FF;
end;
registry.WriteBinaryData(keyValues[i],
buffer[0],
valueInfo.DataSize);
end;
rdUnknown:
begin
// Nada - don't know how to overwrite!
end;
else
begin
// Nada - don't know how to overwrite!
end;
end;
end;
finally
keyValues.Free();
end;
registry.CloseKey();
for i:=0 to (NTsubkeys.count-1) do
begin
DestroyRegKey(rootStr+'\'+NTsubkeys[i]);
end;
end;
finally
NTsubkeys.Free();
end;
end;
registry.DeleteKey(key);
finally
registry.Free();
end;
end;
// Generate a random filename of the same length as the one supplied, but
// preserving the last "." in the filename
// Give it 5 tries to find a filename that doesn't already exist, if we don't
// find one, just return ''
function TShredder.GenerateRndDotFilename(path: string; origFilename: string): string;
var
i: integer;
fndLastDot: boolean;
finished: boolean;
count: integer;
begin
count := 0;
finished:= FALSE;
while not(finished) do
begin
fndLastDot := FALSE;
for i:=length(origFilename) downto 1 do
begin
if fndLastDot then
begin
{$WARNINGS OFF} // Disable useless warning
origFilename[i] := char(ord('A')+random(26));
{$WARNINGS ON}
end
else
begin
if origFilename[i]='.' then
begin
fndLastDot := TRUE;
end
else
begin
{$WARNINGS OFF} // Disable useless warning
origFilename[i] := char(ord('A')+random(26));
{$WARNINGS ON}
end;
end;
end; // for i:=length(origFilename) downto 1 do
finished := not(FileExists(path+origFilename));
if not(finished) then
begin
inc(count);
if count=5 then
begin
origFilename := '';
end;
end;
end; // while not(finished) do
Result := origFilename;
end;
function TShredder.CountFiles(dirName: string): integer;
var
fileIterator: TSDUFileIterator;
cnt: integer;
begin
fileIterator:= TSDUFileIterator.Create(nil);
try
fileIterator.Directory := dirName;
fileIterator.RecurseSubDirs := TRUE;
fileIterator.IncludeDirNames := FALSE;
fileIterator.Reset();
cnt := fileIterator.Count();
finally
fileIterator.Free();
end;
Result := cnt;
end;
END.
|
unit LanguageLoaderUnit;
interface
uses
Classes,
LanguageUnit;
type
{ TLanguageLoader }
TLanguageLoader = class
protected
FStream: TStream;
FLanguage: TLanguage;
property Stream: TStream read FStream;
public
property Language: TLanguage read FLanguage;
procedure Load; virtual; abstract;
constructor Create(const aStream: TStream);
end;
implementation
{ TLanguageLoader }
constructor TLanguageLoader.Create(const aStream: TStream);
begin
inherited Create;
FStream := aStream;
end;
end.
|
unit Command.Button2;
interface
uses
System.Classes, System.SysUtils,
Vcl.StdCtrls, Vcl.Pattern.Command;
type
TButon2Command = class (TCommand)
private
FMemo: TMemo;
FEdit: TEdit;
protected
procedure Guard; override;
public
procedure Execute; override;
published
property Memo: TMemo read FMemo write FMemo;
property Edit: TEdit read FEdit write FEdit;
end;
implementation
procedure TButon2Command.Guard;
begin
inherited;
Assert(Memo<>nil);
Assert(Edit<>nil);
end;
procedure TButon2Command.Execute;
begin
inherited;
Memo.Lines.Add('');
Memo.Lines.Add('Getting info form Edit and put it here ...');
Memo.Lines.Add(' * Edit.Text: '+Edit.Text);
end;
end.
|
unit NewFrontiers.Threading;
interface
uses SysUtils, Classes, System.Generics.Collections;
type
TThreadMessageType = (rtOk, rtInfo, rtWarning, rtError);
/// <summary>
/// Eine Nachricht, die von einem Thread (einer asynchronen Funktionen)
/// erzeugt wurde.
/// </summary>
TThreadMessage = class
protected
_type: TThreadMessageType;
_message: string;
public
property MessageType: TThreadMessageType read _type;
property Message: string read _message;
constructor Create(aType: TThreadMessageType; aMessage: string);
end;
/// <summary>
/// Das Interface dient nur dazu die Referenzzählung zu verwenden und
/// damit keine Speicherlöcher zu hinterlassen
/// </summary>
IThreadResult = interface
procedure setResult(aValue: boolean);
procedure setException(aValue: Exception);
function getResult: boolean;
function getMessages: TObjectList<TThreadMessage>;
function getException: Exception;
property Result: boolean read getResult write setResult;
property Messages: TObjectList<TThreadMessage> read getMessages;
property Exception: Exception read getException write setException;
end;
/// <summary>
/// Das Ergebnis eines Threads. Besteht aus einem Boolean, das angibt ob
/// die Ausführung erfolgreich war, den erzeugten Nachrichten sowie ggf.
/// der aufgetretenen Exception. Muss vom Aufrufer freigeben werden!
/// </summary>
TThreadResult = class(TInterfacedObject, IThreadResult)
protected
_result: boolean;
_messages: TObjectList<TThreadMessage>;
_exception: Exception;
procedure setResult(aValue: boolean);
procedure setException(aValue: Exception);
function getResult: boolean;
function getMessages: TObjectList<TThreadMessage>;
function getException: Exception;
public
constructor Create;
destructor Destroy; override;
end;
/// <summary>
/// Wrapper für einen Thread, der bereits die Grundlogik enthält
/// </summary>
TAsync = class(TThread)
protected
_result: IThreadResult;
procedure doWork; virtual; abstract;
procedure Execute; override;
public
property Result: IThreadResult read _result;
/// <summary>
/// Der Konstruktor sorgt dafür, dass der Thread immer suspended
/// gestartet wird.
/// </summary>
constructor Create; reintroduce;
end;
/// <summary>
/// Anonyme Methode, die mit dem Manager gestartet werden kann
/// </summary>
TAsyncProcedure = reference to procedure;
/// <summary>
/// Async-Klasse, die eine anonyme Methode ausführen kann
/// </summary>
TAsyncProcedureThread = class(TAsync)
protected
_proc: TAsyncProcedure;
procedure doWork; override;
public
property Proc: TAsyncProcedure read _proc write _proc;
end;
/// <summary>
/// Referenz auf eine Klasse vom Typ TAsync
/// </summary>
TAsyncClass = class of TAsync;
/// <summary>
/// Der Thread-Manager wird zum Ausführen von Threads (asynchronen
/// Funktionen) verwendet.
/// </summary>
TThreadManager = class
public
/// <summary>
/// Führt den übergebenen Thread aus und gibt die Kontrolle erst nach
/// dem Abschluss an das Hauptprogramm zurück. Auf diese Weise
/// reagiert die GUI auch während blockender Operationen
/// </summary>
class function await(aClassToExecute: TAsyncClass): IThreadResult; overload;
class function await(aThread: TAsync): IThreadResult; overload;
class function await(aProc: TAsyncProcedure): IThreadResult; overload;
/// <summary>
/// Führt den übergebenen Thread aus und gibt die Kontrolle sofort an
/// das Hauptprogramm zurück. Über die zurückgegebene ID, kann das
/// Ergebnis später abgefragt werden
/// </summary>
class procedure run(aClassToExecute: TAsyncClass); overload;
class procedure run(aThread: TAsync); overload;
class procedure run(aProc: TAsyncProcedure); overload;
end;
implementation
const AWAIT_SLEEP_TIME = 100;
{ TAsync }
constructor TAsync.Create;
begin
inherited Create(true);
end;
procedure TAsync.execute;
begin
inherited;
_result := TThreadResult.Create;
try
doWork;
except
on E:Exception do
begin
_result.Result := false;
_result.Exception := E;
end;
end;
end;
{ TThreadManager }
class function TThreadManager.await(
aClassToExecute: TAsyncClass): IThreadResult;
var curThread: TAsync;
begin
curThread := aClassToExecute.Create;
result := await(curThread);
curThread.Free;
end;
class procedure TThreadManager.run(aClassToExecute: TAsyncClass);
var curThread: TAsync;
begin
curThread := aClassToExecute.Create;
curThread.FreeOnTerminate := true;
run(curThread);
end;
class function TThreadManager.await(aThread: TAsync): IThreadResult;
begin
aThread.FreeOnTerminate := false;
aThread.Start;
aThread.WaitFor;
result := aThread.Result;
end;
class procedure TThreadManager.run(aThread: TAsync);
begin
aThread.Start;
end;
class function TThreadManager.await(aProc: TAsyncProcedure): IThreadResult;
var curThread: TAsyncProcedureThread;
begin
curThread := TAsyncProcedureThread.Create;
curThread.Proc := aProc;
result := await(curThread);
curThread.Free;
end;
class procedure TThreadManager.run(aProc: TAsyncProcedure);
var curThread: TAsyncProcedureThread;
begin
curThread := TAsyncProcedureThread.Create;
curThread.Proc := aProc;
curThread.FreeOnTerminate := true;
run(curThread);
end;
{ TThreadMessage }
constructor TThreadMessage.Create(aType: TThreadMessageType; aMessage: string);
begin
inherited Create;
_type := aType;
_message := aMessage;
end;
{ TThreadResult }
constructor TThreadResult.Create;
begin
_messages := TObjectList<TThreadMessage>.Create(true);
end;
destructor TThreadResult.Destroy;
begin
_messages.Free;
inherited;
end;
function TThreadResult.getException: Exception;
begin
result := _exception;
end;
function TThreadResult.getMessages: TObjectList<TThreadMessage>;
begin
result := _messages;
end;
function TThreadResult.getResult: boolean;
begin
result := _result;
end;
procedure TThreadResult.setException(aValue: Exception);
begin
_exception := aValue;
end;
procedure TThreadResult.setResult(aValue: boolean);
begin
_result := aValue;
end;
{ TAsyncProcedureThread }
procedure TAsyncProcedureThread.doWork;
begin
_proc();
//Terminate;
end;
end.
|
unit NtResourceString;
interface
implementation
uses
System.SyncObjs,
NtResourceEx;
var
cs: TCriticalSection;
function TranslateResourceString(resStringRec: PResStringRec): String;
var
oldLoadResStringFunc: function (ResStringRec: PResStringRec): string;
begin
cs.Acquire;
try
Result := _T(resStringRec);
if Result <> '' then
Exit;
oldLoadResStringFunc := LoadResStringFunc;
try
LoadResStringFunc := nil;
Result := LoadResString(resStringRec);
finally
LoadResStringFunc := oldLoadResStringFunc;
end;
finally
cs.Release;
end;
end;
initialization
// Enable resource string translation
LoadResStringFunc := TranslateResourceString;
cs := TCriticalSection.Create;
finalization
cs.Free;
end.
|
unit KeyboardDialog_U;
// Description: "Secure Keyboard Entry" Dialog
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TKeyboardDialog = class(TComponent)
private
{ Private declarations }
protected
{ Protected declarations }
public
Password: string;
function Execute(): boolean;
procedure BlankPassword();
published
{ Published declarations }
end;
procedure Register;
implementation
uses KeyboardEntryDlg_U;
procedure Register;
begin
RegisterComponents('SDeanSecurity', [TKeyboardDialog]);
end;
function TKeyboardDialog.Execute(): boolean;
var
entryDlg: TKeyboardEntryDlg;
begin
Result := FALSE;
entryDlg:= TKeyboardEntryDlg.create(nil);
try
if entryDlg.Showmodal()=mrOK then
begin
Password := entryDlg.Password;
entryDlg.BlankPassword();
Result := TRUE;
end;
finally
entryDlg.Free();
end;
end;
procedure TKeyboardDialog.BlankPassword();
var
i: integer;
begin
randomize;
for i:=1 to length(Password) do
begin
{$WARNINGS OFF} // Disable useless warning
Password[i] := chr(random(255));
Password[i] := #0;
{$WARNINGS ON}
end;
Password := '';
end;
END.
|
{ ***************************************************************************
Copyright (c) 2016-2022 Kike Pérez / Jens Fudickar
Unit : Quick.Logger.Provider.StringList
Description : Log StringList Provider
Author : Jens Fudickar
Version : 1.23
Created : 12/28/2023
Modified : 12/28/2023
This file is part of QuickLogger: https://github.com/exilon/QuickLogger
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Logger.Provider.StringList;
interface
{$I QuickLib.inc}
uses
System.Classes,
{$IFDEF MSWINDOWS}
WinApi.Windows,
{$IFDEF DELPHIXE8_UP}
Quick.Json.Serializer,
{$ENDIF}
{$ENDIF}
{$IFDEF DELPHILINUX}
Quick.SyncObjs.Linux.Compatibility,
{$ENDIF}
System.SysUtils,
Generics.Collections,
Quick.Commons,
Quick.Logger;
type
TLogStringListProvider = class(TLogProviderBase)
private
fIncludeLogItems: Boolean;
fintLogList: TStringList;
fLogList: TStringList;
fMaxSize: Int64;
fShowEventTypes: Boolean;
fShowTimeStamp: Boolean;
function GetLogList: TStringList;
public
constructor Create; override;
destructor Destroy; override;
// This property defines if the log items should be cloned to the object property of the item list.
property IncludeLogItems: Boolean read fIncludeLogItems write fIncludeLogItems default false;
{$IFDEF DELPHIXE8_UP}[TNotSerializableProperty]{$ENDIF}
// Attention: When assigning an external stringlist to the property and IncludeLogItems = true you have to ensure
// that the external list.ownsobjects is true
property LogList: TStringList read GetLogList write fLogList;
property MaxSize: Int64 read fMaxSize write fMaxSize;
property ShowEventTypes: Boolean read fShowEventTypes write fShowEventTypes;
property ShowTimeStamp: Boolean read fShowTimeStamp write fShowTimeStamp;
procedure Init; override;
procedure Restart; override;
procedure WriteLog (cLogItem: TLogItem); override;
procedure Clear;
end;
var
GlobalLogStringListProvider: TLogStringListProvider;
implementation
var
CS: TRTLCriticalSection;
constructor TLogStringListProvider.Create;
begin
inherited;
LogLevel := LOG_ALL;
fMaxSize := 0;
fShowEventTypes := False;
fShowTimeStamp := False;
fIncludeLogItems := false;
fintLogList := TStringList.Create;
fintLogList.OwnsObjects := true;
end;
destructor TLogStringListProvider.Destroy;
begin
EnterCriticalSection (CS);
try
if Assigned (fintLogList) then
fintLogList.Free;
finally
LeaveCriticalSection (CS);
end;
inherited;
end;
procedure TLogStringListProvider.Init;
begin
inherited;
end;
procedure TLogStringListProvider.Restart;
begin
Stop;
Clear;
EnterCriticalSection (CS);
try
if Assigned (fintLogList) then
fintLogList.Free;
finally
LeaveCriticalSection (CS);
end;
Init;
end;
procedure TLogStringListProvider.WriteLog (cLogItem: TLogItem);
begin
EnterCriticalSection (CS);
LogList.BeginUpdate;
try
if fMaxSize > 0 then
begin
while LogList.Count >= fMaxSize do
LogList.Delete (0);
end;
if CustomMsgOutput then
if IncludeLogItems then
LogList.AddObject (LogItemToFormat(cLogItem), cLogItem.Clone)
else
LogList.Add (LogItemToFormat(cLogItem))
else
begin
if IncludeLogItems then
LogList.AddObject (LogItemToLine(cLogItem, fShowTimeStamp, fShowEventTypes), cLogItem.Clone)
else
LogList.Add (LogItemToLine(cLogItem, fShowTimeStamp, fShowEventTypes));
if cLogItem.EventType = etHeader then
LogList.Add (FillStr('-', cLogItem.Msg.Length));
end;
finally
LogList.EndUpdate;
LeaveCriticalSection (CS);
end;
end;
procedure TLogStringListProvider.Clear;
begin
EnterCriticalSection (CS);
try
LogList.Clear;
finally
LeaveCriticalSection (CS);
end;
end;
function TLogStringListProvider.GetLogList: TStringList;
begin
if Assigned (fLogList) then
Result := fLogList
else
Result := fintLogList;
end;
initialization
{$IF Defined(MSWINDOWS) OR Defined(DELPHILINUX)}
InitializeCriticalSection (CS);
{$ELSE}
InitCriticalSection (CS);
{$ENDIF}
GlobalLogStringListProvider := TLogStringListProvider.Create;
finalization
if Assigned (GlobalLogStringListProvider) and (GlobalLogStringListProvider.RefCount = 0) then
GlobalLogStringListProvider.Free;
{$IF Defined(MSWINDOWS) OR Defined(DELPHILINUX)}
DeleteCriticalSection (CS);
{$ELSE}
DoneCriticalsection (CS);
{$ENDIF}
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: FileMD2<p>
MD2 file loader<p>
<b>Historique : </b><font size=-1><ul>
<li>31/03/07 - DaStr - Added $I GLScene.inc
<li>28/03/07 - DaStr - Added explicit pointer dereferencing
(thanks Burkhard Carstens) (Bugtracker ID = 1678644)
<li>25/08/03 - Php - Added FreeLists & degibbered LoadFromStream
<li>21/07/00 - Egg - Added frame names (Roger Cao/Carlos A. Rivero)
<li>07/06/00 - Egg - Added Header, reduced dependencies,
LoadFromFile replaced with LoadFromStream,
some cleanup & optimizations
</ul></font>
}
unit FileMD2;
interface
{$R-}
{$I GLScene.inc}
uses Classes, TypesMD2;
type
// TFileMD2
//
TFileMD2 = class
private
FiFrames: longint;
FiVertices: longint;
FiTriangles: longint;
procedure FreeLists;
public
m_index_list: PMD2VertexIndex;
m_frame_list: PMD2Frames;
FrameNames : TStrings;
constructor Create; virtual;
destructor Destroy; override;
procedure LoadFromStream(aStream : TStream);
property iFrames: longInt read FiFrames;
property iVertices: longInt read FiVertices;
property iTriangles: longInt read FiTriangles;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses SysUtils, GLVectorGeometry, GLVectorTypes;
// ------------------
// ------------------ TFileMD2 ------------------
// ------------------
// Create
//
constructor TFileMD2.Create;
begin
inherited;
m_index_list := nil;
m_frame_list := nil;
FiFrames := 0;
FiVertices := 0;
FiTriangles := 0;
FrameNames := TStringList.Create;
end;
// Destroy
//
destructor TFileMD2.Destroy;
begin
FreeLists;
FrameNames.Free;
inherited;
end;
procedure TFileMD2.FreeLists;
var
I: integer;
begin
if Assigned(m_frame_list) then begin
for I := 0 to FiFrames - 1 do
Dispose(FrameList(m_frame_list)[i]);
Dispose(m_frame_list);
if Assigned(m_index_list) then
Dispose(m_index_list);
end;
end;
// LoadFromStream
//
procedure TFileMD2.LoadFromStream(aStream : TStream);
var
Skins: array[0..MAX_MD2_SKINS - 1, 0..63] of AnsiChar;
TextureCoords: array[0..MAX_MD2_VERTICES - 1] of TVector2s;
Buffer: array[0..MAX_MD2_VERTICES * 4 + 127] of byte;
Header: TMD2Header;
Triangle: TMD2Triangle;
I: integer;
J: integer;
Frame: PMD2AliasFrame;
FrameName : String;
begin
FreeLists;
// read the modelinfo
aStream.Read(Header, SizeOf(Header));
FiFrames := Header.Num_Frames;
FiVertices := Header.Num_Vertices;
FiTriangles := Header.Num_VertexIndices;
m_index_list := AllocMem(SizeOf(TMD2VertexIndex) * Header.Num_VertexIndices);
m_frame_list := AllocMem(SizeOf(TMD2Frames) * Header.Num_Frames);
for I := 0 to Header.Num_Frames - 1 do
FrameList(m_frame_list)[I] := AllocMem(SizeOf(TVector3f) * Header.Num_Vertices);
// get the skins...
aStream.Read(Skins, Header.Num_Skins * MAX_MD2_SKINNAME);
// ...and the texcoords
aStream.Read(TextureCoords, Header.Num_TextureCoords * SizeOf(TVector2s));
for I := 0 to Header.Num_VertexIndices - 1 do begin
aStream.Read(Triangle, SizeOf(TMD2Triangle));
with IndexList(m_index_list)[I] do begin
A := Triangle.VertexIndex[2];
B := Triangle.VertexIndex[1];
C := Triangle.VertexIndex[0];
A_S := TextureCoords[Triangle.TextureCoordIndex[2]][0] / Header.SkinWidth;
A_T := TextureCoords[Triangle.TextureCoordIndex[2]][1] / Header.SkinHeight;
B_S := TextureCoords[Triangle.TextureCoordIndex[1]][0] / Header.SkinWidth;
B_T := TextureCoords[Triangle.TextureCoordIndex[1]][1] / Header.SkinHeight;
C_S := TextureCoords[Triangle.TextureCoordIndex[0]][0] / Header.SkinWidth;
C_T := TextureCoords[Triangle.TextureCoordIndex[0]][1] / Header.SkinHeight;
end;
end;
for I := 0 to Header.Num_Frames - 1 do begin
Frame := PMD2AliasFrame(@Buffer);
// read animation / frame info
aStream.Read(Frame^, Header.FrameSize);
FrameName := Trim(String(Frame^.Name));
if Copy(FrameName, Length(FrameName) - 1, 1)[1] in ['0'..'9'] then
FrameName := Copy(FrameName, 1, Length(FrameName) - 2)
else
FrameName := Copy(FrameName, 1, Length(FrameName) - 1);
if FrameNames.IndexOf(FrameName) < 0 then
FrameNames.AddObject(FrameName, TObject(Pointer(I)));
// fill the vertices list
for J := 0 to Header.Num_Vertices - 1 do begin
VertexList(FrameList(m_frame_list)[I])[J][0] := Frame^.Vertices[J].V[0] * Frame^.Scale[0] + Frame^.Translate[0];
VertexList(FrameList(m_frame_list)[I])[J][1] := Frame^.Vertices[J].V[1] * Frame^.Scale[1] + Frame^.Translate[1];
VertexList(FrameList(m_frame_list)[I])[J][2] := Frame^.Vertices[J].V[2] * Frame^.Scale[2] + Frame^.Translate[2];
end;
end;
end;
end.
|
unit adot.Collections.Vectors;
interface
{
TArr<T> Ligtweight managed analog of TList<T> / wrapper for TArray<T>
TSliceClass<T> Slice of array
TSlice<T> Managed slice of array
TVectorClass<T> Extended analog of TList<T>
TVector<T> Managed analog of TList<T> with overloaded operators
TVector2D<T> Simple managed analog of TList<T> for 2-dimensional array
}
uses
adot.Types,
adot.Collections.Types,
System.Generics.Collections,
System.Generics.Defaults,
System.SysUtils,
System.Classes;
type
{ Wrapper for TArray<T> (array with Add/Delete functionality). Example:
function GetFiltered(const Src: TArray<integer>; Filter: TFunc<integer, boolean>): TArray<integer>;
var
V: TArr<integer>;
I: integer;
begin
V.Clear;
for I := 0 to High(Src) do
if Filter(Src[I]) then
V.Add(Src[I]); // more efficient than resizing TArray<> every time
Result := V.ToArray; // there is no copying of data here, we get array pointer only
end; }
TArr<T> = record
public
{ we define it before other field to make access more efficient }
Items: TArray<T>;
private
FCount: integer;
procedure SetCount(ACount: integer);
procedure SetCapacity(ACapacity: integer);
procedure Grow;
function GetCapacity: integer;
function GetItem(ItemIndex: integer): T;
procedure SetItem(ItemIndex: integer; const Value: T);
function GetFirst: T;
function GetLast: T;
procedure SetFirst(const Value: T);
procedure SetLast(const Value: T);
function GetEmpty: Boolean;
function GetTotalSizeBytes: int64;
public
type
TEnumerator = record
private
Items: TArray<T>;
Count: integer;
Pos: integer;
function GetCurrent: T;
public
procedure Init(const Items: TArray<T>; ACount: integer);
function MoveNext: Boolean;
property Current: T read GetCurrent;
end;
{ Init is preferred over Create, it is obviously distinguished from classes.
Class-like Create can be useful when new instance is param of some routine }
procedure Init; overload;
procedure Init(ACapacity: integer); overload;
procedure Init(AItems: TArray<T>); overload;
class function Create: TArr<T>; overload; static;
class function Create(ACapacity: integer): TArr<T>; overload; static;
class function Create(AItems: TArray<T>): TArr<T>; overload; static;
function Add: integer; overload;
function Add(const Value: T): integer; overload;
procedure Add(const Value: TArray<T>); overload;
procedure Add(const Value: TEnumerable<T>); overload;
procedure Add(const Value: TArr<T>); overload;
{ Dynamic arrays in Delphi do not support copy-on-write.
TArr is wrapper for TArray and doesn't support COW too. }
function Copy: TArr<T>;
function Insert(Index: integer; const Value: T): integer;
procedure Delete(ItemIndex: integer); overload;
procedure Move(SrcIndex, DstIndex: integer);
procedure Exchange(Index1,Index2: integer);
procedure DeleteLast;
function ExtractLast: T;
function IndexOf(const Value: T): integer; overload;
function IndexOf(const Value: T; Comparer: IComparer<T>): integer; overload;
function FindFirst(const Value: T; var Index: integer): boolean; overload;
function FindFirst(const Value: T; var Index: integer; Comparer: IComparer<T>): boolean; overload;
function FindNext(const Value: T; var Index: integer): boolean; overload;
function FindNext(const Value: T; var Index: integer; Comparer: IComparer<T>): boolean; overload;
{ Trims and returns Items }
function ToArray: TArray<T>;
function GetEnumerator: TEnumerator; reintroduce;
procedure Clear;
procedure TrimExcess;
procedure Sort; overload;
procedure Sort(Comparer: IComparer<T>); overload;
procedure Sort(Comparer: IComparer<T>; AIndex, ACount: Integer); overload;
procedure Sort(Comparer: TFunc<T,T,integer>); overload;
procedure Sort(Comparer: TFunc<T,T,integer>; AIndex, ACount: Integer); overload;
function BinarySearch(const Item: T; out FoundIndex: Integer): Boolean; overload;
function BinarySearch(const Item: T; out FoundIndex: Integer; Comparer: IComparer<T>): Boolean; overload;
function BinarySearch(const Item: T; out FoundIndex: Integer; Comparer: IComparer<T>; AIndex,ACount: Integer): Boolean; overload;
property First: T read GetFirst write SetFirst;
property Last: T read GetLast write SetLast;
property Count: integer read FCount write SetCount;
property Length: integer read FCount write SetCount;
property Capacity: integer read GetCapacity write SetCapacity;
property Elements[ItemIndex: integer]: T read GetItem write SetItem; default;
property Empty: boolean read GetEmpty;
property TotalSizeBytes: int64 read GetTotalSizeBytes;
end;
TSliceClass<T> = class(TEnumerableExt<T>)
private
FValues: TArray<T>;
FSlice: TArray<integer>;
FComparer: IComparer<T>;
function GetSliceIndex(SliceIndex: integer): integer;
function GetValue(SliceIndex: integer): T;
procedure SetCount(const Value: integer);
procedure SetSliceIndex(SliceIndex: integer; const Value: integer);
procedure SetValue(SliceIndex: integer; const Value: T);
function GetCount: integer;
procedure SetComparison(AComparison: TComparison<T>);
procedure SetComparer(AComparer: IComparer<T>);
protected
type
TSliceEnumerator = class(TEnumerator<T>)
protected
FValues: TArray<T>;
FSlice: TArray<integer>;
FPosition: integer;
function DoGetCurrent: T; override;
function DoMoveNext: Boolean; override;
public
constructor Create(ASlice: TSliceClass<T>);
end;
function DoGetEnumerator: TEnumerator<T>; override;
{ Create empty slice (FSlice is empty) }
constructor CreateEmptySlice(const AValues: TArray<T>; AComparer: IComparer<T>); overload;
public
{ Slice from array }
constructor Create(const AValues: TArray<T>; AComparison: TComparison<T> = nil); overload;
constructor Create(const AValues: TArray<T>; AStartIndex,ACount: integer; AComparison: TComparison<T> = nil); overload;
constructor Create(const AValues: TArray<T>; AFilter: TFuncFilterValueIndex<T>; AComparison: TComparison<T> = nil); overload;
{ Create new slice based on current one }
function Copy: TSliceClass<T>; overload;
function Copy(AStartIndex,ACount: integer): TSliceClass<T>; overload;
function Copy(AFilter: TFuncFilterValueIndex<T>): TSliceClass<T>; overload;
procedure Clear;
procedure Sort; overload;
function BinarySearch(const Value: T; out FoundIndex: integer): boolean; overload;
function BinarySearch(const Value: T): boolean; overload;
{ number of elements in the slice }
property Count: integer read GetCount write SetCount;
{ data values }
property Values[SliceIndex: integer]: T read GetValue write SetValue; default;
{ slice values }
property Indices[SliceIndex: integer]: integer read GetSliceIndex write SetSliceIndex;
{ assign new comparer }
property Comparer: IComparer<T> read FComparer write SetComparer;
{ assign comparison routine as comparer (overrides current comparer) }
property Comparison: TComparison<T> write SetComparison;
end;
TSlice<T> = record
private
FSliceInt: IInterfacedObject<TSliceClass<T>>;
function GetReadonly: TSliceClass<T>;
function GetReadWrite: TSliceClass<T>;
function GetComparer: IComparer<T>;
function GetCount: integer;
function GetSliceIndex(SliceIndex: integer): integer;
function GetValue(SliceIndex: integer): T;
procedure SetComparer(const Value: IComparer<T>);
procedure SetCount(const Value: integer);
procedure SetSliceIndex(SliceIndex: integer; const Value: integer);
procedure SetValue(SliceIndex: integer; const Value: T);
procedure SetComparison(AComparison: TComparison<T>);
property RO: TSliceClass<T> read GetReadonly;
property RW: TSliceClass<T> read GetReadWrite;
public
{ Init is preferred over Create, it is obviously distinguished from classes.
Class-like Create can be useful when new instance is param of some routine }
{ Slice from array }
procedure Init(const ASrc: TArray<T>; AComparison: TComparison<T> = nil); overload;
procedure Init(const ASrc: TArray<T>; AStartIndex,ACount: integer; AComparison: TComparison<T> = nil); overload;
procedure Init(const ASrc: TArray<T>; AFilter: TFuncFilterValueIndex<T>; AComparison: TComparison<T> = nil); overload;
{ Slice from array }
class function Create(const ASrc: TArray<T>; Acomparison: TComparison<T> = nil): TSlice<T>; overload; static;
class function Create(const ASrc: TArray<T>; AStartIndex,ACount: integer; Acomparison: TComparison<T> = nil): TSlice<T>; overload; static;
class function Create(const ASrc: TArray<T>; AFilter: TFuncFilterValueIndex<T>; Acomparison: TComparison<T> = nil): TSlice<T>; overload; static;
{ Create new slice }
function Copy: TSlice<T>; overload;
function Copy(AStartIndex,ACount: integer): TSlice<T>; overload;
function Copy(AFilter: TFuncFilterValueIndex<T>): TSlice<T>; overload;
function GetEnumerator: TEnumerator<T>;
procedure Clear;
procedure Sort; overload;
function BinarySearch(const Value: T; out FoundIndex: integer): boolean; overload;
function BinarySearch(const Value: T): boolean; overload;
property Count: integer read GetCount write SetCount;
property Values[SliceIndex: integer]: T read GetValue write SetValue; default;
property Indices[SliceIndex: integer]: integer read GetSliceIndex write SetSliceIndex;
property Comparer: IComparer<T> read GetComparer write SetComparer;
property Comparison: TComparison<T> write SetComparison;
end;
TVectorClass<T> = class(TEnumerableExt<T>)
protected
type
TVectorEnumerator = class(TEnumerator<T>)
protected
FItems: TArray<T>;
FCount: integer;
FCurrentIndex: integer;
function DoGetCurrent: T; override;
function DoMoveNext: Boolean; override;
public
constructor Create(AVector: TVectorClass<T>);
end;
private
function GetCapacity: integer;
function GetEmpty: boolean;
function GetFirst: T;
function GetItem(ItemIndex: integer): T;
function GetLast: T;
function GetTotalSizeBytes: int64;
procedure SetCapacity(const Value: integer);
procedure SetCount(const Value: integer);
procedure SetFirst(const Value: T);
procedure SetItem(ItemIndex: integer; const Value: T);
procedure SetLast(const Value: T);
procedure Grow;
function ContainsAll(V: TArray<T>): boolean;
function GetItemsArray: TArray<T>;
procedure SetItemsArray(const Value: TArray<T>);
procedure FindComparer(var AComparer: IComparer<T>);
procedure SetOwnsValues(const Value: boolean);
procedure SetComparison(AComparison: TComparison<T>);
procedure SetComparer(AComparer: IComparer<T>);
protected
FItems: TArray<T>;
FCount: integer;
FComparer: IComparer<T>;
FOwnsValues: boolean;
function DoGetEnumerator: TEnumerator<T>; override;
public
constructor Create; overload;
constructor Create(AComparer: IComparer<T>); overload;
constructor Create(AComparison: TComparison<T>); overload;
constructor Create(const AItems: TArray<T>); overload;
constructor Create(const AItems: TArray<T>; AComparer: IComparer<T>); overload;
constructor Create(const AItems: TArray<T>; AComparison: TComparison<T>); overload;
destructor Destroy; override;
procedure Clear;
function Add: integer; overload;
function Add(const Value: T): integer; overload;
procedure Add(const Value: TArray<T>); overload;
procedure Add(const Value: TArray<T>; AStartIndex,ACount: integer); overload;
procedure Add(const Value: TEnumerable<T>); overload;
{ Get new instance with copy of the data }
function Copy: TVectorClass<T>;
function Insert(Index: integer; const Value: T): integer;
function Sorted: boolean; overload;
function Sorted(AStartIndex,ACount: integer; AComparer: IComparer<T>): boolean; overload;
function Sorted(AStartIndex,ACount: integer; AComparison: TComparison<T>): boolean; overload;
procedure Delete(ItemIndex: integer); overload;
procedure Delete(AStartIndex,ACount: integer); overload;
procedure Delete(const AIndices: TArray<integer>); overload;
procedure DeleteLast;
procedure Remove(const V: T; AComparer: IComparer<T> = nil); overload;
procedure Remove(const V: TArray<T>; AComparer: IComparer<T> = nil); overload;
procedure Remove(const V: TEnumerable<T>; AComparer: IComparer<T> = nil); overload;
procedure Remove(AFilter: TFuncFilterValueIndex<T>); overload;
{ Removes item from the vector. Unlike Delete it returns the value and will not free the item }
function Extract(ItemIndex: integer): T;
function ExtractAll: TArray<T>;
function ExtractLast: T;
procedure Move(SrcIndex, DstIndex: integer);
function IndexOf(const Value: T): integer; overload;
function IndexOf(const Value: T; AComparer: IComparer<T>): integer; overload;
function FindFirst(const Value: T; var Index: integer): boolean; overload;
function FindFirst(const Value: T; var Index: integer; AComparer: IComparer<T>): boolean; overload;
function FindNext(const Value: T; var Index: integer): boolean; overload;
function FindNext(const Value: T; var Index: integer; AComparer: IComparer<T>): boolean; overload;
function Contains(const Value: T): boolean; overload;
function Contains(const Values: TArray<T>): boolean; overload;
function Contains(const Values: TEnumerable<T>): boolean; overload;
procedure Exchange(Index1,Index2: integer);
{ Reverse( [1,2,3,4,5], 1, 3 ) = [1, 4,3,2, 5] }
procedure Reverse; overload;
procedure Reverse(AStartIndex,ACount: integer); overload;
{ RotateLeft( [1,2,3,4,5], 1, 3, 1 ) = [1, 3,4,2, 5]
RotateLeft( [1,2,3,4,5], 1, 3,-1 ) = [1, 4,2,3, 5] }
procedure RotateLeft(Index1,Index2,Shift: integer);
{ RotateRight( [1,2,3,4,5], 1, 3, 1 ) = [1, 4,2,3, 5]
RotateRight( [1,2,3,4,5], 1, 3,-1 ) = [1, 3,4,2, 5] }
procedure RotateRight(Index1,Index2,Shift: integer);
{ Shuffle items of the range in random order }
procedure Shuffle; overload;
procedure Shuffle(AStartIndex,ACount: integer); overload;
{ Generate all permutations. Permutations of [2,1,3]:
[1,2,3] [1,3,2] [2,1,3] [2,3,1] [3,1,2] [3,2,1] }
procedure FirstPermutation;
function NextPermutation: boolean;
function PrevPermutation: boolean;
procedure TrimExcess;
procedure Sort(AComparer: IComparer<T> = nil); overload;
procedure Sort(AIndex, ACount: Integer; AComparer: IComparer<T> = nil); overload;
procedure Sort(AComparer: TFuncCompareValues<T>); overload;
procedure Sort(AIndex, ACount: Integer; AComparer: TFuncCompareValues<T>); overload;
function BinarySearch(const Item: T; out FoundIndex: Integer; AComparer: IComparer<T> = nil): Boolean; overload;
function BinarySearch(const Item: T; out FoundIndex: Integer; AStartIndex,ACount: Integer; AComparer: IComparer<T> = nil): Boolean; overload;
{ TArray }
function Compare(const B: TArray<T>; AComparer: IComparer<T> = nil): integer; overload;
function Compare(const B: TArray<T>; AStartIndex,BStartIndex,ACount: integer; AComparer: IComparer<T> = nil): integer; overload;
{ TEnumerable }
function Compare(B: TEnumerable<T>; AComparer: IComparer<T> = nil): integer; overload;
function Compare(B: TEnumerable<T>; AStartIndex,BStartIndex,ACount: integer; AComparer: IComparer<T> = nil): integer; overload;
function Equal(const B: TArray<T>): boolean; overload;
function Equal(B: TEnumerable<T>): boolean; overload;
{ get copy of data }
function ToArray: TArray<T>; overload; override;
{ Readonly=False : get copy of data
Readonly=True : get pointer to stored data }
function ToArray(Readonly: boolean): TArray<T>; reintroduce; overload;
function ToString: string; reintroduce; overload;
function ToString(const ValueSeparator: string; SepAfterLastValue: boolean): string; reintroduce; overload;
function ToText: string;
property First: T read GetFirst write SetFirst;
property Last: T read GetLast write SetLast;
property Count: integer read FCount write SetCount;
property Capacity: integer read GetCapacity write SetCapacity;
property Items[ItemIndex: integer]: T read GetItem write SetItem; default;
property Empty: boolean read GetEmpty;
property TotalSizeBytes: int64 read GetTotalSizeBytes;
property Comparer: IComparer<T> read FComparer write SetComparer;
property Comparison: TComparison<T> write SetComparison;
property OwnsValues: boolean read FOwnsValues write SetOwnsValues;
property ItemsArray: TArray<T> read GetItemsArray write SetItemsArray;
end;
TVector<T> = record
private
FVectorInt: IInterfacedObject<TVectorClass<T>>;
procedure CreateVector(ACapacity: integer = 0; AComparer: IComparer<T> = nil);
function GetRO: TVectorClass<T>;
function GetRW: TVectorClass<T>;
function GetItemsArray: TArray<T>;
function GetOwnsValues: boolean;
procedure SetOwnsValues(AOwnsValues: boolean);
function GetCount: integer;
function GetEmpty: Boolean;
function GetCollection: TEnumerable<T>;
function GetCapacity: integer;
function GetFirst: T;
function GetItem(ItemIndex: integer): T;
function GetLast: T;
function GetTotalSizeBytes: int64;
procedure SetCapacity(const Value: integer);
procedure SetCount(const Value: integer);
procedure SetFirst(const Value: T);
procedure SetItem(ItemIndex: integer; const Value: T);
procedure SetLast(const Value: T);
function GetComparer: IComparer<T>;
procedure SetComparer(Value: IComparer<T>);
procedure SetItemsArray(const Value: TArray<T>);
property RO: TVectorClass<T> read GetRO;
property RW: TVectorClass<T> read GetRW;
public
procedure Init(AComparer: IComparer<T> = nil); overload;
procedure Init(AComparer: TComparison<T>); overload;
procedure Init(ACapacity: integer; AComparer: IComparer<T> = nil); overload;
procedure Init(const Values: TArray<T>; AComparer: IComparer<T> = nil); overload;
procedure Init(const Values: TEnumerable<T>; ACapacity: integer = 0; AComparer: IComparer<T> = nil); overload;
{ 1. Delphi doesn't allow parameterless constructor
2. Delphi creates here strange / not optimal code for Linux, but there is no problems with
static functions. Followin example fails with constructor, but works as expected with function:
A := TVector<integer>.Create(10);
A.Add([2,1,3]);
Check(A.Capacity=10); }
class function Create(AComparer: IComparer<T> = nil): TVector<T>; overload; static;
class function Create(AComparer: TComparison<T>): TVector<T>; overload; static;
class function Create(ACapacity: integer; AComparer: IComparer<T> = nil): TVector<T>; overload; static;
class function Create(const Values: TArray<T>; AComparer: IComparer<T> = nil): TVector<T>; overload; static;
class function Create(const Values: TEnumerable<T>; ACapacity: integer = 0; AComparer: IComparer<T> = nil): TVector<T>; overload; static;
function GetEnumerator: TEnumerator<T>;
function Add: integer; overload;
function Add(const Value: T): integer; overload;
procedure Add(const Values: TArray<T>); overload;
procedure Add(const Values: TArray<T>; AStartIndex,ACount: integer); overload;
procedure Add(const Values: TEnumerable<T>); overload;
procedure Add(Values: TVector<T>); overload;
{ Normally it is not necessary to use Copy, TVector supports copy-on-write }
function Copy: TVector<T>;
procedure Clear;
function Insert(Index: integer; const Value: T): integer;
procedure Delete(ItemIndex: integer); overload;
procedure Delete(AStartIndex,ACount: integer); overload;
procedure Delete(const AIndices: TArray<integer>); overload;
procedure DeleteLast;
procedure Remove(const V: T; AComparer: IComparer<T> = nil); overload;
procedure Remove(const V: TArray<T>; AComparer: IComparer<T> = nil); overload;
procedure Remove(const V: TEnumerable<T>; AComparer: IComparer<T> = nil); overload;
procedure Remove(AFilter: TFuncFilterValueIndex<T>); overload;
{ get & delete }
function Extract(ItemIndex: integer): T;
function ExtractAll: TArray<T>;
function ExtractLast: T;
procedure Move(SrcIndex, DstIndex: integer);
function IndexOf(const Value: T): integer; overload;
function IndexOf(const Value: T; AComparer: IComparer<T>): integer; overload;
function FindFirst(const Value: T; var Index: integer): boolean; overload;
function FindFirst(const Value: T; var Index: integer; AComparer: IComparer<T>): boolean; overload;
function FindNext(const Value: T; var Index: integer): boolean; overload;
function FindNext(const Value: T; var Index: integer; AComparer: IComparer<T>): boolean; overload;
function Contains(const Value: T): boolean; overload;
function Contains(const Values: TArray<T>): boolean; overload;
function Contains(const Values: TEnumerable<T>): boolean; overload;
procedure Exchange(Index1,Index2: integer);
{ Reverse( [1,2,3,4,5], 1, 3 ) = [1, 4,3,2, 5] }
procedure Reverse; overload;
procedure Reverse(AStartIndex,ACount: integer); overload;
{ RotateLeft( [1,2,3,4,5], 1, 3, 1 ) = [1, 3,4,2, 5]
RotateLeft( [1,2,3,4,5], 1, 3,-1 ) = [1, 4,2,3, 5] }
procedure RotateLeft(Index1,Index2,Shift: integer);
{ RotateRight( [1,2,3,4,5], 1, 3, 1 ) = [1, 4,2,3, 5]
RotateRight( [1,2,3,4,5], 1, 3,-1 ) = [1, 3,4,2, 5] }
procedure RotateRight(Index1,Index2,Shift: integer);
{ Shuffle items of the range in random order }
procedure Shuffle; overload;
procedure Shuffle(AStartIndex,ACount: integer); overload;
{ Generate all permutations. Permutations of [2,1,3]:
[1,2,3] [1,3,2] [2,1,3] [2,3,1] [3,1,2] [3,2,1 }
procedure FirstPermutation;
function NextPermutation: boolean;
function PrevPermutation: boolean;
procedure TrimExcess;
procedure Sort(AComparer: IComparer<T> = nil); overload;
procedure Sort(AIndex, ACount: Integer; AComparer: IComparer<T> = nil); overload;
procedure Sort(AComparer: TFuncCompareValues<T>); overload;
procedure Sort(AIndex, ACount: Integer; AComparer: TFuncCompareValues<T>); overload;
function BinarySearch(const Item: T; out FoundIndex: Integer; AComparer: IComparer<T> = nil): Boolean; overload;
function BinarySearch(const Item: T; out FoundIndex: Integer; AStartIndex,ACount: Integer; AComparer: IComparer<T> = nil): Boolean; overload;
{ TArray }
function Compare(const B: TArray<T>; AComparer: IComparer<T> = nil): integer; overload;
function Compare(const B: TArray<T>; AStartIndex,BStartIndex,ACount: integer; AComparer: IComparer<T> = nil): integer; overload;
{ TEnumerable }
function Compare(B: TEnumerable<T>; AComparer: IComparer<T> = nil): integer; overload;
function Compare(B: TEnumerable<T>; AStartIndex,BStartIndex,ACount: integer; AComparer: IComparer<T> = nil): integer; overload;
function Equal(const B: TArray<T>): boolean; overload;
function Equal(B: TEnumerable<T>): boolean; overload;
{ Readonly=False : get copy of data
Readonly=True : get pointer to stored data }
function ToArray(ReadOnly: boolean = False): TArray<T>;
function ToString: string; overload;
function ToString(const ValueSeparator: string; SepAfterLastValue: boolean = False): string; overload;
function ToText: string;
procedure SaveToStream(Dst: TStream; Encoding: TEncoding = nil);
procedure SaveToFile(const FileName: string; Encoding: TEncoding = nil; MemStream: boolean = True);
class operator In(const a: T; b: TVector<T>) : Boolean;
class operator In(a: TVector<T>; b: TVector<T>) : Boolean;
class operator In(const a: TArray<T>; b: TVector<T>) : Boolean;
class operator In(const a: TEnumerable<T>; b: TVector<T>) : Boolean;
class operator Implicit(const a : T) : TVector<T>;
class operator Implicit(const a : TArray<T>) : TVector<T>;
class operator Implicit(const a : TEnumerable<T>) : TVector<T>;
{ We don't want to have both conversions: ->TArray and ->TEnumerable,
because in many cases it will create ambiguity (many methods support both as input).
We support TEnumerable because it is safe. If someone needs TArray, he can use
wither AsArray (for readobly access) or ToArray }
class operator Implicit(a : TVector<T>) : TEnumerable<T>;
class operator Explicit(const a : T) : TVector<T>;
class operator Explicit(const a : TArray<T>) : TVector<T>;
class operator Explicit(const a : TEnumerable<T>) : TVector<T>;
{ see comments for Implicit(a : TVector<T>) : TEnumerable<T>; }
class operator Explicit(a : TVector<T>) : TEnumerable<T>;
class operator Add(a: TVector<T>; const b: T): TVector<T>;
class operator Add(a: TVector<T>; b: TVector<T>): TVector<T>;
class operator Add(a: TVector<T>; const b: TArray<T>): TVector<T>;
class operator Add(a: TVector<T>; const b: TEnumerable<T>): TVector<T>;
class operator Add(const a: T; b: TVector<T>): TVector<T>;
class operator Add(const a: TArray<T>; b: TVector<T>): TVector<T>;
class operator Add(const a: TEnumerable<T>; b: TVector<T>): TVector<T>;
class operator Subtract(a: TVector<T>; const b: T): TVector<T>;
class operator Subtract(a: TVector<T>; b: TVector<T>): TVector<T>;
class operator Subtract(a: TVector<T>; const b: TArray<T>): TVector<T>;
class operator Subtract(a: TVector<T>; const b: TEnumerable<T>): TVector<T>;
class operator Subtract(const a: T; b: TVector<T>): TVector<T>;
class operator Subtract(const a: TArray<T>; b: TVector<T>): TVector<T>;
class operator Subtract(const a: TEnumerable<T>; b: TVector<T>): TVector<T>;
class operator Equal(a: TVector<T>; b: TVector<T>) : Boolean;
class operator Equal(a: TVector<T>; const b: TArray<T>) : Boolean;
class operator Equal(a: TVector<T>; const b: TEnumerable<T>) : Boolean;
class operator Equal(const b: TArray<T>; a: TVector<T>): Boolean;
class operator Equal(const b: TEnumerable<T>; a: TVector<T>): Boolean;
class operator NotEqual(a: TVector<T>; b: TVector<T>): Boolean;
class operator NotEqual(a: TVector<T>; const b: TArray<T>) : Boolean;
class operator NotEqual(a: TVector<T>; const b: TEnumerable<T>) : Boolean;
class operator NotEqual(const b: TArray<T>; a: TVector<T>): Boolean;
class operator NotEqual(const b: TEnumerable<T>; a: TVector<T>): Boolean;
class operator GreaterThanOrEqual(a: TVector<T>; b: TVector<T>): Boolean;
class operator GreaterThanOrEqual(a: TVector<T>; const b: TArray<T>): Boolean;
class operator GreaterThanOrEqual(a: TVector<T>; const b: TEnumerable<T>): Boolean;
class operator GreaterThanOrEqual(const b: TArray<T>; a: TVector<T>): Boolean;
class operator GreaterThanOrEqual(const b: TEnumerable<T>; a: TVector<T>): Boolean;
class operator GreaterThan(a: TVector<T>; b: TVector<T>): Boolean;
class operator GreaterThan(a: TVector<T>; const b: TArray<T>): Boolean;
class operator GreaterThan(a: TVector<T>; const b: TEnumerable<T>): Boolean;
class operator GreaterThan(const b: TArray<T>; a: TVector<T>): Boolean;
class operator GreaterThan(const b: TEnumerable<T>; a: TVector<T>): Boolean;
class operator LessThan(a: TVector<T>; b: TVector<T>): Boolean;
class operator LessThan(a: TVector<T>; const b: TArray<T>): Boolean;
class operator LessThan(a: TVector<T>; const b: TEnumerable<T>): Boolean;
class operator LessThan(const b: TArray<T>; a: TVector<T>): Boolean;
class operator LessThan(const b: TEnumerable<T>; a: TVector<T>): Boolean;
class operator LessThanOrEqual(a: TVector<T>; b: TVector<T>): Boolean;
class operator LessThanOrEqual(a: TVector<T>; const b: TArray<T>): Boolean;
class operator LessThanOrEqual(a: TVector<T>; const b: TEnumerable<T>): Boolean;
class operator LessThanOrEqual(const b: TArray<T>; a: TVector<T>): Boolean;
class operator LessThanOrEqual(const b: TEnumerable<T>; a: TVector<T>): Boolean;
property First: T read GetFirst write SetFirst;
property Last: T read GetLast write SetLast;
property Count: integer read GetCount write SetCount;
property Capacity: integer read GetCapacity write SetCapacity;
property Items[ItemIndex: integer]: T read GetItem write SetItem; default;
property Empty: boolean read GetEmpty;
property TotalSizeBytes: int64 read GetTotalSizeBytes;
property ItemsArray: TArray<T> read GetItemsArray write SetItemsArray;
property Collection: TEnumerable<T> read GetCollection;
property OwnsValues: boolean read GetOwnsValues write SetOwnsValues;
property Comparer: IComparer<T> read GetComparer write SetComparer;
end;
{ Dynamic 2-dimensional array }
TVector2D<T> = record
public
Rows: TArr<TArr<T>>;
type
TEnumerator = class(TEnumerator<T>)
protected
Rows: TArr<TArr<T>>;
X,Y: integer;
function DoGetCurrent: T; override;
function DoMoveNext: Boolean; override;
public
constructor Create(const Rows: TArr<TArr<T>>);
end;
TCollection = class(TEnumerableExt<T>)
protected
Rows: TArr<TArr<T>>;
function DoGetEnumerator: TEnumerator<T>; override;
public
constructor Create(const Rows: TArr<TArr<T>>);
end;
private
function GetValue(x,y: integer): T;
procedure SetValue(x, y: integer; const Value: T);
function GetRowCount: integer;
procedure SetRowCount(const Value: integer);
function GetWidth(y: integer): integer;
procedure SetWidth(y: integer; const Value: integer);
public
procedure Init(Width, Height: integer);
procedure Clear;
function AddRow: integer;
function Add(y: integer): integer; overload;
function Add(y: integer; const Value: T): integer; overload;
function Add(y: integer; const Values: TEnumerable<T>): integer; overload;
function Add(y: integer; const Values: TArray<T>): integer; overload;
{ Syntax:
for Value in Vec2d.Collection.Data do }
function Collection: IInterfacedObject<TEnumerable<T>>;
property Elements[x,y: integer]: T read GetValue write SetValue; default;
property RowCount: integer read GetRowCount write SetRowCount;
property Count[y: integer]:integer read GetWidth write SetWidth;
end;
implementation
uses
adot.Collections,
adot.Tools,
adot.Tools.RTTI,
adot.Strings;
{ TArr<T>.TEnumerator }
procedure TArr<T>.TEnumerator.Init(const Items: TArray<T>; ACount: integer);
begin
Self := Default(TEnumerator);
Self.Items := Items;
Self.Count := ACount;
Self.Pos := 0;
end;
function TArr<T>.TEnumerator.GetCurrent: T;
begin
result := Items[Pos-1];
end;
function TArr<T>.TEnumerator.MoveNext: Boolean;
begin
result := Pos < Count;
if result then
inc(Pos);
end;
{ TArr<T> }
class function TArr<T>.Create: TArr<T>;
begin
result.Init;
end;
class function TArr<T>.Create(ACapacity: integer): TArr<T>;
begin
result.Init(ACapacity);
end;
class function TArr<T>.Create(AItems: TArray<T>): TArr<T>;
begin
result.Init(AItems);
end;
procedure TArr<T>.Init;
begin
Self := Default(TArr<T>);
end;
procedure TArr<T>.Init(ACapacity: integer);
begin
Self := Default(TArr<T>);
Capacity := ACapacity;
end;
procedure TArr<T>.Init(AItems: TArray<T>);
begin
Self := Default(TArr<T>);
Items := AItems;
FCount := High(AItems)-Low(AItems)+1;
end;
function TArr<T>.Add: integer;
begin
if Count>=Capacity then
Grow;
result := FCount;
inc(FCount);
end;
function TArr<T>.Add(const Value: T): integer;
begin
result := Add;
Items[result] := Value;
end;
procedure TArr<T>.Add(const Value: TArray<T>);
var
I: Integer;
begin
I := Count + System.Length(Value);
if I > Capacity then
Capacity := I;
for I := Low(Value) to High(Value) do
Add(Value[I]);
end;
procedure TArr<T>.Add(const Value: TEnumerable<T>);
var
V: T;
begin
for V in Value do
Add(V);
end;
procedure TArr<T>.Clear;
begin
Self := Default(TArr<T>);
end;
function TArr<T>.Copy: TArr<T>;
begin
result.Clear;
result.Items := TArrayUtils.Copy<T>(Items, 0, Count);
result.FCount := Count;
end;
procedure TArr<T>.Delete(ItemIndex: integer);
var
I: Integer;
begin
Assert((ItemIndex>=0) and (ItemIndex<FCount));
for I := ItemIndex to Count-2 do
Items[I] := Items[I+1];
Dec(FCount);
Items[FCount] := Default(T);
end;
procedure TArr<T>.Exchange(Index1, Index2: integer);
var Value: T;
begin
Value := Items[Index1];
Items[Index1] := Items[Index2];
Items[Index2] := Value;
end;
function TArr<T>.ToArray: TArray<T>;
begin
TrimExcess;
result := Items;
end;
procedure TArr<T>.DeleteLast;
begin
Assert(FCount>=0);
Dec(FCount);
Items[FCount] := Default(T);
end;
function TArr<T>.ExtractLast: T;
begin
Assert(FCount>=0);
Dec(FCount);
result := Items[FCount];
Items[FCount] := Default(T);
end;
procedure TArr<T>.Grow;
begin
if Capacity < 4 then
Capacity := Capacity+1
else
if Capacity < 64 then
Capacity := 64
else
Capacity := Capacity * 2;
end;
function TArr<T>.IndexOf(const Value: T; Comparer: IComparer<T>): integer;
begin
if not FindFirst(Value, Result, Comparer) then
result := -1;
end;
function TArr<T>.IndexOf(const Value: T): integer;
begin
if not FindFirst(Value, Result) then
result := -1;
end;
function TArr<T>.FindFirst(const Value: T; var Index: integer): boolean;
begin
Index := -1;
result := FindNext(Value, Index, TComparerUtils.DefaultComparer<T>);
end;
function TArr<T>.FindFirst(const Value: T; var Index: integer; Comparer: IComparer<T>): boolean;
begin
Index := -1;
result := FindNext(Value, Index, Comparer);
end;
function TArr<T>.FindNext(const Value: T; var Index: integer): boolean;
begin
result := FindNext(Value, Index, TComparerUtils.DefaultComparer<T>);
end;
function TArr<T>.FindNext(const Value: T; var Index: integer; Comparer: IComparer<T>): boolean;
var
I: Integer;
begin
if Comparer = nil then
Comparer := TComparerUtils.DefaultComparer<T>;
for I := Index+1 to Count-1 do
if Comparer.Compare(Items[I], Value)=0 then
begin
Index := I;
Exit(True);
end;
result := False;
end;
function TArr<T>.Insert(Index: integer; const Value: T): integer;
begin
for result := Add downto Index+1 do
Items[result] := Items[result-1];
result := Index;
Items[result] := Value;
end;
procedure TArr<T>.Move(SrcIndex, DstIndex: integer);
var
I: integer;
Value: T;
begin
if SrcIndex < DstIndex then
begin
{ src dst
1 2 [3] 4 [5] 6 7 }
Value := Items[SrcIndex];
for I := SrcIndex to DstIndex-1 do
Items[I] := Items[I+1];
Items[DstIndex] := Value;
end
else
if SrcIndex > DstIndex then
begin
{ dst src
1 2 [3] 4 [5] 6 7 }
Value := Items[SrcIndex];
for I := SrcIndex downto DstIndex+1 do
Items[I] := Items[I-1];
Items[DstIndex] := Value;
end;
end;
function TArr<T>.GetCapacity: integer;
begin
result := System.Length(Items);
end;
procedure TArr<T>.SetCapacity(ACapacity: integer);
begin
Assert(ACapacity>=Count);
SetLength(Items, ACapacity);
end;
function TArr<T>.GetEmpty: Boolean;
begin
Result := FCount <= 0;
end;
function TArr<T>.GetEnumerator: TEnumerator;
begin
result.Init(Items, Count);
end;
function TArr<T>.GetFirst: T;
begin
Result := Items[0];
end;
procedure TArr<T>.SetFirst(const Value: T);
begin
Items[0] := Value;
end;
function TArr<T>.GetLast: T;
begin
Result := Items[Count-1];
end;
function TArr<T>.GetTotalSizeBytes: int64;
begin
result := (High(Items)-Low(Items)+1)*SizeOf(T);
end;
procedure TArr<T>.SetLast(const Value: T);
begin
Items[Count-1] := Value;
end;
function TArr<T>.GetItem(ItemIndex: integer): T;
begin
{$IF Defined(Debug)} Assert((ItemIndex >= 0) and (ItemIndex < Count)); {$ENDIF}
result := Items[ItemIndex];
end;
procedure TArr<T>.SetItem(ItemIndex: integer; const Value: T);
begin
{$IF Defined(Debug)} Assert((ItemIndex >= 0) and (ItemIndex < Count)); {$ENDIF}
Items[ItemIndex] := Value;
end;
procedure TArr<T>.TrimExcess;
begin
if Capacity>Count then
Capacity := Count;
end;
procedure TArr<T>.SetCount(ACount: integer);
var
I: Integer;
begin
for I := ACount to Count-1 do
Items[I] := Default(T);
FCount := ACount;
if ACount > Capacity then
Capacity := ACount;
end;
procedure TArr<T>.Sort;
begin
TArray.Sort<T>(Items, TComparerUtils.DefaultComparer<T>, 0,Count);
end;
procedure TArr<T>.Sort(Comparer: IComparer<T>);
begin
Sort(Comparer, 0, Count);
end;
procedure TArr<T>.Sort(Comparer: IComparer<T>; AIndex, ACount: Integer);
begin
if Comparer=nil then
Comparer := TComparerUtils.DefaultComparer<T>;
TArray.Sort<T>(Items, Comparer, AIndex, ACount);
end;
procedure TArr<T>.Sort(Comparer: TFunc<T, T, integer>);
begin
Sort(Comparer, 0, Count);
end;
procedure TArr<T>.Sort(Comparer: TFunc<T, T, integer>; AIndex, ACount: Integer);
var
C: IComparer<T>;
begin
C := TDelegatedComparer<T>.Create(
function (const A,B: T): integer
begin
result := Comparer(A,B);
end);
TArray.Sort<T>(Items, C, AIndex, ACount);
end;
function TArr<T>.BinarySearch(const Item: T; out FoundIndex: Integer): Boolean;
begin
result := TArray.BinarySearch<T>(Items, Item, FoundIndex, TComparerUtils.DefaultComparer<T>, 0, Count);
end;
function TArr<T>.BinarySearch(const Item: T; out FoundIndex: Integer; Comparer: IComparer<T>): Boolean;
begin
result := TArray.BinarySearch<T>(Items, Item, FoundIndex, Comparer, 0, Count);
end;
function TArr<T>.BinarySearch(const Item: T; out FoundIndex: Integer; Comparer: IComparer<T>; AIndex,ACount: Integer): Boolean;
begin
result := TArray.BinarySearch<T>(Items, Item, FoundIndex, Comparer, AIndex,ACount);
end;
procedure TArr<T>.Add(const Value: TArr<T>);
var
I: Integer;
begin
for I := 0 to Value.Count-1 do
Items[Add] := Value[I];
end;
{ TSliceClass<T>.TSliceEnumerator }
constructor TSliceClass<T>.TSliceEnumerator.Create(ASlice: TSliceClass<T>);
begin
FValues := ASlice.FValues;
FSlice := ASlice.FSlice;
end;
function TSliceClass<T>.TSliceEnumerator.DoMoveNext: Boolean;
begin
result := FPosition < Length(FSlice);
if Result then
inc(FPosition);
end;
function TSliceClass<T>.TSliceEnumerator.DoGetCurrent: T;
begin
result := FValues[FSlice[FPosition-1]];
end;
{ TSliceClass<T> }
constructor TSliceClass<T>.CreateEmptySlice(const AValues: TArray<T>; AComparer: IComparer<T>);
begin
FValues := AValues;
if Assigned(AComparer)
then FComparer := AComparer
else FComparer := TComparerUtils.DefaultComparer<T>;
end;
constructor TSliceClass<T>.Create(const AValues: TArray<T>; AComparison: TComparison<T>);
begin
Create(AValues, 0, Length(AValues), AComparison);
end;
constructor TSliceClass<T>.Create(const AValues: TArray<T>; AStartIndex, ACount: integer; AComparison: TComparison<T>);
var
I: Integer;
begin
{$If Defined(Debug)}
Assert((AStartIndex>=0) and (ACount>=0) and (AStartIndex+ACount<=Length(AValues)));
{$EndIf}
FValues := AValues;
SetLength(FSlice, ACount);
for I := 0 to ACount-1 do
FSlice[I] := I + AStartIndex;
if Assigned(AComparison)
then FComparer := TDelegatedComparer<T>.Create(AComparison)
else FComparer := TComparerUtils.DefaultComparer<T>;
end;
constructor TSliceClass<T>.Create(const AValues: TArray<T>; AFilter: TFuncFilterValueIndex<T>; AComparison: TComparison<T>);
var
I,D: Integer;
begin
FValues := AValues;
SetLength(FSlice, Length(FValues));
D := 0;
for I := 0 to High(AValues) do
if AFilter(AValues[I], I) then
begin
FSlice[D] := I;
inc(D);
end;
SetLength(FSlice, D);
if Assigned(AComparison)
then FComparer := TDelegatedComparer<T>.Create(AComparison)
else FComparer := TComparerUtils.DefaultComparer<T>;
end;
function TSliceClass<T>.Copy: TSliceClass<T>;
begin
result := TSliceClass<T>.CreateEmptySlice(FValues, FComparer);
result.FSlice := TArrayUtils.Copy<integer>(FSlice);
end;
function TSliceClass<T>.Copy(AStartIndex, ACount: integer): TSliceClass<T>;
var
I: Integer;
begin
{$If Defined(Debug)}
Assert((AStartIndex>=0) and (ACount>=0) and (AStartIndex+ACount<=Length(FSlice)));
{$EndIf}
result := TSliceClass<T>.CreateEmptySlice(FValues, FComparer);
SetLength(result.FSlice, ACount);
for I := 0 to ACount-1 do
result.FSlice[I] := FSlice[I+AStartIndex];
end;
function TSliceClass<T>.Copy(AFilter: TFuncFilterValueIndex<T>): TSliceClass<T>;
var
I,D: Integer;
begin
result := TSliceClass<T>.CreateEmptySlice(FValues, FComparer);
SetLength(result.FSlice, Length(FSlice));
D := 0;
for I := 0 to High(FSlice) do
if AFilter(FValues[FSlice[I]], I) then
begin
result.FSlice[D] := FSlice[I];
inc(D);
end;
SetLength(result.FSlice, D);
end;
procedure TSliceClass<T>.Clear;
begin
SetLength(FSlice, 0);
end;
function TSliceClass<T>.DoGetEnumerator: TEnumerator<T>;
begin
result := TSliceEnumerator.Create(Self);
end;
function TSliceClass<T>.GetCount: integer;
begin
result := Length(FSlice);
end;
function TSliceClass<T>.GetSliceIndex(SliceIndex: integer): integer;
begin
result := FSlice[SliceIndex];
end;
function TSliceClass<T>.GetValue(SliceIndex: integer): T;
begin
result := FValues[FSlice[SliceIndex]];
end;
procedure TSliceClass<T>.SetComparer(AComparer: IComparer<T>);
begin
if AComparer = nil
then FComparer := TComparerUtils.DefaultComparer<T>
else FComparer := AComparer;
end;
procedure TSliceClass<T>.SetComparison(AComparison: TComparison<T>);
begin
if Assigned(AComparison)
then FComparer := TDelegatedComparer<T>.Create(AComparison)
else FComparer := TComparerUtils.DefaultComparer<T>;
end;
procedure TSliceClass<T>.SetCount(const Value: integer);
begin
SetLength(FSlice, Value);
end;
procedure TSliceClass<T>.SetSliceIndex(SliceIndex: integer; const Value: integer);
begin
FSlice[SliceIndex] := Value;
end;
procedure TSliceClass<T>.SetValue(SliceIndex: integer; const Value: T);
begin
FValues[FSlice[SliceIndex]] := Value;
end;
procedure TSliceClass<T>.Sort;
var
IndexComparer: IComparer<integer>;
begin
IndexComparer := TDelegatedComparer<integer>.Create(
function(const L,R: integer): integer
begin
result := FComparer.Compare(FValues[L], FValues[R]);
end);
TArray.Sort<integer>(FSlice, IndexComparer);
end;
function TSliceClass<T>.BinarySearch(const Value: T; out FoundIndex: integer): boolean;
var
L,R,M,C: Integer;
begin
if Length(FValues)=0 then
Exit(False);
L := 0;
R := High(FSlice);
while (R-L > 1) do
begin
M := (L+R) shr 1;
C := FComparer.Compare(FValues[FSlice[M]], Value);
if C < 0 then L := M else
if C > 0 then R := M else
begin
FoundIndex := M;
Exit(True);
end;
end;
if FComparer.Compare(FValues[FSlice[L]], Value) = 0 then
begin
FoundIndex := L;
Result := True;
end
else
if FComparer.Compare(FValues[FSlice[R]], Value) = 0 then
begin
FoundIndex := R;
Result := True;
end
else
Result := False;
end;
function TSliceClass<T>.BinarySearch(const Value: T): boolean;
var
FoundIndex: integer;
begin
result := BinarySearch(Value, FoundIndex);
end;
{ TVectorClass<T>.TVectorEnumerator<T> }
constructor TVectorClass<T>.TVectorEnumerator.Create(AVector: TVectorClass<T>);
begin
inherited Create;
FItems := AVector.FItems;
FCount := AVector.Count;
end;
function TVectorClass<T>.TVectorEnumerator.DoMoveNext: Boolean;
begin
result := FCurrentIndex < FCount;
if result then
inc(FCurrentIndex);
end;
function TVectorClass<T>.TVectorEnumerator.DoGetCurrent: T;
begin
result := FITems[FCurrentIndex-1];
end;
{ TVectorClass<T> }
constructor TVectorClass<T>.Create;
begin
inherited Create;
FComparer := TComparerUtils.DefaultComparer<T>;
end;
constructor TVectorClass<T>.Create(AComparer: IComparer<T>);
begin
inherited Create;
Comparer := AComparer;
end;
constructor TVectorClass<T>.Create(AComparison: TComparison<T>);
begin
inherited Create;
Comparison := AComparison;
end;
constructor TVectorClass<T>.Create(const AItems: TArray<T>);
begin
Create;
Add(AItems);
end;
constructor TVectorClass<T>.Create(const AItems: TArray<T>; AComparer: IComparer<T>);
begin
Create(AComparer);
Add(AItems);
end;
constructor TVectorClass<T>.Create(const AItems: TArray<T>; AComparison: TComparison<T>);
begin
Create(AComparison);
Add(AItems);
end;
procedure TVectorClass<T>.Add(const Value: TArray<T>);
begin
Add(Value, 0, System.Length(Value));
end;
procedure TVectorClass<T>.Add(const Value: TArray<T>; AStartIndex,ACount: integer);
var
I: Integer;
begin
I := Count + ACount;
if I > Capacity then
Capacity := I;
for I := AStartIndex to AStartIndex+ACount-1 do
Add(Value[I]);
end;
procedure TVectorClass<T>.Add(const Value: TEnumerable<T>);
var
V: T;
begin
for V in Value do
Add(V);
end;
function TVectorClass<T>.Add: integer;
begin
if Count>=Capacity then
Grow;
result := FCount;
inc(FCount);
end;
function TVectorClass<T>.Add(const Value: T): integer;
begin
result := Add;
FItems[result] := Value;
end;
procedure TVectorClass<T>.Grow;
begin
if Capacity < 4 then
Capacity := Capacity+1
else
if Capacity < 64 then
Capacity := 64
else
Capacity := Capacity * 2;
end;
function TVectorClass<T>.BinarySearch(const Item: T; out FoundIndex: Integer; AComparer: IComparer<T> = nil): Boolean;
begin
result := BinarySearch(Item, FoundIndex, 0, Count, AComparer);
end;
function TVectorClass<T>.BinarySearch(const Item: T; out FoundIndex: Integer; AStartIndex,ACount: Integer; AComparer: IComparer<T> = nil): Boolean;
begin
FindComparer(AComparer);
result := TArray.BinarySearch<T>(FItems, Item, FoundIndex, AComparer, AStartIndex, ACount);
end;
procedure TVectorClass<T>.Clear;
var
I: Integer;
begin
if FOwnsValues then
for I := FCount-1 downto 0 do
PObject(@FItems[I])^.DisposeOf;
SetLength(FItems, 0);
FCount := 0;
end;
function TVectorClass<T>.Compare(const B: TArray<T>; AComparer: IComparer<T> = nil): integer;
begin
if Count = System.Length(B) then
result := Compare(B,0,0,Count, AComparer)
else
if Count < System.Length(B)
then result := -1
else result := 1;
end;
function TVectorClass<T>.Compare(const B: TArray<T>; AStartIndex,BStartIndex,ACount: integer; AComparer: IComparer<T>): integer;
var
I: Integer;
begin
FindComparer(AComparer);
Assert((ACount=0) or (ACount>0) and (AStartIndex>=0) and (AStartIndex+ACount-1<Count));
Assert((ACount=0) or (ACount>0) and (BStartIndex>=0) and (BStartIndex+ACount-1<System.Length(B)));
if ACount <= 0 then
result := 0
else
for I := 0 to ACount-1 do
begin
result := AComparer.Compare(FItems[I+AStartIndex], B[I+BStartIndex]);
if result <> 0 then
Break;
end;
end;
function TVectorClass<T>.Compare(B: TEnumerable<T>; AComparer: IComparer<T> = nil): integer;
var
Value: T;
BItemsCount: integer;
begin
BItemsCount := 0;
for Value in B do
inc(BItemsCount);
if Count = BItemsCount then
result := Compare(B,0,0,Count, AComparer)
else
if Count < BItemsCount
then result := -1
else result := 1;
end;
function TVectorClass<T>.Compare(B: TEnumerable<T>; AStartIndex,BStartIndex,ACount: integer; AComparer: IComparer<T>): integer;
var
Value: T;
BItemsCount: integer;
begin
FindComparer(AComparer);
BItemsCount := 0;
for Value in B do
inc(BItemsCount);
Assert((ACount=0) or (ACount>0) and (AStartIndex>=0) and (AStartIndex+ACount-1<Count));
Assert((ACount=0) or (ACount>0) and (BStartIndex>=0) and (BStartIndex+ACount-1<BItemsCount));
result := 0;
for Value in B do
if BStartIndex > 0 then
dec(BStartIndex)
else
begin
result := AComparer.Compare(FItems[AStartIndex], Value);
inc(AStartIndex);
dec(ACount);
if (result <> 0) or (ACount <= 0) then
break;
end;
end;
function TVectorClass<T>.ContainsAll(V: TArray<T>): boolean;
var
C: IComparer<T>;
B: TArray<boolean>;
I,J,N: Integer;
begin
if (Length(V) = 0) or (Count = 0) then
Exit(False);
{ We can't use TSet, because it needs IEqualityComparer.GetHash,
IComparer can not be tranformed into IEqualityComparer hasher }
if Comparer=nil
then C := TComparerUtils.DefaultComparer<T>
else C := Comparer;
TArray.Sort<T>(V, C);
{ remove duplicates }
J := 0;
for I := 1 to High(V) do
if C.Compare(V[I], V[J])<>0 then
begin
inc(J);
FItems[J] := FItems[I];
end;
SetLength(V, J+1);
{ find items in sorted version of Values }
SetLength(B, Length(V));
N := Length(V);
for I := 0 to FCount-1 do
if TArray.BinarySearch<T>(V, FItems[I], J, C) and not B[J] then
begin
B[J] := True;
dec(N);
if N <= 0 then
Exit(True);
end;
result := False;
end;
function TVectorClass<T>.Contains(const Values: TArray<T>): boolean;
begin
result := ContainsAll(TArrayUtils.Copy<T>(Values));
end;
function TVectorClass<T>.Contains(const Values: TEnumerable<T>): boolean;
begin
result := ContainsAll(Values.ToArray);
end;
function TVectorClass<T>.Contains(const Value: T): boolean;
begin
result := IndexOf(Value)>=0;
end;
function TVectorClass<T>.Copy: TVectorClass<T>;
begin
result := TVectorClass<T>.Create;
result.FItems := TArrayUtils.Copy<T>(FItems, 0, Count);
result.FCount := Count;
end;
procedure TVectorClass<T>.Delete(AStartIndex, ACount: integer);
var
I,C: Integer;
begin
Assert((AStartIndex>=0) and (AStartIndex<Count) and (ACount>=0) and (AStartIndex+ACount-1<Count));
if FOwnsValues then
for I := AStartIndex to AStartIndex+ACount-1 do
PObject(@FItems[I])^.DisposeOf;
C := Count-ACount; { new Count }
for I := AStartIndex to C-1 do
FItems[I] := FItems[I+ACount];
for I := C to Count-1 do
FItems[I] := Default(T);
FCount := C;
end;
procedure TVectorClass<T>.Delete(ItemIndex: integer);
var
I: Integer;
begin
Assert((ItemIndex>=0) and (ItemIndex<FCount));
if FOwnsValues then
PObject(@FItems[ItemIndex])^.DisposeOf;
for I := ItemIndex to Count-2 do
FItems[I] := FItems[I+1];
Dec(FCount);
FItems[FCount] := Default(T);
end;
procedure TVectorClass<T>.Delete(const AIndices: TArray<integer>);
var
S,D,I: Integer;
Slice: TSliceClass<integer>;
begin
if (Length(AIndices) = 0) or (Count = 0) then
Exit;
Slice := TSliceClass<integer>.Create(AIndices);
try
Slice.Sort;
S := 0;
D := 0;
for I := 0 to Count-1 do
if Slice.BinarySearch(I) then
begin
if FOwnsValues then
PObject(@FItems[I])^.DisposeOf;
end
else
begin
FItems[D] := FItems[I];
inc(D);
end;
for I := D to FCount-1 do
FItems[I] := Default(T);
FCount := D;
finally
Sys.FreeAndNil(Slice);
end;
end;
procedure TVectorClass<T>.DeleteLast;
begin
Assert(FCount>0);
Dec(FCount);
if FOwnsValues then
PObject(@FItems[FCount])^.DisposeOf;
FItems[FCount] := Default(T);
end;
destructor TVectorClass<T>.Destroy;
begin
Clear;
inherited;
end;
function TVectorClass<T>.DoGetEnumerator: TEnumerator<T>;
begin
result := TVEctorEnumerator.Create(Self);
end;
function TVectorClass<T>.Equal(const B: TArray<T>): boolean;
begin
result := Compare(B) = 0;
end;
function TVectorClass<T>.Equal(B: TEnumerable<T>): boolean;
begin
result := Compare(B) = 0;
end;
procedure TVectorClass<T>.Exchange(Index1, Index2: integer);
var Value: T;
begin
Assert((Index1>=0) and (Index1<Count) and (Index2>=0) and (Index2<Count));
Value := FItems[Index1];
FItems[Index1] := FItems[Index2];
FItems[Index2] := Value;
end;
function TVectorClass<T>.Extract(ItemIndex: integer): T;
begin
Assert((ItemIndex>=0) and (ItemIndex<Count));
result := FItems[ItemIndex];
FItems[ItemIndex] := Default(T);
Delete(ItemIndex);
end;
function TVectorClass<T>.ExtractAll: TArray<T>;
begin
TrimExcess;
result := FItems;
SetLength(FItems, 0);
FCount := 0;
end;
function TVectorClass<T>.ExtractLast: T;
begin
Assert(FCount>=0);
Dec(FCount);
result := FItems[FCount];
FItems[FCount] := Default(T);
end;
function TVectorClass<T>.FindFirst(const Value: T; var Index: integer; AComparer: IComparer<T>): boolean;
begin
Index := -1;
result := FindNext(Value, Index, AComparer);
end;
function TVectorClass<T>.FindFirst(const Value: T; var Index: integer): boolean;
begin
Index := -1;
result := FindNext(Value, Index, FComparer);
end;
function TVectorClass<T>.FindNext(const Value: T; var Index: integer; AComparer: IComparer<T>): boolean;
var
I: Integer;
begin
FindComparer(AComparer);
for I := Index+1 to Count-1 do
if AComparer.Compare(FItems[I], Value)=0 then
begin
Index := I;
Exit(True);
end;
result := False;
end;
function TVectorClass<T>.FindNext(const Value: T; var Index: integer): boolean;
begin
result := FindNext(Value, Index, FComparer);
end;
procedure TVectorClass<T>.FirstPermutation;
begin
Sort;
end;
function TVectorClass<T>.NextPermutation: boolean;
var
i,x,n: integer;
C: IComparer<T>;
begin
C := Comparer;
FindComparer(C);
{ find max N where A[N] < A[N+1] }
n := -1;
for i := Count-2 downto 0 do
if C.Compare(FItems[i], FItems[i+1]) < 0 then
begin
n := i;
break;
end;
{ if A[N] > A[N+1] for any N then there is no more permutations }
result := n<>-1;
if not result then
exit;
{ let's order range [N+1; FCount-1]
now it has reverse order so just call .reverse }
Reverse(n+1,FCount-n-1);
{ find value next to A[N] in range [N+1; Count-1]
such value exists because at least original A[N+1] > A[N] }
x := -1;
for i := N+1 to Count-1 do
if C.Compare(FItems[i], FItems[N]) > 0 then
begin
x := i;
break;
end;
{ swap A[N] and A[X] }
Exchange(n, x);
{ change position of A[X] to make range [N+1; FCoun-1] ordered again }
i := x;
while (i > n+1) and (C.Compare(FItems[i-1], FItems[x]) > 0) do
dec(i);
while (i < Count-1) and (C.Compare(FItems[x], FItems[i+1]) > 0) do
inc(i);
if i<>x then
Move(x,i);
end;
function TVectorClass<T>.PrevPermutation: boolean;
var
i,x,n: integer;
C: IComparer<T>;
begin
C := Comparer;
FindComparer(C);
{ find max N where A[N] > A[N+1] }
n := -1;
for i := FCount-2 downto 0 do
if C.Compare(FItems[i], FItems[i+1]) > 0 then
begin
n := i;
break;
end;
{ if A[N] > A[N+1] for any N then there is no more permutations }
result := n<>-1;
if not result then
exit;
{ let's order range [N+1; FCoun-1]
now it has reverse order so just call .reverse }
reverse(n+1,FCount-n-1);
{ find value previous to A[N] in range [N+1; FCount-1]
such value exists because at least original A[N+1] < A[N] }
x := -1;
for i := N+1 to FCount-1 do
if C.Compare(FItems[i], FItems[N]) < 0 then
begin
x := i;
break;
end;
{ swap A[N] and A[X] }
Exchange(n,x);
{ change position of A[X] to make range [N+1; FCoun-1] back ordered again }
i := x;
while (i > n+1) and (C.Compare(FItems[i-1], FItems[x]) < 0) do
dec(i);
while (i < FCount-1) and (C.Compare(FItems[x], FItems[i+1]) < 0) do
inc(i);
if i<>x then
Move(x,i);
end;
function TVectorClass<T>.GetItemsArray: TArray<T>;
begin
TrimExcess;
result := FItems;
end;
function TVectorClass<T>.GetCapacity: integer;
begin
result := System.Length(FItems);
end;
function TVectorClass<T>.GetEmpty: boolean;
begin
Result := FCount <= 0;
end;
function TVectorClass<T>.GetFirst: T;
begin
Assert(FCount>0);
Result := FItems[0];
end;
function TVectorClass<T>.GetItem(ItemIndex: integer): T;
begin
Assert((ItemIndex >= 0) and (ItemIndex < Count));
result := FItems[ItemIndex];
end;
function TVectorClass<T>.GetLast: T;
begin
Assert(FCount>0);
Result := FItems[Count-1];
end;
function TVectorClass<T>.GetTotalSizeBytes: int64;
begin
result := (High(FItems)-Low(FItems)+1)*SizeOf(T);
end;
function TVectorClass<T>.IndexOf(const Value: T; AComparer: IComparer<T>): integer;
begin
if not FindFirst(Value, Result, AComparer) then
result := -1;
end;
function TVectorClass<T>.IndexOf(const Value: T): integer;
begin
if not FindFirst(Value, Result) then
result := -1;
end;
function TVectorClass<T>.Insert(Index: integer; const Value: T): integer;
begin
Assert((Index>=0) and (Index<=Count));
for result := Add downto Index+1 do
FItems[result] := FItems[result-1];
result := Index;
FItems[result] := Value;
end;
procedure TVectorClass<T>.Move(SrcIndex, DstIndex: integer);
var
I: integer;
Value: T;
begin
Assert((SrcIndex>=0) and (SrcIndex<Count) and (DstIndex>=0) and (DstIndex<Count));
if SrcIndex < DstIndex then
begin
{ src dst
1 2 [3] 4 [5] 6 7 }
Value := FItems[SrcIndex];
for I := SrcIndex to DstIndex-1 do
FItems[I] := FItems[I+1];
FItems[DstIndex] := Value;
end
else
if SrcIndex > DstIndex then
begin
{ dst src
1 2 [3] 4 [5] 6 7 }
Value := FItems[SrcIndex];
for I := SrcIndex downto DstIndex+1 do
FItems[I] := FItems[I-1];
FItems[DstIndex] := Value;
end;
end;
procedure TVectorClass<T>.FindComparer(var AComparer: IComparer<T>);
begin
if AComparer = nil then
if FComparer <> nil
then AComparer := FComparer
else AComparer := TComparerUtils.DefaultComparer<T>;
end;
procedure TVectorClass<T>.Remove(const V: T; AComparer: IComparer<T> = nil);
var
I,D: Integer;
begin
FindComparer(AComparer);
D := 0;
for I := 0 to FCount-1 do
if AComparer.Compare(FItems[I], V) = 0 then
begin
if FOwnsValues then
PObject(@FItems[I])^.DisposeOf;
end
else
begin
FItems[D] := FItems[I];
inc(D);
end;
for I := D to FCount-1 do
FItems[I] := Default(T);
FCount := D;
end;
procedure TVectorClass<T>.Remove(AFilter: TFuncFilterValueIndex<T>);
var
I,D: Integer;
begin
D := 0;
for I := 0 to FCount-1 do
if AFilter(FItems[I], I) then
begin
if FOwnsValues then
PObject(@FItems[I])^.DisposeOf;
end
else
begin
FItems[D] := FItems[I];
inc(D);
end;
for I := D to FCount-1 do
FItems[I] := Default(T);
FCount := D;
end;
procedure TVectorClass<T>.Remove(const V: TArray<T>; AComparer: IComparer<T> = nil);
var
S: TSliceClass<T>;
I,D: integer;
begin
if (Length(V)=0) or (Count=0) then
Exit;
FindComparer(AComparer);
S := TSliceClass<T>.Create(V);
try
S.Comparer := AComparer;
S.Sort;
D := 0;
for I := 0 to FCount-1 do
if S.BinarySearch(FItems[I]) then
begin
if FOwnsValues then
PObject(@FItems[I])^.DisposeOf;
end
else
begin
FItems[D] := FItems[I];
inc(D);
end;
for I := D to FCount-1 do
FItems[I] := Default(T);
FCount := D;
finally
Sys.FreeAndNil(S);
end;
end;
procedure TVectorClass<T>.Remove(const V: TEnumerable<T>; AComparer: IComparer<T> = nil);
begin
Remove(V.ToArray, AComparer);
end;
procedure TVectorClass<T>.Reverse;
begin
Reverse(0, Count);
end;
procedure TVectorClass<T>.Reverse(AStartIndex,ACount: integer);
var
I: Integer;
Value: T;
begin
if ACount <= 0 then
Exit;
Assert((AStartIndex >= 0) and (AStartIndex + ACount <= Count));
for I := 0 to (ACount shr 1) - 1 do
begin
Value := FItems[AStartIndex+I];
FItems[AStartIndex+I] := FItems[AStartIndex+ACount-1-I];
FItems[AStartIndex+ACount-1-I] := Value;
end;
end;
procedure TVectorClass<T>.RotateLeft(Index1, Index2, Shift: integer);
var
I: integer;
begin
Assert((Index1>=0) and (Index1<Count) and (Index2>=0) and (Index2<Count));
if Index2 < Index1 then
begin
I := Index1;
Index1 := Index2;
Index2 := I;
end;
I := Index2-Index1+1;
Shift := (I - (Shift mod I)) mod I;
if Shift <= 0 then
if Shift < 0 then
Inc(Shift, I)
else
Exit;
Reverse(Index1, Index2-Index1+1);
Reverse(Index1, Shift);
Reverse(Index1+Shift, Index2-Index1+1-Shift);
end;
procedure TVectorClass<T>.RotateRight(Index1, Index2, Shift: integer);
var
I: integer;
begin
Assert((Index1>=0) and (Index1<Count) and (Index2>=0) and (Index2<Count));
if Index2 < Index1 then
begin
I := Index1;
Index1 := Index2;
Index2 := I;
end;
I := Index2-Index1+1;
Shift := Shift mod I;
if Shift <= 0 then
if Shift < 0 then
Inc(Shift, I)
else
Exit;
Reverse(Index1, Index2-Index1+1);
Reverse(Index1, Shift);
Reverse(Index1+Shift, Index2-Index1+1-Shift);
end;
procedure TVectorClass<T>.SetItemsArray(const Value: TArray<T>);
begin
Clear; { to properly destroy items }
FItems := Value;
FCount := System.Length(FItems);
end;
procedure TVectorClass<T>.SetCapacity(const Value: integer);
begin
Assert(Value>=Count);
SetLength(FItems, Value);
end;
procedure TVectorClass<T>.SetComparer(AComparer: IComparer<T>);
begin
if AComparer=nil
then FComparer := TComparerUtils.DefaultComparer<T>
else FComparer := AComparer;
end;
procedure TVectorClass<T>.SetComparison(AComparison: TComparison<T>);
begin
if not Assigned(AComparison)
then FComparer := TComparerUtils.DefaultComparer<T>
else FComparer := TDelegatedComparer<T>.Create(AComparison);
end;
procedure TVectorClass<T>.SetCount(const Value: integer);
var
I: Integer;
begin
Assert(Value>=0);
if not FOwnsValues then
for I := Value to Count-1 do
FItems[I] := Default(T)
else
for I := Value to Count-1 do
begin
PObject(@FItems[I])^.DisposeOf;
FItems[I] := Default(T)
end;
FCount := Value;
if Value > Capacity then
Capacity := Value;
end;
procedure TVectorClass<T>.SetItem(ItemIndex: integer; const Value: T);
begin
Assert((ItemIndex >= 0) and (ItemIndex < Count));
if FOwnsValues then
PObject(@FItems[ItemIndex])^.DisposeOf;
FItems[ItemIndex] := Value;
end;
procedure TVectorClass<T>.SetFirst(const Value: T);
begin
Assert(Count>0);
if FOwnsValues then
PObject(@FItems[0])^.DisposeOf;
FItems[0] := Value;
end;
procedure TVectorClass<T>.SetLast(const Value: T);
begin
Assert(Count>0);
if FOwnsValues then
PObject(@FItems[Count-1])^.DisposeOf;
FItems[Count-1] := Value;
end;
procedure TVectorClass<T>.SetOwnsValues(const Value: boolean);
begin
if Value and not TRttiUtils.IsInstance<T> then
raise Exception.Create('Generic type is not a class.');
FOwnsValues := Value;
end;
procedure TVectorClass<T>.Shuffle;
begin
Shuffle(0, Count);
end;
procedure TVectorClass<T>.Shuffle(AStartIndex,ACount: integer);
var
I: Integer;
begin
if ACount <= 1 then
Exit;
Assert((AStartIndex >= 0) and (AStartIndex + ACount <= Count));
for I := ACount-1 downto 1 do
Exchange(I+AStartIndex, Random(I+1)+AStartIndex);
end;
procedure TVectorClass<T>.Sort(AComparer: IComparer<T> = nil);
begin
Sort(0, Count, AComparer);
end;
procedure TVectorClass<T>.Sort(AIndex, ACount: Integer; AComparer: IComparer<T> = nil);
begin
FindComparer(AComparer);
TArray.Sort<T>(FItems, AComparer, AIndex, ACount);
end;
procedure TVectorClass<T>.Sort(AComparer: TFuncCompareValues<T>);
begin
Sort(0, Count, AComparer);
end;
procedure TVectorClass<T>.Sort(AIndex, ACount: Integer; AComparer: TFuncCompareValues<T>);
var
C: IComparer<T>;
begin
C := TDelegatedComparer<T>.Create(
function (const A,B: T): integer
begin
result := AComparer(A,B);
end);
TArray.Sort<T>(FItems, C, AIndex, ACount);
end;
function TVectorClass<T>.Sorted: boolean;
begin
result := Sorted(0, Count, FComparer);
end;
function TVectorClass<T>.Sorted(AStartIndex, ACount: integer; AComparison: TComparison<T>): boolean;
begin
if Assigned(AComparison)
then result := Sorted(AStartIndex, ACount, TDelegatedComparer<T>.Create(AComparison))
else result := Sorted(AStartIndex, ACount, FComparer);
end;
function TVectorClass<T>.Sorted(AStartIndex, ACount: integer; AComparer: IComparer<T>): boolean;
begin
FindComparer(AComparer);
result := TArrayUtils.Sorted<T>(FItems, AStartIndex, ACount, AComparer);
end;
function TVectorClass<T>.ToArray: TArray<T>;
var
I: Integer;
begin
SetLength(Result, FCount);
for I := 0 to FCount-1 do
Result[I] := FItems[I];
end;
function TVectorClass<T>.ToArray(Readonly: boolean): TArray<T>;
begin
if not Readonly then
result := ToArray
else
begin
TrimExcess;
result := FItems;
end;
end;
function TVectorClass<T>.ToString: string;
begin
result := ToString(' ', False);
end;
function TVectorClass<T>.ToString(const ValueSeparator: string; SepAfterLastValue: boolean): string;
var
Buf: TStringBuffer;
I: Integer;
begin
Buf.Clear;
if Count > 0 then
Buf.Write(TRttiUtils.ValueAsString<T>(FItems[0]));
for I := 1 to Count-1 do
Buf.Write(ValueSeparator + TRttiUtils.ValueAsString<T>(FItems[I]));
if (Count > 0) and SepAfterLastValue then
Buf.Write(ValueSeparator);
Result := Buf.Text;
end;
function TVectorClass<T>.ToText: string;
begin
result := ToString(#13#10, False);
end;
procedure TVectorClass<T>.TrimExcess;
begin
if Capacity>Count then
Capacity := Count;
end;
{ TVector<T> }
class function TVector<T>.Create(AComparer: IComparer<T> = nil): TVector<T>;
begin
Result.Init(AComparer);
end;
class function TVector<T>.Create(ACapacity: integer; AComparer: IComparer<T>): TVector<T>;
begin
Result.Init(ACapacity, AComparer);
end;
class function TVector<T>.Create(AComparer: TComparison<T>): TVector<T>;
begin
Result.Init(AComparer);
end;
class function TVector<T>.Create(const Values: TEnumerable<T>; ACapacity: integer; AComparer: IComparer<T>): TVector<T>;
begin
Result.Init(Values, ACapacity, AComparer);
end;
class function TVector<T>.Create(const Values: TArray<T>; AComparer: IComparer<T>): TVector<T>;
begin
Result.Init(Values, AComparer);
end;
procedure TVector<T>.Init(AComparer: IComparer<T>);
begin
Self := Default(TVector<T>);
if AComparer<>nil then
CreateVector(0, AComparer);
end;
procedure TVector<T>.Init(ACapacity: integer; AComparer: IComparer<T>);
begin
Self := Default(TVector<T>);
if (ACapacity > 0) or (AComparer<>nil) then
CreateVector(ACapacity, AComparer);
end;
procedure TVector<T>.Init(AComparer: TComparison<T>);
begin
Self := Default(TVector<T>);
CreateVector(0, TDelegatedComparer<T>.Create(AComparer));
end;
procedure TVector<T>.Init(const Values: TEnumerable<T>; ACapacity: integer; AComparer: IComparer<T>);
begin
Self := Default(TVector<T>);
CreateVector(ACapacity, AComparer);
Add(Values);
end;
procedure TVector<T>.Init(const Values: TArray<T>; AComparer: IComparer<T>);
begin
Self := Default(TVector<T>);
CreateVector(System.Length(Values), AComparer);
Add(Values);
end;
procedure TVector<T>.CreateVector(ACapacity: integer; AComparer: IComparer<T>);
begin
FVectorInt := TInterfacedObject<TVectorClass<T>>.Create( TVectorClass<T>.Create(AComparer) );
FVectorInt.Data.Capacity := ACapacity;
end;
class operator TVector<T>.Add(a: TVector<T>; const b: TEnumerable<T>): TVector<T>;
begin
result.Clear;
result.Add(A);
result.Add(B);
end;
class operator TVector<T>.Add(a: TVector<T>; const b: TArray<T>): TVector<T>;
begin
result.Clear;
result.Add(A);
result.Add(B);
end;
class operator TVector<T>.Add(a, b: TVector<T>): TVector<T>;
begin
result.Clear;
result.Add(A);
result.Add(B);
end;
class operator TVector<T>.Add(const a: TEnumerable<T>; b: TVector<T>): TVector<T>;
begin
result.Clear;
result.Add(A);
result.Add(B);
end;
function TVector<T>.BinarySearch(const Item: T; out FoundIndex: Integer; AComparer: IComparer<T>): Boolean;
begin
result := RO.BinarySearch(Item, FoundIndex, AComparer);
end;
function TVector<T>.BinarySearch(const Item: T; out FoundIndex: Integer; AStartIndex, ACount: Integer;
AComparer: IComparer<T>): Boolean;
begin
result := RO.BinarySearch(Item, FoundIndex, AStartIndex, ACount, AComparer);
end;
class operator TVector<T>.Add(const a: TArray<T>; b: TVector<T>): TVector<T>;
begin
result.Clear;
result.Add(A);
result.Add(B);
end;
class operator TVector<T>.Add(const a: T; b: TVector<T>): TVector<T>;
begin
result.Clear;
result.Add(A);
result.Add(B);
end;
procedure TVector<T>.Add(const Values: TArray<T>);
begin
RW.Add(Values);
end;
procedure TVector<T>.Add(const Values: TArray<T>; AStartIndex,ACount: integer);
begin
RW.Add(Values,AStartIndex,ACount);
end;
function TVector<T>.Add(const Value: T): integer;
begin
result := RW.Add(Value);
end;
function TVector<T>.Add: integer;
begin
result := RW.Add;
end;
class operator TVector<T>.Add(a: TVector<T>; const b: T): TVector<T>;
begin
result.Clear;
result.Add(A);
result.Add(B);
end;
procedure TVector<T>.Add(Values: TVector<T>);
var
Src: TVectorClass<T>;
begin
if Values.FVectorInt = nil then
Exit;
Src := Values.RO;
RW.Add(Src.FItems, 0, Src.Count);
end;
procedure TVector<T>.Add(const Values: TEnumerable<T>);
begin
RW.Add(Values);
end;
procedure TVector<T>.Clear;
begin
RW.Clear;
end;
function TVector<T>.Compare(const B: TArray<T>; AComparer: IComparer<T> = nil): integer;
begin
result := RO.Compare(B, AComparer);
end;
function TVector<T>.Compare(const B: TArray<T>; AStartIndex, BStartIndex, ACount: integer;
AComparer: IComparer<T>): integer;
begin
result := RO.Compare(B, AStartIndex, BStartIndex, ACount, AComparer);
end;
function TVector<T>.Compare(B: TEnumerable<T>; AStartIndex, BStartIndex, ACount: integer;
AComparer: IComparer<T>): integer;
begin
result := RO.Compare(B, AStartIndex, BStartIndex, ACount, AComparer);
end;
function TVector<T>.Compare(B: TEnumerable<T>; AComparer: IComparer<T> = nil): integer;
begin
result := RO.Compare(B, AComparer);
end;
function TVector<T>.Contains(const Values: TArray<T>): boolean;
begin
result := RO.Contains(Values);
end;
function TVector<T>.Contains(const Values: TEnumerable<T>): boolean;
begin
result := RO.Contains(Values);
end;
function TVector<T>.Contains(const Value: T): boolean;
begin
result := RO.Contains(Value);
end;
function TVector<T>.Copy: TVector<T>;
begin
result.Init(Comparer);
result.Add(Self);
end;
procedure TVector<T>.Delete(const AIndices: TArray<integer>);
begin
RW.Delete(AIndices);
end;
procedure TVector<T>.Delete(ItemIndex: integer);
begin
RW.Delete(ItemIndex);
end;
procedure TVector<T>.Delete(AStartIndex, ACount: integer);
begin
RW.Delete(AStartIndex, ACount);
end;
procedure TVector<T>.DeleteLast;
begin
RW.DeleteLast;
end;
class operator TVector<T>.Equal(a: TVector<T>; const b: TArray<T>): Boolean;
begin
result := A.Equal(B);
end;
class operator TVector<T>.Equal(a, b: TVector<T>): Boolean;
begin
result := A.Equal(B.Collection);
end;
function TVector<T>.Equal(B: TEnumerable<T>): boolean;
begin
result := RO.Equal(B);
end;
class operator TVector<T>.Equal(a: TVector<T>; const b: TEnumerable<T>): Boolean;
begin
result := A.Equal(B);
end;
function TVector<T>.Equal(const B: TArray<T>): boolean;
begin
result := RO.Equal(B);
end;
procedure TVector<T>.Exchange(Index1, Index2: integer);
begin
RW.Exchange(Index1, Index2);
end;
class operator TVector<T>.Explicit(const a: TArray<T>): TVector<T>;
begin
result.Clear;
result.Add(A);
end;
class operator TVector<T>.Explicit(const a: T): TVector<T>;
begin
result.Clear;
result.Add(A);
end;
class operator TVector<T>.Explicit(const a: TEnumerable<T>): TVector<T>;
begin
result.Clear;
result.Add(A);
end;
function TVector<T>.Extract(ItemIndex: integer): T;
begin
result := RW.Extract(ItemIndex);
end;
function TVector<T>.ExtractAll: TArray<T>;
begin
result := RW.ExtractAll;
end;
function TVector<T>.ExtractLast: T;
begin
result := RW.ExtractLast;
end;
function TVector<T>.FindFirst(const Value: T; var Index: integer): boolean;
begin
result := RO.FindFirst(Value, Index);
end;
function TVector<T>.FindFirst(const Value: T; var Index: integer; AComparer: IComparer<T>): boolean;
begin
result := RO.FindFirst(Value, Index, AComparer);
end;
function TVector<T>.FindNext(const Value: T; var Index: integer): boolean;
begin
result := RO.FindNext(Value, Index);
end;
function TVector<T>.FindNext(const Value: T; var Index: integer; AComparer: IComparer<T>): boolean;
begin
result := RO.FindNext(Value, Index, AComparer);
end;
procedure TVector<T>.FirstPermutation;
begin
RW.FirstPermutation;
end;
function TVector<T>.GetItemsArray: TArray<T>;
begin
result := RW.ItemsArray;
end;
function TVector<T>.GetCapacity: integer;
begin
result := RO.Capacity;
end;
function TVector<T>.GetCollection: TEnumerable<T>;
begin
result := RO;
end;
function TVector<T>.GetComparer: IComparer<T>;
begin
result := RO.Comparer;
end;
function TVector<T>.GetCount: integer;
begin
result := RO.Count;
end;
function TVector<T>.GetEmpty: Boolean;
begin
result := RO.Empty;
end;
function TVector<T>.GetEnumerator: TEnumerator<T>;
begin
result := RO.GetEnumerator;
end;
function TVector<T>.GetFirst: T;
begin
result := RO.First;
end;
function TVector<T>.GetItem(ItemIndex: integer): T;
begin
result := RO[ItemIndex];
end;
function TVector<T>.GetLast: T;
begin
result := RO.Last;
end;
function TVector<T>.GetOwnsValues: boolean;
begin
result := RO.OwnsValues;
end;
function TVector<T>.GetRO: TVectorClass<T>;
begin
if FVectorInt=nil then
CreateVector;
result := FVectorInt.Data;
end;
function TVector<T>.GetRW: TVectorClass<T>;
var
SrcVectorInt: IInterfacedObject<TVectorClass<T>>;
begin
if FVectorInt=nil then
CreateVector
else
if FVectorInt.GetRefCount<>1 then
begin
{ Copy on write }
SrcVectorInt := FVectorInt;
CreateVector(SrcVectorInt.Data.Count, SrcVectorInt.Data.Comparer);
FVectorInt.Data.Add(SrcVectorInt.Data);
FVectorInt.Data.OwnsValues := SrcVectorInt.Data.OwnsValues;
end;
result := FVectorInt.Data;
end;
function TVector<T>.GetTotalSizeBytes: int64;
begin
result := RO.TotalSizeBytes;
end;
class operator TVector<T>.GreaterThan(a: TVector<T>; const b: TEnumerable<T>): Boolean;
begin
result := A.Compare(B) > 0;
end;
class operator TVector<T>.GreaterThan(a, b: TVector<T>): Boolean;
begin
result := A.Compare(B.Collection) > 0;
end;
class operator TVector<T>.GreaterThan(a: TVector<T>; const b: TArray<T>): Boolean;
begin
result := A.Compare(B) > 0;
end;
class operator TVector<T>.GreaterThanOrEqual(a: TVector<T>; const b: TEnumerable<T>): Boolean;
begin
result := A.Compare(B) >= 0;
end;
class operator TVector<T>.GreaterThanOrEqual(a: TVector<T>; const b: TArray<T>): Boolean;
begin
result := A.Compare(B) >= 0;
end;
class operator TVector<T>.GreaterThanOrEqual(a, b: TVector<T>): Boolean;
begin
result := A.Compare(B.Collection) >= 0;
end;
class operator TVector<T>.Implicit(const a: TEnumerable<T>): TVector<T>;
begin
result.Clear;
result.Add(A);
end;
class operator TVector<T>.Implicit(const a: T): TVector<T>;
begin
result.Clear;
result.Add(A);
end;
class operator TVector<T>.Implicit(const a: TArray<T>): TVector<T>;
begin
result.Clear;
result.Add(A);
end;
class operator TVector<T>.In(const a: TArray<T>; b: TVector<T>): Boolean;
begin
result := B.Contains(A);
end;
class operator TVector<T>.In(const a: TEnumerable<T>; b: TVector<T>): Boolean;
begin
result := B.Contains(A);
end;
class operator TVector<T>.In(const a: T; b: TVector<T>): Boolean;
begin
result := B.Contains(A);
end;
class operator TVector<T>.In(a, b: TVector<T>): Boolean;
begin
result := B.Contains(A.Collection);
end;
function TVector<T>.IndexOf(const Value: T; AComparer: IComparer<T>): integer;
begin
result := RO.IndexOf(Value, AComparer);
end;
function TVector<T>.IndexOf(const Value: T): integer;
begin
result := RO.IndexOf(Value);
end;
function TVector<T>.Insert(Index: integer; const Value: T): integer;
begin
result := RW.Insert(Index, Value);
end;
class operator TVector<T>.LessThan(a: TVector<T>; const b: TEnumerable<T>): Boolean;
begin
result := A.Compare(B) < 0;
end;
class operator TVector<T>.LessThan(a: TVector<T>; const b: TArray<T>): Boolean;
begin
result := A.Compare(B) < 0;
end;
class operator TVector<T>.LessThan(a, b: TVector<T>): Boolean;
begin
result := A.Compare(B.Collection) < 0;
end;
class operator TVector<T>.LessThanOrEqual(a: TVector<T>; const b: TEnumerable<T>): Boolean;
begin
result := A.Compare(B) <= 0;
end;
class operator TVector<T>.LessThan(const b: TArray<T>; a: TVector<T>): Boolean;
begin
result := A.Compare(B) > 0;
end;
class operator TVector<T>.LessThan(const b: TEnumerable<T>; a: TVector<T>): Boolean;
begin
result := A.Compare(B) > 0;
end;
class operator TVector<T>.LessThanOrEqual(const b: TEnumerable<T>; a: TVector<T>): Boolean;
begin
result := A.Compare(B) >= 0;
end;
class operator TVector<T>.LessThanOrEqual(a, b: TVector<T>): Boolean;
begin
result := A.Compare(B.Collection) <= 0;
end;
class operator TVector<T>.LessThanOrEqual(a: TVector<T>; const b: TArray<T>): Boolean;
begin
result := A.Compare(B) <= 0;
end;
class operator TVector<T>.LessThanOrEqual(const b: TArray<T>; a: TVector<T>): Boolean;
begin
result := A.Compare(B) >= 0;
end;
procedure TVector<T>.Move(SrcIndex, DstIndex: integer);
begin
RW.Move(SrcIndex, DstIndex);
end;
function TVector<T>.NextPermutation: boolean;
begin
result := RW.NextPermutation;
end;
class operator TVector<T>.NotEqual(const b: TArray<T>; a: TVector<T>): Boolean;
begin
result := not A.Equal(B);
end;
class operator TVector<T>.NotEqual(const b: TEnumerable<T>; a: TVector<T>): Boolean;
begin
result := not A.Equal(B);
end;
class operator TVector<T>.NotEqual(a, b: TVector<T>): Boolean;
begin
result := not A.Equal(B.Collection);
end;
class operator TVector<T>.NotEqual(a: TVector<T>; const b: TArray<T>): Boolean;
begin
result := not A.Equal(B);
end;
class operator TVector<T>.NotEqual(a: TVector<T>; const b: TEnumerable<T>): Boolean;
begin
result := not A.Equal(B);
end;
function TVector<T>.PrevPermutation: boolean;
begin
result := RW.PrevPermutation;
end;
procedure TVector<T>.Remove(const V: T; AComparer: IComparer<T> = nil);
begin
RW.Remove(V, AComparer);
end;
procedure TVector<T>.Remove(const V: TArray<T>; AComparer: IComparer<T> = nil);
begin
RW.Remove(V, AComparer);
end;
procedure TVector<T>.Remove(const V: TEnumerable<T>; AComparer: IComparer<T> = nil);
begin
RW.Remove(V, AComparer);
end;
procedure TVector<T>.Reverse;
begin
RW.Reverse;
end;
procedure TVector<T>.Reverse(AStartIndex,ACount: integer);
begin
RW.Reverse(AStartIndex,ACount);
end;
procedure TVector<T>.RotateLeft(Index1, Index2, Shift: integer);
begin
RW.RotateLeft(Index1, Index2, Shift);
end;
procedure TVector<T>.RotateRight(Index1, Index2, Shift: integer);
begin
RW.RotateRight(Index1, Index2, Shift);
end;
procedure TVector<T>.SaveToFile(const FileName: string; Encoding: TEncoding; MemStream: boolean);
begin
RO.SaveToFile(FileName, Encoding, MemStream);
end;
procedure TVector<T>.SaveToStream(Dst: TStream; Encoding: TEncoding);
begin
RO.SaveToStream(Dst, Encoding);
end;
procedure TVector<T>.SetCapacity(const Value: integer);
begin
RW.Capacity := Value;
end;
procedure TVector<T>.SetComparer(Value: IComparer<T>);
begin
RW.Comparer := Value;
end;
procedure TVector<T>.SetCount(const Value: integer);
begin
RW.Count := Value;
end;
procedure TVector<T>.SetFirst(const Value: T);
begin
RW.First := Value;
end;
procedure TVector<T>.SetItem(ItemIndex: integer; const Value: T);
begin
RW[ItemIndex] := Value;
end;
procedure TVector<T>.SetItemsArray(const Value: TArray<T>);
begin
RW.ItemsArray := Value;
end;
procedure TVector<T>.SetLast(const Value: T);
begin
RW.Last := Value;
end;
procedure TVector<T>.SetOwnsValues(AOwnsValues: boolean);
begin
RW.OwnsValues := AOwnsValues;
end;
procedure TVector<T>.Shuffle;
begin
RW.Shuffle;
end;
procedure TVector<T>.Shuffle(AStartIndex,ACount: integer);
begin
RW.Shuffle(AStartIndex,ACount);
end;
procedure TVector<T>.Sort(AIndex, ACount: Integer; AComparer: IComparer<T>);
begin
RW.Sort(AIndex, ACount, AComparer);
end;
procedure TVector<T>.Sort(AComparer: IComparer<T>);
begin
RW.Sort(AComparer);
end;
procedure TVector<T>.Sort(AIndex, ACount: Integer; AComparer: TFuncCompareValues<T>);
begin
RW.Sort(AIndex, ACount, AComparer);
end;
procedure TVector<T>.Sort(AComparer: TFuncCompareValues<T>);
begin
RW.Sort(AComparer);
end;
class operator TVector<T>.Subtract(const a: TEnumerable<T>; b: TVector<T>): TVector<T>;
begin
result.Clear;
result.Add(A);
result.Remove(B.Collection);
end;
class operator TVector<T>.Subtract(a: TVector<T>; const b: TArray<T>): TVector<T>;
begin
result.Clear;
result.Add(A);
result.Remove(B);
end;
class operator TVector<T>.Subtract(a, b: TVector<T>): TVector<T>;
begin
result.Clear;
result.Add(A);
result.Remove(B.Collection);
end;
class operator TVector<T>.Subtract(a: TVector<T>; const b: T): TVector<T>;
begin
result.Clear;
result.Add(A);
result.Remove(B);
end;
class operator TVector<T>.Subtract(const a: TArray<T>; b: TVector<T>): TVector<T>;
begin
result.Clear;
result.Add(A);
result.Remove(B.Collection);
end;
class operator TVector<T>.Subtract(const a: T; b: TVector<T>): TVector<T>;
begin
result.Clear;
result.Add(A);
result.Remove(B.Collection);
end;
class operator TVector<T>.Subtract(a: TVector<T>; const b: TEnumerable<T>): TVector<T>;
begin
result.Clear;
result.Add(A);
result.Remove(B);
end;
function TVector<T>.ToArray(ReadOnly: boolean): TArray<T>;
begin
result := RO.ToArray(ReadOnly);
end;
function TVector<T>.ToString: string;
begin
result := RO.ToString;
end;
function TVector<T>.ToString(const ValueSeparator: string; SepAfterLastValue: boolean): string;
begin
result := RO.ToString(ValueSeparator, SepAfterLastValue);
end;
function TVector<T>.ToText: string;
begin
result := RO.ToText;
end;
procedure TVector<T>.TrimExcess;
begin
RW.TrimExcess;
end;
class operator TVector<T>.Implicit(a: TVector<T>): TEnumerable<T>;
begin
result := a.Collection;
end;
class operator TVector<T>.Explicit(a: TVector<T>): TEnumerable<T>;
begin
result := a.Collection;
end;
class operator TVector<T>.Equal(const b: TArray<T>; a: TVector<T>): Boolean;
begin
result := A.Equal(B);
end;
class operator TVector<T>.Equal(const b: TEnumerable<T>; a: TVector<T>): Boolean;
begin
result := A.Equal(B);
end;
class operator TVector<T>.GreaterThanOrEqual(const b: TArray<T>; a: TVector<T>): Boolean;
begin
result := A.Compare(B) <= 0;
end;
class operator TVector<T>.GreaterThanOrEqual(const b: TEnumerable<T>; a: TVector<T>): Boolean;
begin
result := A.Compare(B) <= 0;
end;
class operator TVector<T>.GreaterThan(const b: TArray<T>; a: TVector<T>): Boolean;
begin
result := A.Compare(B) < 0;
end;
class operator TVector<T>.GreaterThan(const b: TEnumerable<T>; a: TVector<T>): Boolean;
begin
result := A.Compare(B) < 0;
end;
procedure TVector<T>.Remove(AFilter: TFuncFilterValueIndex<T>);
begin
RW.Remove(AFilter);
end;
{ TVector2D<T>.TCollectionEnumerator }
constructor TVector2D<T>.TEnumerator.Create(const Rows: TArr<TArr<T>>);
begin
inherited Create;
Self.Rows := Rows;
X := -1;
Y := 0;
end;
function TVector2D<T>.TEnumerator.DoMoveNext: Boolean;
begin
if Y >= Rows.Count then
Exit(False);
inc(X);
if X < Rows[Y].Count then
Exit(True);
repeat
inc(Y);
if Y >= Rows.Count then
Exit(False);
until Rows[Y].Count > 0;
X := 0;
Result := True;
end;
function TVector2D<T>.TEnumerator.DoGetCurrent: T;
begin
result := Rows[Y][X];
end;
{ TVector2D<T>.TCollection }
constructor TVector2D<T>.TCollection.Create(const Rows: TArr<TArr<T>>);
begin
inherited Create;
Self.Rows := Rows;
end;
function TVector2D<T>.TCollection.DoGetEnumerator: TEnumerator<T>;
begin
result := TEnumerator.Create(Rows);
end;
{ TVector2D<T> }
procedure TVector2D<T>.Init(Width, Height: integer);
var
Y: integer;
V: TArr<T>;
begin
Self := Default(TVector2D<T>);
Rows := TArr<TArr<T>>.Create(Height);
Rows.Count := Height;
for Y := 0 to Height-1 do
begin
Rows[Y] := TArr<T>.Create(Width);
Rows.Items[Y].Count := Width;
end;
end;
procedure TVector2D<T>.Clear;
begin
Self := Default(TVector2D<T>);
end;
function TVector2D<T>.Collection: IInterfacedObject<TEnumerable<T>>;
begin
result := TInterfacedObject<TEnumerable<T>>.Create(TCollection.Create(Rows));
end;
function TVector2D<T>.Add(y: integer): integer;
begin
result := Rows.Items[y].Add;
end;
function TVector2D<T>.Add(y: integer; const Value: T): integer;
begin
result := Rows.Items[y].Add(Value);
end;
function TVector2D<T>.Add(y: integer; const Values: TEnumerable<T>): integer;
var
Value: T;
begin
result := -1;
for Value in Values do
result := Self.Rows.Items[y].Add(Value);
end;
function TVector2D<T>.Add(y: integer; const Values: TArray<T>): integer;
var
I: Integer;
begin
result := -1;
for I := Low(Values) to High(Values) do
result := Self.Rows.Items[y].Add(Values[I]);
end;
function TVector2D<T>.AddRow: integer;
begin
result := Rows.Add;
end;
function TVector2D<T>.GetValue(x, y: integer): T;
begin
result := Rows.Items[y].Items[x];
end;
procedure TVector2D<T>.SetValue(x, y: integer; const Value: T);
begin
Rows.Items[y].Items[x] := Value;
end;
function TVector2D<T>.GetRowCount: integer;
begin
result := Rows.Count;
end;
procedure TVector2D<T>.SetRowCount(const Value: integer);
begin
Rows.Count := Value;
end;
function TVector2D<T>.GetWidth(y: integer): integer;
begin
result := Rows.Items[y].Count;
end;
procedure TVector2D<T>.SetWidth(y: integer; const Value: integer);
begin
Rows.Items[y].Count := Value;
end;
{ TSlice<T> }
procedure TSlice<T>.Init(const ASrc: TArray<T>; AComparison: TComparison<T>);
begin
{$If SizeOf(TSlice<pointer>)<>SizeOf(IInterfacedObject<TSliceClass<pointer>>)}
Self := Default(TSlice<T>);
{$EndIf}
FSliceInt := TInterfacedObject<TSliceClass<T>>.Create( TSliceClass<T>.Create(ASrc, AComparison) );
end;
procedure TSlice<T>.Init(const ASrc: TArray<T>; AStartIndex, ACount: integer; AComparison: TComparison<T>);
begin
{$If SizeOf(TSlice<pointer>)<>SizeOf(IInterfacedObject<TSliceClass<pointer>>)}
Self := Default(TSlice<T>);
{$EndIf}
FSliceInt := TInterfacedObject<TSliceClass<T>>.Create( TSliceClass<T>.Create(ASrc, AStartIndex, ACount, AComparison) );
end;
procedure TSlice<T>.Init(const ASrc: TArray<T>; AFilter: TFuncFilterValueIndex<T>; AComparison: TComparison<T>);
begin
{$If SizeOf(TSlice<pointer>)<>SizeOf(IInterfacedObject<TSliceClass<pointer>>)}
Self := Default(TSlice<T>);
{$EndIf}
FSliceInt := TInterfacedObject<TSliceClass<T>>.Create( TSliceClass<T>.Create(ASrc, AFilter, AComparison) );
end;
class function TSlice<T>.Create(const ASrc: TArray<T>; AComparison: TComparison<T>): TSlice<T>;
begin
result.Init(ASrc, AComparison);
end;
class function TSlice<T>.Create(const ASrc: TArray<T>; AStartIndex, ACount: integer; AComparison: TComparison<T>): TSlice<T>;
begin
result.Init(ASrc, AStartIndex, ACount, AComparison);
end;
class function TSlice<T>.Create(const ASrc: TArray<T>; AFilter: TFuncFilterValueIndex<T>; AComparison: TComparison<T>): TSlice<T>;
begin
result.Init(ASrc, AFilter, AComparison);
end;
procedure TSlice<T>.Clear;
begin
{ we can't assign Default() here, because we will loose comparer }
RW.Clear;
end;
function TSlice<T>.BinarySearch(const Value: T): boolean;
begin
result := RO.BinarySearch(Value);
end;
function TSlice<T>.BinarySearch(const Value: T; out FoundIndex: integer): boolean;
begin
result := RO.BinarySearch(Value, FoundIndex);
end;
function TSlice<T>.GetComparer: IComparer<T>;
begin
result := RO.Comparer;
end;
function TSlice<T>.GetCount: integer;
begin
result := RO.Count;
end;
function TSlice<T>.GetEnumerator: TEnumerator<T>;
begin
result := RO.GetEnumerator;
end;
function TSlice<T>.GetReadonly: TSliceClass<T>;
begin
{ we can't do anything useful with a slice if it doesn't have values assigned }
Assert(FSliceInt<>nil);
{if FSliceInt=nil then
FSliceInt := TInterfacedObject<TSliceClass<T>>.Create( TSliceClass<T>.Create );}
result := FSliceInt.Data;
end;
function TSlice<T>.GetReadWrite: TSliceClass<T>;
var
SrcSliceInt: IInterfacedObject<TSliceClass<T>>;
begin
{ we can't do anything useful with a slice if it doesn't have values assigned }
Assert(FSliceInt<>nil);
{ if FSliceInt=nil then
FSliceInt := TInterfacedObject<TSliceClass<T>>.Create( TSliceClass<T>.Create )
else}
if FSliceInt.GetRefCount<>1 then
begin
{ Copy on write }
SrcSliceInt := FSliceInt;
FSliceInt := TInterfacedObject<TSliceClass<T>>.Create( SrcSliceInt.Data.Copy );
end;
result := FSliceInt.Data;
end;
function TSlice<T>.GetSliceIndex(SliceIndex: integer): integer;
begin
result := RO.Indices[SliceIndex];
end;
function TSlice<T>.GetValue(SliceIndex: integer): T;
begin
result := RO.Values[SliceIndex];
end;
procedure TSlice<T>.SetComparer(const Value: IComparer<T>);
begin
RW.Comparer := Value;
end;
procedure TSlice<T>.SetComparison(AComparison: TComparison<T>);
begin
RW.Comparison := AComparison;
end;
procedure TSlice<T>.SetCount(const Value: integer);
begin
RW.Count := Value;
end;
procedure TSlice<T>.SetSliceIndex(SliceIndex: integer; const Value: integer);
begin
RW.Indices[SliceIndex] := Value;
end;
procedure TSlice<T>.SetValue(SliceIndex: integer; const Value: T);
begin
RW.Values[SliceIndex] := Value;
end;
function TSlice<T>.Copy: TSlice<T>;
begin
result.Init(RO.FValues);
result.Comparer := RO.Comparer;
end;
function TSlice<T>.Copy(AStartIndex, ACount: integer): TSlice<T>;
begin
result.Init(RO.FValues, AStartIndex, ACount);
result.Comparer := RO.Comparer;
end;
function TSlice<T>.Copy(AFilter: TFuncFilterValueIndex<T>): TSlice<T>;
begin
result.Init(RO.FValues, AFilter);
result.Comparer := RO.Comparer;
end;
procedure TSlice<T>.Sort;
begin
RW.Sort;
end;
end.
|
(* NPC stats and setup *)
unit entities;
{$mode objfpc}{$H+}
{$ModeSwitch advancedrecords}
{$RANGECHECKS OFF}
interface
uses
Graphics, SysUtils, map, globalutils, ui, items,
(* Import item-style entities *)
barrel,
(* Import the NPC's *)
cave_rat, hyena, cave_bear, green_fungus;
type
(* Store information about NPC's *)
{ Creature }
Creature = record
(* Unique ID *)
npcID: smallint;
(* Creature type *)
race: shortstring;
(* Description of creature *)
description: string;
(* health and position on game map *)
currentHP, maxHP, attack, defense, posX, posY, targetX, targetY,
xpReward, visionRange: smallint;
(* Weapon stats *)
weaponDice, weaponAdds: smallint;
(* Character used to represent NPC on game map *)
glyph: char;
(* Size of NPC *)
NPCsize: smallint;
(* Number of turns the entity will track the player when they're out of sight *)
trackingTurns: smallint;
(* Count of turns the entity will keep tracking the player when they're out of sight *)
moveCount: smallint;
(* Is the NPC in the players FoV *)
inView: boolean;
(* First time the player discovers the NPC *)
discovered: boolean;
(* Some entities block movement, i.e. barrels *)
blocks: boolean;
(* Is a weapon equipped *)
weaponEquipped: boolean;
(* Is Armour equipped *)
armourEquipped: boolean;
(* Has the NPC been killed, to be removed at end of game loop *)
isDead: boolean;
(* Whether a special ability has been activated *)
abilityTriggered: boolean;
(* status effects *)
stsDrunk, stsPoison: boolean;
(* status timers *)
tmrDrunk, tmrPoison: smallint;
(* The procedure that allows each NPC to take a turn *)
procedure entityTakeTurn(i: smallint);
end;
var
entityList: array of Creature;
npcAmount, listLength: smallint;
playerGlyph, caveRatGlyph, hyenaGlyph, caveBearGlyph, barrelGlyph,
greenFungusGlyph: TBitmap;
(* Load entity textures *)
procedure setupEntities;
(* Generate list of creatures on the map *)
procedure spawnNPCs;
(* Handle death of NPC's *)
procedure killEntity(id: smallint);
(* Draw entity on screen *)
procedure drawEntity(c, r: smallint; glyph: char);
(* Update NPCs X, Y coordinates *)
procedure moveNPC(id, newX, newY: smallint);
(* Redraw all NPC's *)
procedure redrawNPC;
(* Get creature currentHP at coordinates *)
function getCreatureHP(x, y: smallint): smallint;
(* Get creature maxHP at coordinates *)
function getCreatureMaxHP(x, y: smallint): smallint;
(* Get creature ID at coordinates *)
function getCreatureID(x, y: smallint): smallint;
(* Get creature name at coordinates *)
function getCreatureName(x, y: smallint): shortstring;
(* Check if creature is visible at coordinates *)
function isCreatureVisible(x, y: smallint): boolean;
(* Call Creatures.takeTurn procedure *)
procedure NPCgameLoop;
implementation
uses
player;
procedure setupEntities;
begin
playerGlyph := TBitmap.Create;
playerGlyph.LoadFromResourceName(HINSTANCE, 'PLAYER_GLYPH');
barrelGlyph := TBitmap.Create;
barrelGlyph.LoadFromResourceName(HINSTANCE, 'BARREL');
caveRatGlyph := TBitmap.Create;
caveRatGlyph.LoadFromResourceName(HINSTANCE, 'R_ORANGE');
hyenaGlyph := TBitmap.Create;
hyenaGlyph.LoadFromResourceName(HINSTANCE, 'H_RED');
caveBearGlyph := TBitmap.Create;
caveBearGlyph.LoadFromResourceName(HINSTANCE, 'B_LBLUE');
greenFungusGlyph := TBitmap.Create;
greenFungusGlyph.LoadFromResourceName(HINSTANCE, 'F_GREEN1');
end;
procedure spawnNPCs;
var
i, r, c, percentage: smallint;
begin
npcAmount := (globalutils.currentDgnTotalRooms + 2);
(* initialise array *)
SetLength(entityList, 0);
(* Add player to Entity list *)
player.createPlayer;
(* Create the NPCs *)
for i := 1 to npcAmount do
begin
(* Choose random location on the map *)
repeat
r := globalutils.randomRange(1, MAXROWS);
c := globalutils.randomRange(1, MAXCOLUMNS);
(* choose a location that is not a wall or occupied *)
until (maparea[r][c].Blocks = False) and (maparea[r][c].Occupied = False);
(* Roll for chance of each enemy type appearing *)
percentage := randomRange(1, 100);
if (percentage < 20) then
barrel.createBarrel(i, c, r)
else if (percentage >= 20) and (percentage <= 50) then // Cave rat
cave_rat.createCaveRat(i, c, r)
else if (percentage > 50) and (percentage <= 75) then // Cave bear
cave_bear.createCaveBear(i, c, r)
else if (percentage > 75) and (percentage <= 90) then // Blood hyena
hyena.createHyena(i, c, r)
else // Green fungus
green_fungus.createGreenFungus(i, c, r);
end;
end;
procedure killEntity(id: smallint);
var
i, amount, r, c, attempts: smallint;
begin
entityList[id].isDead := True;
entityList[id].glyph := '%';
entityList[id].blocks := False; // For destroyed barrels
map.unoccupy(entityList[id].posX, entityList[id].posY);
if (entityList[id].race = 'barrel') then
barrel.breakBarrel(entityList[id].posX, entityList[id].posY);
if (entityList[id].race = 'green fungus') then
begin
amount := randomRange(0, 3);
if (amount > 0) then
begin
for i := 1 to amount do
begin
attempts := 0;
repeat
// limit the number of attempts to move so the game doesn't hang if no suitable space found
Inc(attempts);
if attempts > 10 then
exit;
r := globalutils.randomRange(entityList[id].posY - 4, entityList[id].posY + 4);
c := globalutils.randomRange(entityList[id].posX - 4, entityList[id].posX + 4);
(* choose a location that is not a wall or occupied *)
until (maparea[r][c].Blocks <> True) and (maparea[r][c].Occupied <> True);
if (withinBounds(c, r) = True) then
begin
Inc(npcAmount);
green_fungus.createGreenFungus(npcAmount, c, r);
end;
end;
ui.writeBufferedMessages;
ui.bufferMessage('The fungus releases spores into the air');
end;
end;
end;
procedure drawEntity(c, r: smallint; glyph: char);
begin
case glyph of
'8': drawToBuffer(mapToScreen(c), mapToScreen(r), barrelGlyph);
'r': drawToBuffer(mapToScreen(c), mapToScreen(r), caveRatGlyph);
'h': drawToBuffer(mapToScreen(c), mapToScreen(r), hyenaGlyph);
'b': drawToBuffer(mapToScreen(c), mapToScreen(r), caveBearGlyph);
'f': drawToBuffer(mapToScreen(c), mapToScreen(r), greenFungusGlyph);
end;
end;
procedure moveNPC(id, newX, newY: smallint);
var
i: smallint;
begin
(* delete NPC at old position *)
(* First check if they are standing on an item *)
for i := 1 to items.itemAmount do
if (items.itemList[i].posX = entityList[id].posX) and
(items.itemList[i].posX = entityList[id].posX) then
items.redrawItems
(* if not, redraw the floor tile *)
else
if (entityList[id].inView = True) then
map.drawTile(entityList[id].posX, entityList[id].posY, 0);
(* mark tile as unoccupied *)
map.unoccupy(entityList[id].posX, entityList[id].posY);
(* update new position *)
if (map.isOccupied(newX, newY) = True) and (getCreatureID(newX, newY) <> id) then
begin
newX := entityList[id].posX;
newY := entityList[id].posY;
end;
entityList[id].posX := newX;
entityList[id].posY := newY;
(* mark tile as occupied *)
map.occupy(newX, newY);
(* Check if NPC in players FoV *)
if (map.canSee(newX, newY) = True) then
begin
entityList[id].inView := True;
if (entityList[id].discovered = False) then
begin
ui.displayMessage('You see ' + entityList[id].description);
entityList[id].discovered := True;
end;
end
else
entityList[id].inView := False;
end;
procedure redrawNPC;
var
i: smallint;
begin
for i := 1 to npcAmount do
begin
if (entityList[i].inView = True) and (entityList[i].isDead = False) then
begin
drawEntity(entityList[i].posX, entityList[i].posY, entityList[i].glyph);
end;
end;
end;
function getCreatureHP(x, y: smallint): smallint;
var
i: smallint;
begin
for i := 0 to npcAmount do
begin
if (entityList[i].posX = x) and (entityList[i].posY = y) then
Result := entityList[i].currentHP;
end;
end;
function getCreatureMaxHP(x, y: smallint): smallint;
var
i: smallint;
begin
for i := 0 to npcAmount do
begin
if (entityList[i].posX = x) and (entityList[i].posY = y) then
Result := entityList[i].maxHP;
end;
end;
function getCreatureID(x, y: smallint): smallint;
var
i: smallint;
begin
Result := 0; // initialise variable
for i := 0 to npcAmount do
begin
if (entityList[i].posX = x) and (entityList[i].posY = y) then
Result := i;
end;
end;
function getCreatureName(x, y: smallint): shortstring;
var
i: smallint;
begin
for i := 0 to npcAmount do
begin
if (entityList[i].posX = x) and (entityList[i].posY = y) then
Result := entityList[i].race;
end;
end;
function isCreatureVisible(x, y: smallint): boolean;
var
i: smallint;
begin
Result := False;
for i := 0 to npcAmount do
if (entityList[i].posX = x) and (entityList[i].posY = y) then
if (entityList[i].inView = True) then
Result := True;
end;
procedure NPCgameLoop;
var
i: smallint;
begin
for i := 1 to npcAmount do
if (entityList[i].isDead = False) then
entityList[i].entityTakeTurn(i);
end;
{ Creature }
procedure Creature.entityTakeTurn(i: smallint);
begin
if (entityList[i].race = 'barrel') then
barrel.takeTurn(i, entityList[i].posX, entityList[i].posY)
else if (entityList[i].race = 'cave rat') then
cave_rat.takeTurn(i, entityList[i].posX, entityList[i].posY)
else if (entityList[i].race = 'blood hyena') then
hyena.takeTurn(i, entityList[i].posX, entityList[i].posY)
else if (entityList[i].race = 'cave bear') then
cave_bear.takeTurn(i, entityList[i].posX, entityList[i].posY)
else if (entityList[i].race = 'green fungus') then
green_fungus.takeTurn(i, entityList[i].posX, entityList[i].posY);
end;
end.
|
unit frmLearningGroupList;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, dbfunc, uKernel;
type
TfLearningGroupList = class(TForm)
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
cmbChooseAcademicYear: TComboBox;
cmbChooseEducationProgram: TComboBox;
cmbChoosePedagogue: TComboBox;
cmbChooseStatus: TComboBox;
lvLearningGroup: TListView;
Button3: TButton;
bNewRecord: TButton;
bChangeRecord: TButton;
bGroupMembers: TButton;
bDeleteGroup: TButton;
procedure bDeleteGroupeClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure lvLearningGroupSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure bNewRecordClick(Sender: TObject);
procedure bChangeRecordClick(Sender: TObject);
procedure lvLearningGroupCustomDrawItem(Sender: TCustomListView;
Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean);
procedure cmbChooseEducationProgramChange(Sender: TObject);
procedure cmbChoosePedagogueChange(Sender: TObject);
procedure cmbChooseAcademicYearChange(Sender: TObject);
procedure cmbChooseLearningFormChange(Sender: TObject);
procedure cmbChooseStatusChange(Sender: TObject);
procedure bGroupMembersClick(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
AcademicYear: TResultTable;
EducationProgram: TResultTable;
PedagogueSurnameNP: TResultTable;
StatusLearningGroup: TResultTable;
LearningGroupList: TResultTable;
FIDPedagogue: integer;
FIDCurAcademicYear: integer;
procedure ShowLearningGroupList;
procedure OnChangeCMBsSetProperties;
/// //////////////function ChangeCMBsSetProperties: Array of integer; ??????
procedure SetIDPedagogue(const Value: integer);
procedure SetIDCurAcademicYear(const Value: integer);
public
// IDLearningGroup: integer;
property IDPedagogue: integer read FIDPedagogue write SetIDPedagogue;
property IDCurAcademicYear: integer read FIDCurAcademicYear
write SetIDCurAcademicYear;
end;
var
fLearningGroupList: TfLearningGroupList;
implementation
{$R *.dfm}
uses frmLearningGroupEdit, frmLGroupMembers;
procedure TfLearningGroupList.bChangeRecordClick(Sender: TObject);
begin
fLearningGroupEdit.NewRecord := false;
if (not Assigned(fLearningGroupEdit)) then
fLearningGroupEdit := TfLearningGroupEdit.Create(Self);
fLearningGroupEdit.ShowModal;
if fLearningGroupEdit.ModalResult = mrOk then
ShowLearningGroupList;
end;
procedure TfLearningGroupList.bGroupMembersClick(Sender: TObject);
begin
if (not Assigned(fLGroupMembers)) then
fLGroupMembers := TfLGroupMembers.Create(Self);
fLGroupMembers.ShowModal;
if fLGroupMembers.ModalResult = mrOk then
lvLearningGroup.ItemIndex := 0;
end;
procedure TfLearningGroupList.bNewRecordClick(Sender: TObject);
begin
if (cmbChooseEducationProgram.ItemIndex = 0) then
begin
ShowMessage
('Для создания новой группы выберите программу!');
Exit;
end;
fLearningGroupEdit.NewRecord := true;
fLearningGroupEdit.idLearningGroup := -1;
if (not Assigned(fLearningGroupEdit)) then
fLearningGroupEdit := TfLearningGroupEdit.Create(Self);
fLearningGroupEdit.ShowModal;
if fLearningGroupEdit.ModalResult = mrOk then
ShowLearningGroupList;
end;
procedure TfLearningGroupList.Button3Click(Sender: TObject);
begin
Close;
end;
procedure TfLearningGroupList.bDeleteGroupeClick(Sender: TObject);
begin
if Kernel.DeleteGroup([fLearningGroupEdit.idLearningGroup]) then
begin
ShowMessage('Группа удалена!');
// МОЖЕТ НЕ СТОИТ ВЫВОДИТЬ ЭТО СООБЩЕНИЕ!!???
ShowLearningGroupList; // для обновления осн.сведений
end
else
ShowMessage('Ошибка при удалении группы!');
end;
procedure TfLearningGroupList.cmbChooseAcademicYearChange(Sender: TObject);
begin
ShowLearningGroupList;
end;
procedure TfLearningGroupList.cmbChooseEducationProgramChange(Sender: TObject);
begin
ShowLearningGroupList;
end;
procedure TfLearningGroupList.cmbChooseLearningFormChange(Sender: TObject);
begin
ShowLearningGroupList;
end;
procedure TfLearningGroupList.cmbChoosePedagogueChange(Sender: TObject);
begin
ShowLearningGroupList;
end;
procedure TfLearningGroupList.cmbChooseStatusChange(Sender: TObject);
begin
ShowLearningGroupList;
end;
procedure TfLearningGroupList.FormCreate(Sender: TObject);
begin
AcademicYear := nil;
EducationProgram := nil;
PedagogueSurnameNP := nil;
StatusLearningGroup := nil;
LearningGroupList := nil;
end;
procedure TfLearningGroupList.FormDestroy(Sender: TObject);
begin
if Assigned(AcademicYear) then
FreeAndNil(AcademicYear);
if Assigned(EducationProgram) then
FreeAndNil(EducationProgram);
if Assigned(PedagogueSurnameNP) then
FreeAndNil(PedagogueSurnameNP);
if Assigned(StatusLearningGroup) then
FreeAndNil(StatusLearningGroup);
if Assigned(LearningGroupList) then
FreeAndNil(LearningGroupList);
end;
procedure TfLearningGroupList.FormShow(Sender: TObject);
var
i: integer;
begin
if not Assigned(EducationProgram) then
EducationProgram := Kernel.GetEducationProgram;
with cmbChooseEducationProgram do
begin
Clear;
Items.Add('Все');
for i := 0 to EducationProgram.Count - 1 do
Items.Add(EducationProgram[i].ValueStrByName('NAME'));
DropDownCount := EducationProgram.Count + 1;
cmbChooseEducationProgram.ItemIndex := 0;
end;
if not Assigned(AcademicYear) then
AcademicYear := Kernel.GetAcademicYear;
with cmbChooseAcademicYear do
begin
Clear;
Items.Add('Все');
for i := 0 to AcademicYear.Count - 1 do
Items.Add(AcademicYear[i].ValueStrByName('NAME'));
DropDownCount := AcademicYear.Count + 1;
for i := 0 to AcademicYear.Count - 1 do
if AcademicYear[i].ValueByName('ID') = IDCurAcademicYear then
cmbChooseAcademicYear.ItemIndex := i + 1;
end;
if not Assigned(PedagogueSurnameNP) then
PedagogueSurnameNP := Kernel.GetPedagogueSurnameNP;
with cmbChoosePedagogue do
begin
Clear;
Items.Add('Все');
for i := 0 to PedagogueSurnameNP.Count - 1 do
Items.Add(PedagogueSurnameNP[i].ValueStrByName('SurnameNP'));
DropDownCount := PedagogueSurnameNP.Count + 1;
for i := 0 to PedagogueSurnameNP.Count - 1 do
if PedagogueSurnameNP[i].ValueByName('ID_OUT') = IDPedagogue then
cmbChoosePedagogue.ItemIndex := i + 1;
end;
if not Assigned(StatusLearningGroup) then
StatusLearningGroup := Kernel.GetStatusLearningGroup(3);
with cmbChooseStatus do
begin
Clear;
Items.Add('Все');
for i := 0 to StatusLearningGroup.Count - 1 do
Items.Add(StatusLearningGroup[i].ValueStrByName('NOTE'));
DropDownCount := StatusLearningGroup.Count + 1;
cmbChooseStatus.ItemIndex := 0;
end;
ShowLearningGroupList;
end;
procedure TfLearningGroupList.lvLearningGroupCustomDrawItem
(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState;
var DefaultDraw: Boolean);
begin
if Item.SubItems.Strings[5] = 'Расформированная' then
Sender.Canvas.Brush.Color := 6521080; {
Sender.Canvas.Brush.Color := $00FF0000;
else
Sender.Canvas.Brush.Color := clWindow; }
// if Item.Selected { in State } then
// Sender.Canvas.Brush.Color := 6521080 // ан не работает...
end;
procedure TfLearningGroupList.lvLearningGroupSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
var
education_program, pedagogue, academic_year, learning_group_type,
status: integer;
begin
// че попало тут, вродь работает, но столько хлама...
with LearningGroupList[Item.Index] do
begin
fLearningGroupEdit.idLearningGroup := ValueByName('ID_OUT');
fLearningGroupEdit.GName := ValueStrByName('NAME');
fLearningGroupEdit.StrEducationProgram :=
ValueStrByName('EDUCATION_PROGRAM');
fLearningGroupEdit.StrPedagogue := ValueStrByName('SURNAMENP');
fLearningGroupEdit.StrLearningForm := ValueStrByName('LEARNING_GROUP_TYPE');
fLearningGroupEdit.StrStatus := ValueStrByName('STATUS_GROUP');
fLearningGroupEdit.StrAcademicYear := ValueStrByName('ACADEMIC_YEAR');
fLearningGroupEdit.StrLearningLevel := ValueStrByName('LEARNING_LEVEL');
fLearningGroupEdit.IntHoursAmount := ValueByName('WEEK_AMOUNT_HOURS');
// ПЕРЕДАТЬ ЗНАЧЕНИЯ В СВОЙСТВА ФОРМЫ С СОСТАВОМ ГРУПП
fLGroupMembers.idLearningGroup := ValueByName('ID_OUT');
fLGroupMembers.IDEducationProgram := ValueByName('ID_EDUCATION_PROGRAM');
fLGroupMembers.IDPedagogue := ValueByName('ID_PEDAGOGUE');
fLGroupMembers.IDLearningForm := 1; // сие id групповой формы обучения
fLGroupMembers.IDStatus := ValueByName('ID_STATUS');
fLGroupMembers.IDAcademicYear := ValueByName('ID_ACADEMIC_YEAR');
fLGroupMembers.StrLearningGroup := ValueStrByName('NAME');
end;
// КОД НИЖЕ ЗАСУНУТЬ В СПЕЦФУНКЦИЮ, ВОЗВРАЩАЮЩУЮ МАССИВ ЦЕЛЫХ ЧИСЕЛ?????
if cmbChooseEducationProgram.ItemIndex = 0 then
education_program := 0
else
education_program := EducationProgram[cmbChooseEducationProgram.ItemIndex -
1].ValueByName('ID');
if cmbChoosePedagogue.ItemIndex = 0 then
pedagogue := 0
else
pedagogue := PedagogueSurnameNP[cmbChoosePedagogue.ItemIndex - 1]
.ValueByName('ID_OUT');
if cmbChooseAcademicYear.ItemIndex = 0 then
academic_year := 0
else
academic_year := AcademicYear[cmbChooseAcademicYear.ItemIndex - 1]
.ValueByName('ID');
if cmbChooseStatus.ItemIndex = 0 then
status := 0
else
status := StatusLearningGroup[cmbChooseStatus.ItemIndex - 1]
.ValueByName('CODE');
// fLGroupMembers.IDEducationProgram := education_program;
// fLGroupMembers.IDPedagogue := pedagogue;
// fLGroupMembers.IDLearningForm := 1; // сие id групповой формы обучения
// fLGroupMembers.IDStatus := status;
// fLGroupMembers.IDAcademicYear := academic_year;
fLearningGroupEdit.IDEducationProgram := education_program;
fLearningGroupEdit.IDPedagogue := pedagogue;
// fLearningGroupEdit.IDAcademicYear := academic_year;
// fLearningGroupEdit.IDLearningGroup := LearningGroupList[Item.Index].ValueByName('ID_OUT');
end;
// ВМЕСТО ПРОЦЕДУРЫ ЗАМУТИТЬ ФУНКЦИЮ!!!!!!!!!!!!!!!!!!!!!!????????????????
procedure TfLearningGroupList.OnChangeCMBsSetProperties;
var
education_program, pedagogue, academic_year, learning_group_type,
status: integer;
begin
if cmbChooseEducationProgram.ItemIndex = 0 then
education_program := 0
else
education_program := EducationProgram[cmbChooseEducationProgram.ItemIndex -
1].ValueByName('ID');
if cmbChoosePedagogue.ItemIndex = 0 then
pedagogue := 0
else
pedagogue := PedagogueSurnameNP[cmbChoosePedagogue.ItemIndex - 1]
.ValueByName('ID_OUT');
if cmbChooseAcademicYear.ItemIndex = 0 then
academic_year := 0
else
academic_year := AcademicYear[cmbChooseAcademicYear.ItemIndex - 1]
.ValueByName('ID');
if cmbChooseStatus.ItemIndex = 0 then
status := 0
else
status := StatusLearningGroup[cmbChooseStatus.ItemIndex - 1]
.ValueByName('CODE');
// fLGroupMembers.IDEducationProgram := education_program;
// fLGroupMembers.IDPedagogue := pedagogue;
// // fLGroupMembers.IDLearningForm := learning_group_type;
// fLGroupMembers.IDLearningForm := 1; // сие id групповой формы обучения
// fLGroupMembers.IDStatus := status;
// fLGroupMembers.IDAcademicYear := academic_year;
//
// fLearningGroupEdit.IDEducationProgram := education_program;
// fLearningGroupEdit.IDPedagogue := pedagogue;
// fLearningGroupEdit.IDAcademicYear := academic_year;
end;
procedure TfLearningGroupList.SetIDCurAcademicYear(const Value: integer);
begin
if FIDCurAcademicYear <> Value then
FIDCurAcademicYear := Value;
end;
procedure TfLearningGroupList.SetIDPedagogue(const Value: integer);
begin
if FIDPedagogue <> Value then
FIDPedagogue := Value;
end;
procedure TfLearningGroupList.ShowLearningGroupList;
var
education_program, pedagogue, academic_year, learning_group_type,
status: integer;
begin
if cmbChooseEducationProgram.ItemIndex = 0 then
education_program := 0
else
education_program := EducationProgram[cmbChooseEducationProgram.ItemIndex -
1].ValueByName('ID');
if cmbChoosePedagogue.ItemIndex = 0 then
pedagogue := 0
else
pedagogue := PedagogueSurnameNP[cmbChoosePedagogue.ItemIndex - 1]
.ValueByName('ID_OUT');
if cmbChooseAcademicYear.ItemIndex = 0 then
academic_year := 0
else
academic_year := AcademicYear[cmbChooseAcademicYear.ItemIndex - 1]
.ValueByName('ID');
if cmbChooseStatus.ItemIndex = 0 then
status := 0
else
status := StatusLearningGroup[cmbChooseStatus.ItemIndex - 1]
.ValueByName('CODE');
learning_group_type := 1; // я не получаю программно этот тип, а закладываю
//вручную - несовершенство, с которым нужно смириться? как изменить не знаю пока
// fLGroupMembers.IDEducationProgram := education_program;
// fLGroupMembers.IDPedagogue := pedagogue;
// fLGroupMembers.IDLearningForm := learning_group_type;
// fLGroupMembers.IDStatus := status;
// fLGroupMembers.IDAcademicYear := academic_year;
OnChangeCMBsSetProperties;
if Assigned(LearningGroupList) then
FreeAndNil(LearningGroupList);
LearningGroupList := Kernel.GetLearningGroupList(education_program, pedagogue,
academic_year, learning_group_type, status);
Kernel.GetLVLearningGroup(lvLearningGroup, LearningGroupList);
if lvLearningGroup.Items.Count > 0 then
begin
lvLearningGroup.ItemIndex := 0;
bChangeRecord.Enabled := true;
bGroupMembers.Enabled := true;
bDeleteGroup.Enabled := true;
end
else
begin
bChangeRecord.Enabled := false;
bGroupMembers.Enabled := false;
bDeleteGroup.Enabled := false;
end;
end;
end.
|
unit QuranImgView;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, RXSpin, ExtCtrls, Htmlview, AmlView, XmlObjModel, QuranStruct,
CompDoc, QuranView, RXCtrls, islctrls, moneyctrls;
type
TQuranImgData = class(TAmlData)
protected
FSura : Cardinal;
FSuraData : TXmlElement;
FPage : Cardinal;
FPageData : TXmlElement;
FPageFNameFmt : String;
FMaxPage : Cardinal;
function GetLibName : String; override;
function CreateViewer : TAmlViewer; override;
procedure SetPage(APage : Cardinal);
function GetFirstAyah : TSuraAyah;
function GetLastAyah : TSuraAyah;
function GetSuraData(ASura : TSuraNum) : TXmlElement;
procedure ClearActivePage; virtual;
procedure ClearActiveSura; virtual;
public
destructor Destroy; override;
function InitializeLoad(const AFileName : String;
const ACatalog : TXmlElement) : Boolean; override;
function GetAddressCaption(const AAddress : TAddress; const AIncludeName : Boolean) : String; override;
function GetAyahPage(Ayah : TSuraAyah) : Cardinal;
property Page : Cardinal read FPage write SetPage;
property PageData : TXmlElement read FPageData;
property FirstAyah : TSuraAyah read GetFirstAyah;
property LastAyah : TSuraAyah read GetLastAyah;
property MaxPage : Cardinal read FMaxPage;
end;
TQuranImgViewer = class(TAmlViewer)
HtmlViewer: THTMLViewer;
LocationPanel: TWallpaperPanel;
Location: TRxLabel;
HeadingPanel: TWallpaperPanel;
procedure HtmlViewerImageRequest(Sender: TObject; const SRC: String;
var Stream: TMemoryStream);
protected
FActivePage : Cardinal;
FBook : TQuranImgData;
FPageImage : TMemoryStream;
function GetActiveData : TAmlData; override;
procedure ClearContents; virtual;
procedure UpdateContents; virtual;
procedure UpdateNavigation; virtual;
procedure SetAddress(const AAddress : TAddress); override;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure Navigate(const AType : TNavigate; const ADirection : TNavigateDirection; const AAddress : TCaptionedAddress = Nil); override;
procedure ExecuteQuranCmd(const ACommand : TQuranCommand); override;
function SelectSura(const ASura : TSuraNum) : Boolean; override;
property Book : TQuranImgData read FBook;
end;
implementation
uses IslUtils;
{$R *.DFM}
destructor TQuranImgData.Destroy;
begin
ClearActiveSura;
ClearActivePage;
inherited Destroy;
end;
procedure TQuranImgData.ClearActivePage;
begin
if FPageData <> Nil then
FPageData.Free;
FPageData := Nil;
FPage := 0;
end;
procedure TQuranImgData.ClearActiveSura;
begin
if FSuraData <> Nil then
FSuraData.Free;
FSuraData := Nil;
FSura := 0;
end;
function TQuranImgData.InitializeLoad(const AFileName : String;
const ACatalog : TXmlElement) : Boolean;
begin
Result := inherited InitializeLoad(AFileName, ACatalog);
if Result then begin
//FAddrMgr.AddShortcut(LibName, Format('%s:%s', [FId, '']), FName, '01' + FName).SmallIconIdx := BookIconSmallIdxQuran;
FPageFNameFmt := FCatalogContent.GetAttribute('imgfmt');
FMaxPage := StrToInt(FCatalogContent.GetAttribute('maxpage'));
end;
SetFlag(adfShareViewer+adfIsQuranData);
end;
function TQuranImgData.GetAddressCaption(const AAddress : TAddress; const AIncludeName : Boolean) : String;
begin
if Pos(SuraAyahStrDelim, AAddress.BookPage) > 0 then begin
if AIncludeName then
Result := Format('%s (Sura %s Ayah %s)', [Name, AAddress.Volume, AAddress.Element])
else
Result := Format('Sura %s Ayah %s', [AAddress.Volume, AAddress.Element]);
end else begin
if AIncludeName then
Result := Format('%s (Page %s)', [Name, AAddress.BookPage])
else
Result := 'Page ' + AAddress.BookPage;
end;
end;
function TQuranImgData.GetLibName : String;
begin
Result := 'Quran';
end;
function TQuranImgData.CreateViewer : TAmlViewer;
begin
Result := TQuranImgViewer.Create(Application);
end;
function TQuranImgData.GetFirstAyah : TSuraAyah;
var
AyahElem : TXmlElement;
begin
Result.SuraNum := 1;
Result.AyahNum := 1;
if FPageData <> Nil then begin
AyahElem := GetChildElem(FPageData, True);
if AyahElem <> Nil then begin
Result.SuraNum := StrToInt(AyahElem.GetAttribute('sura'));
Result.AyahNum := StrToInt(AyahElem.GetAttribute('num'));
end;
end;
end;
function TQuranImgData.GetLastAyah : TSuraAyah;
var
AyahElem : TXmlElement;
begin
Result.SuraNum := 1;
Result.AyahNum := 1;
if FPageData <> Nil then begin
AyahElem := GetChildElem(FPageData, False);
if AyahElem <> Nil then begin
Result.SuraNum := StrToInt(AyahElem.GetAttribute('sura'));
Result.AyahNum := StrToInt(AyahElem.GetAttribute('num'));
end;
end;
end;
procedure TQuranImgData.SetPage(APage : Cardinal);
var
StreamName : String;
begin
if FPage = APage then
Exit;
ClearActivePage;
FStatus.StatusBegin(Format('Loading Page %d...', [APage]), True);
try
StreamName := 'P'+IntToStr(APage);
FPageData := ReadXML(StreamName);
FPage := APage;
except
ShowMessage(Format('Page %s Data not found.', [StreamName]));
FPageData := Nil;
FPage := 0;
end;
FStatus.StatusEnd;
end;
function TQuranImgData.GetAyahPage(Ayah : TSuraAyah) : Cardinal;
var
AyahsList : TXmlNodeList;
AyahElem : TXmlElement;
begin
GetSuraData(Ayah.SuraNum);
Result := 0;
if FSuraData <> Nil then begin
AyahsList := FSuraData.GetElementsByTagNameWithAttribute('ayah', 'num', IntToStr(Ayah.AyahNum));
if AyahsList.Length = 1 then begin
AyahElem := AyahsList.Item(0) as TXmlElement;
Result := StrToInt(AyahElem.GetAttribute('page'));
end;
end;
end;
function TQuranImgData.GetSuraData(ASura : TSuraNum) : TXmlElement;
begin
if FSura = ASura then begin
Result := FSuraData;
Exit;
end;
ClearActiveSura;
FStatus.StatusBegin(Format('Loading Sura %d...', [ASura]), True);
try
FSuraData := ReadXML('S'+IntToStr(ASura));
FSura := ASura;
except
FSuraData := Nil;
FSura := 0;
end;
FStatus.StatusEnd;
Result := FSuraData;
end;
{------------------------------------------------------------------------------}
constructor TQuranImgViewer.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
FActivePage := 1;
HtmlViewer.OnHotSpotCovered := DefaultHtmlHotSpotCovered;
HtmlViewer.OnHotSpotClick := DefaultHtmlHotspotClick;
HtmlViewer.OnRightClick := DefaultHtmlRightClick;
// the image request is special for this viewer
//HtmlViewer.OnImageRequest := DefaultHtmlImageRequest;
end;
destructor TQuranImgViewer.Destroy;
begin
if FPageImage <> Nil then
FPageImage.Free;
inherited Destroy;
end;
procedure TQuranImgViewer.Navigate(const AType : TNavigate; const ADirection : TNavigateDirection; const AAddress : TCaptionedAddress);
begin
if (FBook = Nil) or (ADirection = nvdCaptionedAddr) or (AType <> nvPage) then
Exit;
case ADirection of
nvdPrevious :
if FActivePage > 1 then
FActivePage := Pred(FActivePage)
else
FActivePage := FBook.MaxPage;
nvdNext :
if FActivePage < FBook.MaxPage then
FActivePage := Succ(FActivePage)
else
FActivePage := 1;
end;
UpdateContents;
UpdateNavigation;
end;
function TQuranImgViewer.GetActiveData : TAmlData;
begin
Result := FBook;
end;
procedure TQuranImgViewer.ClearContents;
begin
FActivePage := 0;
HtmlViewer.LoadFromBuffer(PChar(''), 0);
end;
procedure TQuranImgViewer.UpdateContents;
const
PageImageWidth = 456;
SuraNameBoxHeight = 115;
OneLineHeight = 45;
MinimumLineHeight = 25;
function GetAyahBoundingBox(x, y : Cardinal) : TRect;
begin
if x < PageImageWidth then begin
Result.Left := x - 17;
Result.Right := x + 17;
end else begin
Result.Left := PageImageWidth;
Result.Right := PageImageWidth;
end;
if y > 0 then begin
Result.Top := y - 7;
Result.Bottom := y + 37;
end else begin
Result.Top := 0;
Result.Bottom := 0;
end;
end;
function CreateImageMap(Ayahs : TXmlElement) : String;
const
AreaFmt = '<area shape="rect" coords="%d,%d,%d,%d" href="%s">';
var
A, xStart, xEnd, yStart, yEnd, AyahNum, SuraNum : Cardinal;
AyahImgHeight : Cardinal;
AyahElem : TXmlElement;
StartRect, EndRect : TRect;
MultiQuranRef : String;
begin
Result := '';
if (Ayahs = Nil) or (Ayahs.ChildNodes.Length <= 0) then
Exit;
for A := 0 to Ayahs.ChildNodes.Length-1 do begin
if Ayahs.ChildNodes.Item(A).NodeType <> ELEMENT_NODE then
continue;
AyahElem := Ayahs.ChildNodes.Item(A) as TXmlElement;
SuraNum := StrToInt(AyahElem.GetAttribute('sura'));
AyahNum := StrToInt(AyahElem.GetAttribute('num'));
xStart := StrToInt(AyahElem.GetAttribute('xstart'));
xEnd := StrToInt(AyahElem.GetAttribute('xend'));
yStart := StrToInt(AyahElem.GetAttribute('ystart'));
yEnd := StrToInt(AyahElem.GetAttribute('yend'));
MultiQuranRef := CreateQuranAddress(qatMultiQuran, SuraNum, AyahNum);
// starting ayahs have the sura name block above them
if AyahNum = 1 then
StartRect := GetAyahBoundingBox(PageImageWidth, yStart+SuraNameBoxHeight)
else
StartRect := GetAyahBoundingBox(xStart, yStart);
EndRect := GetAyahBoundingBox(xEnd, yEnd);
// if the ayah doesn't start on the same line as it "number block", go to the next line
if (StartRect.Left < 50) and (StartRect.Left > 0) then begin
StartRect.Left := PageImageWidth;
StartRect.Right := PageImageWidth;
StartRect.Top := StartRect.Top + OneLineHeight;
end;
AyahImgHeight := EndRect.Bottom - StartRect.Top;
if(AyahImgHeight < MinimumLineHeight) then
continue;
Result := Result + Format(AreaFmt, [EndRect.Left, EndRect.Top, EndRect.Right, EndRect.Bottom, MultiQuranRef]);
end;
Result := '<map name="ayahs">' + Result + '</map>';
end;
var
Html : String;
begin
Assert(FBook <> Nil);
FBook.Page := FActivePage;
if FBook.FPageData = Nil then begin
ClearContents;
Exit;
end;
FStatus.StatusBegin('Rendering...', True);
Html := Format('<center>%s<img src="%d" usemap="#ayahs"></center>', [CreateImageMap(FBook.PageData), FActivePage]);
HtmlViewer.LoadFromBuffer(PChar(Html), Length(Html));
FStatus.StatusEnd;
end;
procedure TQuranImgViewer.UpdateNavigation;
var
FirstAyah, LastAyah : TSuraAyah;
FirstName, LastName : String;
begin
Assert(FBook <> Nil);
FirstAyah := FBook.FirstAyah;
LastAyah := FBook.LastAyah;
FillQuickLinksWithQurans(FBook.ShortName, FirstAyah.suraNum, FirstAyah.ayahNum, LocationPanel.Color);
FAddrMgr.SetActiveSuraAyah(FirstAyah);
if FBook.QuranStruct <> Nil then begin
FirstName := FBook.QuranStruct.Sura[FirstAyah.SuraNum].suraName;
LastName := FBook.QuranStruct.Sura[LastAyah.SuraNum].suraName;
if FirstName = LastName then
Location.Caption := Format('Page %d (Sura %d. %s Ayaat %d to %d)', [FActivePage, FirstAyah.SuraNum, FirstName, FirstAyah.AyahNum, LastAyah.AyahNum])
else
Location.Caption := Format('Page %d (Sura %s Ayah %d to Sura %s Ayah %d)', [FActivePage, FirstName, FirstAyah.AyahNum, LastName, LastAyah.AyahNum]);
end else begin
FirstName := '';
LastName := '';
if FirstAyah.SuraNum = LastAyah.SuraNum then
Location.Caption := Format('Page %d (Sura %d Ayaat %d to %d)', [FActivePage, FirstAyah.SuraNum, FirstAyah.AyahNum, LastAyah.AyahNum])
else
Location.Caption := Format('Page %d (Sura %d Ayah %d to Sura %d Ayah %d)', [FActivePage, FirstAyah.SuraNum, FirstAyah.AyahNum, LastAyah.SuraNum, LastAyah.AyahNum]);
end;
end;
procedure TQuranImgViewer.SetAddress(const AAddress : TAddress);
var
BookChanged : Boolean;
NewBook : TAmlData;
NewPage : Integer;
NewAyah : TSuraAyah;
begin
NewBook := FDataMgr.DataIds[AAddress.BookId];
if not (NewBook is TQuranImgData) then begin
ClearContents;
Exit;
end;
BookChanged := NewBook <> FBook;
if BookChanged then begin
FBook := NewBook as TQuranImgData;
end;
Assert(FBook <> Nil);
Assert(FBook.QuranStruct <> Nil);
if AAddress.BookPage <> '' then begin
if Pos(SuraAyahStrDelim, AAddress.BookPage) > 0 then begin
NewAyah := FBook.QuranStruct.StrToSuraAyah(AAddress.BookPage, SuraAyah(1, 1));
NewPage := FBook.GetAyahPage(NewAyah)
end else
NewPage := StrToInt(AAddress.BookPage);
end else
NewPage := FActivePage;
if BookChanged or (Cardinal(NewPage) <> FActivePage) then begin
FActivePage := NewPage;
UpdateContents;
end;
UpdateNavigation;
end;
procedure TQuranImgViewer.ExecuteQuranCmd(const ACommand : TQuranCommand);
var
FirstAyah : TSuraAyah;
begin
if FBook = Nil then
Exit;
FirstAyah := FBook.FirstAyah;
case ACommand of
qcArabicSearch :
ShowMessage('Arabic Searching is performed in the Arabic Quran (text) only. Please open the Arabic Quran (text) and try again.');
qcViewSuraIntro : GlobalSetAddress(CreateQuranAddress(qatSuraIntro, FirstAyah.suraNum, 1));
qcRecite : GlobalSetAddress(CreateQuranAddress(qatReciteContinue, FirstAyah.suraNum, FirstAyah.ayahNum));
else
inherited ExecuteQuranCmd(ACommand);
end;
end;
function TQuranImgViewer.SelectSura(const ASura : TSuraNum) : Boolean;
var
Active : TSuraAyah;
begin
Assert(FBook <> Nil);
Active.suraNum := ASura;
Active.ayahNum := 1;
FActivePage := FBook.GetAyahPage(Active);
if FActivePage >= 1 then begin
UpdateContents;
UpdateNavigation;
end else
ClearContents;
Result := True;
end;
procedure TQuranImgViewer.HtmlViewerImageRequest(Sender: TObject;
const SRC: String; var Stream: TMemoryStream);
var
StorageName : String;
begin
Assert(FBook <> Nil);
if FPageImage <> Nil then
FPageImage.Free;
FStatus.StatusBegin('Loading page...', True);
StorageName := Format(FBook.FPageFNameFmt, [StrToInt(SRC)]);
FPageImage := FBook.ReadStream(StorageName);
if FPageImage = Nil then
ShowMessage(Format('Error reading page Image %s.', [StorageName]));
Stream := FPageImage;
FStatus.StatusEnd;
end;
end.
|
{: GLCarbonContext<p>
Carbon specific Context.<p>
<b>History : </b><font size=-1><ul>
<li>10/06/09 - DanB - Added to main GLScene CVS repository (from GLScene-Lazarus).
<li>14/11/08 - Creation
</ul></font>
}
unit GLCarbonContext;
{$i ../GLScene.inc}
interface
uses
MacOSAll,
Classes, sysutils, GLCrossPlatform, GLContext, LCLProc, Forms, Controls,
OpenGL1x, agl, CarbonDef, CarbonCanvas, CarbonProc, CarbonPrivate;
type
// TGLCarbonContext
//
{: A context driver for standard XOpenGL. }
TGLCarbonContext = class (TGLContext)
private
{ Private Declarations }
FContext: TAGLContext;
FBounds: TRect;
FViewer, FForm: TControl;
FIAttribs : packed array of Integer;
function GetFormBounds: TRect;
procedure BoundsChanged;
protected
{ Protected Declarations }
procedure ClearIAttribs;
procedure AddIAttrib(attrib, value : Integer);
procedure ChangeIAttrib(attrib, newValue : Integer);
procedure DropIAttrib(attrib : Integer);
procedure DoCreateContext(outputDevice : Cardinal); override;
procedure DoCreateMemoryContext(outputDevice : Cardinal;width, height : Integer; BufferCount : integer); override;
procedure DoShareLists(aContext : TGLContext); override;
procedure DoDestroyContext; override;
procedure DoActivate; override;
procedure DoDeactivate; override;
public
{ Public Declarations }
constructor Create; override;
destructor Destroy; override;
function IsValid : Boolean; override;
procedure SwapBuffers; override;
function RenderOutputDevice : Integer; override;
end;
implementation
var
vLastVendor : String;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
resourcestring
cIncompatibleContexts = 'Incompatible contexts';
cDeleteContextFailed = 'Delete context failed';
cContextActivationFailed = 'Context activation failed: %X, %s';
cContextDeactivationFailed = 'Context deactivation failed';
cUnableToCreateLegacyContext= 'Unable to create legacy context';
{ TGLCarbonContext }
function TGLCarbonContext.GetFormBounds: TRect;
begin
Result.TopLeft := FForm.ScreenToClient(FViewer.ControlToScreen(Point(0, 0)));
Result.Right := Result.Left + FViewer.Width;
Result.Bottom := Result.Top + FViewer.Height;
end;
procedure TGLCarbonContext.BoundsChanged;
var
Bounds: Array [0..3] of GLint;
begin
Bounds[0] := FBounds.Left;
Bounds[1] := FForm.Height - FBounds.Bottom;
Bounds[2] := FBounds.Right - FBounds.Left;
Bounds[3] := FBounds.Bottom - FBounds.Top;
aglSetInteger(FContext, AGL_BUFFER_RECT, @Bounds[0]);
aglEnable(FContext, AGL_BUFFER_RECT);
{$MESSAGE Warn 'Removing child controls from clip region needs to be implemented'}
(*BoundsRGN := NewRgn;
RectRgn(BoundsRGN, GetCarbonRect(TCarbonControlContext(DC).Owner.LCLObject.BoundsRect));
aglSetInteger(FContext, AGL_CLIP_REGION, PGLInt(BoundsRGN));
aglEnable(FContext, AGL_CLIP_REGION);*)
aglUpdateContext(FContext);
end;
procedure TGLCarbonContext.ClearIAttribs;
begin
SetLength(FIAttribs, 1);
FiAttribs[0]:=0;
end;
procedure TGLCarbonContext.AddIAttrib(attrib, value: Integer);
var
N: Integer;
begin
N := Length(FIAttribs);
SetLength(FIAttribs, N+2);
FiAttribs[N-1]:=attrib;
FiAttribs[N]:=value;
FiAttribs[N+1]:=0;
end;
procedure TGLCarbonContext.ChangeIAttrib(attrib, newValue: Integer);
var
i : Integer;
begin
i:=0;
while i<Length(FiAttribs) do begin
if FiAttribs[i]=attrib then begin
FiAttribs[i+1]:=newValue;
Exit;
end;
Inc(i, 2);
end;
AddIAttrib(attrib, newValue);
end;
procedure TGLCarbonContext.DropIAttrib(attrib: Integer);
var
i: Integer;
begin
i:=0;
while i<Length(FiAttribs) do begin
if FiAttribs[i]=attrib then begin
Inc(i, 2);
while i<Length(FiAttribs) do begin
FiAttribs[i-2]:=FiAttribs[i];
Inc(i);
end;
SetLength(FiAttribs, Length(FiAttribs)-2);
Exit;
end;
Inc(i, 2);
end;
end;
procedure TGLCarbonContext.DoCreateContext(outputDevice: Cardinal);
var
DC: TCarbonDeviceContext absolute outputDevice;
Window: WindowRef;
Disp: GDHandle;
PixelFmt: TAGLPixelFormat;
begin
if not (CheckDC(outputDevice, 'DoCreateContext') or (DC is TCarbonControlContext)) then
raise EGLContext.Create('Creating context failed: invalid device context!');
FViewer := TCarbonControlContext(DC).Owner.LCLObject;
FForm := FViewer.GetTopParent;
if not (FForm is TCustomForm) then
raise EGLContext.Create('Creating context failed: control not on the form!');
Window := TCarbonWindow((FForm as TWinControl).Handle).Window;
// create the AGL context
Disp := GetMainDevice();
AddIAttrib(AGL_WINDOW, GL_TRUE);
AddIAttrib(AGL_RGBA, GL_TRUE);
AddIAttrib(AGL_RED_SIZE, Round(ColorBits / 3));
AddIAttrib(AGL_GREEN_SIZE, Round(ColorBits / 3));
AddIAttrib(AGL_BLUE_SIZE, Round(ColorBits / 3));
AddIAttrib(AGL_DEPTH_SIZE, DepthBits);
if AlphaBits > 0 then AddIAttrib(GLX_ALPHA_SIZE, AlphaBits);
AddIAttrib(AGL_DEPTH_SIZE, DepthBits);
if StencilBits > 0 then AddIAttrib(GLX_STENCIL_SIZE, StencilBits);
if AccumBits > 0 then
begin
AddIAttrib(AGL_ACCUM_RED_SIZE, round(AccumBits/4));
AddIAttrib(AGL_ACCUM_GREEN_SIZE, round(AccumBits/4));
AddIAttrib(AGL_ACCUM_BLUE_SIZE, round(AccumBits/4));
end;
if AuxBuffers > 0 then AddIAttrib(AGL_AUX_BUFFERS, AuxBuffers);
if (rcoDoubleBuffered in Options) then AddIAttrib(AGL_DOUBLEBUFFER, GL_TRUE);
// choose the best compatible pixel format
PixelFmt := aglChoosePixelFormat(@Disp, 1, @FIAttribs[0]);
if PixelFmt = nil then
begin
if DepthBits >= 32 then ChangeIAttrib(AGL_DEPTH_SIZE, 24);
PixelFmt := aglChoosePixelFormat(@Disp, 1, @FIAttribs[0]);
if PixelFmt = nil then
begin
if DepthBits >= 24 then ChangeIAttrib(AGL_DEPTH_SIZE, 16);
PixelFmt := aglChoosePixelFormat(@Disp, 1, @FIAttribs[0]);
if PixelFmt = nil then
begin
AddIAttrib(AGL_RED_SIZE, 4);
AddIAttrib(AGL_GREEN_SIZE, 4);
AddIAttrib(AGL_BLUE_SIZE, 4);
PixelFmt := aglChoosePixelFormat(@Disp, 1, @FIAttribs[0]);
end;
end;
end;
FContext := aglCreateContext(PixelFmt, nil);
aglDestroyPixelFormat(PixelFmt);
aglSetDrawable(FContext, GetWindowPort(Window));
FBounds := GetFormBounds;
BoundsChanged;
if FContext = nil then
raise EGLContext.Create('Failed to create rendering context!');
if PtrUInt(FContext) = AGL_BAD_CONTEXT then
raise EGLContext.Create('Created bad context!');
end;
procedure TGLCarbonContext.DoCreateMemoryContext(outputDevice: Cardinal; width,
height: Integer; BufferCount: integer);
begin
{$MESSAGE Warn 'DoCreateMemoryContext: Needs to be implemented'}
end;
procedure TGLCarbonContext.DoShareLists(aContext: TGLContext);
begin
{$MESSAGE Warn 'DoShareLists: Needs to be implemented'}
end;
procedure TGLCarbonContext.DoDestroyContext;
begin
if (aglGetCurrentContext = FContext) and
(aglSetCurrentContext(nil) = GL_FALSE) then
raise EGLContext.Create('Failed to deselect rendering context');
aglDestroyContext(FContext);
FContext := nil;
end;
procedure TGLCarbonContext.DoActivate;
var
B: TRect;
begin
B := GetFormBounds;
if (B.Left <> FBounds.Left) or (B.Top <> FBounds.Top) or
(B.Right <> FBounds.Right) or (B.Bottom <> FBounds.Bottom) then
begin
FBounds := B;
BoundsChanged;
end;
if aglSetCurrentContext(FContext) = GL_FALSE then
raise EGLContext.Create(cContextActivationFailed);
if glGetString(GL_VENDOR) <> vLastVendor then
begin
ReadExtensions;
ReadImplementationProperties;
vLastVendor:=glGetString(GL_VENDOR);
end;
end;
procedure TGLCarbonContext.DoDeactivate;
begin
if aglSetCurrentContext(nil) = GL_FALSE then
raise EGLContext.Create(cContextDeactivationFailed);
end;
constructor TGLCarbonContext.Create;
begin
inherited Create;
ClearIAttribs;
end;
destructor TGLCarbonContext.Destroy;
begin
inherited Destroy;
end;
function TGLCarbonContext.IsValid: Boolean;
begin
Result := (FContext <> nil);
end;
procedure TGLCarbonContext.SwapBuffers;
begin
if (FContext <> nil) and (rcoDoubleBuffered in Options) then
aglSwapBuffers(FContext);
end;
function TGLCarbonContext.RenderOutputDevice: Integer;
begin
Result := 0;
end;
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
RegisterGLContextClass(TGLCarbonContext);
end.
|
unit uLayer;
interface
uses uPoint, uLine, uMaths, uArrayListOfPoint, uArrayListOfLine, uUtils;
const MAX_POINTS = 300;
const MAX_LINES = 300;
{
For serialization
}
type layerRecord = record
name: String[255];
points: PointRecordList;
lines: LineRecordList;
currentPoint, currentLine: integer;
end;
type LayerRecordList = Array of LayerRecord;
{
Provides containers for containers of points
}
type Layer = class(TObject)
name: String[255];
points: ArrayListOfPoint;
currentPoint: integer;
lines: ArrayListOfLine;
currentLine: integer;
constructor Create(name: String);
function hasCurrentPoint(): boolean;
function getCurrentPoint(): Point;
procedure setCurrentPoint(p: Point);
function selectPrevPoint(): boolean;
function selectNextPoint(): boolean;
function addPoint(p: Point): boolean;
function removePoint(i: integer): boolean;
procedure addRandomPoints(n: integer; minX, maxX, minY, maxY: real);
procedure translatePoints(b, e: integer; dx, dy: real);
procedure cutPoints(b, e: integer);
function hasCurrentLine(): boolean;
function getCurrentLine(): Line;
procedure setCurrentLine(l: Line);
function selectPrevLine(): boolean;
function selectNextLine(): boolean;
function addLine(l: Line): boolean;
function removeLine(i: integer): boolean;
procedure cutLines(b, e: integer);
procedure updateLines();
end;
type LayerList = Array of Layer;
{
Draws poligon
}
procedure poligon(p: PointList; l: Layer);
function lyToClass(r: layerRecord): Layer;
function lyToRecord(l: Layer): LayerRecord;
implementation
// Layer
constructor Layer.Create(name: String);
begin
self.name := name;
points := ArrayListOfPoint.Create(50);
currentPoint := -1;
lines := ArrayListOfLine.Create(50);
currentLine := -1;
end;
// Layer
function Layer.hasCurrentPoint(): boolean;
begin
hasCurrentPoint := currentPoint <> -1;
end;
// Layer
function Layer.getCurrentPoint(): Point;
begin
getCurrentPoint := points.get(currentPoint);
end;
// Layer
procedure Layer.setCurrentPoint(p: Point);
begin
points.put(p, currentPoint);
end;
// Layer
function Layer.selectPrevPoint(): boolean;
begin
selectPrevPoint := false;
if currentPoint > 0 then begin
dec(currentPoint, 1);
selectPrevPoint := true; // success
end;
end;
// Layer
function Layer.selectNextPoint(): boolean;
begin
selectNextPoint := false;
if currentPoint < points.size() - 1 then begin
inc(currentPoint, 1);
selectNextPoint := true; // success
end;
end;
// Layer
function Layer.addPoint(p: Point): boolean;
begin
addPoint := false;
if points.size() < MAX_POINTS then begin
currentPoint := points.size();
points.add(p);
addPoint := true; // success
end;
end;
// Layer
procedure Layer.addRandomPoints(n: integer; minX, maxX, minY, maxY: real);
var
i, rest, req: integer;
begin
rest := MAX_POINTS - points.size();
req := n;
if (req > rest) then
req := rest;
for i := 1 to req do
addPoint(getRandPoint(minX, maxX, minY, maxY));
end;
// Layer
function Layer.removePoint(i: integer): boolean;
var j: integer;
begin
removePoint := false;
if (i > -1) and (i < points.size()) then
if (points.get(i) <> nil) then begin
points.remove(i);
if currentPoint = points.size() then
dec(currentPoint, 1);
updateLines();
removePoint := true;
end;
end;
// Layer
procedure Layer.cutPoints(b, e: integer);
var
i: integer;
begin
if b < 0 then
b := 0;
if b > points.size() - 1 then
b := points.size() - 1;
if e < 0 then
e := 0;
if e > points.size() - 1 then
e := points.size() - 1;
if b >= 0 then
for i := b to e do
removePoint(b);
end;
// Layer
procedure Layer.translatePoints(b, e: integer; dx, dy: real);
var
i: integer;
begin
if b < 0 then
b := 0;
if b > points.size() - 1 then
b := points.size() - 1;
if e < 0 then
e := 0;
if e > points.size() - 1 then
e := points.size() - 1;
if b >= 0 then
for i := b to e do begin
points.get(i).x := points.get(i).x + dx;
points.get(i).y := points.get(i).y + dy;
end;
end;
// Layer
function Layer.hasCurrentLine(): boolean;
begin
hasCurrentLine := currentLine <> -1;
end;
// Layer
function Layer.getCurrentLine(): Line;
begin
getCurrentLine := lines.get(currentLine);
end;
// Layer
procedure Layer.setCurrentLine(l: Line);
begin
lines.put(l, currentLine);
end;
// Layer
function Layer.selectPrevLine(): boolean;
begin
selectPrevLine := false;
if currentLine > 0 then begin
dec(currentLine, 1);
selectPrevLine := true; // success
end;
end;
// Layer
function Layer.selectNextLine(): boolean;
begin
selectNextLine := false;
if currentLine < lines.size() - 1 then begin
inc(currentLine, 1);
selectNextLine := true; // success
end;
end;
// Layer
function Layer.addLine(l: Line): boolean;
begin
addLine := false;
if lines.size() < MAX_LINES then begin
currentLine := lines.size();
lines.add(l);
addLine := true; // success
end;
end;
// Layer
function Layer.removeLine(i: integer): boolean;
var j: integer;
begin
removeLine := false;
if (i > -1) and (i < lines.size()) then
if (lines.get(i) <> nil) then begin
lines.remove(i);
if currentLine = lines.size() then
dec(currentLine, 1);
removeLine := true;
end;
end;
// Layer
procedure Layer.cutLines(b, e: integer);
var
i: integer;
begin
if b < 0 then
b := 0;
if b > lines.size() - 1 then
b := lines.size() - 1;
if e < 0 then
e := 0;
if e > lines.size() - 1 then
e := lines.size() - 1;
if b >= 0 then
for i := b to e do
removeLine(b);
end;
// Layer
procedure Layer.updateLines();
var i: integer;
begin
i := 0;
while i < lines.size() do begin
if (points.get(lines.get(i).p1) = nil) or (points.get(lines.get(i).p2) = nil) then
removeLine(i)
else
i := i + 1;
end;
end;
procedure poligon(p: PointList; l: Layer);
var
i, c: integer;
begin
c := 0;
for i := 0 to length(p) - 1 do begin
l.addPoint(p[i]);
if i > 0 then
l.addLine(Line.Create(l.currentPoint - 1, l.currentPoint))
else
c := l.currentPoint;
end;
if length(p) > 1 then
l.addLine(Line.Create(c, l.currentPoint));
end;
function lyToClass(r: layerRecord): Layer;
var
i: integer;
l: Layer;
begin
l := Layer.Create(r.name);
for i := 0 to length(r.points) - 1 do
l.addPoint(Point.Create(r.points[i].x, r.points[i].y));
for i := 0 to length(r.lines) - 1 do
l.addLine(Line.Create(r.lines[i].p1, r.lines[i].p2));
l.currentPoint := r.currentPoint;
l.currentLine := r.currentLine;
l.name := r.name;
lyToClass := l;
end;
function lyToRecord(l: Layer): LayerRecord;
var
i: integer;
r: LayerRecord;
begin
SetLength(r.points, l.points.size());
for i := 0 to l.points.size() - 1 do begin
r.points[i].x := l.points.get(i).x;
r.points[i].y := l.points.get(i).y;
end;
SetLength(r.lines, l.lines.size());
for i := 0 to l.lines.size() - 1 do begin
r.lines[i].p1 := l.lines.get(i).p1;
r.lines[i].p2 := l.lines.get(i).p2;
end;
r.currentPoint := l.currentPoint;
r.currentLine := l.currentLine;
r.name := l.name;
lyToRecord := r;
end;
end.
|
{ This unit contains class for Active Directory Schema Manipulation.
Author: Ismagilov Ilshat (student group 4410)
Email: ilshat.ismagilov2014@gmail.com
Organisation: KAI (kai.ru)
Version: 2.0
}
unit ADSchemaUnit;
interface
uses Windows, Classes, SysUtils, ADSchemaTypes, ADSchemaHelpUnit, LDAPClientUnit;
type
EntryType = (
ClassEntry,
AttributeEntry);
{ Public class for administrating the Active Directory(AD) Schema }
ADSchema = class
strict private
//working with LDAPClient
client : LDAPClient;
//Stores the state of connection
isSchemaActive : boolean;
//Client Info
_HostName, _UserName, _Password : string;
_PortNumber : integer;
//Schema Catalog DN
SchemaDN : string;
currentUserDN : string;
{ Private function for establishing connection }
function pvEstablishConnection() : ADSchemaStatus;
{ Private Function that tries to reconnect to server with current Client Info
*returns the statues of connection }
function pvTryConnect() : ADSchemaStatus;
{ Private Function that checks connection by sending simple query
*if fails return false
*if succeeds return true}
function pvCheckConnection() : boolean;
{ The only function that can change SchemaDN value!
*Returns true if success }
function pvSetSchemaDN() : boolean;
//working with LDAPClient - Clearing return values of Search
procedure pvClearLDAPSearchResults(var searchResults : LDAPEntryArray);
//search and get
function pvGetEntries(dn : string;
filter : string;
withAttr : array of string;
var status : ADSchemaStatus) : ADEntryList;
//Checks if entry has all needed attributes
function pvCheckEntry(chEntry : ADEntry;
var neededAttributes : TStringList) : boolean;
//Extended Search if too many values is expected
function pvSearchExtended(dn : string;
entrType : EntryType;
withAttr : array of string;
var status : ADSchemaStatus) : ADEntryList;
public
property isActive : boolean
read isSchemaActive;
{ -----------------------------------------------------------------
--------------------- Connection functions ---------------------- }
//Constructor creates an object and connects to server: isActive = true
constructor Create(hostName, userName, password: string; portNumber : integer;
var status : ADSchemaStatus); overload;
//Just creating object: isActive = false. You need to use Connect procedure
constructor Create();overload;
//Destructor
destructor Destroy(); override;
//Connects to server: if success changes isActive to True
procedure Connect(hostName, userName, password: string; portNumber : integer;
var status : ADSchemaStatus);
{ Disconnects from server
*it also called from destructor if isActive=true }
procedure Disconnect();
{ -----------------------------------------------------------------
---------------------- Data Handling Functions ------------------ }
{ Function returns ADEntry object with all attributes }
function GetEntry(CNname : string;
entrType : EntryType;
var status : ADSchemaStatus) : ADEntry; overload;
{ Function returns ADEntry object with given attributes }
function GetEntry(CNname : string;
entrType : EntryType;
withAttr : array of string;
var status : ADSchemaStatus) : ADEntry; overload;
{ Function returns List of ADEntry with ALL attributes }
function GetAll(entrType : EntryType;
var status : ADSchemaStatus) : ADEntryList; overload;
{ Function returns List of ADEntry with GIVEN attributes }
function GetAll(entrType : EntryType;
withAttr : array of string;
var status : ADSchemaStatus) : ADEntryList; overload;
{ Search and get function with LDAP filter }
function GetEntries(filter : string;
withAttr : array of string;
var status : ADSchemaStatus) : ADEntryList;
{ Function adds new entry to schema
* given ADEntry object is not freed in function }
function AddEntry(newEntry : ADEntry) : ADSchemaStatus;
{ Function modifies Entry (only attributes that given)
* given ADEntry object is not freed in function }
function ModifyEntryAttributes(modifiedEntry : ADEntry) : ADSchemaStatus;
{ Function deletes all attributes in given ADEntryObject
* given ADEntry object is not freed in function }
function DeleteEntryAttributes(entryWithDeleteAttributes : ADEntry)
: ADSchemaStatus; overload;
{ Function deletes given attributes of entry with given name }
function DeleteEntryAttributes(name : string;
attrToDelete : array of string)
: ADSchemaStatus; overload;
{ Function for activating defunct class or attribute }
function ActivateEntry(defunctEntryName : string) : ADSchemaStatus;
{ Function for deactivating active class or attribute }
function DeactivateEntry(activeEntryName : string) : ADSchemaStatus;
end;
implementation
{ --------------------------------------------------------
------------------- IMPLEMENTATION ---------------------
------------------- ADSchema ---------------------------
-------------------------------------------------------- }
{ Public }
constructor ADSchema.Create(hostName, userName, password: string; portNumber : integer;
var status : ADSchemaStatus);
begin
client := LDAPClient.Create;
Connect(hostName, userName, password, portNumber, status);
end;
{ Public }
constructor ADSchema.Create();
begin
client := LDAPClient.Create;
isSchemaActive := false;
end;
{ Public }
destructor ADSchema.Destroy();
begin
if isSchemaActive then
begin
Disconnect;
end;
if client <> nil then
begin
client.Free;
client := nil;
end;
inherited;
end;
{ Public }
procedure ADSchema.Connect(hostName, userName, password: string; portNumber : integer;
var status : ADSchemaStatus);
begin
{if status <> nil then
status.free; }
//check in values
//set in values
_HostName := hostName;
_PortNumber := portNumber;
_UserName := userName;
_Password := password;
//establishConnection function
status := pvEstablishConnection();
if status.StatusType <> SuccessStatus then
begin
if isSchemaActive then
isSchemaActive := false;
Exit;
end;
isSchemaActive := true;
//Forming SchemaDN
if not pvSetSchemaDN then
begin
status.Free;
status := ADSchemaStatus.Create(1, ADSchemaError, 'SetSchemaDN error!');
isSchemaActive := false;
Disconnect;
Exit;
end;
end;
{ Public }
procedure ADSchema.Disconnect();
begin
//LDAPClient disconnect
client.Disconnect;
_HostName := '';
_UserName := '';
_Password := '';
isSchemaActive := false;
end;
{ ----------------------------------------------
------------- Private functions -------------- }
{ Private }
function ADSchema.pvEstablishConnection() : ADSchemaStatus;
var
clientStatus : LDAPClientStatus;
begin
//LDAPCLient connect
clientStatus := client.Init(_HostName, _PortNumber);
if clientStatus.numb <> 0 then
begin
result := ADSchemaStatus.Create(clientStatus.numb, LDAPError, clientStatus.msg);
Exit;
end;
clientStatus := client.ConnectSimple(_UserName, _Password);
if clientStatus.numb <> 0 then
begin
result := ADSchemaStatus.Create(clientStatus.numb, LDAPError, clientStatus.msg);
Exit;
end;
result := ADSchemaStatus.Create();
end;
{ Private }
function ADSchema.pvTryConnect() : ADSchemaStatus;
begin
//try to establishConnection
result := pvEstablishConnection;
//if connection is established
if result.StatusType = SuccessStatus then
begin
//set isSchemaActive = true
isSchemaActive := true;
Exit;
end;
isSchemaActive := false;
end;
{ Private }
function ADSchema.pvCheckConnection() : boolean;
var
clientStatus : LDAPClientStatus;
searchResult : LDAPEntryArray;
begin
//Check is Schema Active
if isSchemaActive = false then
begin
result := isSchemaActive;
Exit;
end;
//Simple query to check connection
clientStatus := client.Search('CN=top,' + SchemaDN, '(objectClass=classSchema)', [], searchResult);
pvClearLDAPSearchResults(searchResult);
//if false then call Disconnect to clear memory
if clientStatus.numb <> 0 then
begin
Disconnect;
end;
//return isSchemaActive
result := isSchemaActive;
end;
{ Private }
function ADSchema.pvSetSchemaDN() : boolean;
var
dn : string;
parsedDn : string;
begin
dn := GetUserNameExString(NameFullyQualifiedDN);
currentUserDN := dn;
//parse the dn
if pos('DC=', dn) = 0 then
begin
result := false;
Exit;
end;
parsedDn := copy(dn, pos('DC=', dn));
Insert('CN=Schema,CN=Configuration,', parsedDn, 0);
SchemaDN := parsedDn;
result := true;
end;
{ -----------------------------------------------------------------
---------------------- Data Handling Functions ------------------ }
{ Public }
{ Function returns ADEntry object with all attributes }
function ADSchema.GetEntry(CNname : string;
entrType : EntryType;
var status : ADSchemaStatus) : ADEntry;
begin
result := GetEntry(CNname, entrType, [], status);
end;
{ Public }
{ Function returns ADEntry object with given attributes }
function ADSchema.GetEntry(CNname : string;
entrType : EntryType;
withAttr : array of string;
var status : ADSchemaStatus) : ADEntry;
var
entryDN, filter : string;
resTemp : ADEntryList;
begin
//forming entry dn
entryDN := 'CN=' + CNname + ',' + SchemaDN;
//forming filter
case entrType of
ClassEntry: filter := '(objectClass=classSchema)';
AttributeEntry: filter := '(objectClass=attributeSchema)';
end;
resTemp := pvGetEntries(entryDN, filter, withAttr, status);
//Check item count
if resTemp = nil then
begin
result := nil;
Exit;
end;
if resTemp.EntriesCount <> 1 then
begin
status.free;
status := ADSchemaStatus.Create(2, ADSchemaError, 'Wrong number of entries');
result := nil;
resTemp.Destroy;
Exit;
end;
result := resTemp.Items[0];
end;
{ Public }
{ Function returns List of ADEntry with ALL attributes }
function ADSchema.GetAll(entrType : EntryType;
var status : ADSchemaStatus) : ADEntryList;
begin
result := GetAll(entrType, [], status);
end;
{ Public }
{ Function returns List of ADEntry with GIVEN attributes }
function ADSchema.GetAll(entrType : EntryType;
withAttr : array of string;
var status : ADSchemaStatus) : ADEntryList;
var
entryDN, filter : string;
begin
//forming entry dn
entryDN := SchemaDN;
//forming filter
case entrType of
ClassEntry: filter := '(objectClass=classSchema)';
AttributeEntry: filter := '(objectClass=attributeSchema)';
end;
{result := pvGetEntries(entryDN, filter, withAttr, status);
if status.StatusNumb = 4 then
begin
if result <> nil then
begin
result.Destroy;
result := nil;
end;
status.Free;
status := nil;}
result := pvSearchExtended(entryDN, entrType, withAttr, status);
//end;
end;
{ Public }
{ Search and get function with LDAP filter }
function ADSchema.GetEntries(filter : string;
withAttr : array of string;
var status : ADSchemaStatus) : ADEntryList;
var
entryDN : string;
begin
entryDN := SchemaDN;
result := pvGetEntries(entryDN, filter, withAttr, status);
end;
{ Public }
{ Function adds new entry to schema }
function ADSchema.AddEntry(newEntry : ADEntry) : ADSchemaStatus;
var
neededAttributes : TStringList;
clientStatus : LDAPClientStatus;
entryDN : string;
attributes : array of LDAPAttribute;
attr : LDAPAttribute;
iAttribute, iValue : integer;
begin
//Check connection
//if connection lost exit
if pvCheckConnection = false then
begin
result := pvTryConnect;
if result.StatusType <> SuccessStatus then
begin
Exit;
end;
result.Free;
result := nil;
end;
//check given entry attributes
if pvCheckEntry(newEntry, neededAttributes) = false then
begin
//if there is no all "must" attributes,
//exit with message of needed attributes
Result := ADSchemaStatus.Create(3, ADSchemaError, neededAttributes.CommaText);
neededAttributes.Free;
neededAttributes := nil;
Exit;
end;
//form data for calling the LDAPClient function
entryDN := 'cn=' + newEntry.Name + ',' + SchemaDN;
SetLength(attributes, newEntry.AttributesCount);
for iAttribute := 0 to Length(attributes) - 1 do
begin
attr := LDAPAttribute.Create(newEntry.Attributes[iAttribute].ValuesCount);
attr.Name := newEntry.Attributes[iAttribute].Name;
for iValue := 0 to attr.ValueCount - 1 do
begin
attr.Value[iValue] := newEntry.Attributes[iAttribute].Values[iValue];
end;
attributes[iAttribute] := attr;
end;
//call LDAPClient AddEntry function
clientStatus := client.AddEntry(entryDN, attributes);
//check status
if clientStatus.numb <> 0 then
begin
//if fail, form ADSchemaStatus with LDAPError
Result :=ADSchemaStatus.Create(clientStatus.numb, LDAPError, clientStatus.msg);
Exit;
end;
//if success, form ADSchemaStatus with SuccessStatus
result := ADSchemaStatus.Create;
end;
{ Public }
{ Function modifies Entry (only attributes that given) }
function ADSchema.ModifyEntryAttributes(modifiedEntry : ADEntry) : ADSchemaStatus;
var
clientStatus : LDAPClientStatus;
entryDN : string;
attributes : array of LDAPAttribute;
attr : LDAPAttribute;
iAttribute, iValue : integer;
begin
//Check connection
//if connection lost exit
if pvCheckConnection = false then
begin
result := pvTryConnect;
if result.StatusType <> SuccessStatus then
begin
Exit;
end;
result.Free;
result := nil;
end;
//form data for calling the LDAPClient function
entryDN := 'CN=' + modifiedEntry.Name + ',' + SchemaDN;
SetLength(attributes, modifiedEntry.AttributesCount);
for iAttribute := 0 to Length(attributes) - 1 do
begin
attr := LDAPAttribute.Create(modifiedEntry.Attributes[iAttribute].ValuesCount);
attr.Name := modifiedEntry.Attributes[iAttribute].Name;
for iValue := 0 to attr.ValueCount - 1 do
begin
attr.Value[iValue] := modifiedEntry.Attributes[iAttribute].Values[iValue];
end;
attributes[iAttribute] := attr;
end;
//call LDAPClient ModfiyEntry function
clientStatus := client.ModifyEntry(entryDN, attributes, MODIFY_TYPE_REPLACE);
//check status
if clientStatus.numb <> 0 then
begin
//if fail, form ADSchemaStatus with LDAPError
Result := ADSchemaStatus.Create(clientStatus.numb, LDAPError, clientStatus.msg);
Exit;
end;
//if success, form ADSchemaStatus with SuccessStatus
result := ADSchemaStatus.Create;
end;
{ Public }
{ Function deletes all attributes in given ADEntryObject }
function ADSchema.DeleteEntryAttributes(entryWithDeleteAttributes : ADEntry)
: ADSchemaStatus;
var
clientStatus : LDAPClientStatus;
entryDN : string;
attributes : array of LDAPAttribute;
attr : LDAPAttribute;
iAttribute, iValue : integer;
begin
//Check connection
//if connection lost exit
if pvCheckConnection = false then
begin
result := pvTryConnect;
if result.StatusType <> SuccessStatus then
begin
Exit;
end;
result.Free;
result := nil;
end;
//form data for calling the LDAPClient function
entryDN := 'CN=' + entryWithDeleteAttributes.Name + ',' + SchemaDN;
SetLength(attributes, entryWithDeleteAttributes.AttributesCount);
for iAttribute := 0 to Length(attributes) - 1 do
begin
attr := LDAPAttribute.Create(entryWithDeleteAttributes.Attributes[iAttribute].ValuesCount);
attr.Name := entryWithDeleteAttributes.Attributes[iAttribute].Name;
for iValue := 0 to attr.ValueCount - 1 do
begin
attr.Value[iValue] := entryWithDeleteAttributes.Attributes[iAttribute].Values[iValue];
end;
attributes[iAttribute] := attr;
end;
//call LDAPClient Modify function
clientStatus := client.ModifyEntry(entryDN, attributes, MODIFY_TYPE_DELETE);
//check status
if clientStatus.numb <> 0 then
begin
//if fail, form ADSchemaStatus with LDAPError
Result := ADSchemaStatus.Create(clientStatus.numb, LDAPError, clientStatus.msg);
Exit;
end;
//if success, form ADSchemaStatus with SuccessStatus
result := ADSchemaStatus.Create;
end;
{ Public }
{ Function deletes given attributes of entry with given name }
function ADSchema.DeleteEntryAttributes(name : string;
attrToDelete : array of string)
: ADSchemaStatus;
var
clientStatus : LDAPClientStatus;
entryDN : string;
attributes : array of LDAPAttribute;
attr : LDAPAttribute;
iAttribute : integer;
begin
//Check connection
//if connection lost exit
if pvCheckConnection = false then
begin
result := pvTryConnect;
if result.StatusType <> SuccessStatus then
begin
Exit;
end;
result.Free;
result := nil;
end;
//form data for calling the LDAPClient function
entryDN := 'CN=' + name + ',' + SchemaDN;
SetLength(attributes, Length(attrToDelete));
for iAttribute := 0 to Length(attributes) - 1 do
begin
attr := LDAPAttribute.Create(0);
attr.Name := attrToDelete[iAttribute];
attributes[iAttribute] := attr;
end;
//call LDAPClient MofifyEntry function
clientStatus := client.ModifyEntry(entryDN, attributes, MODIFY_TYPE_DELETE);
//check status
if clientStatus.numb <> 0 then
begin
//if fail, form ADSchemaStatus with LDAPError
Result := ADSchemaStatus.Create(clientStatus.numb, LDAPError, clientStatus.msg);
Exit;
end;
//if success, form ADSchemaStatus with SuccessStatus
result := ADSchemaStatus.Create;
end;
{ Public }
{ Function for activating defunct class or attribute }
function ADSchema.ActivateEntry(defunctEntryName : string) : ADSchemaStatus;
var
defunctEntry : ADEntry;
begin
defunctEntry := ADEntry.Create(defunctEntryName);
defunctEntry.AddAttribute('isDefunct', ['FALSE']);
Result := ModifyEntryAttributes(defunctEntry);
end;
{ Public }
{ Function for deactivating active class or attribute }
function ADSchema.DeactivateEntry(activeEntryName : string) : ADSchemaStatus;
var
activeEntry : ADEntry;
begin
activeEntry := ADEntry.Create(activeEntryName);
activeEntry.AddAttribute('isDefunct', ['TRUE']);
Result := ModifyEntryAttributes(activeEntry);
end;
{ Private }
procedure ADSchema.pvClearLDAPSearchResults(var searchResults : LDAPEntryArray);
var
iEntry : integer;
iAttribute : integer;
begin
for iEntry := 0 to Length(searchResults) - 1 do
begin
for iAttribute := 0 to searchResults[iEntry].attributes.Count - 1 do
begin
LDAPAttribute(searchResults[iEntry].attributes).Free;
LDAPAttribute(searchResults[iEntry].attributes) := nil;
end;
searchResults[iEntry].attributes.Free;
searchResults[iEntry].attributes := nil;
end;
SetLength(searchResults, 0);
end;
{ Private }
//search and get
function ADSchema.pvGetEntries(dn : string;
filter : string;
withAttr : array of string;
var status : ADSchemaStatus) : ADEntryList;
var
entryDN, searchFilter : string;
attrs : array of LDAPAttribute;
attr : LDAPAttribute;
iAttribute, iValue, iEntry : integer;
searchResults : LDAPEntryArray;
ldapStatus : LDAPClientStatus;
attributeIndex, entryIndex : integer;
parsedName : string;
begin
//Check Connection
if pvCheckConnection = false then
begin
status := pvTryConnect;
if status.StatusType <> SuccessStatus then
begin
result := nil;
Exit;
end;
if status <> nil then
begin
status.Free;
status := nil;
end;
if pvCheckConnection = false then
begin
result := nil;
status := ADSchemaStatus.Create(4, ADSchemaError, 'Cant get schema entries!');
Exit;
end;
end;
//forming entry dn
entryDN := dn;
//forming filter
searchFilter := filter;
//forming attributes array
SetLength(attrs, Length(withAttr));
for iAttribute := 0 to Length(withAttr) - 1 do
begin
attr := LDAPAttribute.Create(0);
attr.Name := withAttr[iAttribute];
attrs[iAttribute] := attr;
end;
//Call LDAPClient function
ldapStatus := client.Search(entryDN, searchFilter, attrs, searchResults);
if ldapStatus.numb <> 0 then
begin
status := ADSchemaStatus.Create(ldapStatus.numb, LDAPError, ldapStatus.msg);
result := nil;
Exit;
end;
//parse Search Results and form return object
result := ADEntryList.Create;
for iEntry := 0 to Length(searchResults) - 1 do
begin
parsedName := searchResults[iEntry].dn;
//delete 'CN='
Delete(parsedName,1,3);
//copy
parsedName := copy(parsedName, 1, pos(',CN=', parsedName)-1);
//create new entry
entryIndex := Result.AddEntry(parsedName);
for iAttribute := 0 to searchResults[iEntry].attributes.Count - 1 do
begin
attr := LDAPAttribute(searchResults[iEntry].attributes[iAttribute]);
attributeIndex := result.Items[entryIndex].AddAttribute(attr.Name);
for iValue := 0 to attr.ValueCount - 1 do
result.Items[entryIndex].Attributes[attributeIndex].AddValue(attr.Value[iValue]);
end;
end;
//Clearing return values of client.Search
pvClearLDAPSearchResults(searchResults);
status := ADSchemaStatus.Create;
end;
{ PRIVATE }
//Extended Search if too many values is expected
function ADSchema.pvSearchExtended(dn : string;
entrType : EntryType;
withAttr : array of string;
var status : ADSchemaStatus) : ADEntryList;
var
entryDN, searchFilter : string;
attrs : array of LDAPAttribute;
attr : LDAPAttribute;
iAttribute, iValue, iEntry, i: integer;
searchResults : LDAPEntryArray;
ldapStatus : LDAPClientStatus;
attributeIndex, entryIndex : integer;
parsedName : string;
helpString : string;
begin
helpString := 'abcdefghijklmnopqrstuvwxyz'; //26
//forming entry dn
entryDN := dn;
result := ADEntryList.Create;
for i := 1 to Length(helpString) do
begin
//forming filter
case entrType of
ClassEntry: searchFilter := '(&(objectClass=classSchema)(cn='+ helpString[i] + '*))';
AttributeEntry: searchFilter := '(&(objectClass=attributeSchema)(cn='+ helpString[i] + '*))';
end;
//forming attributes array
SetLength(attrs, Length(withAttr));
for iAttribute := 0 to Length(withAttr) - 1 do
begin
attr := LDAPAttribute.Create(0);
attr.Name := withAttr[iAttribute];
attrs[iAttribute] := attr;
end;
//Call LDAPClient function
ldapStatus := client.Search(entryDN, searchFilter, attrs, searchResults);
if ldapStatus.numb <> 0 then
begin
status := ADSchemaStatus.Create(ldapStatus.numb, LDAPError, ldapStatus.msg);
result.Destroy;
result := nil;
Exit;
end;
//parse Search Results and form return object
for iEntry := 0 to Length(searchResults) - 1 do
begin
parsedName := searchResults[iEntry].dn;
//delete 'CN='
Delete(parsedName,1,3);
//copy
parsedName := copy(parsedName, 1, pos(',CN=', parsedName)-1);
//create new entry
entryIndex := Result.AddEntry(parsedName);
for iAttribute := 0 to searchResults[iEntry].attributes.Count - 1 do
begin
attr := LDAPAttribute(searchResults[iEntry].attributes[iAttribute]);
attributeIndex := result.Items[entryIndex].AddAttribute(attr.Name);
for iValue := 0 to attr.ValueCount - 1 do
result.Items[entryIndex].Attributes[attributeIndex].AddValue(attr.Value[iValue]);
end;
end;
//Clearing return values of client.Search
pvClearLDAPSearchResults(searchResults);
end;
status := ADSchemaStatus.Create;
end;
{ Private }
//Checks if entry has all needed attributes
function ADSchema.pvCheckEntry(chEntry : ADEntry;
var neededAttributes : TStringList) : boolean;
type
objectType = (notDefined, attributeType, classType);
var
iAttribute, iValue, i : integer;
objectClasses : array of string;
oType : objectType;
isCnExist,
isObjectClassesExist,
isGovernsIDExist,
isAttributeIDExist,
isAttributeSyntaxExist,
isOMSyntaxExist : boolean;
begin
//Check if 'cn' attribute is set
//Check if 'objectClass' attriubute is set
isCnExist := false;
isObjectClassesExist := false;
isGovernsIDExist := false;
isAttributeIDExist := false;
isAttributeSyntaxExist := false;
isOMSyntaxExist := false;
for iAttribute := 0 to chEntry.AttributesCount - 1 do
begin
if not isObjectClassesExist then
begin
if chEntry.Attributes[iAttribute].Name = 'objectClass' then
begin
SetLength(objectClasses, chEntry.Attributes[iAttribute].ValuesCount);
for iValue := 0 to Length(objectClasses) - 1 do
begin
objectClasses[iValue] := chEntry.Attributes[iAttribute].Values[iValue];
end;
isObjectClassesExist := true;
end;
end;
if not isCnExist then
begin
if chEntry.Attributes[iAttribute].Name = 'cn' then
isCnExist := true;
end;
if not isGovernsIDExist then
begin
if chEntry.Attributes[iAttribute].Name = 'governsID' then
isGovernsIDExist := true;
end;
if not isAttributeIDExist then
begin
if chEntry.Attributes[iAttribute].Name = 'attributeID' then
isAttributeIDExist := true;
end;
if not isAttributeSyntaxExist then
begin
if chEntry.Attributes[iAttribute].Name = 'attributeSyntax' then
isAttributeSyntaxExist := true;
end;
if not isOMSyntaxExist then
begin
if chEntry.Attributes[iAttribute].Name = 'oMSyntax' then
isOMSyntaxExist := true;
end;
end;
if not isCnExist then
begin
neededAttributes := TStringList.Create;
neededAttributes.Add('cn');
result := false;
Exit;
end;
if not isObjectClassesExist then
begin
neededAttributes := TStringList.Create;
neededAttributes.Add('objectClass');
result := false;
Exit;
end;
{ write check of must attributes }
//Check existence of 'must' attributes
for i := 0 to Length(objectClasses) - 1 do
begin
if objectClasses[i] = 'classSchema' then
begin
oType := classType;
Break;
end;
if objectClasses[i] = 'attributeSchema' then
begin
oType := attributeType;
Break;
end;
end;
if oType = notDefined then
begin
neededAttributes := TStringList.Create;
neededAttributes.Add('classSchema');
neededAttributes.Add('attributeSchema');
result := false;
Exit;
end;
if oType = attributeType then
begin
{ Check existence:
*attributeID
*attributeSyntax
*oMSyntax }
if not isAttributeIDExist or not isAttributeSyntaxExist or not isOMSyntaxExist then
begin
neededAttributes := TStringList.Create;
neededAttributes.Add('attributeID');
neededAttributes.Add('attributeSyntax');
neededAttributes.Add('oMSyntax');
result := false;
Exit;
end;
end;
if oType = classType then
begin
{ Check existence:
*governsID }
if not isGovernsIDExist then
begin
neededAttributes := TStringList.Create;
neededAttributes.Add('governsID');
result := false;
Exit;
end;
end;
result := true;
end;
end.
|
//////////////////////////////////////////////////////////////
// //
// //
// 加密/解密单元 //
// 清清 2007.10.14 //
// //
// //
//////////////////////////////////////////////////////////////
unit EDcodeUnit;
interface
uses
Windows, SysUtils, DESTR, Des;
type
TStringInfo = packed record
btLength: Byte;
nUniCode: Integer;
sString: array[0..High(Byte) - 1] of Char;
end;
pTStringInfo = ^TStringInfo;
TString = packed record
btLength: Byte;
nUniCode: Integer;
sString: array[0..High(Word) - 1] of Char;
end;
pTString = ^TString;
function EncodeString(Str: string): string;
function DecodeString(Str: string): string;
function EncodeBuffer(Buf: PChar; bufsize: Integer): string;
procedure DecodeBuffer(Src: string; Buf: PChar; bufsize: Integer);
procedure Decode6BitBuf(sSource: PChar; pBuf: PChar; nSrcLen, nBufLen: Integer);
procedure Encode6BitBuf(pSrc, pDest: PChar; nSrcLen, nDestLen: Integer);
function Encrypt_Decrypt(m: Int64; E: Int64 = $2C86F9; n: Int64 = $69AAA0E3): Integer;
function Chinese2UniCode(AiChinese: string): Integer;
function GetUniCode(msg: string): Integer;
function Str_ToInt(Str: string; Def: LongInt): LongInt;
function Encode(Src: string; var Dest: string): Boolean;
function Decode(Src: string; var Dest: string): Boolean;
function Base64EncodeStr(const Value: string): string;
{ Encode a string into Base64 format }
function Base64DecodeStr(const Value: string): string;
{ Decode a Base64 format string }
function Base64Encode(pInput: Pointer; pOutput: Pointer; Size: LongInt): LongInt;
{ Encode a lump of raw data (output is (4/3) times bigger than input) }
function Base64Decode(pInput: Pointer; pOutput: Pointer; Size: LongInt): LongInt;
{ Decode a lump of raw data }
function EncodeString_3des(Source, Key: string): string;
function DecodeString_3des(Source, Key: string): string;
function CalcFileCRC(sFileName: string): Integer;
function CalcBufferCRC(Buffer: PChar; nSize: Integer): Integer;
function DecryptString(Src: string): string;
function EncryptString(Src: string): string;
function EncryptBuffer(Buf: PChar; bufsize: Integer): string;
procedure DecryptBuffer(Src: string; Buf: PChar; bufsize: Integer);
implementation
const
BUFFERSIZE = 10000;
B64: array[0..63] of Byte = (65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108,
109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53,
54, 55, 56, 57, 43, 47);
Key: array[0..2, 0..7] of Byte = (($FF, $FE, $FF, $FE, $FF, $FE, $FF, $FF), ($FF, $FE, $FF, $FE, $FF, $FE, $FF, $FF), ($FF, $FE, $FF, $FE, $FF, $FE, $FF, $FF));
var
CSEncode: TRTLCriticalSection;
function CalcFileCRC(sFileName: string): Integer;
var
I: Integer;
nFileHandle: Integer;
nFileSize, nBuffSize: Integer;
Buffer: PChar;
Int: ^Integer;
nCrc: Integer;
begin
Result := 0;
if not FileExists(sFileName) then Exit;
nFileHandle := FileOpen(sFileName, fmOpenRead or fmShareDenyNone);
if nFileHandle = 0 then
Exit;
nFileSize := FileSeek(nFileHandle, 0, 2); //改变文件的指针
nBuffSize := (nFileSize div 4) * 4;
GetMem(Buffer, nBuffSize);
FillChar(Buffer^, nBuffSize, 0);
FileSeek(nFileHandle, 0, 0);
FileRead(nFileHandle, Buffer^, nBuffSize);
FileClose(nFileHandle);
Int := Pointer(Buffer);
nCrc := 0;
//Exception.Create(IntToStr(SizeOf(Integer)));//20080303 异常提示,注释掉此句就可以不泄漏内存
for I := 0 to nBuffSize div 4 - 1 do begin
nCrc := nCrc xor Int^;
Int := Pointer(Integer(Int) + 4);
end;
FreeMem(Buffer);
Result := nCrc;
end;
function CalcBufferCRC(Buffer: PChar; nSize: Integer): Integer;
var
I: Integer;
Int: ^Integer;
nCrc: Integer;
begin
Int := Pointer(Buffer);
nCrc := 0;
for I := 0 to nSize div 4 - 1 do begin
nCrc := nCrc xor Int^;
Int := Pointer(Integer(Int) + 4);
end;
Result := nCrc;
end;
function Base64Encode(pInput: Pointer; pOutput: Pointer; Size: LongInt): LongInt;
var
I, iptr, optr: Integer;
Input, Output: PByteArray;
begin
Input := PByteArray(pInput); Output := PByteArray(pOutput);
iptr := 0; optr := 0;
for I := 1 to (Size div 3) do begin
Output^[optr + 0] := B64[Input^[iptr] shr 2];
Output^[optr + 1] := B64[((Input^[iptr] and 3) shl 4) + (Input^[iptr + 1] shr 4)];
Output^[optr + 2] := B64[((Input^[iptr + 1] and 15) shl 2) + (Input^[iptr + 2] shr 6)];
Output^[optr + 3] := B64[Input^[iptr + 2] and 63];
Inc(optr, 4); Inc(iptr, 3);
end;
case (Size mod 3) of
1: begin
Output^[optr + 0] := B64[Input^[iptr] shr 2];
Output^[optr + 1] := B64[(Input^[iptr] and 3) shl 4];
Output^[optr + 2] := Byte('=');
Output^[optr + 3] := Byte('=');
end;
2: begin
Output^[optr + 0] := B64[Input^[iptr] shr 2];
Output^[optr + 1] := B64[((Input^[iptr] and 3) shl 4) + (Input^[iptr + 1] shr 4)];
Output^[optr + 2] := B64[(Input^[iptr + 1] and 15) shl 2];
Output^[optr + 3] := Byte('=');
end;
end;
Result := ((Size + 2) div 3) * 4;
end;
function Base64EncodeStr(const Value: string): string;
begin
setlength(Result, ((Length(Value) + 2) div 3) * 4);
Base64Encode(@Value[1], @Result[1], Length(Value));
end;
function Base64Decode(pInput: Pointer; pOutput: Pointer; Size: LongInt): LongInt;
var
I, J, iptr, optr: Integer;
temp: array[0..3] of Byte;
Input, Output: PByteArray;
begin
Input := PByteArray(pInput); Output := PByteArray(pOutput);
iptr := 0; optr := 0;
Result := 0;
for I := 1 to (Size div 4) do begin
for J := 0 to 3 do begin
case Input^[iptr] of
65..90: temp[J] := Input^[iptr] - Ord('A');
97..122: temp[J] := Input^[iptr] - Ord('a') + 26;
48..57: temp[J] := Input^[iptr] - Ord('0') + 52;
43: temp[J] := 62;
47: temp[J] := 63;
61: temp[J] := $FF;
end;
Inc(iptr);
end;
Output^[optr] := (temp[0] shl 2) or (temp[1] shr 4);
Result := optr + 1;
if (temp[2] <> $FF) and (temp[3] = $FF) then begin
Output^[optr + 1] := (temp[1] shl 4) or (temp[2] shr 2);
Result := optr + 2;
Inc(optr)
end
else if (temp[2] <> $FF) then begin
Output^[optr + 1] := (temp[1] shl 4) or (temp[2] shr 2);
Output^[optr + 2] := (temp[2] shl 6) or temp[3];
Result := optr + 3;
Inc(optr, 2);
end;
Inc(optr);
end;
end;
function Base64DecodeStr(const Value: string): string;
begin
setlength(Result, (Length(Value) div 4) * 3);
setlength(Result, Base64Decode(@Value[1], @Result[1], Length(Value)));
end;
function Str_ToInt(Str: string; Def: LongInt): LongInt;
begin
Result := Def;
if Str <> '' then begin
if ((Word(Str[1]) >= Word('0')) and (Word(Str[1]) <= Word('9'))) or
(Str[1] = '+') or (Str[1] = '-') then try
Result := StrToInt64(Str);
except
end;
end;
end;
procedure Encode6BitBuf(pSrc, pDest: PChar; nSrcLen, nDestLen: Integer);
var
I, nRestCount, nDestPos: Integer;
btMade, btCh, btRest: Byte;
begin
nRestCount := 0;
btRest := 0;
nDestPos := 0;
for I := 0 to nSrcLen - 1 do begin
if nDestPos >= nDestLen then Break;
btCh := Byte(pSrc[I]);
btMade := Byte((btRest or (btCh shr (2 + nRestCount))) and $3F);
btRest := Byte(((btCh shl (8 - (2 + nRestCount))) shr 2) and $3F);
Inc(nRestCount, 2);
if nRestCount < 6 then begin
pDest[nDestPos] := Char(btMade + $3C);
Inc(nDestPos);
end else begin
if nDestPos < nDestLen - 1 then begin
pDest[nDestPos] := Char(btMade + $3C);
pDest[nDestPos + 1] := Char(btRest + $3C);
Inc(nDestPos, 2);
end else begin
pDest[nDestPos] := Char(btMade + $3C);
Inc(nDestPos);
end;
nRestCount := 0;
btRest := 0;
end;
end;
if nRestCount > 0 then begin
pDest[nDestPos] := Char(btRest + $3C);
Inc(nDestPos);
end;
pDest[nDestPos] := #0;
end;
procedure Decode6BitBuf(sSource: PChar; pBuf: PChar; nSrcLen, nBufLen: Integer);
const
Masks: array[2..6] of Byte = ($FC, $F8, $F0, $E0, $C0);
//($FE, $FC, $F8, $F0, $E0, $C0, $80, $00);
var
I, {nLen,} nBitPos, nMadeBit, nBufPos: Integer;
btCh, btTmp, btByte: Byte;
begin
// nLen:= Length (sSource);
nBitPos := 2;
nMadeBit := 0;
nBufPos := 0;
btTmp := 0;
btCh := 0;//20080521
for I := 0 to nSrcLen - 1 do begin
if Integer(sSource[I]) - $3C >= 0 then
btCh := Byte(sSource[I]) - $3C
else begin
nBufPos := 0;
Break;
end;
if nBufPos >= nBufLen then Break;
if (nMadeBit + 6) >= 8 then begin
btByte := Byte(btTmp or ((btCh and $3F) shr (6 - nBitPos)));
pBuf[nBufPos] := Char(btByte);
Inc(nBufPos);
nMadeBit := 0;
if nBitPos < 6 then Inc(nBitPos, 2)
else begin
nBitPos := 2;
Continue;
end;
end;
btTmp := Byte(Byte(btCh shl nBitPos) and Masks[nBitPos]); // #### ##--
Inc(nMadeBit, 8 - nBitPos);
end;
pBuf[nBufPos] := #0;
end;
function DecodeString(Str: string): string;
var
EncBuf: array[0..BUFFERSIZE - 1] of Char;
begin
try
EnterCriticalSection(CSEncode);
Decode6BitBuf(PChar(Str), @EncBuf, Length(Str), SizeOf(EncBuf));
Result := StrPas(EncBuf);
finally
LeaveCriticalSection(CSEncode);
end;
end;
procedure DecodeBuffer(Src: string; Buf: PChar; bufsize: Integer);
var
EncBuf: array[0..BUFFERSIZE - 1] of Char;
begin
try
EnterCriticalSection(CSEncode);
Decode6BitBuf(PChar(Src), @EncBuf, Length(Src), SizeOf(EncBuf));
Move(EncBuf, Buf^, bufsize);
finally
LeaveCriticalSection(CSEncode);
end;
end;
function EncodeString(Str: string): string;
var
EncBuf: array[0..BUFFERSIZE - 1] of Char;
begin
try
EnterCriticalSection(CSEncode);
Encode6BitBuf(PChar(Str), @EncBuf, Length(Str), SizeOf(EncBuf));
Result := StrPas(EncBuf);
finally
LeaveCriticalSection(CSEncode);
end;
end;
function EncodeBuffer(Buf: PChar; bufsize: Integer): string;
var
EncBuf, TempBuf: array[0..BUFFERSIZE - 1] of Char;
begin
try
EnterCriticalSection(CSEncode);
if bufsize < BUFFERSIZE then begin
Move(Buf^, TempBuf, bufsize);
Encode6BitBuf(@TempBuf, @EncBuf, bufsize, SizeOf(EncBuf));
Result := StrPas(EncBuf);
end else Result := '';
finally
LeaveCriticalSection(CSEncode);
end;
end;
function ReverseStr(SourceStr: string): string;
var
Counter: Integer;
begin
Result := '';
for Counter := 1 to Length(SourceStr) do
Result := SourceStr[Counter] + Result;
end;
{function Encry(Src, Key: string): string;
var
sSrc, sKey: string;
begin
EnterCriticalSection(CSEncode);
try
if Key = '' then sKey := IntToStr(240621028)
else sKey := Key;
sSrc := EncryStrHex(Src, sKey);
Result := ReverseStr(sSrc);
finally
LeaveCriticalSection(CSEncode);
end;
end;
function Decry(Src, Key: string): string;
var
sSrc, sKey: string;
begin
EnterCriticalSection(CSEncode);
try
try
if Key = '' then sKey := IntToStr(240621028)
else sKey := Key;
sSrc := ReverseStr(Src);
Result := DecryStrHex(sSrc, sKey);
except
Result := '';
end;
finally
LeaveCriticalSection(CSEncode);
end;
end;}
function Chinese2UniCode(AiChinese: string): Integer;
var
Ch, cl: string[2];
A: array[1..2] of Char;
begin
StringToWideChar(Copy(AiChinese, 1, 2), @(A[1]), 2);
Ch := IntToHex(Integer(A[2]), 2);
cl := IntToHex(Integer(A[1]), 2);
Result := StrToInt('$' + Ch + cl);
end;
function GetUniCode(msg: string): Integer;
var
I: Integer;
begin
Result := -1;
for I := 1 to Length(msg) do begin
Result := Result + Chinese2UniCode(msg[I]) * I;
end;
end;
function PowMod(base: Int64; pow: Int64; n: Int64): Int64;
var
A, b, c: Int64;
begin
A := base;
b := pow;
c := 1;
while (b > 0) do begin
while (not ((b and 1) > 0)) do begin
b := b shr 1;
A := A * A mod n;
end;
Dec(b);
c := A * c mod n;
end;
Result := c;
end;
//RSA的加密和解密函数,等价于(m^e) mod n(即m的e次幂对n求余)
function Encrypt_Decrypt(m: Int64; E: Int64 = $2C86F9; n: Int64 = $69AAA0E3): Integer;
var
A, b, c: Int64;
// nN: Integer;
const
nNumber = 100000;
MaxValue = 1400000000;
MinValue = 1299999999;
function GetInteger(n: Int64): Int64;
var
D: Int64;
begin
D := n;
while D > MaxValue do D := D - nNumber;
while D < MinValue do D := D + nNumber;
if D = MinValue then D := D + m;
if D = MaxValue then D := D - m;
Result := D;
end;
begin
EnterCriticalSection(CSEncode);
try
A := m;
b := E;
c := 1;
while b <> 0 do
if (b mod 2) = 0
then begin
b := b div 2;
A := (A * A) mod n;
end
else begin
b := b - 1;
c := (A * c) mod n;
end;
while (c < MinValue) or (c > MaxValue) do c := GetInteger(c);
Result := c;
finally
LeaveCriticalSection(CSEncode);
end;
end;
function DecodeString_3des(Source, Key: string): string;
var
DesDecode: TDCP_3des;
Str: string;
begin
try
Result := '';
DesDecode := TDCP_3des.Create(nil);
DesDecode.InitStr(Key);
DesDecode.Reset;
Str := DesDecode.DecryptString(Source);
DesDecode.Reset;
Result := Str;
DesDecode.Free;
except
Result := '';
end;
end;
function EncodeString_3des(Source, Key: string): string;
var
DesEncode: TDCP_3des;
Str: string;
begin
try
Result := '';
DesEncode := TDCP_3des.Create(nil);
DesEncode.InitStr(Key);
DesEncode.Reset;
Str := DesEncode.EncryptString(Source);
DesEncode.Reset;
Result := Str;
DesEncode.Free;
except
Result := '';
end;
end;
function Encode(Src: string; var Dest: string): Boolean;
var
StringInfo: TStringInfo;
sDest: string;
begin
// Result := False;
Dest := '';
FillChar(StringInfo, SizeOf(TStringInfo), 0);
StringInfo.btLength := Length(Src);
StringInfo.nUniCode := GetUniCode(Src);
FillChar(StringInfo.sString, SizeOf(StringInfo.sString), 0);
Move(Src[1], StringInfo.sString, StringInfo.btLength);
setlength(sDest, SizeOf(Byte) + SizeOf(Integer) + StringInfo.btLength);
Move(StringInfo, sDest[1], SizeOf(Byte) + SizeOf(Integer) + StringInfo.btLength);
Dest := ReverseStr(EncryStrHex(sDest, IntToStr(398432431{240621028})));
Result := True;
end;
function Decode(Src: string; var Dest: string): Boolean;
var
StringInfo: TStringInfo;
sDest: string;
sSrc: string;
begin
Result := False;
Dest := '';
sDest := ReverseStr(Trim(Src));
try
sDest := DecryStrHex(sDest, IntToStr(398432431{240621028}));
except
Exit;
end;
FillChar(StringInfo, SizeOf(TStringInfo), 0);
Move(sDest[1], StringInfo, Length(sDest));
sSrc := StrPas(@StringInfo.sString);
if (GetUniCode(sSrc) = StringInfo.nUniCode) and (Length(sSrc) = StringInfo.btLength) then begin
Dest := sSrc;
Result := True;
end;
end;
function DecryptString(Src: string): string;
begin
Result := ReverseStr(Base64DecodeStr(Src));
end;
function EncryptString(Src: string): string;
begin
Result := Base64EncodeStr(ReverseStr(Src));
end;
function EncryptBuffer(Buf: PChar; bufsize: Integer): string;
var
Src: string;
begin
setlength(Src, bufsize + 1);
Move(Buf^, Src[1], bufsize + 1);
Result := EncryptString(Src);
end;
procedure DecryptBuffer(Src: string; Buf: PChar; bufsize: Integer);
var
Dest: string;
begin
Dest := DecryptString(Src);
if Dest <> '' then
Move(Dest[1], Buf^, bufsize);
end;
initialization
begin
InitializeCriticalSection(CSEncode);
end;
finalization
begin
DeleteCriticalSection(CSEncode);
end;
end.
|
unit frmOutGoFabricRules;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, DBClient, ExtCtrls, Grids, DBGrids, Buttons, frmBase,
StdCtrls, Mask, DBCtrls, ComCtrls
;
type
TOutGoFabricRulesForm = class(TBaseForm)
Panel1: TPanel;
CDSRules: TClientDataSet;
DSRules: TDataSource;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
DBEdtName: TDBEdit;
DBEdtValue1: TDBEdit;
DBEdtValue2: TDBEdit;
DBEdtValue3: TDBEdit;
DBEdtValue4: TDBEdit;
DBEdtType: TDBEdit;
Label7: TLabel;
DBEdtRules: TDBEdit;
Label8: TLabel;
DBEdtPriority: TDBEdit;
GroupBox1: TGroupBox;
DBGrdTerms: TDBGrid;
CDSTerms: TClientDataSet;
DSTerms: TDataSource;
GroupBox2: TGroupBox;
DBGrid1: TDBGrid;
Panel2: TPanel;
Panel3: TPanel;
SBtnAdd: TSpeedButton;
SBtnRemove: TSpeedButton;
SBtnSave: TSpeedButton;
SBtnExit: TSpeedButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure SBtnExitClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure SBtnSaveClick(Sender: TObject);
procedure SBtnAddClick(Sender: TObject);
procedure SBtnRemoveClick(Sender: TObject);
private
{ Private declarations }
procedure init;
procedure GetOutGoFabricRulesData;
procedure GetOutGoFabricTermsData;
procedure Save;
public
{ Public declarations }
end;
var
OutGoFabricRulesForm: TOutGoFabricRulesForm;
implementation
uses uFNMResource, ServerDllPub, uShowMessage, uGridDecorator, uLogin,
uGlobal;
{$R *.dfm}
procedure TOutGoFabricRulesForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if CDSRules.ChangeCount > 0 then
if MessageDlg('提示: 数据已修改, 尚未保存, 是否继续退出操作?', mtConfirmation, [mbYes, mbNo],0) = mrNo then
begin
Action := caNone;
Exit;
end;//if
Action := caFree;
end;
procedure TOutGoFabricRulesForm.FormDestroy(Sender: TObject);
begin
OutGoFabricRulesForm := nil;
end;
procedure TOutGoFabricRulesForm.SBtnExitClick(Sender: TObject);
begin
Close;
end;
procedure TOutGoFabricRulesForm.init;
begin
SBtnAdd.Glyph.LoadFromResourceName(HInstance, RES_NEW);
SBtnRemove.Glyph.LoadFromResourceName(HInstance, RES_DELETE);
SBtnSave.Glyph.LoadFromResourceName(HInstance, RES_SAVE);
SBtnExit.Glyph.LoadFromResourceName(HInstance, RES_EXIT);
GetOutGoFabricRulesData;
GetOutGoFabricTermsData;
end;
procedure TOutGoFabricRulesForm.GetOutGoFabricRulesData;
var
sql, sErrorMsg : WideString;
vData : OleVariant;
begin
try
ShowMsg('正在获取数据稍等!', crHourGlass);
sql := QuotedStr('GetOutGoFabricRulesData') + ',' + QuotedStr('');
FNMServerObj.GetQueryData(vData,'GiFullCarFabricsData', sql, sErrorMsg);
if Trim(sErrorMsg) <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrorMsg, mtError);
Exit;
end;//if
CDSRules.Data := vData;
finally
ShowMsg('', crDefault);
end;//finally
end;
procedure TOutGoFabricRulesForm.GetOutGoFabricTermsData;
var
sql, sErrorMsg : WideString;
vData : OleVariant;
begin
try
ShowMsg('正在获取数据稍等!', crHourGlass);
sql := QuotedStr('GetOutGoFabricTermsData') + ',' + QuotedStr('');
FNMServerObj.GetQueryData(vData,'GiFullCarFabricsData', sql, sErrorMsg);
if Trim(sErrorMsg) <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrorMsg, mtError);
Exit;
end;//if
CDSTerms.Data := vData;
finally
ShowMsg('', crDefault);
end;//finally
end;
procedure TOutGoFabricRulesForm.FormShow(Sender: TObject);
begin
init;
end;
procedure TOutGoFabricRulesForm.Save;
var
sErrMsg : WideString;
vData : OleVariant;
begin
try
uShowMessage.ShowStatusMessage('正在保存数据...', crHourGlass);
if CDSRules.State in [dsEdit, dsInsert] then
CDSRules.Post;
if CDSRules.ChangeCount > 0 then
begin
vData := CDSRules.Delta;
FNMServerObj.SaveBaseTableInfo(vData, 'OutGoFabricRules', '', sErrMsg);
if sErrMsg <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrMsg, mtError);
Exit;
end;//if
CDSRules.MergeChangeLog;
TMsgDialog.ShowMsgDialog('数据保存成功!', mtInformation);
end;//if
finally
uShowMessage.ShowStatusMessage('', crDefault);
end;//finally
end;
procedure TOutGoFabricRulesForm.SBtnSaveClick(Sender: TObject);
begin
Save;
end;
procedure TOutGoFabricRulesForm.SBtnAddClick(Sender: TObject);
begin
CDSRules.Append;
end;
procedure TOutGoFabricRulesForm.SBtnRemoveClick(Sender: TObject);
begin
CDSRules.Delete;
end;
end.
|
unit uExplorerDateStackProviders;
interface
uses
System.Classes,
System.SysUtils,
System.StrUtils,
Vcl.Graphics,
Data.DB,
Dmitry.Utils.System,
Dmitry.Utils.ShellIcons,
Dmitry.PathProviders,
Dmitry.PathProviders.MyComputer,
uConstants,
uMemory,
uTranslate,
uExplorerPathProvider,
uExplorerGroupsProvider,
uExplorerPersonsProvider,
uDBConnection,
uDBContext,
uDBEntities,
uDBManager,
uDateUtils;
type
TDateStackItem = class(TPathItem)
protected
function InternalGetParent: TPathItem; override;
function InternalCreateNewInstance: TPathItem; override;
function GetIsDirectory: Boolean; override;
public
function LoadImage(Options, ImageSize: Integer): Boolean; override;
constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override;
end;
TCalendarItem = class(TPathItem)
protected
FCount: Integer;
function GetOrder: Integer; virtual; abstract;
public
procedure SetCount(Count: Integer);
procedure IntCount;
property Order: Integer read GetOrder;
end;
TDateStackYearItem = class(TCalendarItem)
private
function GetYear: Integer;
protected
function InternalGetParent: TPathItem; override;
function InternalCreateNewInstance: TPathItem; override;
function GetIsDirectory: Boolean; override;
function GetDisplayName: string; override;
function GetOrder: Integer; override;
public
procedure Assign(Item: TPathItem); override;
function LoadImage(Options, ImageSize: Integer): Boolean; override;
constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override;
property Year: Integer read GetYear;
end;
TDateStackMonthItem = class(TCalendarItem)
private
function GetMonth: Integer;
function GetYear: Integer;
protected
function InternalGetParent: TPathItem; override;
function InternalCreateNewInstance: TPathItem; override;
function GetIsDirectory: Boolean; override;
function GetDisplayName: string; override;
function GetOrder: Integer; override;
public
procedure Assign(Item: TPathItem); override;
function LoadImage(Options, ImageSize: Integer): Boolean; override;
constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override;
property Month: Integer read GetMonth;
property Year: Integer read GetYear;
end;
TDateStackDayItem = class(TCalendarItem)
private
function GetDay: Integer;
function GetMonth: Integer;
function GetYear: Integer;
function GetDate: TDateTime;
protected
function InternalGetParent: TPathItem; override;
function InternalCreateNewInstance: TPathItem; override;
function GetIsDirectory: Boolean; override;
function GetDisplayName: string; override;
function GetOrder: Integer; override;
public
procedure Assign(Item: TPathItem); override;
function LoadImage(Options, ImageSize: Integer): Boolean; override;
constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override;
property Day: Integer read GetDay;
property Month: Integer read GetMonth;
property Year: Integer read GetYear;
property Date: TDateTime read GetDate;
end;
type
TExplorerDateStackProvider = class(TExplorerPathProvider)
public
function GetTranslateID: string; override;
function Supports(Item: TPathItem): Boolean; override;
function Supports(Path: string): Boolean; override;
function CreateFromPath(Path: string): TPathItem; override;
function InternalFillChildList(Sender: TObject; Item: TPathItem; List: TPathItemCollection; Options, ImageSize: Integer; PacketSize: Integer; CallBack: TLoadListCallBack): Boolean; override;
end;
implementation
{ TExplorerDateStackProvider }
function TExplorerDateStackProvider.CreateFromPath(Path: string): TPathItem;
var
S: string;
P: Integer;
function CreateDateItem(S: string): TPathItem;
var
SL: TStrings;
I: Integer;
begin
Result := nil;
SL := TStringList.Create;
try
SL.Delimiter := '\';
SL.DelimitedText := S;
for I := SL.Count - 1 downto 0 do
if SL[I] = '' then
SL.Delete(I);
if SL.Count = 0 then
Result := TDateStackItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0);
if SL.Count = 1 then
Result := TDateStackYearItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0);
if SL.Count = 2 then
Result := TDateStackMonthItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0);
if SL.Count = 3 then
Result := TDateStackDayItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0);
finally
F(SL);
end;
end;
begin
Result := nil;
S := ExcludeTrailingPathDelimiter(Path);
if StartsText(cDatesPath, AnsiLowerCase(S)) then
begin
Delete(S, 1, Length(cDatesPath));
Result := CreateDateItem(S);
end;
if StartsText(cGroupsPath + '\', AnsiLowerCase(S)) then
begin
Delete(S, 1, Length(cGroupsPath) + 1);
P := Pos('\', S);
if P > 0 then
Result := CreateDateItem(Copy(S, P + 1, Length(S) - P));
end;
if StartsText(cPersonsPath + '\', AnsiLowerCase(S)) then
begin
Delete(S, 1, Length(cPersonsPath) + 1);
P := Pos('\', S);
if P > 0 then
Result := CreateDateItem(Copy(S, P + 1, Length(S) - P));
end;
end;
function TExplorerDateStackProvider.GetTranslateID: string;
begin
Result := 'CalendarProvider';
end;
function Capitalize(const S: string): string;
begin
Result := S;
if Length(Result) > 0 then
Result[1] := AnsiUpperCase(Result[1])[1];
end;
function TExplorerDateStackProvider.InternalFillChildList(Sender: TObject;
Item: TPathItem; List: TPathItemCollection; Options, ImageSize,
PacketSize: Integer; CallBack: TLoadListCallBack): Boolean;
var
Cancel: Boolean;
Count, Year, Month, Day: Integer;
DSI: TDateStackItem;
YI: TDateStackYearItem;
MI: TDateStackMonthItem;
DI: TDateStackDayItem;
GI: TGroupItem;
PI: TPersonItem;
FDateRangeDS: TDataSet;
Filter, SQL, Table: string;
Context: IDBContext;
function ImagesFilter: string;
begin
Result := FormatEx('(Attr <> {0} AND Attr <> {1} AND DateToAdd > ' + IntToStr(cMinEXIFYear) + ' and IsDate = True)', [Db_attr_missed, Db_attr_deleted]);
end;
function PersonsJoin: string;
begin
Result := FormatEx(' INNER JOIN (SELECT DISTINCT ObjectId, ImageId FROM {1}) PM on PM.ImageID = IM.ID) INNER JOIN {0} P on P.ObjectID = PM.ObjectID', [ObjectTableName, ObjectMappingTableName]);
end;
function FromTable(ForPersons: Boolean): string;
begin
if not ForPersons then
Result := 'ImageTable'
else
Result := Format('(SELECT ImageID, DateToAdd, Attr, IsDate, ObjectName FROM ($DB$ IM %s)', [PersonsJoin]);
end;
begin
inherited;
Result := True;
Cancel := False;
if Options and PATH_LOAD_ONLY_FILE_SYSTEM > 0 then
Exit;
if Item is THomeItem then
begin
DSI := TDateStackItem.CreateFromPath(cDatesPath, Options, ImageSize);
List.Add(DSI);
end;
if Item is TDateStackItem then
begin
Context := DBManager.DBContext;
FDateRangeDS := Context.CreateQuery(dbilRead);
try
ForwardOnlyQuery(FDateRangeDS);
SetSQL(FDateRangeDS, 'SELECT Year(DateToAdd) as GroupYear, Count(1) as ItemCount FROM (select DateToAdd from ImageTable where ' + ImagesFilter + ' ) Group BY Year(DateToAdd) Order by Year(DateToAdd) desc');
OpenDS(FDateRangeDS);
while not FDateRangeDS.EOF do
begin
Year := FDateRangeDS.Fields[0].AsInteger;
Count := FDateRangeDS.Fields[1].AsInteger;
YI := TDateStackYearItem.CreateFromPath(cDatesPath + '\' + IntToStr(Year), Options, ImageSize);
YI.SetCount(Count);
List.Add(YI);
FDateRangeDS.Next;
end;
finally
FreeDS(FDateRangeDS);
end;
end;
if Item is TGroupItem then
begin
Context := DBManager.DBContext;
GI := TGroupItem(Item);
FDateRangeDS := Context.CreateQuery(dbilRead);
try
ForwardOnlyQuery(FDateRangeDS);
Filter := ImagesFilter;
Filter := Filter + ' AND (Groups like "' + TGroup.GroupSearchByGroupName(GI.GroupName) + '")';
SetSQL(FDateRangeDS, 'SELECT Year(DateToAdd) as "GroupYear", Count(1) as ItemCount FROM (select DateToAdd from ImageTable where ' + Filter + ' ) Group BY Year(DateToAdd) Order by Year(DateToAdd) desc');
OpenDS(FDateRangeDS);
while not FDateRangeDS.EOF do
begin
Year := FDateRangeDS.Fields[0].AsInteger;
Count := FDateRangeDS.Fields[1].AsInteger;
YI := TDateStackYearItem.CreateFromPath(ExcludeTrailingPathDelimiter(Item.Path) + '\' + IntToStr(Year), Options, ImageSize);
YI.SetCount(Count);
List.Add(YI);
FDateRangeDS.Next;
end;
finally
FreeDS(FDateRangeDS);
end;
end;
if Item is TPersonItem then
begin
Context := DBManager.DBContext;
PI := TPersonItem(item);
FDateRangeDS := Context.CreateQuery(dbilRead);
try
ForwardOnlyQuery(FDateRangeDS);
Table := FromTable(True);
Filter := ImagesFilter;
Filter := Filter + ' AND (trim(P.ObjectName) like ' + NormalizeDBString(NormalizeDBStringLike(PI.PersonName)) + ')';
SetSQL(FDateRangeDS, 'SELECT Year(DateToAdd) as "GroupYear", Count(1) as ItemCount FROM (select DateToAdd from ' + Table + ' where ' + Filter + ' ) Group BY Year(DateToAdd) Order by Year(DateToAdd) desc');
OpenDS(FDateRangeDS);
while not FDateRangeDS.EOF do
begin
Year := FDateRangeDS.Fields[0].AsInteger;
Count := FDateRangeDS.Fields[1].AsInteger;
YI := TDateStackYearItem.CreateFromPath(ExcludeTrailingPathDelimiter(Item.Path) + '\' + IntToStr(Year), Options, ImageSize);
YI.SetCount(Count);
List.Add(YI);
FDateRangeDS.Next;
end;
finally
FreeDS(FDateRangeDS);
end;
end;
if Item is TDateStackYearItem then
begin
Context := DBManager.DBContext;
YI := TDateStackYearItem(Item);
FDateRangeDS := Context.CreateQuery(dbilRead);
try
ForwardOnlyQuery(FDateRangeDS);
Filter := ImagesFilter;
if (YI.Parent is TGroupItem) then
begin
GI := TGroupItem(YI.Parent);
Filter := Filter + ' AND (Groups like "' + TGroup.GroupSearchByGroupName(GI.GroupName) + '")';
end;
Table := FromTable(False);
if (YI.Parent is TPersonItem) then
begin
Table := FromTable(True);
PI := TPersonItem(YI.Parent);
Filter := Filter + ' AND (trim(P.ObjectName) like ' + NormalizeDBString(NormalizeDBStringLike(PI.PersonName)) + ')';
end;
SQL := 'SELECT Month(DateToAdd) as "GroupMonth", Count(1) as ItemCount FROM (select DateToAdd from ' + Table + ' where ' + Filter + ' and Year(DateToAdd) = ' + IntToStr(YI.Year) + ') Group BY Month(DateToAdd) Order by Month(DateToAdd) desc';
SetSQL(FDateRangeDS, SQL);
OpenDS(FDateRangeDS);
while not FDateRangeDS.EOF do
begin
Month := FDateRangeDS.Fields[0].AsInteger;
Count := FDateRangeDS.Fields[1].AsInteger;
MI := TDateStackMonthItem.CreateFromPath(ExcludeTrailingPathDelimiter(Item.Path) + '\' + IntToStr(Month), Options, ImageSize);
MI.SetCount(Count);
List.Add(MI);
FDateRangeDS.Next;
end;
finally
FreeDS(FDateRangeDS);
end;
end;
if Item is TDateStackMonthItem then
begin
Context := DBManager.DBContext;
MI := TDateStackMonthItem(Item);
FDateRangeDS := Context.CreateQuery(dbilRead);
try
ForwardOnlyQuery(FDateRangeDS);
Filter := ImagesFilter;
if (MI.Parent <> nil) and (MI.Parent.Parent is TGroupItem) then
begin
GI := TGroupItem(MI.Parent.Parent);
Filter := Filter + ' AND (Groups like "' + TGroup.GroupSearchByGroupName(GI.GroupName) + '")';
end;
Table := FromTable(False);
if (MI.Parent <> nil) and (MI.Parent.Parent is TPersonItem) then
begin
Table := FromTable(True);
PI := TPersonItem(MI.Parent.Parent);
Filter := Filter + ' AND (trim(P.ObjectName) like ' + NormalizeDBString(NormalizeDBStringLike(PI.PersonName)) + ')';
end;
SQL := 'SELECT Day(DateToAdd) as "GroupDay", Count(1) as ItemCount FROM (select DateToAdd from ' + Table + ' where ' + Filter + ' and Year(DateToAdd) = ' + IntToStr(MI.Year) + ' and Month(DateToAdd) = ' + IntToStr(MI.Month) + ') Group BY Day(DateToAdd) Order by Day(DateToAdd) desc';
SetSQL(FDateRangeDS, SQL);
OpenDS(FDateRangeDS);
while not FDateRangeDS.EOF do
begin
Day := FDateRangeDS.Fields[0].AsInteger;
Count := FDateRangeDS.Fields[1].AsInteger;
DI := TDateStackDayItem.CreateFromPath(ExcludeTrailingPathDelimiter(Item.Path) + '\' + IntToStr(Day), Options, ImageSize);
DI.SetCount(Count);
List.Add(DI);
FDateRangeDS.Next;
end;
finally
FreeDS(FDateRangeDS);
end;
end;
if Assigned(CallBack) then
CallBack(Sender, Item, List, Cancel);
end;
function TExplorerDateStackProvider.Supports(Item: TPathItem): Boolean;
begin
Result := Item is TDateStackItem;
Result := Result or Supports(Item.Path);
end;
function TExplorerDateStackProvider.Supports(Path: string): Boolean;
begin
Result := StartsText(L(cDatesPath), AnsiLowerCase(Path));
if not Result then
begin
if StartsText(cGroupsPath + '\', AnsiLowerCase(Path)) then
begin
Delete(Path, 1, Length(cGroupsPath) + 1);
Result := Pos('\', Path) > 0;
end;
end;
if not Result then
begin
if StartsText(cPersonsPath + '\', AnsiLowerCase(Path)) then
begin
Delete(Path, 1, Length(cPersonsPath) + 1);
Result := Pos('\', Path) > 0;
end;
end;
end;
{ TDateStackItem }
constructor TDateStackItem.CreateFromPath(APath: string; Options,
ImageSize: Integer);
begin
inherited;
FDisplayName := TA('Calendar', 'CalendarProvider');
if Options and PATH_LOAD_NO_IMAGE = 0 then
LoadImage(Options, ImageSize);
end;
function TDateStackItem.GetIsDirectory: Boolean;
begin
Result := True;
end;
function TDateStackItem.InternalCreateNewInstance: TPathItem;
begin
Result := TDateStackItem.Create;
end;
function TDateStackItem.InternalGetParent: TPathItem;
begin
Result := THomeItem.Create;
end;
function TDateStackItem.LoadImage(Options, ImageSize: Integer): Boolean;
var
Icon: TIcon;
begin
F(FImage);
FindIcon(HInstance, 'CALENDAR', ImageSize, 32, Icon);
FImage := TPathImage.Create(Icon);
Result := True;
end;
{ TDateStackYearItem }
procedure TDateStackYearItem.Assign(Item: TPathItem);
begin
inherited;
FCount := TDateStackYearItem(Item).FCount;
end;
constructor TDateStackYearItem.CreateFromPath(APath: string; Options,
ImageSize: Integer);
begin
inherited;
if Options and PATH_LOAD_NO_IMAGE = 0 then
LoadImage(Options, ImageSize);
end;
function TDateStackYearItem.GetDisplayName: string;
begin
Result := IntToStr(Year);
if FCount > 0 then
Result := Result + ' (' + IntToStr(FCount) + ')';
end;
function TDateStackYearItem.GetIsDirectory: Boolean;
begin
Result := True;
end;
function TDateStackYearItem.GetOrder: Integer;
begin
Result := Year * 10000;
end;
function TDateStackYearItem.GetYear: Integer;
var
S: string;
P: Integer;
begin
Result := 0;
S := ExcludeTrailingPathDelimiter(FPath);
P := LastDelimiter('/\', S);
if P > 0 then
begin
S := System.Copy(S, P + 1, Length(S) - P);
Result := StrToInt64Def(S, 0);
end;
end;
function TDateStackYearItem.InternalCreateNewInstance: TPathItem;
begin
Result := TDateStackYearItem.Create;
end;
function TDateStackYearItem.InternalGetParent: TPathItem;
var
S: string;
P: Integer;
begin
S := ExcludeTrailingPathDelimiter(FPath);
P := LastDelimiter('/\', S);
if P > 0 then
begin
S := System.Copy(S, 1, P - 1);
Result := PathProviderManager.CreatePathItem(S);
Exit;
end;
Result := nil;
end;
function TDateStackYearItem.LoadImage(Options, ImageSize: Integer): Boolean;
var
Icon: TIcon;
begin
F(FImage);
FindIcon(HInstance, 'YEARICON', ImageSize, 32, Icon);
FImage := TPathImage.Create(Icon);
Result := True;
end;
{ TDateStackMonthItem }
procedure TDateStackMonthItem.Assign(Item: TPathItem);
begin
inherited;
FCount := TDateStackMonthItem(Item).FCount;
end;
constructor TDateStackMonthItem.CreateFromPath(APath: string; Options,
ImageSize: Integer);
begin
inherited;
if Options and PATH_LOAD_NO_IMAGE = 0 then
LoadImage(Options, ImageSize);
end;
function TDateStackMonthItem.GetDisplayName: string;
begin
Result := Capitalize(MonthToString(Month));
if FCount > 0 then
Result := Result + ' (' + IntToStr(FCount) + ')';
end;
function TDateStackMonthItem.GetIsDirectory: Boolean;
begin
Result := True;
end;
function TDateStackMonthItem.GetMonth: Integer;
var
S: string;
P: Integer;
begin
Result := 0;
S := ExcludeTrailingPathDelimiter(FPath);
P := LastDelimiter('/\', S);
if P > 0 then
begin
S := System.Copy(S, P + 1, Length(S) - P);
Result := StrToInt64Def(S, 0);
end;
end;
function TDateStackMonthItem.GetOrder: Integer;
begin
Result := Year + 10000 + Month + 100;
end;
function TDateStackMonthItem.GetYear: Integer;
var
S: string;
P: Integer;
begin
Result := 0;
S := ExcludeTrailingPathDelimiter(FPath);
P := LastDelimiter('/\', S);
if P > 0 then
begin
S := System.Copy(S, 1, P - 1);
P := LastDelimiter('/\', S);
if P > 0 then
begin
S := System.Copy(S, P + 1, Length(S) - P);
Result := StrToInt64Def(S, 0);
end;
end;
end;
function TDateStackMonthItem.InternalCreateNewInstance: TPathItem;
begin
Result := TDateStackMonthItem.Create;
end;
function TDateStackMonthItem.InternalGetParent: TPathItem;
var
S: string;
P: Integer;
begin
S := ExcludeTrailingPathDelimiter(FPath);
P := LastDelimiter('/\', S);
if P > 0 then
begin
S := System.Copy(S, 1, P - 1);
Result := TDateStackYearItem.CreateFromPath(S, PATH_LOAD_NORMAL or PATH_LOAD_NO_IMAGE or PATH_LOAD_FAST, 0);
Exit;
end;
Result := nil;
end;
function TDateStackMonthItem.LoadImage(Options, ImageSize: Integer): Boolean;
var
Icon: TIcon;
begin
F(FImage);
FindIcon(HInstance, 'MONTHICON', ImageSize, 32, Icon);
FImage := TPathImage.Create(Icon);
Result := True;
end;
{ TDateStackDayItem }
procedure TDateStackDayItem.Assign(Item: TPathItem);
begin
inherited;
FCount := TDateStackDayItem(Item).FCount;
end;
constructor TDateStackDayItem.CreateFromPath(APath: string; Options,
ImageSize: Integer);
begin
inherited;
if Options and PATH_LOAD_NO_IMAGE = 0 then
LoadImage(Options, ImageSize);
end;
function TDateStackDayItem.GetDate: TDateTime;
begin
Result := EncodeDate(Year, Month, Day);
end;
function TDateStackDayItem.GetDay: Integer;
var
S: string;
P: Integer;
begin
Result := 0;
S := ExcludeTrailingPathDelimiter(FPath);
P := LastDelimiter('/\', S);
if P > 0 then
begin
S := System.Copy(S, P + 1, Length(S) - P);
Result := StrToInt64Def(S, 0);
end;
end;
function TDateStackDayItem.GetMonth: Integer;
var
S: string;
P: Integer;
begin
Result := 0;
S := ExcludeTrailingPathDelimiter(FPath);
P := LastDelimiter('/\', S);
if P > 0 then
begin
S := System.Copy(S, 1, P - 1);
P := LastDelimiter('/\', S);
if P > 0 then
begin
S := System.Copy(S, P + 1, Length(S) - P);
Result := StrToInt64Def(S, 0);
end;
end;
end;
function TDateStackDayItem.GetOrder: Integer;
begin
Result := Year * 10000 + Month * 100 + Day;
end;
function TDateStackDayItem.GetYear: Integer;
var
S: string;
P: Integer;
begin
Result := 0;
S := ExcludeTrailingPathDelimiter(FPath);
P := LastDelimiter('/\', S);
if P > 0 then
begin
S := System.Copy(S, 1, P - 1);
P := LastDelimiter('/\', S);
if P > 0 then
begin
S := System.Copy(S, 1, P - 1);
P := LastDelimiter('/\', S);
if P > 0 then
begin
S := System.Copy(S, P + 1, Length(S) - P);
Result := StrToInt64Def(S, 0);
end;
end;
end;
end;
function TDateStackDayItem.GetDisplayName: string;
begin
Result := IntToStr(Day);
if FCount > 0 then
Result := Result + ' (' + IntToStr(FCount) + ')';
end;
function TDateStackDayItem.GetIsDirectory: Boolean;
begin
Result := False;
end;
function TDateStackDayItem.InternalCreateNewInstance: TPathItem;
begin
Result := TDateStackDayItem.Create;
end;
function TDateStackDayItem.InternalGetParent: TPathItem;
var
S: string;
P: Integer;
begin
S := ExcludeTrailingPathDelimiter(FPath);
P := LastDelimiter('/\', S);
if P > 0 then
begin
S := System.Copy(S, 1, P - 1);
Result := TDateStackMonthItem.CreateFromPath(S, PATH_LOAD_NORMAL or PATH_LOAD_NO_IMAGE or PATH_LOAD_FAST, 0);
Exit;
end;
Result := nil;
end;
function TDateStackDayItem.LoadImage(Options, ImageSize: Integer): Boolean;
var
Icon: TIcon;
begin
F(FImage);
FindIcon(HInstance, 'DAYICON', ImageSize, 32, Icon);
FImage := TPathImage.Create(Icon);
Result := True;
end;
{ TCalendarItem }
procedure TCalendarItem.IntCount;
begin
Inc(FCount);
end;
procedure TCalendarItem.SetCount(Count: Integer);
begin
FCount := Count;
end;
end.
|
unit AccessForTns;
interface
uses
ADODB, SysUtils, Common, ENUtil, bsDBGrids, bsSkinCtrls;
type
TTNS = class(TObject)
public
TID, TNAME, TCP, HOST, PORT, SID: string;
constructor Create; overload;
end;
TTNSARR = array of TTNS;
TnsManage = class(TObject)
public
ADOQuery, ADOQueryop: TADOQuery;
ADOConnection: TADOConnection;
procedure InitADO;
function GetCurrentDir: string;
procedure InitAll();
procedure SaveAll(bsSkinGauge: TbsSkinGauge);
procedure Search(TSQL, FileName: string; DBGrid: TbsSkinDBGrid);
function GetTnsById(Tid: string): TTNS;
function AddTns(TNS: TTNS): Boolean;
function UpdateTns(TNS: TTNS): Boolean;
function DeleteTns(TNS: TTNS): Boolean;
function DeleteAll: Boolean;
function CheckTnsName(Tns, TID: string): Boolean;
constructor Create; overload;
destructor Destroy; override;
end;
implementation
constructor TTNS.Create;
begin
Self.TID := Common.CreateOnlyId;
inherited Create;
end;
constructor TnsManage.Create;
begin
Self.ADOQuery := TADOQuery.Create(nil);
Self.ADOQueryop := TADOQuery.Create(nil);
Self.ADOConnection := TADOConnection.Create(nil);
Self.ADOQuery.Connection := ADOConnection;
Self.ADOQueryop.Connection := ADOConnection;
InitADO;
inherited Create;
end;
destructor TnsManage.Destroy;
begin
ADOQuery.Close;
ADOQueryop.Close;
ADOConnection.Close;
ADOQuery.Destroy;
ADOQueryop.Destroy;
ADOConnection.Destroy;
inherited Destroy;
end;
procedure TnsManage.InitADO;
begin
ADOConnection.ConnectionString :=
'Provider=Microsoft.Jet.OLEDB.4.0;Password="";Data Source=' +
GetCurrentDir +
'\Oracle.mdb;Persist Security Info=True';
ADOConnection.LoginPrompt := false;
ADOConnection.Open;
end;
function TnsManage.GetCurrentDir: string;
begin
GetDir(0, Result);
end;
function TnsManage.GetTnsById(Tid: string): TTNS;
var
TNS: TTNS;
begin
try
with ADOQueryop do
begin
Close;
Sql.Clear;
Sql.Add('select * from tns where TID = ''' + Tid + '''');
Open;
if ADOQuery.RecordCount > 0 then
begin
TNS := TTNS.Create;
TNS.TID := FieldByName('TID').AsString;
TNS.TNAME := FieldByName('TNAME').AsString;
TNS.TCP := FieldByName('TCP').AsString;
TNS.HOST := FieldByName('HOST').AsString;
TNS.PORT := FieldByName('PORT').AsString;
TNS.SID := FieldByName('SID').AsString;
Result := TNS;
Close;
end
else
begin
Result := nil;
Close;
end;
end;
except
end;
end;
function TnsManage.AddTns(TNS: TTNS): Boolean;
begin
Result := false;
try
with ADOQueryop do
begin
Close;
Sql.Clear;
Sql.Add
('insert into tns values (:TID,:TNAME,:TCP,:HOST,:PORT,:SID)');
Parameters.ParamByName('TID').Value := TNS.TID;
Parameters.ParamByName('TNAME').Value := TNS.TNAME;
Parameters.ParamByName('TCP').Value := TNS.TCP;
Parameters.ParamByName('HOST').Value := TNS.HOST;
Parameters.ParamByName('PORT').Value := TNS.PORT;
Parameters.ParamByName('SID').Value := TNS.SID;
ExecSQL;
Close;
end;
except
end;
Result := true;
end;
function TnsManage.UpdateTns(TNS: TTNS): Boolean;
begin
Result := false;
try
with ADOQueryop do
begin
Close;
Sql.Clear;
Sql.Add(
'update tns set TNAME = :TNAME, TCP = :TCP,HOST = :HOST ,PORT = :PORT,SID = :SID where TID =:TID');
Parameters.ParamByName('TID').Value := TNS.TID;
Parameters.ParamByName('TNAME').Value := TNS.TNAME;
Parameters.ParamByName('TCP').Value := TNS.TCP;
Parameters.ParamByName('HOST').Value := TNS.HOST;
Parameters.ParamByName('PORT').Value := TNS.PORT;
Parameters.ParamByName('SID').Value := TNS.SID;
ExecSQL;
Close;
end;
except
end;
Result := true;
end;
function TnsManage.DeleteTns(TNS: TTNS): Boolean;
begin
Result := false;
try
with ADOQueryop do
begin
Close;
Sql.Clear;
Sql.Add('delete from tns where TID =:TID');
Parameters.ParamByName('TID').Value := TNS.TID;
ExecSQL;
Close;
end;
except
end;
Result := true;
end;
function TnsManage.DeleteAll: Boolean;
begin
Result := false;
try
with ADOQueryop do
begin
Close;
Sql.Clear;
Sql.Add('delete from tns ');
ExecSQL;
Close;
end;
except
end;
Result := true;
end;
procedure TnsManage.InitAll();
var
F: TextFile;
FileName, Str: string;
I, EmptyRows, HROWS: Integer;
TNS: TTNS;
begin
EmptyRows := 0;
HROWS := 0;
FileName := ExtractFileDir(PARAMSTR(0)) + '\oran\network\ADMIN\tnsnames.ora';
AssignFile(F, FileName);
Reset(F);
for I := 0 to 9999999 do begin
Readln(F, Str);
if Str = '' then
begin
Inc(EmptyRows);
TNS := TTNS.Create;
HROWS := 0;
end
else
begin
if TNS <> nil then
begin
if HROWS = 0 then
begin
TNS.TNAME := Common.Split(Str, ' ')[0];
end
else if HROWS = 3 then
begin
TNS.TCP := Common.Split(Common.Split(Str, ')(')[0], ' = ')[2];
TNS.HOST := Common.Split(Common.Split(Str, 'HOST = ')[1], ')(')[0];
TNS.PORT := Common.Split(Common.Split(Str, 'PORT = ')[1], '))')[0];
end
else if HROWS = 6 then
begin
TNS.SID := Common.Split(Common.Split(Str, ' = ')[1], ')')[0];
Self.AddTns(TNS);
EmptyRows := 0;
end;
end;
Inc(HROWS);
end;
if EmptyRows >= 3 then break;
end;
CloseFile(F);
end;
procedure TnsManage.SaveAll(bsSkinGauge: TbsSkinGauge);
var
F: TextFile;
FileName: string;
begin
try
FileName := ExtractFileDir(PARAMSTR(0)) + '\oran\network\ADMIN\tnsnames.ora';
AssignFile(F, FileName);
Reset(F);
ReWrite(F);
with ADOQueryop do
begin
Close;
Sql.Clear;
Sql.Add('select * from tns');
Open;
while not Eof do
begin
Writeln(F, '');
Writeln(F, Trim(FieldByName('TNAME').AsString) + ' = ');
Writeln(F, ' (DESCRIPTION =');
Writeln(F, ' (ADDRESS_LIST =');
Writeln(F, ' (ADDRESS = (PROTOCOL = ' + Trim(FieldByName('TCP').AsString) + ')(HOST = ' + Trim(FieldByName('HOST').AsString) + ')(PORT = ' + Trim(FieldByName('PORT').AsString) + '))');
Writeln(F, ' )');
Writeln(F, ' (CONNECT_DATA =');
Writeln(F, ' (SID = ' + Trim(FieldByName('SID').AsString) + ')');
Writeln(F, ' )');
Writeln(F, ' )');
Writeln(F, '');
bsSkinGauge.Value := bsSkinGauge.Value + 10;
Next;
end;
Close;
Self.DeleteAll;
CloseFile(F);
end;
except
end;
end;
procedure TnsManage.Search(TSQL, FileName: string; DBGrid: TbsSkinDBGrid);
begin
try
with ADOQuery do
begin
Close;
ENUtil.changeDB(FileName, 'count', DBGrid);
Sql.Clear;
Sql.Add(TSQL);
Open;
DBGrid.Refresh;
end;
except
end;
end;
function TnsManage.CheckTnsName(Tns, TID: string): Boolean;
begin
try
with ADOQueryop do
begin
Close;
Sql.Clear;
Sql.Add('select * from tns where TNAME = ''' + Tns + ''' and TID <> ''' + TID + '''');
Open;
if RecordCount > 0 then Result := true
else Result := false;
Close;
end;
except
end;
end;
end.
|
unit Informe_ViewModel_Implementation;
interface
uses
Classes,
Informe_Model, Informe_ViewModel;
type
TInforme_ViewModel = class
private
fDesdeFecha,
fHastaFecha: TDateTime;
fOnCambioPropiedades: TNotifyEvent;
fPropiedadesCambiadas: boolean;
fCambioPropiedadesDisabled: integer;
fNombrePlantilla: string;
fModel: TdmInforme_Model;
fTickInforme: TNotifyEvent;
procedure SetDesdeFecha(const Value: TDateTime);
procedure SetHastaFecha(const Value: TDateTime);
procedure CambioPropiedades;
function GetEmitirInformeOK: boolean;
procedure CambiarPropiedadesDisable;
procedure CambiarPropiedadesEnable;
function GetDesdeFecha: TDateTime;
function GetHastaFecha: TDateTime;
function GetOnCambioPropiedades: TNotifyEvent;
procedure SetOnCambioPropiedades(const Value: TNotifyEvent);
function GetTickInforme: TNotifyEvent;
procedure SetTickInforme(const Value: TNotifyEvent);
function GetNombrePlantilla: string;
procedure SetNombrePlantilla(const Value: string);
public
procedure Iniciar(const aOnCambiosEnViewModel:TNotifyEvent;const aDesde,aHasta:TDateTime;const aNombrePlantilla:string);
procedure Actualizar(const aDesdeFecha,aHastaFecha:TDateTime);
procedure EmitirInforme;
property DesdeFecha:TDateTime read GetDesdeFecha write SetDesdeFecha;
property HastaFecha:TDateTime read GetHastaFecha write SetHastaFecha;
property OnCambioPropiedades:TNotifyEvent read GetOnCambioPropiedades write SetOnCambioPropiedades;
property EmitirInformeOK:boolean read GetEmitirInformeOK;
property TickInforme:TNotifyEvent read GetTickInforme write SetTickInforme;
property NombrePlantilla:string read GetNombrePlantilla write SetNombrePlantilla;
constructor Create;
destructor Destroy; override;
end;
implementation
uses
Forms;
procedure TInforme_ViewModel.Iniciar(const aOnCambiosEnViewModel:TNotifyEvent;const aDesde,aHasta:TDateTime;const aNombrePlantilla:string);
begin
fOnCambioPropiedades:=aOnCambiosEnViewModel;
CambiarPropiedadesDisable;
try
DesdeFecha:=aDesde;
HastaFecha:=aHasta;
NombrePlantilla:=aNombrePlantilla;
finally
CambiarPropiedadesEnable;
end;
end;
procedure TInforme_ViewModel.EmitirInforme;
begin
fModel.EmitirInforme;
end;
procedure TInforme_ViewModel.Actualizar(const aDesdeFecha,aHastaFecha:TDateTime);
begin
if (DesdeFecha<>aDesdeFecha) or (HastaFecha<>aHastaFecha) then begin
fDesdeFecha:=aDesdeFecha;
fHastaFecha:=aHastaFecha;
CambioPropiedades;
end;
end;
procedure TInforme_ViewModel.SetDesdeFecha(const Value: TDateTime);
begin
if FDesdeFecha<>Value then begin
FDesdeFecha := Value;
CambioPropiedades;
end;
end;
procedure TInforme_ViewModel.SetHastaFecha(const Value: TDateTime);
begin
if FHastaFecha<>Value then begin
FHastaFecha := Value;
CambioPropiedades;
end;
end;
procedure TInforme_ViewModel.CambiarPropiedadesDisable;
begin
inc(fCambioPropiedadesDisabled);
end;
procedure TInforme_ViewModel.CambiarPropiedadesEnable;
begin
dec(fCambioPropiedadesDisabled);
if (fCambioPropiedadesDisabled=0) and fPropiedadesCambiadas then
CambioPropiedades;
end;
procedure TInforme_ViewModel.CambioPropiedades;
begin
if (fCambioPropiedadesDisabled<>0) then
fPropiedadesCambiadas:=True
else begin
fPropiedadesCambiadas:=False;
CambiarPropiedadesDisable;
try
if Assigned(fOnCambioPropiedades) then
fOnCambioPropiedades(Self);
finally
CambiarPropiedadesEnable;
end;
end;
end;
function TInforme_ViewModel.GetEmitirInformeOK: boolean;
begin
result:=(DesdeFecha<>0) and (DesdeFecha<=HastaFecha);
end;
function TInforme_ViewModel.GetDesdeFecha: TDateTime;
begin
result:=fDesdeFecha;
end;
function TInforme_ViewModel.GetHastaFecha: TDateTime;
begin
result:=fHastaFecha;
end;
function TInforme_ViewModel.GetOnCambioPropiedades: TNotifyEvent;
begin
result:=fOnCambioPropiedades;
end;
procedure TInforme_ViewModel.SetOnCambioPropiedades(const Value: TNotifyEvent);
begin
fOnCambioPropiedades:=Value;
end;
destructor TInforme_ViewModel.Destroy;
begin
fModel.Free;
fModel:=nil;
inherited;
end;
constructor TInforme_ViewModel.Create;
begin
inherited Create;
Application.CreateForm(TdmInforme_Model,fModel);
end;
function TInforme_ViewModel.GetTickInforme: TNotifyEvent;
begin
result:=fTickInforme;
end;
procedure TInforme_ViewModel.SetTickInforme(const Value: TNotifyEvent);
begin
if @FTickInforme<>@Value then begin
FTickInforme:=Value;
CambioPropiedades;
end;
end;
function TInforme_ViewModel.GetNombrePlantilla: string;
begin
result:=FNombrePlantilla;
end;
procedure TInforme_ViewModel.SetNombrePlantilla(const Value: string);
begin
if FNombrePlantilla<>Value then begin
FNombrePlantilla:= Value;
CambioPropiedades;
end;
end;
end.
|
unit Un_R_file_Alex;
interface
const M_WAIT : array [1..2] of string[30] = ('Зачекайте!', 'Ожидайте!');
const M_CONST_MESSAGE_WARNING : array [1..2] of string[10] = ('Увага!', 'Внимание!');
const M_CONST_VIHOD : array [1..2] of string[48] = ('Ви дійсно бажаєте вийти з програми?', 'Вы действительно желаете выйти из программы?');
const BANK_MO_CAPTION : array [1..2] of string[40] = ('Вікно формування меморіальних ордерів', 'Окно формирования мемориальных ордеров');
const BANK_MO_TAKE_MONT : array [1..2] of string[15] = ('Вкажіть місяць', 'Выберите месяц');
const BANK_MO_TAKE_YEAR : array [1..2] of string[3] = ('рік', 'год');
const BANK_MO_TAKE_PEREFORM : array [1..2] of string[12] = ('Сформувати', 'Сформировать');
const BANK_MO_EXIT : array [1..2] of string[5] = ('Вихід', 'Выход');
const BANK_MO_PRINT : array [1..2] of string[12] = ('Друкувати', 'Печатать');
const BANK_MO_PRINT_M : array [1..2] of string[19] = ('Показати на екрані', 'Показать на экране');
const BANK_MO_REG_SHORT : array [1..2] of string[10] = ('Рег.обліку', 'Рег.учета');
const BANK_MO_SCH_KOD : array [1..2] of string[8] = ('Рахунок', 'Счет');
const BANK_MO_SCH_TITLE : array [1..2] of string[15] = ('Рахунок (опис)', 'Счет (описание)');
const BANK_MO_MO : array [1..2] of string[2] = ('МО', 'МО');
const BANK_MO_RAS : array [1..2] of string[11] = ('Розшифровка', 'Расшифровка');
const BANK_MO_NAME_FINANCE : array [1..2] of string[19] = ('Тип фінансування', 'Тип финанасирования');
const BANK_MO_BUKVA : array [1..2] of string[19] = ('Буква', 'Буква');
const BANK_MO_KOD_REG : array [1..2] of string[10] = ('Код.обліку', 'Код.учета');
const BANK_MO_PROGRAMM : array [1..2] of string[10] = ('Програма', 'Программа');
const BANK_MO_MES1 : array [1..2] of string[25] = ('необхідно перевести у', 'необходимо перевести в ');
const BANK_MO_MES2 : array [1..2] of string[30] = ('НЕМОЖЛИВО зформувати звіт', 'НЕВОЗМОЖНО сформировать отчет');
const AVANCE_N72 : array [1..2] of string[35] = ('Формування меморіальних ордерів', 'Формирование мемориальних ордеров');
const AVANCE_MO_SCH : array [1..2] of string[10] = ('Рахунок ', 'Счет ');
const BANK_DOC_INFO_DOG : array [1..2] of string[25] = ('Інформація по договору', 'Информация по договору');
const BANK_DOC_INFO : array [1..2] of string[12] = ('Інформація', 'Информация');
const J4_MAIN_DOC_SUMMA_NEOS : array [1..2] of string[17] = ('Сума неголовних', 'Сумма неосновных');
const BANK_N62 : array [1..2] of string[80] = ('Додавання об''єктів по управлінню доступом на старих зв''язках рахунків', 'Создание объектов по разграничению прав доступа на старых связках счетов');
const BANK_ADD_OBJ_OK : array [1..2] of string[80] = ('Додавання об''єктів по управлінню доступом закінчилося', 'Создание объектов по разграничению прав доступа прошло успешно');
const BANK_ADD_OBJ_NO : array [1..2] of string[80] = ('При додавання об''єктів по управлінню доступом виникла помилка', 'При создание объектов по разграничению прав доступа произошла ошибка');
const BANK_OSTATOK_MAIN_CAP : array [1..2] of string[30] = ('Довідник залишків по рахункам', 'Справочник остатков по счетам');
const BANK_OSTATOK_ADD_CAP : array [1..2] of string[30] = ('Вікно редагування залишків', 'Окно редактирования остатков');
const BANK_OSTATOK_ADD_EXIT : array [1..2] of string[30] = ('Такий залишок вже існує!', 'Такой остаток уже есть!');
const BANK_OSTATOK_DEL_OST : array [1..2] of string[40] = ('Ви дійсно бажаєте вилучити?', 'Вы действительно желаете удалить?');
const ADD_CONST : array [1..2] of string[20] = ('Додати', 'Добавить');
const DELETE_CONST : array [1..2] of string[20] = ('Видалити', 'Удалить');
const UPDATE_CONST : array [1..2] of string[20] = ('Змінити', 'Изменить');
const REFRESH_CONST : array [1..2] of string[20] = ('Відновити', 'Обновить');
const CLOSE_CONST : array [1..2] of string[20] = ('Закрити', 'Закрыть');
const CLOSE_VIH : array [1..2] of string[20] = ('Вихід', 'Выход');
const PRINT_CONST : array [1..2] of string[20] = ('Друкувати', 'Печать');
const HELP_CONST : array [1..2] of string[20] = ('Допомога', 'Помощь');
const CHOOSE_CONST : array [1..2] of string[20] = ('Вибрати', 'Выбрать');
const FILTER_CONST : array [1..2] of string[20] = ('Фільтр', 'Фильтр');
const ANALIZE_CONST : array [1..2] of string[20] = ('Аналіз', 'Анализ');
const SET_CONST : array [1..2] of string[20] = ('Встановити', 'Установить');
const OK : array [1..2] of string[20] = ('Прийняти', 'Принять');
const N_KASSA_SCH : array [1..2] of string[20] = ('Рахунок', 'Счет');
const N_KASSA_SMETA : array [1..2] of string[20] = ('Бюджет', 'Бюджет');
const N_KASSA_STAT : array [1..2] of string[20] = ('Стаття', 'Статья');
const N_KASSA_RAZD : array [1..2] of string[20] = ('Розділ', 'Раздел');
const N_KASSA_DEBET : array [1..2] of string[20] = ('Дебет', 'Дебет');
const N_KASSA_KREDIT : array [1..2] of string[20] = ('Кредит', 'Кредит');
const N_KASSA_KEKV : array [1..2] of string[20] = ('КЕКЗ', 'КЭКЗ');
const N_KASSA_SUMMA : array [1..2] of string[20] = ('Сума', 'Сумма');
const BANK_OBJ_PRAV : array [1..2] of string[50] = ('Об''єкт у системі розмежування прав доступу', 'Объект в системе разграничения прав доступа');
const BANK_COL_DAY_FOR_SHOW : array [1..2] of string[70] = ('Кількість днів тому для відображення платежів', 'Количество дней назад для отображения платежей');
const BANK_COL_DAY_FOR_FIND_RASH : array [1..2] of string[70] = ('Кількість днів тому для обробки платежів', 'Количество дней назад для обработки платежей');
const KASSA_DONT_DEL_ALL_DOC : array [1..2] of string[255] = ('Видалити касовий ордер НЕМОЖЛИВО! Документ проведено по бухгалтерії. Відмініть проводку документа по бухгалтерії (операція "Повернути"), або змінить налаштовування каси "Не видаляти проведенні по бухгалтерії документи"', 'Удалить кассовый ордер НЕВОЗМОЖНО! Документ проведен по бухгалтерии. Отмените проводку документа по бухгалтерии (операция "Повернути"), или измените настройку кассы "Не удалять проведенные по бухгалтерии документы"');
const proba ='test';
resourcestring
{Глобальные константы системы}
J4_IS_SELECT_TYPE_VVOD_VEDOM = 'Використання алгоритма введення відомостей через авансові звіти';
MY_ACTION_ADD_CONST = 'Додати';//'Добавить';
MY_ACTION_DELETE_CONST = 'Видалити';//'Удалить';
MY_ACTION_UPDATE_CONST = 'Змінити';//'Изменить';
MY_ACTION_REFRESH_CONST = 'Відновити';//'Обновить';
MY_ACTION_CLOSE_CONST = 'Закрити';//'Закрыть';
MY_ACTION_CLOSE_VIH = 'Вихід';//'Выход';
MY_ACTION_PRINT_CONST = 'Друкувати';//'Печать';
MY_ACTION_HELP_CONST = 'Допомога';//'Помощь';
MY_ACTION_CHOOSE_CONST = 'Вибрати';//'Выбрать';
MY_ACTION_FILTER_CONST = 'Фільтр';//'Фильтр';
MY_ACTION_ANALIZE_CONST = 'Аналіз';//'Анализ';
MY_ACTION_SET_CONST = 'Встановити';//'Установить';
MY_ACTION_OK = 'Ввести';//'Ввести';
MY_ACTION_PRINT = 'Друкувати';//'Печатать';
MY_ACTION_PRINT_PRN = 'Друкувати на прінтер';//'Печать на принтер';
MY_VALUE_PRINT_CAPTION = 'Ознака друку';
MY_ACTION_SHOW = 'Перегляд';//'Просмотр';
MY_BUTTON_OK_CONST = 'Прийняти';//'Принять';
MY_BUTTON_CANCEL_CONST = 'Відмінити';//'Отменить';
MY_BUTTON_YES_CONST = 'Да';//'Да';
MY_BUTTON_NO_CONST = 'Ні';//'Нет';
MY_BUTTON_CHOOSE_CONST = 'Вибрати';//'Выбрать';
MY_MESSAGE_WARNING = 'Увага!';//'Внимание!';
MY_MESSAGE_ERROR = 'Помилка! ';//'Ошибка!';
MY_FATAL_ERROR_SYS = 'Помилка в системі безпеки!';//'Ошибка в системе безопасности!';
MY_ERROR_KERNELL = 'Помилка ядра (система Головна книга)';//'Ошибка ядра ';
MY_FATAL_ERROR = 'Фатальна помилка в системі безпеки : ';//'Фатальная ошибка в системе безопасности : ';
MY_ERROR_DONT_WORK = 'Ви не маєте права працювати в цій системі!';//'Вы не имеете права работать в этой системе!';
MY_FORM_FORM = 'При з''єднанні з БД виникла помилка: " ';//'При соединении с БД возникла ошибка: "';
MY_MESSAGE_HINT = 'Попередження!';//'Предупреждение!';
MY_UNDER_CONSTRUCTION_CONST = 'На стадії розробки';//'На стадии разработки';
MY_DOC_ERROR_KERNELL = 'При проведенні документа виникли помилки';//'При проведении документа возникли ошибки';
MY_BUTTON_EXPORT_TO_EXCEL = 'Експорт до Excel';
MY_MESSAGE_WARNING_ADD = 'Ви не маєте прав проводити операцію додавання!';
MY_MESSAGE_WARNING_EDIT = 'Ви не маєте прав проводити операцію редагування!';
MY_MESSAGE_WARNING_DEL = 'Ви не маєте прав проводити операцію видалення!';
MY_MESSAGE_WARNING_VIEW = 'Ви не маєте прав проводити операцію перегляду!';
MY_MESSAGE_WARN_NO = 'Ви не маєте прав працювати з цим пунктом меню!';
MY_STATE_ON_DATE_CONST = 'Стан на ';//'Состояние на ';
MY_KEKV_SPR = 'Довідник КЕКЗів';//'Справочник КЕКВов';
MY_GROUP_CONST = 'Панель для групування інформиції';//'Панель для группировки информации';
MY_B_N = 'б\н';//'б\н';
MY_DA = 'Да';//'Да';
MY_COLTITL_PROP_TITLE = 'Назва властивості';//'Название свойства';
MY_COLTITL_DATE_BEG = 'Дата початку';//'Дата начала';
MY_COLTITL_DATE_END = 'Дата закінчення';//'Дата окончания';
MY_COLTITL_GROUP = 'Група';//'Группа';
MY_COLTITL_SCH_TITLE = 'Рахунок';//'Счет';
MY_COLTITL_ID_PROP = 'Ід.властивості.';//'Ид.свойства.';
MY_COLTITL_ID_SCH = 'Ід.рах.';//'Ид.счета.';
MY_COLTITL_SCH_END = 'Початок функціонування рахунку';//'Начало функционирования счета';
MY_COLTITL_SCH_BEG = 'Кінець функціонування рахунку';//'Конец функционирования счета.';
MY_FORM_KASSA_FIND_RAZ = 'Друкарська форма по витраті на стадії розробки';//'Печатная форма по расходу на стадии разработки';
MY_DOC_NO = 'Документів не існує';//'Документов нет';
MY_COLTITL_PR_NUM = 'Номер';//'Номер';
MY_COLTITL_PR_TIT = 'Властивість';//'Свойство';
MY_COLTITL_PR_VAL = 'Значення';//'Значение';
MY_COLTITL_PR_GRP = 'Група';//'Группа';
MY_NAME = 'Ім''я';//'Имя:';
MY_PAROL = 'Пароль';//'Пароль:';
MY_IDENTIFICATION = 'Ідентифікація';//'Идентификация';
MY_OTMENA = 'Гаразд';//'Да';
MY_OK = 'Відміна';//'Отмена';
MY_ERROR_SUMMA_LENGTH = 'Довжина суми перевищує допустиме значення (Макс. значення - 16 знаків до коми)';//'Длинна суммы превышает допустимое значение (Макс. значение - 16 знаков до запятой)';
MY_MAIN_PROV = 'Ви бажаєте додати основну проводку?';//'Вы желаете добавить основную проводку?';
MY_MAIN_PROV_NEOS = '(Допоміжна проводка не аналізується при розрахунку суми документа і звичайно не використовує рахунок журналу)';//'(Вспомагательная проводка не анализируется при расчете суммы документа и обычно не использует счет журнала)';
MY_SVERKA_DANNIH = 'Йде перевірка даних!';//'Идет проверка данных!';
MY_ERROR_DEADLOCK_TRANSACTION = 'Дані заблоковані. Зверніться до системного адміністратора. '+#13+'подивиться інші програми';// 'Данные заблокированы. Обратитесь к системному администратору. '+#13+'посмотрите другие программы';
MY_LOAD_BPL = 'Завантаження пакету';//'Загрузка пакета ';
URSPL = 'Підсистема "Облік розрахунків з підзвітними особами" системи фінансового і управлінського обліку';//'Подсистема "Учёт расчётов с подотчётными лицами" системы финансового и управленческого учета ';
WARNINH_CLOSE_JORNAL = 'Не існує журналу завантаження! Буде проведено вихід з системи. Зверніться до системного адміністратора.';//'Не существуеи журнала загрузки! Будет произведен выход из системы. Оборатитесь к системному администратору.';
BANK = 'Підсистема "Облік банківських операцій" системи фінансового і управлінського обліку';//'Подсистема "Учет банковских операций" системы финансо- вого и управленческого учета';
MY_ADD = 'Додати (Insert)';//'Добавить (Insert)';
MY_EDIT = 'Змінити (F2)';//'Изменить (F2)';
MY_DELETE = 'Видалити (Del)';//'Удалить (Del)';
MY_REFRESH = 'Оновити (F5)';//'Обновить (F5)';
MY_EXIT = 'Вихід (Esc)';//'Виход (Esc)';
MY_HELP = 'Допомога (F1)';//'Помощь (F1)';
MY_CLOSE = 'Закрити (Alt+F4)';//'Закрыть (Alt+F4)';
MY_GET = 'Вибрати (Enter)';//'Выбрать (Enter)';
MY_BUTTON_F = 'Знайти (F10)';//'Найти (F10)';
MY_BUTTON_ADD = 'Додати';//'Добавить';
MY_BUTTON_DELETE = 'Видалити';//'Удалить';
MY_BUTTON_GET = 'Вибрати';//'Выбрать';
MY_BUTTON_REFRESH = 'Оновити';//'Обновить';
MY_BUTTON_HELP = 'Допомога';//'Помощь';
MY_BUTTON_CLOSE = 'Закрити';//'Закрыть';
MY_BUTTON_EDIT = 'Змінити';//'Изменить';
MY_BUTTON_PRINT = 'Друк';//'Печать';
MY_BUTTON_FIND = 'Пошук';//'Поиск';
MY_BUTTON_UP = 'Вверх';//'Вверх';
MY_BUTTON_INFO = 'Інформація';
MY_BUTTON_FILTER = 'Фільтрувати';
MY_ADD_SCH = 'Додати рах-к';//'Добавить счет';
MY_EDIT_SCH = 'Змінити рах-к';//'Изменить счет';
MY_DELETE_SCH = 'Видалити рах-к';//'Удалить счет';
N_TAB_NUM_LONG = 'Табельний номер';//'Табельный номер';
N_TAB_NUM = 'Таб.№';//'Таб.№';
MY_JANUARY = 'січень';//'январь';
MY_FEBRIARY = 'лютий';//'февраль';
MY_MARCH = 'березень';//'март';
MY_APRILE = 'квітень';//'апрель';
MY_MAY = 'травень';//'май';
MY_JUNE = 'червень';//'июнь';
MY_JULY = 'липень';//'июль';
MY_AUGUST = 'серпень';//'август';
MY_SEPTEMBER = 'вересень';//'сентябрь';
MY_OCTOBER = 'жовтень';//'октябрь';
MY_NOVEMBER = 'листопад';//'ноябрь';
MY_DESEMBER = 'грудень';//'декабрь';
MY_BUTTON_SHOW_NEOBR = 'Показати необроблені';
N_AUTOKOD_FORM_CANCLE = 'Відмінити';//'Отменить';
N_AUTOKOD_FORM_ERROR_DEL = 'Що ви бажаєте видалити?';//'Что вы желаете удалить?';
N_AUTOKOD_MESSAGE_DEL = 'Ви дійсно бажаєте видалити';//'Вы дейтвительно желаете удалить';
N_AUTOKOD_MESSAGE_OK = 'Підтвердження';//'Подтверждение';
N_AUTOKOD_ADD_VETKA_ERROR_MESS = 'Ви не все заповнили';//'Вы не все заполнили!';
N_AUTOKOD_FORM_WARNING = 'Довідка!';//'Справка!';
MY_USER = 'Користувач :';//'Пользователь :';
MY_ERROR_SAVE_DOG = 'Не можна зберегти документ. Ви повинні вибрати договір.';//'Нельзя сохранить документ. Вы должны выбрать договор.';
MY_ENTER_KASSA_DOC = 'Вихід на касовий ордер';//'Выход на кассовый ордер';
SOGLASNO_SPISKU_DOG = 'Згідно списку договорів:';//'Согласно списку договоров:';
ERROR_SCH_DOG_FIO = 'Цей кореспондуючий рахунок обов''язково вимагає вибір договору і підзвітної особи';//'Этот корреспондирующий счет обязательно требует выбор договора и подотчетного лица';
ERROR_SCH_DOG = 'Цей кореспондуючий рахунок обов''язково вимагає вибір договору';//'Этот корреспондирующий счет обязательно требует выбор договора';
WAIT_OTBOR_D = 'Чекайте! Йде відбір даних.';//'Ожидайте! Идет отбор данных.';
ERROR_MAN_PROV = 'Один з рахунків в проводках вимагає обов''язкового вибору фізліца з довідника';//'Один из счетов в проводках требует обязательного выбора физлица из справочника';
ERROR_DOG_PROV = 'Один з рахунків в проводках вимагає обов''язкового вибору договору';//'Один из счетов в проводках требует обязательного выбора договора';
WAIT_UPDATE_DATA = 'Чекайте! Йде процес оновлення даних';//'Ожидайте! Идет процесс обновления данных';
WAIT_DELETE_DATA = 'Чекайте! Йде процес видалення даних';//'Ожидайте! Идет процесс удаления данных';
FORMA_WORK = 'Форма на стадії розробки';//'Форма на стадии разработки';
FORM_DATABASE_OPEN = 'З''єднуємося з базою даних ...';//'Соединяемся с базой данных ...';
FORM_READ_CONFIG = 'Прочитуємо настройки з файлу "config.ini" ...';//'Считываем настройки из файла "config.ini" ...';
WAIT_FORM_D = 'Чекайте! Йде формування.';
INFO_CAPTION_DOC = 'Вікно довідної інформації по документу';
INFO_TIME = 'останній час редагування';
INFO_FIO = 'ПІБ останнього, хто редагував';
INFO_COMP = 'з якої машини редагували';
INFO_CHANGE_DATE = 'дата/час редагування';
INFO_OPERATION = 'операція над документом';
INFO_USER = 'П.І.Б. користувача, хто редагував документ';
INFO_USER_DEL = 'П.І.Б. користувача, хто видалив документ';
INFO_HISTORY_DOC = 'Перегляд історії змін документу';
INFO_HISTORY_DOC_PROV = 'Перегляд історії змін проводок';
MY_WHAT_NEW = 'Нові можливості та усунення зауважень';
MY_NA_SUMMU = 'на суму';
MY_PROV = 'Проводка';
MY_YEAR = ' р.';
MY_PERESCHET = 'Перерахувати';
{Константы используемые в системе касса}
KASSA_SCH = 'Рахунок';//'Счет';
KASSA_SMETA = 'Бюджет';//'Бюджет';
KASSA_STAT = 'Стаття';//'Статья';
KASSA_RAZD = 'Розділ';//'Раздел';
KASSA_DEBET = 'Дебет';//'Дебет';
KASSA_KREDIT = 'Кредит';//'Кредит';
KASSA_KEKV = 'КЕКВ';//'КЭКЗ';
KASSA_SMETA_RAZD_ST = 'Бюджет/Розділ/Стаття';//'Бюджет\Раздел\Статья';
KASSA_SCH_KASSA = 'Основний рахунок';//'Основной счет';
KASSA_KOD_S_R_S_K = 'б/р/ст/К';//'б/р/ст/К';
TAB_NUM = 'Таб.№';//'Таб.№';
KOR_SCH_SHORT = 'кор.рах';//'кор.сч';
TYPE_DOC_SHORT = 'тип.док.';//'тип.док';
PRIHODNIH = ' прибуткових';//' приходных';
RASHODNIH = ' вибуткових';//' расходных';
KASSA_BLOCK_SALDO = ' для блокування (розблокування) сальдо';//' для блокировки (разблокировки) сальдо';
KASSA_BLOCK_O_DEB = ' для блокування (розблокування) оборотів за дебетом';//' для блокировки (разблокировки) оборотов по дебету';
KASSA_BLOCK_O_KRED = ' для блокування (розблокування) оборотів за кредитом';//' для блокировки (разблокировки) оборотов по кредиту';
KASSA_SP_AND_SCH = 'Довідник кас та їх рахунків';//'Справочник касс и их счетов';
KASSA_ADD_KASSA = 'Додати касу';//'Добавить кассу';
KASSA_CHANGE_KASSA = 'Редагувати касу';//'Редактировать кассу';
KASSA_DELETE_KASSA = 'Видалити касу';//'Удалить кассу';
KASSA_EXISTS_KASSA = 'Діючі каси';//'Действующие кассы';
KASSA_EXISTS_SCH = 'Діючи рахунки відповідної каси';//'Действующие счета соответствующей кассы';
KASSA_ADD_SCH = 'Додати рахунок';//'Добавить счет';
KASSA_CHANGE_SCH = 'Змінити рахунок';//'Изменить счет';
KASSA_DELETE_SCH = 'Видалити рахунок';//'Удалить счет';
KASSA_FULL_NAME = 'Повна назва';//'Полное название';
KASSA_SHORT_NAME = 'Коротка назва';//'Короткое название';
KASSA_KOD = 'Код';//'Код';
KASSA_DATE_BEGIN = 'Дата відкриття';//'Дата открытия';
KASSA_SCH_NAME = 'Рахунок системи';//'Счет системы';
KASSA_ADDSCH_FORM = 'Вікно додавання рахунку в систему';//'Окно дабавления счета в систему';
KASSA_ADDSCH_FORM_SCH = 'Виберіть рахунок';//'Выберите счет';
KASSA_ADDSCH_FORM_DATE_BEG = 'Виберіть дату початку дії рахунку';//'Выберите дату начала действия счета';
KASSA_ADDSCH_FORM_DATE_END = 'Виберіть дату кінця дії рахунку';//'Выберите дату конца действия счета';
KASSA_ADDSCH_FORM_FLAG = 'Рахунок за умовчанням';//'Счет по умолчанию';
KASSA_ADD_KASSA_FORM = 'Вікно додавання нової системи';//'Окно добавления новой системы';
KASSA_ADD_KASSA_FORM_FULL = 'Введіть повну назву системи';//'Введите полное название системы';
KASSA_ADD_KASSA_FORM_SHORT = 'Введіть коротку назву системи';//'Введите короткое название системы';
KASSA_ADD_KASSA_FORM_BLOCK_SALDO = 'Дата блокування кінцевого сальдо';//'Дата блокировки конечного сальдо';
KASSA_ADD_KASSA_FORM_DATE_CLOSE = 'Дата закриття системи';//'Дата закрытия системы';
KASSA_CHANGESCH_FORM = 'Вікно редагування рахунку в системі';//'Окно редактирования счета в системе';
KASSA_CHANGESCH_FORM_SCH = 'Змінить рахунок системи';//'Измените счет системы';
KASSA_CHANGESCH_FORM_DATE_BEG = 'Змінить дату початка дії рахунку';//'Измените дату начала действия счета';
KASSA_CHANGESCH_FORM_DATE_END = 'Змінить дату кінця дії рахунку';//'Измените дату конца действия счета';
KASSA_CHANGE_KASSA_FORM = 'Вікно зміни системи';//'Окно изменения системы';
KASSA_CHANGE_KASSA_FORM_FULL = 'Змінить повну назву системи';//'Измените полное название системы';
KASSA_CHANGE_KASSA_FORM_SHORT = 'Змінить коротку назву системи';//'Измените короткое название системы';
KASSA_DOC_KASSA = 'Каса';//'Касса';
KASSA_DOC_DAY = 'Касовий день';//'Кассовый день';
KASSA_DOC_NUMBER = 'Касовий номер';//'Кассовый номер';
KASSA_DOC_PRIHOD = 'Прибуток';//'Приход';
KASSA_DOC_RASHOD = 'Видаток';//'Расход';
KASSA_DOC_CAPTION = 'Список касових ордерів';//'Список кассовых ордеров';
KASSA_DOC_FIO = 'П.І.Б.';//'Ф.И.О.';
KASSA_DOC_SCH = 'Рахунок';//'Счет';
KASSA_DOC_SELECT_PRIH_CAPTION = 'Вибір ознаки прибутковості';//'Выбор признака доходности';
KASSA_SELECT_SHOBLON_CAPTION = 'Шаблони введення документів';//'Шаблоны ввода документов';
KASSA_SELECT_SHOBLON_LABEL = 'Вкажіть тип документа';//'Укажите тип документа';
KASSA_SELECT_SHABLON_NAME = 'Назва шаблону';//'Название шаблонов';
KASSA_ADD_PROVODKA_CAPTION = 'Додавання проводок';//'Добавление проводок';
KASSA_ADD_PROVODKA_SCH = 'Вкажіть рах-к';//'Укажите счет';
KASSA_ADD_PROVODKA_ST = 'Вкажіть статтю';//'Укажите статью';
KASSA_ADD_PROVODKA_SM = 'Вкажіть бюджет';//'Укажите бюджет';
KASSA_ADD_PROVODKA_RAZD = 'Вкажіть розділ';//'Укажите раздел';
KASSA_ADD_PROVODKA_KEKV = 'Вкажіть КЕКВ';//'Укажите КЭКЗ';
KASSA_ADD_PROVODKA_SUMMA_PROV = 'Сума проводки';//'Сумма проводки';
KASSA_DOC_ORDER_CAPTION = 'Касовий ордер';
KASSA_DOC_ORDER_PRIH_KAS_ORD = 'Прибутковий касовий ордер №';
KASSA_DOC_ORDER_RASH_KAS_ORD = 'Видатковий касовий ордер №';
KASSA_DOC_ORDER_PRIH_ = 'Прибутковий касовий ордер';
KASSA_DOC_ORDER_RASH_ = 'Видатковий касовий ордер';
KASSA_DOC_ORDER_FROM = 'від';
KASSA_DOC_ORDER_PRINYATO = 'Отримано від';
KASSA_DOC_ORDER_VIDANO = 'Видано від';
KASSA_DOC_ORDER_FROM_SP = 'з довідника фіз.осіб';
KASSA_DOC_ORDER_FROM_KLAVA = 'уведено користувачем';
KASSA_DOC_ORDER_TIN = 'податковий код';
KASSA_DOC_ORDER_BIRTHDAY = 'дата народження';
KASSA_DOC_ORDER_OSNOVANIE = 'Підстава';
KASSA_DOC_ORDER_SUMMA_ALL = 'Сума';
KASSA_DOC_ORDER_BUHG_PROVODKI = 'Бухгалтерські проводки';
KASSA_DOC_ORDER_PREDV_PROVODKI = 'Попередні проводки';
KASSA_DOC_ORDER_SAVE_ALL_PROV = 'Записати усі проводки (+бух.)';
KASSA_DOC_ORDER_SAVE_PRED_PROV = 'Записати тільки попередні проводки';
KASSA_DOC_ADD_PROV_NEOS_PROV = 'Неосновна проводка';
KASSA_DOC_ADD_SUMM_NOT_NOL = 'Сума документа не повинна дорівнювати нулю';
KASSA_DAY_CAPTION = 'Касовий день';
KASSA_DAY_SALDO_BEGIN = 'Початкове сальдо';
KASSA_DAY_SALDO_END = 'Кінцеве сальдо';
KASSA_DAY_SUM_DEBET = 'Сума за дебетом';
KASSA_DAY_SUM_KREDIT = 'Сума за кредитом';
KASSA_DAY_CLOSE = 'Закриття дня';
KASSA_DAY_KOL_PRIH = 'Кількість прибуткових\видаткових';
KASSA_DAY_ADD_CAPTION = 'Додавання нового дня';
KASSA_DAY_ADD_DAY = 'День';
KASSA_DAY_BLOK_DEBET = 'Заблокувати дебет';
KASSA_DAY_BLOK_KREDIT = 'Заблокувати кредит';
KASSA_DAY_CLOSE_DAY = 'Закрити день';
KASSA_DAY_BLOK_SALDO = 'Заблокувати кінцеве сальдо дня';
KASSA_SUMMA = 'Сума';
KASSA_WARNING = 'Увага!';
KASSA_DONT_LOAD_KASSA = 'Виберіть касу, яку необхідно завантажити (див. настроювання).';
KASSA_DAY_ERROR_DAY_BEG = 'Дата дня повинна належати діапазону умов фільтрації касових днів';
KASSA_DAY_ERROR_DAY_END = 'Дата дня не повинна перевищувати сьогоднішньої дати';
KASSA_ADD_PROV = 'Вікно додавання проводок';
KASSA_ADD_PROV_DONT_MAIN = 'Вікно додавання неголовних проводок';
KASSA_CHANGE_PROV = 'Вікно зміни проводок';
KASSA_SCH_KORESPOND = 'Кореспондуючий рахунок';
KASSA_SCH_KOR_SHORT = 'Корресп. рахунок';
KASSA_EXIT_ERROR = 'Ви дійсно бажаєте вийти не зберігши?';
KASSA_LOOK_FOR = 'Увага!';
KASSA_ERROR_SCH = 'Відсутній рахунок системи. Заповніть довідник рахунків системи.';
KASSA_ERROR_ADD_NUMBER = 'Неможливо додати новий документ';
KASSA_ERROR_NAME_FIO = 'Дані по ПІБ змінені.'+#13+'ПІБ буде розглядатися як дані НЕ з довідника фіз. осіб';
KASSA_PRINT_PRIHOD_LIST = 'Журнал реєстрації прибуткових ордерів';
KASSA_PRINT_RASHOD_LIST = 'Журнал реєстрації видаткових ордерів';
KASSA_PRINT_SHOW_OTCHET = 'Показати звіт на екрані';
KASSA_PRINT_CAPTION = 'Друк звітів';
KASSA_PRINT_OTCHET_KASIRA = 'Звіт касира';
KASSA_PRINT_OTCHET_PROV = 'Розшифровка Звіту касира';
KASSA_PRINT_COM_OTCHET_CAPTION = 'Інформація друку за ';
KASSA_DELETE_DOC = 'Ви дійсно бажаєте видалити документ';
KASSA_DELETE_PLUS_FIO = 'на ім''я';
KASSA_DELETE_ALL_DOC = 'Документ відпрацьований в обліку. Ви дійсно бажаєте видалити документ ';
KASSA_DELETE_PROV = 'Ви дійсно бажаєте видалити проводку на суму ';
KASSA_ERROR_SM_RAZD_ST = 'У вас немає бюджету/розділу/статті';
KASSA_MAIN_FORM_CAPTION_A = 'Головне вікно системи "Облік касових операцій"';
KASSA_CAPTION_A = 'Система "Облік касових операцій"';
KASSA_N1 = 'Робота';
KASSA_N7 = 'Робота з документами';
KASSA_N9 = 'Робота з виправними довідками';
KASSA_N10 = 'Керування балансовими рахунками системи (блокування, закриття)';
KASSA_N2 = 'Звітні форми';
KASSA_N11 = 'Формування звітів';
KASSA_N3 = 'Довідники';
KASSA_N12 = 'Довідник фізичних осіб';
KASSA_N19 = 'Довідник діючих систем та їхніх рахунків';
KASSA_N20 = 'Довідник касових операцій';
KASSA_N13 = 'Довідник балансових рахунків';
KASSA_N14 = 'Довідник кошторисів';
KASSA_N15 = 'Довідник розділів/статей';
KASSA_N8 = 'Довідник КЕКВів';
KASSA_N4 = 'Параметри';
KASSA_N5 = 'Вихід';
KASSA_N6 = 'Інформація';
KASSA_N21 = 'Пошук касових ордерів';
KASSA_N16 = 'Перегляд вилучених касових документів';
KASSA_PRINT_DATE_EROR = 'Дата друку виходить за рамки дозволеного (або менше дати інсталяції, або перевищує поточний період)';
KASSA_PRINT_STUD_OSNOV = 'Оплата за проживання у гурт. з';
KASSA_PRINT_CAPTION_MONTH = 'Вікно друку звітних форм';
KASSA_PRINT_SCH_BALL = 'Укажіть балансовий рахунок каси';
KASSA_PRINT_SELMONTH = 'Укажіть місяць';
KASSA_PRINT_J1 = 'Журнал-ордер № 1 (по кредиту рахунку)';
KASSA_PRINT_V1 = 'Відомість № 1 (за дебетом рахунку)';
KASSA_PRINT_R_D = 'Розшифровка кореспонденції за дебетом рахунку';
KASSA_PRINT_R_K = 'Розшифровка кореспонденції за кредитом рахунку';
KASSA_CLOSE_CAPTION = 'Форма закриття (відкриття) рахунків';
KASSA_CLOSE_WAIT = 'Очікуйте! Іде перевірка всіх операцій по рахунку.';
KASSA_CLOSE_WAIT_O = 'Очікуйте! Іде процес відкриття рахунку.';
KASSA_CLOSE_OPEN = 'Рахунок успішно відкритий';
KASSA_CLOSE_UNBLOC = 'Розблокувати';
KASSA_CLOSE_BLOC = 'Заблокувати';
KASSA_CLOSE_CLOSE = 'Рахунок успішно закритий!';
KASSA_OPEN_SCH = 'Відкрити рахунок';
KASSA_CLOSE_SCH = 'Закрити рахунок';
KASSA_CLOSE_NUMBER_SCH = 'Номер рахунку';
KASSA_CLOSE_NAME_SCH = 'Назва рахунку';
KASSA_CLOSE_BLOCK_SCH = 'Блокування';
KASSA_CLOSE_DATE_SCH = 'Дата відкриття';
KASSA_PRINT_DOC_OT_2 = 'Касовий звіт (варіант 2)';
KASSA_PRINT_DOC_OT_3 = 'Касовий звіт (варіант 3)';
KASSA_PRINT_DOC_OT_4 = 'Касовий звіт (розширений)';
KASSA_PRINT_DOC_OT_5 = 'Перегляд вилучених за день';
KASSA_PRINT_BOOOK_PRIH = 'Книга реєстрації прибутку з';
KASSA_PRINT_BOOK_RASH = 'Книга реєстрації витрати з';
KASSA_PRINT_OTC_SCH = 'Звіт за рахунками';
KASSA_COL_COPY = 'кол. копій';
KASSA_PRINT_FROM = 'друкувати з';
KASSA_PAGE = 'стор.';
KASSA_ORDER = 'Касовий ордер';
KASSA_FIND_CAPTION_SCH = 'Виберіть рахунок';
KASSA_FIND_DATE_DOC = 'Дата документа';
KASSA_FIND_CAP_1 = 'Усі основні рахунки';
KASSA_FIND_CAP_2 = 'з';
KASSA_FIND_CAP_3 = 'до';
KASSA_FIND_CAP_4 = 'Без обмеження на СУМУ документа';
KASSA_FIND_CAP_5 = 'Без обмеження на ПІБ';
KASSA_FIND_CAP_6 = 'Без обмеження на ПІДСТАВУ';
KASSA_FIND_CAP_7 = 'Тільки ПРИБУТКОВІ документи';
KASSA_FIND_CAP_8 = 'Тільки ВИДАТКОВІ документи';
KASSA_FIND_CAP_9 = 'ПРИБУТКОВІ й ВИДАТКОВІ документи';
KASSA_FIND_CAP_10 = 'За ДАТОЮ документа :';
KASSA_FIND_CAP_18 = 'За ДАТОЮ проведення :';
KASSA_FIND_CAP_11 = 'За СУМОЮ документа :';
KASSA_FIND_CAP_12 = 'За фрагментом ПІБ :';
KASSA_FIND_CAP_13 = 'За фрагментом ПІДСТАВИ :';
KASSA_FIND_CAP_14 = 'За основними рахунками';
KASSA_FIND_CAP_15 = 'Форма пошуку касових ордерів';
KASSA_FIND_CAP_16 = 'Без обмеження на кореспондуючі рахунки';
KASSA_FIND_CAP_17 = 'За кореспондуючими рахунками';
KASSA_FIND_RESULT_CAPTION = 'Результат пошуку';
KASSA_COUNT_PAGE = 'Кількість ордерів : ';
KASSA_FIND_ERROR_SUMMA = 'У поле пошуку "По СУМІ документа" сума "з" більше, ніж сума "по"';
KASSA_FIND_NUM_DOC = 'Номер документа';
KASSA_FIND_NOT_RECORD = 'За таких умов фільтрації ДАНИХ НЕМАЄ';
KASSA_FIND_SCH_COL_1 = 'Обрано рахунків у кіл-ті ';
KASSA_PRINT_FIND_1 = 'Друкувати без підстави';
KASSA_PRINT_FIND_2 = 'Друкувати з підставою';
KASSA_PRINT_FIND_3 = 'Друк довідки';
KASSA_ORDER_ADD_PROV_SUMMA_ERROR = 'Сума не повинна дорівнювати нулю!';
KASSA_ORDER_ERROR_ADD_KERNEL = 'При додаванні документа виникла помилка у системі Головна книга (ядро системи). Не закривайте це повідомлення. Викличте системного адміністратора й передайте це повідомлення розроблювачам... ';
KASSA_ORDER_ERROR_ADD_DOC = 'При проведенні документа виникли помилки у системі Головна книга (ядро системи)';
KASSA_ERROR = 'ПОМИЛКА у системі Головна книга (ядро системи) - ';
KASSA_ERROR_ADD_PROV_ = 'Не введені проводки в документі.';
KASSA_ERROR_ADD_PROV_KOR_SCH = 'Не можна додати бухг. проводку без кореспондуючого рахунку';
KASSA_SHABLON_SUMMA_CAPTION = 'Вікно введення загальної суми';
KASSA_SHABLON_SUMMA_LAB = 'Для уведення даних по шаблону ';
KASSA_SHABLON_SUMMA_LAB_1 = 'необхідно ввести загальну суму касового ордера';
KASSA_SHABLON_SUMMA_LAB_2 = 'необхідно ввести загальну суму касового ордера (з ПДВ)';
KASSA_FIND_WARNING_CAPTION = 'Іде процес пошуку. Очікуйте!';
KASSA_REG_NUM = 'регістр. № ';
KASSA_PROV_SHOW_PROV = 'Перегляд даних';
KASSA_SOGL_DOG = 'Відп. договору № ';
KASSA_INFO_VSTRECH = 'Інформація із зустрічного документу';
KASSA_INPUT_SUMMA_ALL = 'Уведіть загальну суму';
KASSA_OSNOVANIE_ZA_REGISTR = 'За реєстрацію в паспортному столі (у тому числі й ПДВ)';
KASSA_OSNOVANIE_KVARTPLATA = 'Посуточное проживання в тому числі й ПДВ';
KASSA_DELETE_CAPTION = 'Вікно перегляду видалених касових ордерів';
KASSA_FIO_DELETED = 'Користувач, який видалив документ';
KASSA_DATE_DELETE = 'Дата видалення';
KASSA_ERROR_DAY_SALDO_END = 'Зміна суми документу неприпустимо.' + #13 + ' тому що заблоковано кінцеве сальдо за станом на - ';
KASSA_ERROR_DAY_ADD_OBOROT_DEB = 'Заблоковані обороти по кредиту!';
KASSA_ERROR_DAY_CHANGE_OBOROT_DEB = 'Заблоковані обороти по кредиту!';
KASSA_ERROR_DAY_ADD_OBOROT_KRED = 'Заблоковані обороти по дебету!';
KASSA_ERROR_DAY_CHANGE_OBOROT_KRED = 'Заблоковані обороти по дебету!';
KASSA_USER_PODPIS = 'Підпис користувача';
KASSA_BLOCK_DEBET = 'Заблоковані обороти по дебету';
KASSA_BLOCK_KREDIT = 'Заблоковані обороту по кредиту';
KASSA_BLOCK_SALDO_END = 'Заблоковане кінцеве сальдо';
KASSA_QUECKLY_FIND_FIO = 'Швидкий пошук по ПІБ';
KASSA_PRINT_PASS_DATA = 'Друкувати паспортні дані?';
KASSA_PASPORT = 'паспорт ';
KASSA_VIDAN = ' виданий ';
KASSA_OT = ' від ';
KASSA_FIO_PROJIV = 'ПІБ проживаючого ';
KASSA_FIO_OBUCH = 'ПІБ що навчається ';
KASSA_REG_N = ' рег.н. - ';
KASSA_OT_D = ' від - ';
KASSA_NAME_CUS = ' наймен. контрагента - ';
KASSA_DOG_N = ' ( дог.№ ';
KASSA_PRINT_WITHOUT_PODPIS = 'Без підпису!';
KASSA_CLOSE_JORNAL = 'Немає доступу ні до однієї каси системи';
KASSA_PERESCHET_FORM = 'Вікно перерахунку за день оборотів та сальдо';
KASSA_PERESCHET_SALDO_OB = 'Перерахувати сальдо і обороти за день';
KASSA_BARCODE = 'Штрих-код';
KASSA_INPUT_BARCODE = 'Введення штрих-коду';
KASSA_SEL_PKV_TF_SCH = 'Вікно вибору рахунку, програми та типу коштів';
KASSA_NOT_SEL_SCH = 'Ви не вибрали рахунок';
KASSA_PRINT_WITH_SM = 'Друк за бюджетами' ;
KASSA_PRINT_WITH_GR_SM = 'Друк за групами бюджетiв';
KASSA_BOOK_REESTR_PERIOD = 'Книга реєстрації з';
KASSA_PRINT_CUR_USER = 'Друк документів проведенних за бух. обліком поточним користувачем';
KASSA_PRINT_WITH_ITOG = 'Друк з підсумковою сумою';
KASSA_PRINT_FILTR_WIDE = 'Книга реєстрації прибутку/видатку за період, з розширенним фільтром';
KASSA_RETURN_BUHG_DOC = 'Ви не маєте прав повертати з бух. обліку цей документ!';
KASSA_CANT_EDIT_DOC = 'Ви не маєте прав редагувати документ!';
KASSA_CANT_ADD_DOC = 'Ви не маєте прав додавати документ!';
KASSA_CANT_DEL_DOC = 'Ви не маєте прав видаляти документ!';
KASSA_NOT_SHABLONS = 'Ви не маєте доступу до шаблонів!';
KASSA_PRINT_BUHG = 'Друк бухгалтерських документів';
KASSA_PRINT_ALL = 'Друк уведених документів';
KASSA_PRINT_ORDER_SHABL = 'Довідник шаблонів друку касових ордерів';
KASSA_CHECK_SETUP_PRINT_ORD = 'Перевірте настроювання друку касових ордерів за замовчуванням';
KASSA_BOOK_PRINT = 'Касова книга (сторінок)';
KASSA_BOOK_PRINT_LAST_PAGE = 'Остання сторінка';
KASSA_BOOK_PRINT_FIRST_PAGE = 'Перша сторніка';
KASSA_BOOK_PRINT_NOTE = 'З підставою';
{Константи використовувані в системі авансовий очет}
J4_SP_RAZDELENIE_FORM_CAPTION = 'Довідник разшифровок';
J4_SP_COST_FORM_CAPTION = 'Довідник витрат';
J4_SP_RAZDELENIE_FORM_LONG_NAME = 'Повна назва';
J4_SP_RAZDELENIE_FORM_SHORT_NAME = 'коротка назва';
J4_SP_RAZDELENIE_FORM_FIND_LONG_NAME = 'Пошук по повній назві';
J4_SP_RAZDELENIE_FORM_FIND_SHORT_NAME = 'Пошук по короткій назві';
J4_SP_RAZDELENIE_ADD_FORM_CAPTION = 'Додати нове поле';
J4_SP_RAZDELENIE_ADD_FORM_BUTTON_ADD = 'Додати';
J4_SP_RAZDELENIE_ADD_FORM_LABLE_LONG = 'Уведіть повну назву';
J4_SP_RAZDELENIE_ADD_FORM_LABLE_SHORT = 'Уведіть коротку назву';
J4_SP_RAZDELENIE_CHANGE_FORM_CAPTION = 'Змінити поле';
J4_SP_RAZDELENIE_CHANGE_FORM_BUTTON_ADD = 'Змінити';
J4_SP_RAZDELENIE_CHANGE_FORM_LABLE_LONG = 'Змінити повну назву';
J4_SP_RAZDELENIE_CHANGE_FORM_LABLE_SHORT = 'Змінити коротку назву';
J4_SP_RAZDELENIE_ADD_NEW_MESS = 'Ви бажаєте додати кореневу гілку?';
J4_SP_RAZDELENIE_MESSAGA = 'Увага!';
J4_SYSTEM = 'Система';
J4_MAIN_FORM_BUTTON_DELETE = 'Видалити';
J4_MAIN_FORM_BUTTON_FIND = 'Знайти';
J4_MAIN_FORM_BUTTON_REFRESH = 'Обновити';
J4_MAIN_FORM_BUTTON_EXIT = 'Вийти';
J4_MAIN_FORM_PERIOD = 'Період відбору';
J4_MAIN_FORM_FILTER = 'Фільтрувати';
J4_MAIN_FORM_SYSTEM = 'Змінити систему';
J4_MAIN_FORM_FROM = 'з';
J4_MAIN_FORM_TO = 'до';
J4_MAIN_FORM_DEBET = 'Дебет';
J4_MAIN_FORM_KREDIT = 'Кредит';
J4_MAIN_FORM_DEBET_KREDIT = 'Дебет/Кредит';
J4_MAIN_FORM_SUMMA = 'Сума';
J4_MAIN_FORM_DATA = 'Дата';
J4_MAIN_FORM_SMETA_RAZ_STATTA = 'Бюджет/Розділ/Стаття';
J4_MAIN_FORM_FIO = 'ПІБ';
J4_MAIN_FORM_NUMBER = 'Номер';
J4_MAIN_FORM_RASPR = 'Разшифровка';
J4_MAIN_FORM_KEKV = 'КЭКВ';
J4_MAIN_FORM_PASPORT = 'Паспорт';
J4_MAIN_FORM_POL = 'Стать';
J4_MAIN_FORM_DATA_BORN = 'Дата народження';
J4_MAIN_FORM_IDEN_KOD = 'Податковий код';
J4_MAIN_FORM_OSNOVA = 'Підстава';
J4_MAIN_FORM_SERIA = 'Серія';
J4_MAIN_ADD_NUM_DOC_DEB = 'Дебетовий документ №';
J4_MAIN_ADD_NUM_DOC_AVANCE = 'Авансовий звіт №';
J4_MAIN_NUM_DOC_AVANCE_OF = 'За авансовим звітом №';
J4_MAIN_HAVE_PAY = 'є виплати у заробітній платі';
J4_MAIN_ADD_TAKE_INI = 'Прізвище підзвітної особи';
J4_MAIN_ADD_DATA_DOC = 'від';
J4_MAIN_ADD_TYPE_DOC = 'Тип документа';
J4_MAIN_ADD_NEXT = 'Наступна вкладка';
J4_MAIN_ADD_UP = 'На один нагору';
J4_MAIN_ADD_DOWN = 'На один вниз';
J4_MAIN_ADD_ALL_SUMMA = 'Загальна сума по розподілу';
J4_MAIN_OTMENA = 'Скасування';
J4_MAIN_PRINAT = 'Прийняти';
J4_CONNECTION_BASE = 'З''єднуємося з базою даних ...';
J4_READ_PARAMS = 'Зчитуємо настроювання з файлу "config.ini" ...';
J4_ERROR_CONNECTE = 'При з''єднанні із БД виникла помилка: "';
J4_ADD_VETKA_ERROR_MESS = 'Ви не все заповнили!';
J4_FORM_ERROR_DEL = 'Що ви бажаєте видалити?';
J4_FORM_WARNING = 'Довідка!';
J4_DOCUMENT = 'документ №';
J4_MESSAGE_DEL = 'Ви дійсно бажаєте видалити';
J4_MESSAGE_OK = 'Підтвердження';
J4_PROP_CAPTION_BUTTON_CLOSE = 'Закрити';
J4_FORM_CANCLE = 'Скасувати';
J4_FORM_TAKE_ERROR = 'Ви нічого не вибрали!';
J4_DEL_VETKA_ERROR = 'Під цією групою існує інша';
J4_MAIN_FORM_CAPTION = 'Розрахунок з підзвітними особами';
J4_MAIN_MENU_N1 = 'Робота';
J4_MAIN_MENU_N2 = 'Звіти';
J4_MAIN_MENU_N3 = 'Довідники';
J4_MAIN_MENU_N4 = 'Настроювання';
J4_MAIN_MENU_N5 = 'Вихід';
J4_MAIN_MENU_N6 = 'Інформація';
J4_MAIN_MENU_N7 = 'Робота з документами';
J4_MAIN_MENU_N8 = 'Робота із залишками';
J4_MAIN_MENU_N9 = 'Робота з довідками';
J4_MAIN_MENU_N10 = 'Керування балансовими рахунками системи (блокування, закриття)';
J4_MAIN_MENU_N11 = 'Формування Журналів-ордерів та Відомостей';
J4_MAIN_MENU_N12 = 'Довідник фізичних осіб';
J4_MAIN_MENU_N13 = 'Довідник балансових рахунків';
J4_MAIN_MENU_N14 = 'Довідник кошторисів';
J4_MAIN_MENU_N15 = 'Довідник розшифровок авансових звітів';
J4_MAIN_MENU_N16 = 'Довідник типів документів';
J4_MAIN_MENU_N17 = 'Довідник балансових рахунків системи';
J4_MAIN_MENU_N18 = 'Довідник типів документів';
J4_MAIN_MENU_N19 = 'Довідник діючих систем та їхніх рахунків';
J4_MAIN_MENU_N20 = 'Пошук авансових документів';
J4_DONT_NAME = 'Ви не ввели назву';
J4_SUTOCHNIE = 'Добові';
J4_OSTATOK_ADD_FORM_CAPTION = 'Форма додавання залишку';
J4_OSTATOK_CHANGE_FORM_CAPTION = 'Форма зміни залишку';
J4_OSTATOK_ADD_FORM_GR_1 = 'Дані про проводку';
J4_OSTATOK_ADD_FORM_GR_4 = 'Кнопки керування';
J4_OSTATOK_ADD_FORM_D_K = 'Дебет/Кредит';
J4_OSTATOK_PO = 'Залишок по';
J4_OSTATOK_ADD_FORM_NOT_FIO = 'Ви не вказали прізвище';
J4_OSTATOK_ADD_FORM_NOT_SCH = 'Ви не вказали рахунок';
J4_OSTATOK_ADD_FORM_NOT_SMETA = 'Ви не вказали бюджет';
J4_OSTATOK_ADD_FORM_NOT_RAZD = 'Ви не вказали розділ';
J4_OSTATOK_ADD_FORM_NOT_STATE = 'Ви не вказали статтю';
J4_OSTATOK_ADD_FORM_NOT_KEKV = 'Ви не вказали КЭКВ';
J4_OSTATOK_ADD_FORM_NOT_DOG = 'Ви не вибрали договір';
J4_OSTATOK_ADD_FORM_NOT_SUMMA = 'Ви не ввели суму проводки';
J4_OSTATOK_FORM_CAPTION = 'Головне вікно перегляду залишків';
J4_OSTATOK_FORM_JORNAL = 'Журнал';
J4_OSTATOK_FORM_PERIOD = 'Показати за період: місяць';
J4_OBOROT_FORM_PERIOD = 'Показати за період:';
J4_OSTATOK_FORM_YEAR = 'рік';
J4_OSTATOK_FORM_OST_DEB = 'Ост. за дебетом';
J4_OSTATOK_FORM_FIO = 'ПІБ підзвітної особи';
J4_OSTATOK_FORM_OST_KRID = 'Зал. по кредиту';
J4_OSTATOK_ERROR_MAN = 'Підзвітна особа по залишку й договору не збігаються:';
J4_OSTATOK_IN_OST = 'у залишку - ';
J4_OSTATOK_IN_DOG = 'у договорі - ';
J4_OSTATOK_DATE_ERROR = 'Дата закладу залишку менше дати інсталяції системи. Неможливо додати залишок!';
J4_SELECT_DOC_DEB = 'Дебетовий документ (ОРзПО)';
J4_SELECT_DOC_AVANCE = 'Авансовий звіт';
J4_ADD_DATE_ERROR = 'Дата виникнення залишку не повинна перевищувати дати відкритого періоду';
J4_ADD_DATE_CAPTION = 'Дата виникнення залишку';
J4_ADD_AVANCE_DEBET_CAPION = 'Додавання авансового звіту (Дебет)';
J4_ADD_AVANCE_AVANCE_CAPTION = 'Додавання авансового звіту (Кредит)';
J4_CHANGE_AVANCE_DEBET_CAPTION = 'Зміна авансового звіту (Дебет)';
J4_CHANGE_AVANCE_AVANCE_CAPTION = 'Зміна авансового звіту (Кредит)';
J4_POL_MAN = 'Чоловічий';
J4_POL_WOMAN = 'Жіночий';
J4_WARNING_LOAD_JORNAL = 'Немає журнали, що завантажується за замовчуванням! Система автоматично закриється. Звернетеся до системного адміністратора.';
J4_ADD_WARNING_FIO = 'Уведіть прізвище.';
J4_ADD_WARNING_NOTE = 'Уведіть підставу.';
J4_ADD_WARNING_NUMBER = 'Уведіть номер документа.';
J4_ADD_WARNING_SUMMA = 'Уведіть суму документа.';
J4_ADD_WARNING_PROV = 'Сума в проводках і документі не збігаються.';
J4_ADD_WARNING_DONT_CREATE = 'Неможливо додати документ!';
J4_ADD_WARNING_DATE = 'Дата початку відрядження не може бути більшою за кінець!';
J4_ADD_PROV_RAS = 'Виберіть розшифровку';
J4_ADD_NAME_RAS = 'Назва розшифровки';
J4_SCH_KORESPOND = 'Корресп. рахунок';
J4_KOD_ERROR = 'Код помилки';
J4_SOOBSCHENIE = 'Повідомлення';
J4_ERROR_DOC = 'Помилки про документ';
J4_ERROR_PROV = 'Помилки про проводки';
j4_po_smetam = 'Бухгалтерська кореспонденція';
J4_RAS = 'Розшифровки';
J4_SEL_SCH_OSTATOK = 'Вікно вибору рахунку залишку';
J4_NAME_SMETA = 'Назва бюджету';
J4_KOD_SM_RA_ST = 'Код бюд/роз/ст';
J4_SCH_ = 'Укажіть рахунок залишку';
J4_SMETA_ = 'Укажіть кошторис залишку';
J4_STATE_ = 'Укажіть бюджет залишку';
J4_RAZD_ = 'Укажіть розділ залишку';
J4_KEKV_ = 'Укажіть КЭКЗ залишку';
J4_OBOROT_CAPTION = 'Вікно перегляду оборотів системи ОРзПО';
J4_OBOROT_MAIN_CAPTION = 'Перегляд оборотів';
J4_OBOROT_BAND_OST_VHOD = 'Вхідний залишок';
J4_OBOROT_BAND_OST_VIHOD = 'Вихідний залишок';
J4_OBOROT_BAND_REKV_DOC = 'Реквізити документа';
J4_OBOROT_BAND_REKV_PROV = 'Реквізити проводки';
J4_OBOROT_SHOW_DOC = 'Показувати документи';
J4_OSTATOK_WARNING_DEL = 'Ви не маєте права видаляти залишок, що розрахован системою';
J4_OSTATOK_PO_DEBETU = 'дебету';
J4_OSTATOK_PO_KREDITU = 'кредиту';
J4_ADD_PROVODKA_SUMMA_PROV = 'Сума залишку';
J4_MAIN_ADD_KREDIT_SCH = 'Рахунок (кредит)';
J4_MAIN_ADD_DEBET_SCH = 'Рахунок (дебет)';
J4_ADD_PROVODKA_ost_all = 'У вас проводки у кількості: ';
MAIN_NAME = 'Ім''я';
MAIN_PAROL = 'Пароль';
MAIN_CAPTION = 'Ідентифікація';
MAIN_OK = 'Зайти';
MAIN_CANCLE = 'Скасування';
Main_MAIN_CAPTION = 'Система Обліку розрахунків з підзвітними особами';
J4_PRINT_SLECT_JORNAL = 'Виберіть звітну форму для друку';
J4_SELECT_SCH = 'Виберіть основний рахунок';
J4_FORM_SELECT_SCH = 'Вікно вибору основного рахунку';
AVANCE_FIND_CAP_15 = 'Форма пошуку авансових документів';
AVANCE_OBOROT = 'Обороти';
J4_FIND_DOC_NUM = 'Номер документа';
J4_FIND_DOC_SHORT_NAME = 'Тип док.';
J4_WAIT_DANN = 'Очікуйте. Іде процес відбору даних';
J4_ERROR_CELOSTNOCT_DANNIH = 'Порушена цілісність даних. Звернетеся до системного адміністратора. Під договором перебувають кілька людей, а необхідно - один!!!';
J4_JORNAL_KOR_SCH = 'Друк кореспонденції';
J4_JORNAL_SMETA_PRINT = 'Друк розшифровки по бюджетах';
J4_JORNAL_RASHIFR_PRINT = 'Друк кореспонденції (варіант 2)';
J4_AVANCE_NOTE_TEXT = 'Ком. витрати';
J4_AVANCE_KOM = 'Відрядження';
J4_AVANCE_KOM_SEARCH = 'Пошук за відрядженням ';
J4_TYPE_DOC = 'Тип документа';
J4_RAS_DEBET_SCH = 'Розшифровка рахунків за дебетом рахунку';
J4_RAS_KREDIT_SCH = 'розшифровка рахунків за кредитом рахунку';
J4_COLTITL_SCH_BEG = 'Початок функціонування рахунку системи';
J4_COLTITL_SCH_END = 'Кінець функціонування рахунку системи';
J4_COLTITL_SCH_BEG_CHANGE = 'Змінити початок функціонування рахунку системи';
J4_COLTITL_SCH_END_CHANGE = 'Змінити кінець функціонування рахунку системи';
J4_FIND_CAPTION_SCH = 'Виберіть рахунок системи';
J4_NUM_VEDOMOST = 'Номер відомості';
J4_DATE_VEDOMOST = 'Дата відомості';
J4_CHOOSE_PROV_FROM_VED = 'Вибір проводки із відомості';
J4_FOND = 'Фонд';
J4_SHOW_ALL_PEOPLE = 'Показати всe за період';
J4_SHOW_SHABLONS = 'Використовувати шаблони';
J4_USED_RECORD = 'Цей запис вже використовувався! Номер авансового звіту ';
J4_GROUP_MEN = 'Друкувати групуючи за людиною';
J4_WARNING_DATE_BEG_END = 'Дата початку не може бути більшою за кінець!';
J4_CLON_DOC = 'Вікно клонування документу';
J4_APP_TO = 'додаток до';
J4_REESTR = 'Реєстри';
J4_REESTR_ADD_HAND = 'Додати вручну по-одному';
J4_REESTR_ADD_AUTO = 'Додати множину за критеріями';
J4_REESTR_NUM = 'Номер реєстру';
J4_NUM_AO = 'Номер авансового звіту';
J4_COUNT_RECORDS = 'Кількість записів';
J4_COUNT_RECORDS_NE = 'Кількість необраних авансових звітів';
J4_SELECT_BY_SCH = 'За основним рахунком';
J4_SELECT_BY_NUM = 'За номером авансового звіту';
J4_NO_OGR_BY_SCH = 'Без обмежень на основний рахунок';
J4_NO_OGR_BY_NUM = 'Без обмежень на номер авансового звіту';
J4_COMMENT = 'Коментар';
J4_FORM_REESTR = 'Робота з реєстрами';
J4_FORM_REESTR_ADD = 'Форма додавання реєстрів';
J4_FORM_REESTR_EDIT = 'Форма редагування реєстрів';
J4_FORM_REESTR_FILTER = 'Фільтр відбору авансових звітів';
J4_FORM_REESTR_ADD_HAND = 'Форма додавання підзвітних осіб вручну';
J4_NOT_ACCESS_FORM_REESTR = 'Ви не маєте прав формувати реєстри!';
J4_ACCESS_DIVIDE = 'Розділяти права доступа до різних систем підзвіта';
J4_HEAD_PRINT_REEST = 'Заголовок до друку при формуванні реєстрів';
J4_NO_FIND_AO = 'За заданними даними не знайдено жодного авансового звіту!';
J4_EXIST_NUMBER_REESTR = 'Неможливо додати реєстр. З таким номером вже існує реєстр у цьому місяці!';
J4_DEL_ALLAO_REESTR = 'Видалити всі авансові звіти реєстру';
J4_NUM_DOC_D = 'Номер дебетового документа';
J4_NUM_DOC_K = 'Номер кредитового документа';
J4_EXIST_NUM_AO = 'Авансовий звіт з таким номером вже існує!';
J4_KOD_SCH_AO_EMPTY = 'Відсутній код рахунку для формування нової нумерації! Перевірте настроювання рахунків у довіднику систем!';
J4_USE_ALG_FORM_NEW_NUM_AO = 'Використання алгоритм формування номерів з кодом рахнуку';
J4_DATE_ALG_FORM_NEW_NUM_AO = 'Дата початку алгоритму для нової нумерації';
J4_FIO_CHECK_REPORT = 'ПІБ у підписах в звітах у графі "Перевірив"';
J4_FIO_GL_BUHG_REPORT = 'ПІБ у підписах в звітах у графі "Головний бухгалтер"';
J4_BUHG = 'Виконавець';
J4_CHECK = 'Перевірив';
J4_GL_BUHG = 'Головний бухгалтер';
J4_REPORT_SV_1DF = 'Друк зведених даних для 1 ДФ';
J4_MO_PRINT_DOC_OST = 'Друкувати у меморіальному ордері дату і номер документа виникнення залишку за людиною';
J4_MO_PRINT_ONLY_VIKON = 'Друкувати у журналі,кореспонденції,варіант 2, розшифровки по бюджетам, меморіальному ордері тільки "виконав"';
J4_IS_DEFAULT_COMMENT_VEDOMOST = 'Задати за замовчуванням коментар до відомості';
J4_DEFAULT_COMMENT_VEDOMOST = 'коментар до відомості';
//Костанты для Банку BANK_MAIN_FORM_CAPTION_A = 'Головне вікно системи "Облік банківських операцій"';
BANK_MAIN_FORM_CAPTION_A = 'Головне вікно системи "Облік банківських операцій"';
BANK_CAP = '"Облік банківських операцій"';
BANK_WARNING_EXISTS_SCH = 'Існують балансові рахунки, у яких не виставлений розрахунковий рахунок.';
BANK_WARNING_EXISTS_SCH_2 = 'Звертатися до системного адміністратора!!!';
BANK_DAY_SHOW_SCH_CAPTION = 'Вікно вибору розрахункового рахунку';
BANK_DAY_SHOW_SCH_RAS = 'Розрахунковий рахунок';
BANK_DAY_SHOW_SCH_BALL = 'Балансовий рахунок';
BANK_DAY_SHOW_SCH_NAME_BALL = 'Назва бал-го рахунку';
BANK_ADD_DAY_ERROR_DATE = 'Не можливо додати день, що виходить за дати періоду';
BANK_R_S = 'Р/р';
BANK_MFO = 'МФО';
BANK_BANK = 'Банк';
BANK_RECVIZ = 'Реквізити Р/р';
BANK_RECVIZ_BALL_SCH = 'Реквізити балансового рахунку';
BANK_DANNIE_SCH = 'Показники балансового рахунку';
BANK_PERIOD_MONTH_YEAR = 'Період';
BANK_BLOCK = 'Блок';
BANK_PRINYATO_OT = 'Прийнято від';
BANK_DAY_SHOW_SCH_NAME_ = 'Назва рахунку';
BANK_TYPE_RAS_SCH = 'Тип рахунку :';
BANK_PERIOD_DATE = 'Період дії р/р : с';
BANK_OPEN_WITH = 'Закритий операційний період до :';
BANK_OPEN_WITH_2 = '(тобто все зведено, розраховано і заборонено змінювати)';
BANK_BLOCK_WHO = 'Заблокував (ПІБ):';
BANK_CLOSE_WHO = 'Закрив (ПІБ):';
BANK_OTOBRAJAT_S = 'Відображати показники за періодом розрахункових і балансових рахунків з';
BANK_OTOBR_DAY_S = 'Виписки банку з';
BANK_DATE_VIP = 'Дата виписки';
bank_rekv_cust = 'Реквізити контрагента: ОКПО ';
BANK_REK_DOCUMENT = 'Реквізити документа';
BANK_NAME_CUSTMERA = 'Наймен. контрагента';
BANK_NAZVANIE = 'Назва';
BANK_SHOW_OBRABOTANIE = 'Показати оброблені документи за днем';
BANK_SALDO = 'Сальдо';
BANK_SALDO_BEG = 'початкове';
BANK_SALDO_END = 'кінцеве';
BANK_SUM_DEBET = 'за дебетом (прибуток)';
BANK_SUM_KREDIT = 'за кредитом (видаток)';
BANK_DAY = 'День';
BANK_SELECT_DOC_CAPTION = 'Вікно вибору неопрацьованих документів за банківським днем ';
BANK_DATE_DOCUMENT = 'Дата документа';
BANK_SUMMA_DOC = 'Сума документа';
BANK_NOTE = 'Підстава документа';
BANK_NUM_DOCUMENT = 'Номер документа';
BANK_DOC_DAY = 'Список банківських виписок за Р/р ';
BANK_DOC_CAPTION = 'Список банківських документів за ';
BANK_ORDER = 'Банківський документ';
BANK_DOC_ORDER_PRIH_KAS_ORD = 'Прибутковий банківський документ №';
BANK_DOC_ORDER_RASH_KAS_ORD = 'Видатковий банківський документ №';
BANK_DOC_ORDER_PRIH_ = 'Прибутковий банківський документ';
BANK_DOC_ORDER_RASH_ = 'Видатковий банківський документ';
BANK_DOC_ORDER_CHANGE_DOG = 'Зміна договорів';
BANK_SELECT_DOG_CAPTION = 'Довідник набору бюджетів, розділів, статей і Кэквів по договорах';
BANK_ERROR_ADD_PROV_KOR_SCH = 'Не можна додати проводку без кореспондуючого рахунку';
BANK_SELECT_DOG_S_1 = 'Для вибору даних за договорами';
BANK_N12 = 'Пошук банківських документів';
BANK_N61 = 'Настроювання імпорту із клієнт-банку';
BANK_N14 = 'Імпорт даних із систем "Клієнт-банк"';
BANK_N15 = 'Перегляд імпортованих даних';
BANK_N21 = 'Формування звітів за балансовими рахунками за місяць';
BANK_N35 = 'Довідник контрагетнів';
BANK_N36 = 'Довідник банків';
BANK_N37 = 'Довідник розрахункових рахунків підприємства';
BANK_N16 = 'Робота з виправними довідками';
BANK_N22 = 'Виписка клієнт-банку';
BANK_PRINT_SCH_BALL = 'Укажіть балансовий рахунок банку';
BANK_DOGOVOR = 'Договір';
BANK_TYPE_DOGOVOR = 'Тип договору';
BANK_DOG_NUM = ' договір № ';
BANK_PROV = ' проводку ';
BANK_WITH_SUMMA = ' із сумою ';
BANK_RAZB_PO_DOG = 'Розбивка за договорами';
BANK_DATE_DOG = 'Дата договору';
BANK_FIND_CAP_15 = 'Форма пошуку банківських документів';
BANK_COUNT_PAGE = 'Кількість документів : ';
BANK_ERROR_PROVE_KOR_SCH = 'Ви не виставили кореспондуючий рахунок.';
BANK_ERROR_PROVE_DOG = 'Ви не вибрали договір.';
BANK_RAS_SCH_NE_OPREDELEN = 'Рахунок не визначений';
BANK_SELECT_PL = 'Вибір певного платіжного доручення';
BANK_P_S_NAME_CUSTOMER = 'Р/р контрагента';
BANK_FULL_NAME_CUSTOMER = 'Найменування контрагента';
BANK_NUM_DOG = '№ договору';
BANK_ERROR_VIBOR_PL_FROM_LENA = 'Невірно виставлений прапор експорту із Клієнт-банку. Дані не повинні експортуватися! ';
BANK_ADD_TO_DEL_PL = 'Позначити до видалення';
BANK_DEL_TO_DEL_PL = 'Скасувати позначку';
BANK_TYPE_KASSA_BANK = 'Рух наявних : Каса-Банк';
BANK_TYPE_NICH = 'Фінансування НІЧ';
BANK_TYPE_OTHER = 'Інші документи';
BANK_SHABLON = 'Шаблони обробки';
BANK_TYPE_CAPTION = 'Вибір шаблону';
BANK_SELECT_VSTRECH_CAPTION = 'Вибір зустрічних проводок';
BANK_SELECT_VSTRECH_ALL_SUM = 'Загальна сума за обраними проводками';
BANK_DANNIE_PO_DOC = 'Дані з документів';
BANK_DANNIE_PO_PROV = 'Дані проводок';
BANK_PRINT_J1 = 'Журнал-ордер № 2 (за кредитом рахунку)';
BANK_PRINT_V1 = 'Відомість № 2 (за дебетом рахунку)';
BANK_NEOBRABOTAN = 'Необроб.';
BANK_SELECT_KOMIS_DOC = 'Вікно вибору документа комісії';
BANK_MULTY_DOC_KOMIS = '';
BANK_NO_DOC_KOMIS = 'Немає документів. Ви бажаєте повернутися у вікно з банківським документом?';
BANK_KOMIS = 'комісія';
BANK_SHOW_KOM = 'Показати тільки комісію';
BANK_FIND_CUST = 'За КОНТРАГЕНТОМ';
BANK_FIND_CUST_WITHOUT = 'Без обмеження на КОНТРАГЕНТА';
BANK_FIND_RS_WITHOUT = 'Без обмеження на р/р';
BANK_FIND_KOR_BAL_SCH = 'За кореспонденцією балансових рахунків';
BANK_FIND_CUSTOMER = 'За КОНТРАГЕНТОМ';
BANK_FIND_R_S_PRED = 'За р/р підприємства (наші р/р)';
BANK_FIND_CUST_SP = 'За КОНТРАГЕНТОМ з довідника';
BANK_FIND_R_S_SP = 'За р/р із довідника';
BANK_FIND_NAME = 'По включенню в назву';
BANK_FIND_SHOW_PROV = 'Показати проводку';
BANK_QUCKLY_FIND = 'Швидкий пошук за контрагентом';
BANK_QUICKLY_FIND_CUST = 'Швидкий пошук за назвою контрагента';
BANK_OTV_DOC = 'Відв''язати документ';
BANK_Q_F = 'Швидкий пошук';
BANK_DOC_DONT_EDIT = 'Цей документ НЕ МОЖНА редагувати. На ньому порушена цілісність даних. Його можна тільки видалити.';
BANK_DOC_DONT_EDIT_KOM = 'Це комісійний документ, його НЕ МОЖНА редагувати. Для його редагування необхідно спочатку відв''язати його.';
BANK_DEL_OS_DOC = 'Ви бажаєте видалити й основний документ';
BANK_KOM_DOC_DEL = ' Це комісійний документ';
BANK_OTV_DOC_PROCESS = 'Іде процес відв''язування документа';
BANK_R_S_DONT_KOM = 'На цьому р/р немає ознаки комісії. Що ви хочете відв''язати?';
BANK_NARUSCH_CELOST = 'На цьому документі порушена целосность. Не можна відв''язати комісію.';
BANK_PRIH_DOC_KOM = 'Це прибутковий документ. У нього немає комісії.';
BANK_KOM_DOC_DONT_OTV = 'Це кимисійний документ. На ньому не можна відв''язати комісію.';
BANKVOPROS_OTV_DOC = 'Ви дійсно бажаєте відв''язати документ?';
BANK_PRIV_KOM = 'Прив''язати комісію';
BANK_PROVERKA_SUMM = 'Сума документа комісії й сума проводок у комісії не збігаються. Звернетеся до розроблювача!';
BANK_REG_NUM = ' рег.н. - ';
BANK_DOG_OBUCH = 'Договори за навчання';
BANK_NASTROYKA_DAY_AGO_SHOW = 'Кількість днів тому для відображення платежів';
BANK_NASTROYKA_DAY_AGO_DO = 'Кількість днів тому для обробки платежів';
BANK_EXPORT_EXCEL = 'Для експорту в Excel';
BANK_PRINT_PERIOD_BY_GR = 'Звіт за групами надходженнь';
BANK_PRINT_PERIOD_BY_GR_SM = 'Звіт за групами надходженнь у розрізі бюджетів';
BANK_PRINT_PERIOD = 'Формування звітів за балансовими рахунками за період';
BANK_CHANGE_PERIOD = 'Змінити період';
BANK_SHABLON_TRANZ = 'Транзит';
BANK_NASTR_TRANZ_SCH = 'Настроювання транзитних рахунків';
BANK_WORK_TRANZ_SCH = 'Робота з шаблонами транзитних рахунків';
BANK_ADD_TRANZ_SCH = 'Форма додавання шаблону';
BANK_EDIT_TRANZ_SCH = 'Форма редагування шаблону';
BANK_SEL_RS = 'Виберіть р/р';
BANK_SEL_RS_CUST = 'Виберіть р/р контрагента';
BANK_SEL_KOR_R = 'Виберіть коресп. рахунок';
BANK_SEL_BUD = 'Виберіть бюджет';
BANK_SEL_KEKV = 'Виберіть КЕКВ';
BANK_SEL_DOG = 'Виберіть договір';
BANK_ADD_ALL_TRANZ = 'Обробити весь транзит автоматом';
BANK_DEL_ALL = 'Видалити всі оброблені документи за день';
BANK_OROB_PL = 'Обробка платежу';
BANK_DEL_PL = 'Видалення платежу';
BANK_FROM = 'із';
BANK_EDRPOU = 'ЄДРПОУ';
BANK_DEL_ALL_OBROB = 'Ви дійсно бажаєте видалити УСІ оброблені документи за день?';
BANK_ZA = 'За';
BANK_OBROB_BUH = 'відпрацьованних в обліку';
BANK_DOCS = 'документів';
BANK_NO_SHABLON = 'Для цього запису не знайден відповідний шаблон. Перевірте настроювання шаблонів транзиту!';
BANK_DAYS_AGO = 'Настроювання кількості днів на р/р для відображення, обробки платежів';
BANK_COUNT_DAYS = 'Кіл-ь днів';
BANK_DOC_BLOCK_DEB = 'Заблоковані документи за дебетом';
BANK_DOC_BLOCK_KR = 'Заблоковані документи за кредитом';
BANK_DOC_BLOCK_SAL = 'Заблоковане кінцеве сальдо';
BANK_INVOICE = 'Накладні';
BANK_INVOICE_FORM = 'Формування податкових накладних';
BANK_INVOICE_PRINT = 'Друк накладної';
BANK_INVOICE_PRINT_REESTR = 'Друк реєстру';
BANK_INVOICE_PRINT_REESTR_ER = 'Друк реєстру помилкових';
CN_BANK_INVOICE = 'Накладна на навчання';
ST_BANK_INVOICE = 'Накладна на гуртожиток';
BANK_BUDGET_SMALL = 'бюджет';
BANK_INVOICE_PRINT_USER = 'Надрукував:';
BANK_INVOICE_PRINT_DATE = 'Дата друку:';
BANK_INVOICE_DONE = 'Накладна сформована!';
BANK_INVOICE_UNDONE = 'При формуванні накладної виникла помилка!';
BANK_INVOICE_NO_NUMB = 'Необхїдно ввести номер накладної!';
BANK_COMMENT = 'Примітка';
BANK_COMMENT_PROV = 'Примітка до проводки';
BANK_COMMENT_PROV_FIND = 'За фрагментои примітки до проводки';
BANK_CLON = 'Клонувати';
BANK_CLON_FORM = 'Вікно клонування проводки';
BANK_FIND_OGR_COMMENT = 'Без обмеження на примітку до проводки';
BANK_FIND_BY_MEN = 'За фізичною особою';
BANK_PRINT_B_RZ_ST_KEKV = 'Розшифровка за бюджетами/розділами/статтями/КЕКВами';
BANK_ANALYZ_ER_Prov = 'Аналіз помилково рознесенних документів';
BANK_ANALYZ_REESTR = 'Друкувати реєстр';
BANK_ANALYZ_REESTR_NOTE = 'Друкувати реєстр з підставою';
BANK_ANALYZ_REESTR_KOR = 'Друкувати реєстр з кореспонденцією і підставою';
BANK_ANALYZ_ER_Prov_FILTER = 'Фільтр пошуку помилково рознесенних документів';
BANK_FORM_PERESCHET = 'Форма перерахунку сальдо й обротів за період';
BANK_PERESCHET_SALDO = 'Перерахунок сальдо й обротів';
BANK_DO_PERESCHET = 'Перерахувати сальдо й оброти з';
BANK_BEGIN_PERESCHET = 'Почати перерахунок';
BANK_PERESCHET_OK = 'Сальдо й обороти перерахувалось';
BANK_PERESCHET_NOT = 'Сальдо й обороти не перерахувалось';
BANK_PERESCHET_DATE_BEG = 'Укажіть дату з якої перераховувати сальдо й обороти';
BANK_PERESCHET_DATE_END = 'Укажіть дату до якої перераховувати сальдо й обороти';
BANK_NO_MOVE_DAY = 'Неможна перенести документ в виписку дата, якої менша за дату документа!';
BANK_MOVE_DAY = 'Документ перенесен в виписку від ';
BANK_MOVE_PERIOD_NO ='Не можна змінювати період!';
BANK_DATE_PROV = 'Дата проводки';
BANK_ER_VSTRECH = 'Форма віброжаюча список документів, які потребують зустрічні';
BANK_USE_EXPERT_SYS = 'Використовувати експертну систему';
BANK_ORDER_SCH = 'Порядок відображення рахунків на формі банківського документа';
BANK_DEL_ALL_NeOBROB = 'Ви дійсно бажаєте видалити УСІ необроблені документи за день?';
BANK_ZA_VIP = 'За випискою від';
BANK_NEOBR_DOCOV = ' необроблених документів ';
BANK_BUTTON_DEL_ALL_NEOBROB = 'Видалити усі документи з КБ, які відображені';
J4_BAR_SELECT_PEOPLE = 'Вибрати фіз. особу';
J4_BAR_TAB_SELECT = 'Переміщення';
J4_BAR_PROV = ' проводку';
J4_BAR_ADD = 'Доб.';
J4_BAR_EDIT = 'Зм.';
J4_BAR_DEL = 'Уд.';
J4_PRIKAZ = 'Наказ';
J4_DANNIE_PO_PRIKAZU = 'Дані за наказом';
J4_Period_from = 'Період з';
{
KASSA_DOC_ORDER_CAPTION = 'Касовый ордер';
KASSA_DOC_ORDER_PRIH_KAS_ORD = 'Приходный кассовый ордер №';
KASSA_DOC_ORDER_RASH_KAS_ORD = 'Расходный кассовый ордер №';
KASSA_DOC_ORDER_PRIH_ = 'Приходный кассовый ордер';
KASSA_DOC_ORDER_RASH_ = 'Расходный кассовый ордер';
KASSA_DOC_ORDER_FROM = 'от';
KASSA_DOC_ORDER_PRINYATO = 'Принято от';
KASSA_DOC_ORDER_VIDANO = 'Выдано от';
KASSA_DOC_ORDER_FROM_SP = 'из справочника физ.лиц';
KASSA_DOC_ORDER_FROM_KLAVA = 'введено пользователем';
KASSA_DOC_ORDER_TIN = 'налоговый код';
KASSA_DOC_ORDER_BIRTHDAY = 'дата рождения';
KASSA_DOC_ORDER_OSNOVANIE = 'Основание';
KASSA_DOC_ORDER_SUMMA_ALL = 'Сумма ордера';
KASSA_DOC_ORDER_BUHG_PROVODKI = 'Бухгалтерские проводки';
KASSA_DOC_ORDER_PREDV_PROVODKI = 'Предварительные проводки';
KASSA_DOC_ORDER_SAVE_ALL_PROV = 'Записать все проводки (+бух.)';
KASSA_DOC_ORDER_SAVE_PRED_PROV = 'Записать только предварительные проводки';
KASSA_DOC_ADD_PROV_NEOS_PROV = 'Неосновная проводка';
KASSA_DOC_ADD_SUMM_NOT_NOL = 'Сумма документа не должна равняться нулю';
KASSA_DAY_CAPTION = 'Кассовый день';
KASSA_DAY_SALDO_BEGIN = 'Начальное сальдо';
KASSA_DAY_SALDO_END = 'Конечное сальдо';
KASSA_DAY_SUM_DEBET = 'Сумма по дебету';
KASSA_DAY_SUM_KREDIT = 'Сумма по кредиту';
KASSA_DAY_CLOSE = 'Закрытие дня';
KASSA_DAY_KOL_PRIH = 'Количество приходных\расходных';
KASSA_DAY_ADD_CAPTION = 'Добавление нового дня';
KASSA_DAY_ADD_DAY = 'День';
KASSA_DAY_BLOK_DEBET = 'Заблокировать дебет';
KASSA_DAY_BLOK_KREDIT = 'Заблокировать кредит';
KASSA_DAY_CLOSE_DAY = 'Закрыть день';
KASSA_DAY_BLOK_SALDO = 'Заблокировать конечное сальдо дня';
KASSA_SUMMA = 'Сумма';
KASSA_WARNING = 'Внимание!';
KASSA_DONT_LOAD_KASSA = 'Выберите кассу, которую необходимо загрузить (см. настройки).';
KASSA_DAY_ERROR_DAY_BEG = 'Дата дня должна лежать в диапазоне условий фильтрации кассовых дней';
KASSA_DAY_ERROR_DAY_END = 'Дата дня не должна превышать сегодняшней даты';
KASSA_ADD_PROV = 'Окно добавления проводок';
KASSA_ADD_PROV_DONT_MAIN = 'Окно добавления неосновных проводок';
KASSA_CHANGE_PROV = 'Окно изменения проводок';
KASSA_SCH_KORESPOND = 'Корреспондирующий счет';
KASSA_SCH_KOR_SHORT = 'Корресп. счет';
KASSA_EXIT_ERROR = 'Вы действительно хотите выйти не сохранив?';
KASSA_LOOK_FOR = 'Внимание!';
KASSA_ERROR_SCH = 'Отсутствует счет системы. Заполните справочник счетов системы.';
KASSA_ERROR_ADD_NUMBER = 'Невозможно добавить новый документ';
KASSA_ERROR_NAME_FIO = 'Данные по ФИО были изменены.'+#13+'ФИО будет рассматриваться как данные НЕ из справочника физ. лиц';
KASSA_PRINT_PRIHOD_LIST = 'Регистрационный лист (ПРИХОД)';
KASSA_PRINT_RASHOD_LIST = 'Регистрационный лист (РАСХОД)';
KASSA_PRINT_SHOW_OTCHET = 'Показать отчет на экране';
KASSA_PRINT_CAPTION = 'Печать отчетов';
KASSA_PRINT_OTCHET_KASIRA = 'Отчет кассира';
KASSA_PRINT_OTCHET_PROV = 'Расшифровка Отчета кассира';
KASSA_DELETE_DOC = 'Вы действительно желаете удалить документ';
KASSA_DELETE_PLUS_FIO = 'на имя';
KASSA_DELETE_ALL_DOC = 'Документ отработан в учете. Вы действительно желаете удалить документ';
KASSA_DELETE_PROV = 'Вы действительно желаете удалить проводку на сумму ';
KASSA_ERROR_SM_RAZD_ST = 'У вас нет бюджета/раздела/статьи';
KASSA_MAIN_FORM_CAPTION_A = 'Главное окно системы "Учет кассовых операций"';
KASSA_CAPTION_A = 'Система "Учет кассовых операций"';
KASSA_N1 = 'Работа';
KASSA_N7 = 'Работа с документами';
KASSA_N9 = 'Работа с исправительными справками';
KASSA_N10 = 'Управление баллансовыми счетами системы (блокировка, закрытие)';
KASSA_N2 = 'Отчётные формы';
KASSA_N11 = 'Формирование отчётов';
KASSA_N3 = 'Справочники';
KASSA_N12 = 'Справочник физических лиц';
KASSA_N19 = 'Справочник действующих систем и их счетов';
KASSA_N20 = 'Справочник кассовых операций';
KASSA_N13 = 'Справочник баллансовых счетов';
KASSA_N14 = 'Справочник смет';
KASSA_N15 = 'Справочник разделов/статей';
KASSA_N8 = 'Справочник КЭКЗов';
KASSA_N4 = 'Настройки';
KASSA_N5 = 'Выход';
KASSA_N6 = 'Информация';
KASSA_N21 = 'Поиск кассовых ордеров';
KASSA_N16 = 'Просмотр удаленных кассовых документов';
KASSA_PRINT_DATE_EROR = 'Дата печати выходит за рамки позволеного (либо меньше даты инсталяции, либо превышает текущий период)';
KASSA_PRINT_STUD_OSNOV = 'Оплата за проживание в общ. с';
KASSA_PRINT_CAPTION_MONTH = 'Окно печати отчетных форм';
KASSA_PRINT_SCH_BALL = 'Укажите балансовый счёт кассы';
KASSA_PRINT_SELMONTH = 'Укажите месяц';
KASSA_PRINT_J1 = 'Журнал-ордер № 1 (по кредиту счёта)';
KASSA_PRINT_V1 = 'Ведомость № 1 (по дебету счёта)';
KASSA_PRINT_R_D = 'Расшифровка корреспонденции по дебету счёта';
KASSA_PRINT_R_K = 'Расшифровка корреспонденции по кредиту счёта';
KASSA_CLOSE_CAPTION = 'Форма закрытия (открытия) счетов';
KASSA_CLOSE_WAIT = 'Ожидайте! Идет проверка всех операций по счету.';
KASSA_CLOSE_WAIT_O = 'Ожидайте! Идет процесс открытия счета.';
KASSA_CLOSE_OPEN = 'Счет успешно открыт';
KASSA_CLOSE_UNBLOC = 'Разблокировать';
KASSA_CLOSE_BLOC = 'Заблокировать';
KASSA_CLOSE_CLOSE = 'Счет успешно закрыт!';
KASSA_OPEN_SCH = 'Открыть счет';
KASSA_CLOSE_SCH = 'Закрыть счет';
KASSA_CLOSE_NUMBER_SCH = 'Номер счета';
KASSA_CLOSE_NAME_SCH = 'Название счета';
KASSA_CLOSE_BLOCK_SCH = 'Блокировка';
KASSA_CLOSE_DATE_SCH = 'Дата открытия';
KASSA_PRINT_DOC_OT_2 = 'Кассовый отчет (вариант 2)';
KASSA_PRINT_DOC_OT_3 = 'Кассовый отчет (вариант 3)';
KASSA_PRINT_DOC_OT_4 = 'Кассовый отчет (расширенный)';
KASSA_PRINT_DOC_OT_5 = 'Просмотр удаленных за день';
KASSA_PRINT_BOOOK_PRIH = 'Книга регистрации прихода с';
KASSA_PRINT_BOOK_RASH = 'Книга регистрации расхода с';
KASSA_PRINT_OTC_SCH = 'Отчет по счетам';
KASSA_COL_COPY = 'кол. копий';
KASSA_PRINT_FROM = 'печатать с';
KASSA_PAGE = 'стр.';
KASSA_ORDER = 'Кассовый ордер';
KASSA_FIND_CAPTION_SCH = 'Выберите счета';
KASSA_FIND_DATE_DOC = 'Дата документа';
KASSA_FIND_CAP_1 = 'Все основные счета';
KASSA_FIND_CAP_2 = 'с';
KASSA_FIND_CAP_3 = 'по';
KASSA_FIND_CAP_4 = 'Без ограничения по Сумме документа';
KASSA_FIND_CAP_5 = 'Без ограничения на ФИО';
KASSA_FIND_CAP_6 = 'Без ограничения на Основание';
KASSA_FIND_CAP_7 = 'Только Приходные документы';
KASSA_FIND_CAP_8 = 'Только Расходные документы';
KASSA_FIND_CAP_9 = 'Приходные и Расходные документы';
KASSA_FIND_CAP_10 = 'По Дате документа :';
KASSA_FIND_CAP_11 = 'По Сумме документа :';
KASSA_FIND_CAP_12 = 'По фрагменту ФИО :';
KASSA_FIND_CAP_13 = 'По фрагменту Основания :';
KASSA_FIND_CAP_14 = 'По основным счетам';
KASSA_FIND_CAP_15 = 'Форма поиска кассовых ордеров';
KASSA_FIND_CAP_16 = 'Без ограничения на корреспондирующие счета';
KASSA_FIND_CAP_17 = 'По корреспондирующим счетам';
KASSA_FIND_RESULT_CAPTION = 'Результат поиска';
KASSA_COUNT_PAGE = 'Колличество ордеров : ';
KASSA_FIND_ERROR_SUMMA = 'В поле поиска "По Сумме документа" сумма "с" больше, чем сумма "по"';
KASSA_FIND_NUM_DOC = 'Номер документа';
KASSA_FIND_NOT_RECORD = 'При таких условиях фильтрации ДАННЫХ НЕТ';
KASSA_FIND_SCH_COL_1 = 'Выбрано счетов в кол-ве ';
KASSA_PRINT_FIND_1 = 'Печатать без основания';
KASSA_PRINT_FIND_2 = 'Печатать с основанием';
KASSA_PRINT_FIND_3 = 'Печать справки';
KASSA_ORDER_ADD_PROV_SUMMA_ERROR = 'Сумма не должна равняться нулю!';
KASSA_ORDER_ERROR_ADD_KERNEL = 'При добавлении документа возникла ошибка. Не закрывайте это сообщение. Вызовите системного администратора и передайте это сообщение разработчикам... ';
KASSA_ORDER_ERROR_ADD_DOC = 'При проведении документа возникли ошибки';
KASSA_ERROR = 'ОШИБКА- ';
KASSA_ERROR_ADD_PROV_ = 'Не введены проводки в документе.';
KASSA_ERROR_ADD_PROV_KOR_SCH = 'Нельзя добавить бухг. проводку без корреспондирующего счета';
KASSA_SHABLON_SUMMA_CAPTION = 'Окно ввода суммы для договоров';
KASSA_SHABLON_SUMMA_LAB = 'Для ввода данных по шаблону ';
KASSA_SHABLON_SUMMA_LAB_1 = 'необходимо ввести сумму';
KASSA_FIND_WARNING_CAPTION = 'Идёт процесс поиска. Ожидайте!';
KASSA_REG_NUM = 'регистр. № ';
KASSA_PROV_SHOW_PROV = 'Просмотр данных';
KASSA_SOGL_DOG = 'Согл. договору № ';
KASSA_INFO_VSTRECH = 'Информация по встречному документу';
KASSA_INPUT_SUMMA_ALL = 'Введите общую сумму';
KASSA_OSNOVANIE_ZA_REGISTR = 'За регистрацию в паспортном столе (в том числе и НДС)';
KASSA_OSNOVANIE_KVARTPLATA = 'Посуточное проживание в том числе и НДС';
KASSA_DELETE_CAPTION = 'Окно просмотра удаленных кассовых ордеров';
KASSA_FIO_DELETED = 'Пользователь, удаливший документ';
KASSA_DATE_DELETE = 'Дата удаления';
KASSA_ERROR_DAY_SALDO_END = 'Изменение суммы документа недопустимо.' + #13 + ' так как заблокировано конечное сальдо по состоянию на - ';
KASSA_ERROR_DAY_ADD_OBOROT_DEB = 'Заблокировы обороты по кредиту!';
KASSA_ERROR_DAY_CHANGE_OBOROT_DEB = 'Заблокировы обороты по кредиту!';
KASSA_ERROR_DAY_ADD_OBOROT_KRED = 'Заблокировы обороты по дебету!';
KASSA_ERROR_DAY_CHANGE_OBOROT_KRED = 'Заблокировы обороты по дебету!';
KASSA_USER_PODPIS = 'Подпись пользователя';
KASSA_BLOCK_DEBET = 'Заблокированы обороты по дебету';
KASSA_BLOCK_KREDIT = 'Заблокированы обороту по кредиту';
KASSA_BLOCK_SALDO_END = 'Заблокировано конечное сальдо';
KASSA_QUECKLY_FIND_FIO = 'Быстрый поиск по ФИО';
KASSA_PRINT_PASS_DATA = 'Печатать паспортные данные?';
KASSA_PASPORT = 'паспорт ';
KASSA_VIDAN = ' выдан ';
KASSA_OT = ' от ';
KASSA_FIO_PROJIV = 'ФИО проживающего ';
KASSA_FIO_OBUCH = 'ФИО обучающегося ';
KASSA_REG_N = ' рег.н. - ';
KASSA_OT_D = ' от - ';
KASSA_NAME_CUS = ' Наимен. контрагента - ';
KASSA_DOG_N = ' ( дог.№ ';
KASSA_PRINT_WITHOUT_PODPIS = 'Без подписи!';
//Константы используемые в системе авансовый очет
J4_SP_RAZDELENIE_FORM_CAPTION = 'Справочник разшифровок';
J4_SP_RAZDELENIE_FORM_LONG_NAME = 'Полное название';
J4_SP_RAZDELENIE_FORM_SHORT_NAME = 'короткое название';
J4_SP_RAZDELENIE_FORM_FIND_LONG_NAME = 'Поиск по полному названию';
J4_SP_RAZDELENIE_FORM_FIND_SHORT_NAME = 'Поиск по короткому названию';
J4_SP_RAZDELENIE_ADD_FORM_CAPTION = 'Добавить новое поле';
J4_SP_RAZDELENIE_ADD_FORM_BUTTON_ADD = 'Добавить';
J4_SP_RAZDELENIE_ADD_FORM_LABLE_LONG = 'Введите полное название';
J4_SP_RAZDELENIE_ADD_FORM_LABLE_SHORT = 'Введите короткое название';
J4_SP_RAZDELENIE_CHANGE_FORM_CAPTION = 'Изменить поле';
J4_SP_RAZDELENIE_CHANGE_FORM_BUTTON_ADD = 'Изменить';
J4_SP_RAZDELENIE_CHANGE_FORM_LABLE_LONG = 'Изменить полное название';
J4_SP_RAZDELENIE_CHANGE_FORM_LABLE_SHORT = 'Изменить короткое название';
J4_SP_RAZDELENIE_ADD_NEW_MESS = 'Вы хотите добавить корневую ветку?';
J4_SP_RAZDELENIE_MESSAGA = 'Внимание!';
J4_SYSTEM = 'Система';
J4_MAIN_FORM_BUTTON_DELETE = 'Удалить';
J4_MAIN_FORM_BUTTON_FIND = 'Найти';
J4_MAIN_FORM_BUTTON_REFRESH = 'Обновить';
J4_MAIN_FORM_BUTTON_EXIT = 'Выйти';
J4_MAIN_FORM_PERIOD = 'Период отбора';
J4_MAIN_FORM_FILTER = 'Фильтровать';
J4_MAIN_FORM_SYSTEM = 'Изменить систему';
J4_MAIN_FORM_FROM = 'с';
J4_MAIN_FORM_DEBET = 'Дебет';
J4_MAIN_FORM_KREDIT = 'Кредит';
J4_MAIN_FORM_DEBET_KREDIT = 'Дебет/Кредит';
J4_MAIN_FORM_SUMMA = 'Сумма';
J4_MAIN_FORM_DATA = 'Дата';
J4_MAIN_FORM_SMETA_RAZ_STATTA = 'Смета/Раздел/Статья';
J4_MAIN_FORM_FIO = 'ФИО';
J4_MAIN_FORM_NUMBER = 'Номер';
J4_MAIN_FORM_RASPR = 'Разшифровка';
J4_MAIN_FORM_KEKV = 'КЭКЗ';
J4_MAIN_FORM_PASPORT = 'Паспорт';
J4_MAIN_FORM_POL = 'Пол';
J4_MAIN_FORM_DATA_BORN = 'Дата рождения';
J4_MAIN_FORM_IDEN_KOD = 'Налоговый код';
J4_MAIN_FORM_OSNOVA = 'Причина';
J4_MAIN_FORM_SERIA = 'Серия';
J4_MAIN_ADD_NUM_DOC_DEB ='Дебетовый документ №';
J4_MAIN_ADD_NUM_DOC_AVANCE ='Авансовый отчет №';
J4_MAIN_ADD_TAKE_INI ='Фамилия подотчетного лица';
J4_MAIN_ADD_DATA_DOC ='от';
J4_MAIN_ADD_TYPE_DOC ='Тип документа';
J4_MAIN_ADD_NEXT ='Следующая вкладка';
J4_MAIN_ADD_UP ='На один вверх';
J4_MAIN_ADD_DOWN ='На один вниз';
J4_MAIN_ADD_ALL_SUMMA ='Общая сумма по распределению';
J4_MAIN_OTMENA ='Отмена';
J4_MAIN_PRINAT ='Принять';
J4_CONNECTION_BASE ='Соединяемся с базой данных ...';
J4_READ_PARAMS ='Считываем настройки из файла "config.ini" ...';
J4_ERROR_CONNECTE ='При соединении с БД возникла ошибка: "';
J4_ADD_VETKA_ERROR_MESS ='Вы не все заполнили!';
J4_FORM_ERROR_DEL ='Что вы желаете удалить?';
J4_FORM_WARNING ='Справка!';
J4_DOCUMENT ='документ №';
J4_MESSAGE_DEL ='Вы действительно желаете удалить';
J4_MESSAGE_OK ='Подтверждение';
J4_PROP_CAPTION_BUTTON_CLOSE ='Закрыть';
J4_FORM_CANCLE ='Отменить';
J4_FORM_TAKE_ERROR ='Вы ничего не выбрали!';
J4_DEL_VETKA_ERROR ='Под этой группой существует другая';
J4_MAIN_FORM_CAPTION ='Расчет с подотчетными лицами';
J4_MAIN_MENU_N1 ='Работа';
J4_MAIN_MENU_N2 ='Отчёты';
J4_MAIN_MENU_N3 ='Справочники';
J4_MAIN_MENU_N4 ='Настройки';
J4_MAIN_MENU_N5 ='Выход';
J4_MAIN_MENU_N6 ='Информация';
J4_MAIN_MENU_N7 ='Работа с документами';
J4_MAIN_MENU_N8 ='Работа с остатками';
J4_MAIN_MENU_N9 ='Работа со справками';
J4_MAIN_MENU_N10 ='Управление баллансовыми счетами системы (блокировка, закрытие)';
J4_MAIN_MENU_N11 ='Формирование Ж-О';
J4_MAIN_MENU_N12 ='Справочник физических лиц';
J4_MAIN_MENU_N13 ='Справочник баллансовых счетов';
J4_MAIN_MENU_N14 ='Справочник смет';
J4_MAIN_MENU_N15 ='Справочник расшифровок авансовых отчётов';
J4_MAIN_MENU_N16 ='Справочник типов документов';
J4_MAIN_MENU_N17 ='Справочник баллансовых счетов системы';
J4_MAIN_MENU_N18 ='Справочник типов документов';
J4_MAIN_MENU_N19 ='Справочник действующих систем и их счетов';
J4_MAIN_MENU_N20 ='Поиск авансовых документов';
J4_DONT_NAME ='Вы не ввели название';
J4_SUTOCHNIE ='Суточные';
J4_OSTATOK_ADD_FORM_CAPTION ='Форма добавления остатка';
J4_OSTATOK_CHANGE_FORM_CAPTION ='Форма изменения остатка';
J4_OSTATOK_ADD_FORM_GR_1 ='Данные о проводке';
J4_OSTATOK_ADD_FORM_GR_4 ='Кнопки управления';
J4_OSTATOK_ADD_FORM_D_K ='Дебет/Кредит';
J4_OSTATOK_PO ='Остаток по';
J4_OSTATOK_ADD_FORM_NOT_FIO ='Вы не указали фамиилю';
J4_OSTATOK_ADD_FORM_NOT_SCH ='Вы не указали счет';
J4_OSTATOK_ADD_FORM_NOT_SMETA ='Вы не указали смету';
J4_OSTATOK_ADD_FORM_NOT_RAZD ='Вы не указали раздел';
J4_OSTATOK_ADD_FORM_NOT_STATE ='Вы не указали статью';
J4_OSTATOK_ADD_FORM_NOT_KEKV ='Вы не указали КЭКЗ';
J4_OSTATOK_ADD_FORM_NOT_DOG ='Вы не выбрали договор';
J4_OSTATOK_ADD_FORM_NOT_SUMMA ='Вы не ввели сумму проводки';
J4_OSTATOK_FORM_CAPTION ='Главное окно просмотра остатков';
J4_OSTATOK_FORM_JORNAL ='Журнал';
J4_OSTATOK_FORM_PERIOD ='Показать за период: месяц';
J4_OSTATOK_FORM_YEAR ='год';
J4_OSTATOK_FORM_OST_DEB ='Ост. по дебету';
J4_OSTATOK_FORM_FIO ='ФИО подотчётного лица';
J4_OSTATOK_FORM_OST_KRID ='Ост. по кредиту';
J4_OSTATOK_ERROR_MAN ='Подотчетное лицо по остатку и договору не совпадают:';
J4_OSTATOK_IN_OST ='в остатке - ';
J4_OSTATOK_IN_DOG ='в договоре - ';
J4_OSTATOK_DATE_ERROR ='Дата заведения остатка меньше даты инсталяции системы. Невозможно добавить остаток!';
J4_SELECT_DOC_DEB ='Дебетовый документ (УРсПЛ)';
J4_SELECT_DOC_AVANCE ='Авансовый отчет';
J4_ADD_DATE_ERROR ='Дата возникновения остатка не должна превышать даты открытого периода';
J4_ADD_DATE_CAPTION ='Дата возникновения остатка';
J4_ADD_AVANCE_DEBET_CAPION ='Добавление авансового отчёта (Дебет)';
J4_ADD_AVANCE_AVANCE_CAPTION ='Добавление авансового отчета (Кредит)';
J4_CHANGE_AVANCE_DEBET_CAPTION ='Изменение авансового отчёта (Дебет)';
J4_CHANGE_AVANCE_AVANCE_CAPTION ='Изменение авансового отчета (Кредит)';
J4_POL_MAN ='Мужской';
J4_POL_WOMAN ='Женский';
J4_WARNING_LOAD_JORNAL ='Нет журнала, который загружается по умолчанию! Система автоматически закроется. Обратитесь к системному администратору.';
J4_ADD_WARNING_FIO ='Введите фамилию.';
J4_ADD_WARNING_NOTE ='Введите основание.';
J4_ADD_WARNING_NUMBER ='Введите номер документа.';
J4_ADD_WARNING_SUMMA ='Введите сумму документа.';
J4_ADD_WARNING_PROV ='Сумма в проводках и документе не совпадают.';
J4_ADD_WARNING_DONT_CREATE ='Невозможно добавить документ!';
J4_ADD_PROV_RAS ='Выберите расшифровку';
J4_ADD_NAME_RAS ='Название расшифровки';
J4_SCH_KORESPOND ='Корресп. счет';
J4_KOD_ERROR ='Код ошибки';
J4_SOOBSCHENIE ='Сообщение';
J4_ERROR_DOC ='Ошибки о документе';
J4_ERROR_PROV ='Ошибки о проводках';
j4_po_smetam ='Бухгалтерская корреспонденция';
J4_RAS ='Расшифровки';
J4_SEL_SCH_OSTATOK ='Окно выбора счета остатка';
J4_NAME_SMETA ='Название сметы';
J4_KOD_SM_RA_ST ='Код см/раз/ст';
J4_SCH_ ='Укажите счёт остатка';
J4_SMETA_ ='Укажите смету остатка';
J4_STATE_ ='Укажите бюджет остатка';
J4_RAZD_ ='Укажите раздел остатка';
J4_KEKV_ ='Укажите КЭКЗ остатка';
J4_OBOROT_CAPTION ='Окно просмотра оборотов системы УРсПЛ';
J4_OBOROT_MAIN_CAPTION ='Просмотр оборотов';
J4_OBOROT_BAND_OST_VHOD ='Входящий остаток';
J4_OBOROT_BAND_OST_VIHOD ='Выходящий остаток';
J4_OBOROT_BAND_REKV_DOC ='Реквизиты документа';
J4_OBOROT_BAND_REKV_PROV ='Реквизиты проводки';
J4_OBOROT_SHOW_DOC ='Показывать документы';
J4_OSTATOK_WARNING_DEL ='Вы не имеете права удалять остаток, который расчитан системой';
J4_OSTATOK_PO_DEBETU ='дебету';
J4_OSTATOK_PO_KREDITU ='кредиту';
J4_ADD_PROVODKA_SUMMA_PROV ='Сумма остатка';
J4_MAIN_ADD_KREDIT_SCH ='Счет (кредит)';
J4_MAIN_ADD_DEBET_SCH ='Счет (дебет)';
J4_ADD_PROVODKA_ost_all ='У вас проводки в колличестве: ';
MAIN_NAME ='Имя';
MAIN_PAROL ='Пароль';
MAIN_CAPTION ='Идентификация';
MAIN_OK ='Зайти';
MAIN_CANCLE ='Отмена';
Main_MAIN_CAPTION ='Система Учета расчетов с подотчётными лицами';
J4_PRINT_SLECT_JORNAL ='Выберите журнал для печати';
J4_SELECT_SCH ='Выберите основной счет';
J4_FORM_SELECT_SCH ='Окно выбора основного счета';
AVANCE_FIND_CAP_15 = 'Форма поиска авансовых документов';
AVANCE_OBOROT = 'Обороты';
J4_FIND_DOC_NUM = 'Номер документа';
J4_FIND_DOC_SHORT_NAME = 'Тип док.';
J4_WAIT_DANN = 'Ожидайте. Идет процесс отбора данных';
J4_ERROR_CELOSTNOCT_DANNIH = 'Нарушена целостность данных. Обратитесь к системному администратору. Под договором находятся несколько человек, а необходимо - один!!!';
J4_JORNAL_KOR_SCH = 'Печать корреспонденции';
J4_JORNAL_SMETA_PRINT = 'Печать расшифровки по сметам';
J4_AVANCE_NOTE_TEXT = 'Ком. расходы';
J4_TYPE_DOC = 'Тип документа';
J4_RAS_DEBET_SCH = 'Расшифровка счетов по дебету счета';
J4_RAS_KREDIT_SCH = 'расшифровка счетов по кредиту счета';
//Костанты для Банка
BANK_MAIN_FORM_CAPTION_A = 'Главное окно системы "Учет банковских операций"';
BANK_CAP = '"Учет банковских операций"';
BANK_WARNING_EXISTS_SCH = 'Существуют расчетные счета, у которых не выставлен баллансовый счет.';
BANK_WARNING_EXISTS_SCH_2 = 'Обратитесь к системному администратору!!!';
BANK_DAY_SHOW_SCH_CAPTION = 'Окно выбора расчетного счета';
BANK_DAY_SHOW_SCH_RAS = 'Расчетный счет';
BANK_DAY_SHOW_SCH_BALL = 'Баллансовый счет';
BANK_DAY_SHOW_SCH_NAME_BALL = 'Название балл-го счета';
BANK_ADD_DAY_ERROR_DATE = 'Нельзя добавить день, который выходит за даты периода';
BANK_R_S = 'Р/с';
BANK_MFO = 'МФО';
BANK_BANK = 'Банк';
BANK_RECVIZ = 'Реквизиты Р/с';
BANK_RECVIZ_BALL_SCH = 'Реквизиты баллансового счета';
BANK_DANNIE_SCH = 'Данные баллансового счета';
BANK_PERIOD_MONTH_YEAR = 'Период';
BANK_BLOCK = 'Блок';
BANK_PRINYATO_OT = 'Принято от';
BANK_DAY_SHOW_SCH_NAME_ = 'Название счета';
BANK_TYPE_RAS_SCH = 'Тип счета :';
BANK_PERIOD_DATE = 'Период действия р/с : с';
BANK_OPEN_WITH = 'Закрытый операционный период до :';
BANK_OPEN_WITH_2 = '(т.е. все сведено, распечатано и запрещено на изменение)';
BANK_BLOCK_WHO = 'Заблокировал (ФИО):';
BANK_CLOSE_WHO = 'Закрыл (ФИО):';
BANK_OTOBRAJAT_S = 'Отображать данные по периоду действия расч-х и балл-х счетов с';
BANK_OTOBR_DAY_S = 'Выписки банка с';
BANK_DATE_VIP = 'Дата выписки';
bank_rekv_cust = 'Реквизиты контрагента: ОКПО ';
BANK_REK_DOCUMENT = 'Реквизиты документа';
BANK_NAME_CUSTMERA = 'Наимен. контрагента';
BANK_NAZVANIE = 'Название';
BANK_SHOW_OBRABOTANIE = 'Показать обработанные документы по дню';
BANK_SALDO = 'Сальдо';
BANK_SALDO_BEG = 'начальное';
BANK_SALDO_END = 'конечное';
BANK_SUM_DEBET = 'по дебету (приход)';
BANK_SUM_KREDIT = 'по кредиту (расход)';
BANK_DAY = 'День';
BANK_SELECT_DOC_CAPTION = 'Окно выбора необработанных документов по банковскому дню ';
BANK_DATE_DOCUMENT = 'Дата документа';
BANK_SUMMA_DOC = 'Сумма документа';
BANK_NOTE = 'Основание документа';
BANK_NUM_DOCUMENT = 'Номер документа';
BANK_DOC_DAY ='Список банковских выписок по Р/с ';
BANK_DOC_CAPTION ='Список банковских документов за ';
BANK_ORDER ='Банковский документ';
BANK_DOC_ORDER_PRIH_KAS_ORD ='Приходный банковский документ №';
BANK_DOC_ORDER_RASH_KAS_ORD ='Расходный банковский документ №';
BANK_DOC_ORDER_PRIH_ ='Приходный банковский документ';
BANK_DOC_ORDER_RASH_ ='Расходный банковский документ';
BANK_DOC_ORDER_CHANGE_DOG ='Изменение договоров';
BANK_SELECT_DOG_CAPTION ='Справочник набора смет, разделов, статей и КЭКЗов по договорам';
BANK_ERROR_ADD_PROV_KOR_SCH ='Нельзя добавить проводку без корреспондирующего счета';
BANK_SELECT_DOG_S_1 = 'Для выбора данных по договорам';
BANK_N12 = 'Поиск банковских документ';
BANK_N61 = 'Настройки импорта из клиент-банка';
BANK_N14 = 'Импорт данных из систем "Клиент-банк"';
BANK_N15 = 'Просмотр импортированых данных';
BANK_N21 = 'Формирование отчетов по баллансовым счетам за месяц';
BANK_N35 = 'Справочник контрагетнов';
BANK_N36 = 'Справочник банков';
BANK_N37 = 'Справочник расчетных счетов предприятия';
BANK_N16 = 'Работа с исправительными справками';
BANK_N22 = 'Выписка клиент-банка';
BANK_PRINT_SCH_BALL = 'Укажите балансовый счёт банка';
BANK_DOGOVOR = 'Договор';
BANK_TYPE_DOGOVOR = 'Тип договора';
BANK_DOG_NUM = ' договор № ';
BANK_PROV = ' проводку ';
BANK_WITH_SUMMA = ' с суммой ';
BANK_RAZB_PO_DOG = 'Разбивка по договорам';
BANK_DATE_DOG = 'Дата договора';
BANK_FIND_CAP_15 = 'Форма поиска банковских документов';
BANK_COUNT_PAGE = 'Колличество документов : ';
BANK_ERROR_PROVE_KOR_SCH = 'Вы не выставили корреспондирующий счет.';
BANK_ERROR_PROVE_DOG = 'Вы не выбрали договор.';
BANK_RAS_SCH_NE_OPREDELEN = 'Счет не определен';
BANK_SELECT_PL = 'Выбор определенного платежного поручения';
BANK_P_S_NAME_CUSTOMER = 'Р/с контрагента';
BANK_FULL_NAME_CUSTOMER = 'Наименование контрагента';
BANK_NUM_DOG = '№ договора';
BANK_ERROR_VIBOR_PL_FROM_LENA = 'Неправильно выставлен флаг экспорта из КЛИЕНТ-БАНКа. Данные не должны экспортироваться! ';
BANK_ADD_TO_DEL_PL = 'Пометить к удалению';
BANK_DEL_TO_DEL_PL = 'Отменить пометку';
BANK_TYPE_KASSA_BANK = 'Движение наличных : Касса-Банк';
BANK_TYPE_OTHER = 'Прочие документы';
BANK_SHABLON = 'Шаблоны обработки';
BANK_TYPE_CAPTION = 'Выбор шаблона';
BANK_SELECT_VSTRECH_CAPTION = 'Выбор встречных проводок';
BANK_SELECT_VSTRECH_ALL_SUM = 'Общая сумма по выбранным проводкам';
BANK_DANNIE_PO_DOC = 'Данные по документам';
BANK_DANNIE_PO_PROV = 'Данные по проводкам';
BANK_PRINT_J1 = 'Журнал-ордер № 2 (по кредиту счёта)';
BANK_PRINT_V1 = 'Ведомость № 2 (по дебету счёта)';
BANK_NEOBRABOTAN = 'Необраб.';
BANK_SELECT_KOMIS_DOC = 'Окно выбора документа комиссии';
BANK_MULTY_DOC_KOMIS = '';
BANK_NO_DOC_KOMIS = 'Нет документов. Вы желаете вернуться в окно с банковским документом?';
BANK_KOMIS = 'комиссия';
BANK_SHOW_KOM = 'Показать только комиссию';
BANK_FIND_CUST = 'По контрагенту';
BANK_FIND_CUST_WITHOUT = 'Без ограничения на контрагента';
BANK_FIND_RS_WITHOUT = 'Без ограничения на р/с';
BANK_FIND_KOR_BAL_SCH = 'По корреспонденции балансовых счетов';
BANK_FIND_CUSTOMER = 'По контрагенту';
BANK_FIND_R_S_PRED = 'По р/с предприятия (наши р/с)';
BANK_FIND_CUST_SP = 'По контрагенту из справочника';
BANK_FIND_R_S_SP = 'По р/с из справочника';
BANK_FIND_NAME = 'По включению в название';
BANK_FIND_SHOW_PROV = 'Показать проводку';
BANK_QUCKLY_FIND = 'Быстрый поиск по контрагенту';
BANK_QUICKLY_FIND_CUST = 'Быстрый поиск по названию контрагента';
BANK_OTV_DOC = 'Отвязать документ';
BANK_Q_F = 'Быстрый поиск';
BANK_DOC_DONT_EDIT = 'Этот документ НЕЛЬЗЯ редактировать. На нем нарушена целостность данных. Его можно только удалить.';
BANK_DOC_DONT_EDIT_KOM = 'Это комиссионный документ, его НЕЛЬЗЯ редактировать. Для его редактирования необходимо сначала отвязать его.';
BANK_DEL_OS_DOC = 'Вы желаете удалить и основной документ';
BANK_KOM_DOC_DEL = ' Это комиссионный документ';
BANK_OTV_DOC_PROCESS = 'Идет процесс отвязывания документа';
BANK_R_S_DONT_KOM = 'На этом р/с нет признака комиссии. Что вы хотите отвязать?';
BANK_NARUSCH_CELOST = 'На этом документе нарушена целосность. Нельзя отвязать комиссию.';
BANK_PRIH_DOC_KOM = 'Это приходный документ. У него нет кимиссии.';
BANK_KOM_DOC_DONT_OTV = 'Это кимиссионный документ. На нём нельзя отвязать комиссию.';
BANKVOPROS_OTV_DOC = 'Вы действительно желаете отвязать документ?';
BANK_PRIV_KOM = 'Привязать комиссию';
BANK_PROVERKA_SUMM = 'Сумма документа комиссии и сумма проводок в комиссии не совпадают. Обратитесь к разработчику!';
BANK_REG_NUM = ' рег.н. - ';
BANK_DOG_OBUCH = 'Договора за обучение';
J4_BAR_SELECT_PEOPLE = 'Выбрать физ лицо';
J4_BAR_TAB_SELECT = 'Перемещение';
J4_BAR_PROV = ' проводку';
J4_BAR_ADD = 'Доб.';
J4_BAR_EDIT = 'Изм.';
J4_BAR_DEL = 'Уд.';
J4_PRIKAZ = 'Приказ';
J4_DANNIE_PO_PRIKAZU = 'Данные по приказу';
}
BANK_STUD_CITY = 'Студмістечко';
BANK_N23 = 'Формування розшифровки рахунків у розрізі бюджетів';
BANK_DOC_OBRABOTAN = 'Цей документ вже відпрацьований в бухгалтерському обліку!';
BANK_DAY_NOT_DELETE = 'Цей день неможливо вилучити, бо в ньому існують документи, що вже відпрацьовані в бухгалтерському обліку!';
KOD_ERROR = 'Код помилки';
KOD_WARNING = 'Повідомлення';
DEPONENT_SYSTEM = '("Депоненти")';
BANK_SYSTEM = '(Підсистема "Банк")';
KASSA_RASSHIFROVKA_PO_SMETAM = 'Розшифровка за бюджетами';
KASSA_PO_SCH = 'по рахунку';
BANK_N24 = 'Звіт за приватними підприємцями';
BANK_DONT_FIND_DOG_NA_RS_RS = 'Не знайден договір при обробці банківської виписки типу "Р/р-Р/р". Зверніться до розробників!';
KASSA_FIND_PO_SMETA = 'Пошук по бюджету';
KASSA_FIND_PO_RAZD = 'Пошук по розділу';
KASSA_FIND_PO_STATE = 'Пошук по статті';
KASSA_FIND_PO_KEKV = 'Пошук по КЕКВ';
KASSA_VEDOMOST_CAPTION = 'Форма вибору проводок з підсистеми "ОРзПО"';
KASSA_ALL_SUMMA = 'Сума обраних проводок';
KASSA_DONT_SELECT_ANYONE_CELL = 'Ви нічого не вибрали';
KASSA_VEDOMOST = 'Відомість № ';
KASSA_VIDSHKODUVANNYA_GOSP = 'на виплату відшкодування на господарські витрати за ';
KASSA_VIDSHKODUVANNYA_VIDR = 'на виплату відшкодування на відрядження за ';
KASSA_PRINT_VEDOM = 'Друк відомості';
KASSA_MEMO_ID_KASSA_LOAD = 'ознака завантаження системи за замовчуванням';
KASSA_MEMO_ID_SM = 'Иден-р бюджету за замовчуванням';
KASSA_MEMO_ID_RAZD = 'Иден-р разділу за замовчуванням';
KASSA_MEMO_ID_ST = 'Иден-р статті за замовчуванням';
KASSA_MEMO_PREDVARIT_PROV = 'Умова показу попередніх проводок';
KASSA_MEMO_KASSA_BEGIN_PERIOD = 'З якого періоду відкрита каса';
KASSA_MEMO_KASSA_DAY_SHOW_LAST = 'Кількість касових днів, які необхідно показати';
KASSA_MEMO_NDS = 'ПДВ за замовчуванням (у відсотках)';
KASSA_MEMO_PRINT_PASPORT = 'Ознака друку паспортних данних в ордері';
KASSA_MEMO_ID_GROUP = 'Under Construction';
KASSA_MESSAGE_ALL = 'Каса настроена';
KASSA_MESSAGE_NOT_ALL = 'Каса настроена, але деякі параметри не були заповнені';
KASSA_ALERT_INSERT = 'Введіть данні';
KASSA_NASTROYKA_CAPTION = 'Настройка каси';
BANK_INFO_SYSTEM = 'Підсистема "Облік банківських операцій" системи "Бухгалтерія"'; //'Подсистема "Учёт банковских операций" системы "Бухгалтерия"';
BANK_INFO_RAZRAB = 'Розробники : Мічківський С.М., Гаврилюк О.Г., Моісеєнко О.П.';//'Разработчики : Мичкивский С.Н., Гаврилюк А.Г.';
BANK_CLBANK_INFO_RAZRAB = 'Розробники : Мічківський С.М., Гаврилюк О.Г., Моісеєнко О.П. клієнт-банк : Щеглов. С.С., Моісеєнко О.П.';//'Разработчики : Мичкивский С.Н., Гаврилюк А.Г.';
BANK_INFO_VERSION = 'Версія 1.1 від 26.06.2012 року';//'Версия 1.1 от 14.03.2005 года';
BANK_INFO_PRAVA = 'Права на даний продукт захищені українським та міжнародними законодавствами. Всі права належать ДонНУ.'; //'Права на данный продукт защищены украинским и международными законодательством. Все права принадлежат ДонНУ.';
KASSA_INFO_SYSTEM = 'Підсистема "Облік касових операцій" системи "Бухгалтерія"'; //Подсистема "Учёт кассовых операций" системы "Бухгалтерия"
KASSA_INFO_VERSION = 'Версія 1.1 від 26.06.2012 року'; //Версия 1.1 от 14.03.2005 года
AVANCE_INFO_SYSTEM = 'Підсистема "Облік розрахунків з підзвітними особами" системи "Бухгалтерія"'; //Подсистема "Учёт расчётов с подотчётными лицами" системы "Бухгалтерия"
AVANCE_INFO_VERSION = 'Версія 1.1 від 26.06.2012 року'; //Версия 1.1 от 14.02.2004 года
BANK_FIND_PRINT_SPRAV = 'Друкувати довідку';
KASSA_ARE_YOU_SURE_TEXT = 'Ви дiйсно бажаєте видалити касу?';
KASSA_ARE_YOU_SURE_CAPTION = 'Видалити касу';
KASSA_CHOOSE_BUTTON_TOOLBAR = 'Вибiр';
KASSA_DOG_NOT_GOS = 'Існує проводка, в якій наказ не є наказом на господарські витрати';
KASSA_DOG_NOT_KOM = 'Існує проводка, в якій наказ не є наказом на відрядження';
J4_DATE_OST = 'Дата зал.';
J4_PRINT_J4 = 'Друкувати журнал';
J4_MAIN_N61 = 'Про систему'; //'О системе';
J4_MAIN_N62 = 'Нові можливості та усунення зауважень'; //'Последние разработки';
J4_N60 = 'Довідник неголовних проводок';
J4_DEL_NEOSNOV = 'Ви дійсно бажаєте вилучити проводку з рахунком ';
J4_DEL_ALL_NEOSNOV = 'Ви дійсно бажаєте вилучити всі проводки з кодом ';
J4_CAPTION = 'Вікно неголовних проводок';
J4_NEOSNOV_KOD = 'Код';
J4_NEOSNOV_FULL_NAME = 'Повна назва';
J4_NEOSNOV_PERSEND = '% відношення';
J4_ADD_PROV = 'Додати проводку';
J4_UPDATE_PROV = 'Змінити проводку';
J4_DEL_PROV = 'Видалити проводку';
J4_ADD_NEOSNOV_CAPTION = 'Вікно додавання назви проводок';
J4_ADD_NEOSNOV_SHORT_NAME = 'Коротка назва';
J4_PERSENT_CAPTION = 'Вікно вводу відсоткового відношеня';
J4_ADD_PROV_PO_NEOSNOVNIM = 'Розбити цю проводку по неголовним';
BANK_N38 = 'Настроювання банку';
CLBANK_CHANGES = 'Нові можливості та усунення зауважень у "Кліент-банку"';
BANK_CHANGES = 'Нові можливості та усунення зауважень у "Банку"';
BANK_NASTROYKA_FM_CAPTION = 'Настройка банку';
BANK_NASTROYKA_DAY_SHOW_LAST = 'За скільки днів показувати банківські виписки до поточної дати';
BANK_NASTROYKA_DATE_INSTALL_SYSTEM = 'Дата инсталяції системи';
BANK_NASTROYKA_ID_DOC_KOMIS = 'Договір для комісійного документу';
BANK_NASTROYKA_KOD_DOC_KOMIS = 'Договір, який підставляється в дебет проводки при обрабці р/р-р/р і видаткового документу';
BANK_NASTROYKA_STATE = 'Стаття для комісійного документу';
BANK_NASTROYKA_KOMIS = 'Рахунок для комісійного документу по умовчанню';
BANK_NASTROYKA_GROUP = 'Група договорів на вибір';
BANK_NASTROYKA_GROUP_ADD_PR = 'Тип договора на додавання прибуткових документів';
BANK_NASTROYKA_GROUP_ADD_RAS = 'Тип договора на додавання видаткових документів';
BANK_MESSAGE_SUCSESSFUL = 'Настройку проведено успiшно';
BANK_MESSAGE_UN_SUCSESSFUL = 'Настройку не проведено!';
BANK_NASTROYKA_VID = ' від ';
BANK_NASTROYKA_ALERT1 = 'Виберіть "Рахунок для комісійного документу по умовчанню" та спробуйте ще раз';
BANK_NASTROYKA_KEKV_CAPTION = 'КЕКD по умовчанню для старого шаблону "Договора за навчання"';
BANK_NASTROYKA_NICH = 'Ознака відображення шаблону для НІЧ';
BANK_NASTROYKA_RAZDEL_NICH = 'Розділ для НІЧ за замовчуванням';
BANK_NASTROYKA_DOG_NICH = 'Договір для НІЧ за замовчуванням';
J4_N71 = 'Друк розшифровок по неосновних проводках';
J4_N711 = 'Друк розшифровки по рахунку';
J4_SELECT_DATE = 'Вкажіть дату';
J4_PO_DEBETU = 'за дебетом рахунку';
J4_PO_KREDITU = 'за кредитом рахунку';
{Update}
KASSA_ADD_KASSA_FORM1 = 'Вікно додавання нової системи';//'Окно добавления новой системы';
KASSA_UPDATE_KASSA_FORM1 = 'Вікно редагування';//'Окно добавления новой системы';
KASSA_MY_BUTTON_ADD1 = 'Додати';//'Добавить';
KASSA_ADD_KASSA_FORM_SHORT1 = 'Введіть коротку назву системи';//'Введите короткое название системы';
KASSA_ADD_KASSA_FORM_FULL1 = 'Введіть повну назву системи';//'Введите полное название системы';
KASSA_DATE_BEG_LABEL1 = 'Дата початку дії системи';
MY_BUTTON_CLOSE1 = 'Вiдмiнити';
KASSA_FLAG_LOAD_DEF_SYSTEM1 = 'Загрузки системи за замовчуванням';
KASSA_UPDATE_KASSA_FORM_SHORT1 = 'Введіть нову коротку назву системи';
KASSA_UPDATE_KASSA_FORM_FULL1 = 'Введіть нову повну назву системи';
KASSA_MY_BUTTON_UPDATE1 = 'Змiнити';
KASSA_EMPTY_MESSAGE1 = 'Ви заповнили не всi поля';
//KASSA_SCHET_DIALOG
KASSA_DIALOG_SCHET_FM_CAPTION_ADD = 'Вsкно додавання рахунку';
KASSA_DIALOG_SCHET_LABEL = 'Рахунок:';
KASSA_DIALOG_SCHET_FLAG = 'Рахунок за замовчуванням';
KASSA_DIALOG_SCHET_FM_CAPTION_UP = 'Вікно редагування рахунку';
KASSA_FLAG_DEFAULT = 'Рахунок за замовчуванням';//'Признак счёта по-умолчанию';
KASSA_PROV_NALICHEE_DOG_OBUCH = 'Проводка обов''язково потребує введеня договора за навчання';
KASSA_PROV_NALICHEE_DOG_STUD = 'Проводка обов''язково потребує введеня договора по студмістечку';
KASSA_DIALOG_SCHET_MESSAGE1 = 'Ціq рахунок вже закріплен за іншої системою!';
KASSA_DIALOG_SCHET_MESSAGE2 = 'Виберіть рахунок';
KASSA_SALDO_MAIN_YES = 'Відобразити сальдо за проведеними документами';
KASSA_SALDO_MAIN_NO = 'Відобразити сальдо за виписанимм документамм';
KASSA_DOC_ZAPIS_V_ALL_DOC = 'Провести по бух.обліку';
KASSA_DOC_VOZVRAT_V_BUFF = 'Повернути з бух.пров.';
KASSA_DOC_SUM_VIP = 'Виписано';
KASSA_DOC_SUM_PROV = 'Проведено';
KASSA_DOC_VOZVRAT_VOPROS = 'Ви дійсно бажаєте повернути документ ';
KASSA_DOC_VOZVRAT_FIO = 'П.І.Б.';
KASSA_Z_BUHG_OBLICU = 'з бух.обліку?';
KASSA_DOC_DEL_NUM = 'Ви дійсно бажаєте видалити документ № ';
KASSA_DOC_DEL_FIO = ' на ім''я ';
KASSA_NASTROYKA_MAKE_PROVERKA_TO_BUFF = '';
KASSA_NASTROYKA_ID_GROUP_ADD_PR = 'Ідентифікатор групи договорів на додавання прибуткових';
KASSA_NASTROYKA_ID_GROUP_ADD_RAS = 'Ідентифікатор групи договорів на додавання видаткових';
KASSA_WARNING_SUM_CHANGE_ORDER = 'Документ проведено по бух.обліку, тому суму документа неможливо змінити. Вона повинна дорівнювати ';
KASSA_TAKE_REFRESH = 'Автовідновлення';
JNASTROYKA_RAZCHIFROVKA = 'Показувати розшифровки';
JNASTROYKA_SMETA = 'Бюджет за замовчуванням';
JNASTROYKA_RAZDEL = 'Розділ за замовчуванням';
JNASTROYKA_STATE = 'Стаття за замовчуванням';
JNASTROYKA_KEKV = 'КЕКВ за замовчуванням';
JNASTROYKA_SHOW_DEBET = 'Показувати дебет';
JNASTROYKA_DAY_SHOW_LAST = 'Кількість днів для показу документів';
JNASTROYKA_NEW_ALGORYTHM = 'Дата початку дії нового алгоритму';
JNASTROYKA_SHOW_NEOSN_PROV = 'Можливість додавання неголовних проводок';
JNASTROYKA_DEL_BUFFER = 'Очищати буфер';
JNASTROYKA_ID_GROUP = 'Група договорів для вибору';
JNASTROYKA_ID_GROUP_ADD_PR = 'Група договорів на додовання прибуткових';
JNASTROYKA_ID_GROUP_ADD_RAS = 'Група договорів на додовання видаткових';
JNASTROYKA_FORM_CAPTION = 'Настроювання';
JNASTROYKA_SHOW_KOM = 'Показувати блок з датами по відрядженням';
J4_ALERT_TABLE_EMPTY = 'Настройку не проведено'; // Когда в таблице нет ни одной J4_INI строки
J4_ALERT_CHOOSE_DATE_ALG = 'Виберіть "Дату початку дії нового алгоритму" та спробуйте ще раз';
J4_NASTROENO = 'Настройку проведено успішно';
J4_CAPTION_MSG = 'Настроювання'; //заголовок в MessageBox - ах
BANK_ADD_NOT_ADD_DAY_AFTER_CUR = 'Неможливо додати день більшим, ніж сьогодняшня дата';
BANK_NEOBR_FILTER_CAPTION = 'Вікно фільтру необроблених документів';
BANK_NEOBR_LABLE1 = 'Показати необроблені документи по даті : ';
BANK_RAD1 = 'Всі документи';
BANK_RAD2 = 'Тільки основні';
BANK_RAD3 = 'Тільки комісію';
BANK_ERROR_DATE = 'Введіть правильно дату';
KASSA_ANALITIC_PO_SCH = 'Зформувати картку по рахунку';
KASSA_ANALITIC_FORM_CAPTION = 'Фільтр формування картки аналітичного обліку готівкових операцій';
KASSA_CREATE_PO_MONTH = 'Зформувати за місяць';
KASSA_CREATE_DAY = 'Зформувати з';
KASSA_ANALIT_KEKV = 'КЄКВ';
KASSA_ANALIT_RAZD = 'Розділи';
KASSA_ANAKIT_KEKV_RAZD = 'КЄКВ + Розділи';
KASSA_ANALIT_KFK = 'КФК, загальний фонд, види спеціального фонду';
KASSA_ANALIT_OST_MONTH = 'Залишок на початок місяця';
KASSA_ANALIT_RESULT = 'Зформована картка обліку готівкових операцій';
KASSA_ANALIT_DATE_SCH = 'Для вірного формування картки потрібно закрити балансовий рахунок до дати ';
KASSA_ANALIT_NAME = 'Картка аналітичного обліку готівкових операцій';
J4_PRINT_NEW_ALG_CAP = 'помітити друк звіту';
J4_NAME_OTCHET = 'Назва звіту';
J4_NEOSN_SUMMA = 'сума неголовних пр.';
J4_OSN_SUMMA = 'сума головних пр.';
J4_SELECT_NEOSN_PROV_RAS_CAPTION = 'Вікно приєднання неголовної проводки до розшифровки';
J4_PRIVYAZAT_K_NEOSN = 'Прив''язати до неголовної пр.';
BANK_PRINT_REESTR_PRINT = 'Друкувати реєстр';
BANK_PRINT_WITH_SONOVANIE = 'з підставою';
BANK_PRINT_WITH_KORRESP = 'з кореспонденцією';
BANK_AUTOR_SPRAVKI = 'Автор довідки';
BANK_KOMENTAR_SPRAVKI = 'Коментар до довідки';
BANK_SELECT_PRINT_VIPISKA = 'банківську виписку';
BANK_SELECT_PRINT_REESTR_VIPISKA = 'реєстр документів по банківській виписки';
BANK_PRINT_MEMORIAL_ORDER = 'Меморіальний ордер';
KASSA_ANALIT_PROGRAMM = 'Програма';
KASSA_ANALIT_TYPE_KOSHTIV = 'Тип коштів';
KASSA_ANALIT_NO_PROGRAMM = 'Ви не вибрали програму';
KASSA_ANALIT_NOTYPE_KOSHTIV = 'Ви не вибрали тип коштів';
KASSA_PO_PROGRAMM = ' по програмі ';
KASSA_PO_TYPE = ' по типу коштів ';
BANK_PRINT_VED_PRINT = 'Друкувати';
BANK_PRINT_RAS_DAY = 'Друкувати розшифровку по рахункам';
AVANCE_FIND_PO_NUMBER = 'Пошук по номеру';
AVANCE_FIND_PO_NUMBER_LABEL = 'Без обмеження на Номер';
AVANCE_FIND_FIO = 'Пошук по П.І.Б.';
AVANCE_FIND_FIO_PO_SP = 'по даним з довідника';
AVANCE_FIND_FIO_PO_VKL = 'по включенню';
AVANCE_OSTATOK_CANT_EDIT = 'Редагувати можливо тільки проводку (данні знаходяться в правій таблиці).';
AVANCE_OSTATOK_CANT_EDIT_SYS = 'Неможливо редагувати залишок, що розрахувала система!';
BANK_SP_SCH_SZYAZ = 'Зв''язати рахунки';
BANK_SP_SVYAZ_FORM_CAPTION = 'Вікно зв''язування рахунків';
BANK_SP_DATA_RAS = 'Данні по розрахунковому рахунку';
BANK_SP_DATA_SCH = 'Данні по балансовому рахунку';
BANK_SP_CHANGE_RAS = 'Змінити розрахунковий рахунок';
BANK_SP_CHANGE_SCH = 'Змінити балансовий рахунок';
BANK_SP_ADD_NEW_SV = 'Додати нову зв''язку';
BANK_SP_DELETE_SV = 'Видалити зв''язку';
BANK_SP_CHANGE_RAS_1 = 'Треба вибрати розрахунковий рахунок';
BANK_SP_CHANGE_SCH_1 = 'Треба змінити балансовий рахунок';
BANK_SP_LAB_1 = 'Показувати рахунки з ';
BANK_FIND_DOG = 'За ДОГОВОРОМ';
BANK_FIND_DOG_FGD = 'За ДОГОВОРОМ ФГД';
BANK_FIND_DOG_CN = 'За ДОГОВОРОМ за навчання';
BANK_FIND_DOG_NO = 'Без обмежання на ДОГОВІР';
BANK_N25 = 'Формування меморіальних ордерів';
J4_MAIN_FORM_TO_1 = 'за';
KASSA_PRINT_OLD_ORDER = 'Касовий ордер до 2008р.';
implementation
end.
|
unit SysExtraFunc;
interface
type
TEXEVersionData = record
CompanyName,
FileDescription,
FileVersion,
InternalName,
LegalCopyright,
LegalTrademarks,
OriginalFileName,
ProductName,
ProductVersion,
Comments,
PrivateBuild,
SpecialBuild: string;
end;
function GetEXEVersionDataW(const FileName: UnicodeString;var verInfo:TEXEVersionData):LongBool;
implementation
uses
Windows,SysUtils;
function GetEXEVersionDataW(const FileName: UnicodeString;var verInfo:TEXEVersionData):LongBool;
type
PLandCodepage = ^TLandCodepage;
TLandCodepage = record
wLanguage,
wCodePage: word;
end;
var
dummy,len: cardinal;
buf:array of Byte;
pntr: Pointer;
lang: UnicodeString;
begin
Result:=False;
len := GetFileVersionInfoSizeW(PwideChar(FileName), dummy);
if len = 0 then
Exit;
buf:=nil;
try
SetLength(buf,len);
if not GetFileVersionInfoW(PwideChar(FileName), 0, len, buf) then
exit;
if not VerQueryValueW(buf, '\VarFileInfo\Translation\', pntr, len) then
exit;
lang := Format('%.4x%.4x', [PLandCodepage(pntr)^.wLanguage, PLandCodepage(pntr)^.wCodePage]);
if VerQueryValueW(buf, PwideChar('\StringFileInfo\' + lang + '\CompanyName'), pntr, len){ and (@len <> nil)} then
verInfo.CompanyName := PwideChar(pntr);
if VerQueryValueW(buf, PwideChar('\StringFileInfo\' + lang + '\FileDescription'), pntr, len){ and (@len <> nil)} then
verInfo.FileDescription := PwideChar(pntr);
if VerQueryValueW(buf, PwideChar('\StringFileInfo\' + lang + '\FileVersion'), pntr, len){ and (@len <> nil)} then
verInfo.FileVersion := PwideChar(pntr);
if VerQueryValueW(buf, PwideChar('\StringFileInfo\' + lang + '\InternalName'), pntr, len){ and (@len <> nil)} then
verInfo.InternalName := PwideChar(pntr);
if VerQueryValueW(buf, PwideChar('\StringFileInfo\' + lang + '\LegalCopyright'), pntr, len){ and (@len <> nil)} then
verInfo.LegalCopyright := PwideChar(pntr);
if VerQueryValueW(buf, PwideChar('\StringFileInfo\' + lang + '\LegalTrademarks'), pntr, len){ and (@len <> nil)} then
verInfo.LegalTrademarks := PwideChar(pntr);
if VerQueryValueW(buf, PwideChar('\StringFileInfo\' + lang + '\OriginalFileName'), pntr, len){ and (@len <> nil)} then
verInfo.OriginalFileName := PwideChar(pntr);
if VerQueryValueW(buf, PwideChar('\StringFileInfo\' + lang + '\ProductName'), pntr, len){ and (@len <> nil)} then
verInfo.ProductName := PwideChar(pntr);
if VerQueryValueW(buf, PwideChar('\StringFileInfo\' + lang + '\ProductVersion'), pntr, len){ and (@len <> nil)} then
verInfo.ProductVersion := PwideChar(pntr);
if VerQueryValueW(buf, PwideChar('\StringFileInfo\' + lang + '\Comments'), pntr, len){ and (@len <> nil)} then
verInfo.Comments := PwideChar(pntr);
if VerQueryValueW(buf, PwideChar('\StringFileInfo\' + lang + '\PrivateBuild'), pntr, len){ and (@len <> nil)} then
verInfo.PrivateBuild := PwideChar(pntr);
if VerQueryValueW(buf, PwideChar('\StringFileInfo\' + lang + '\SpecialBuild'), pntr, len){ and (@len <> nil)} then
verInfo.SpecialBuild := PwideChar(pntr);
Result:=True;
finally
IF buf <> nil then SetLength(buf,0);
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 uCEFInterfaces;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
{$IFDEF DELPHI16_UP}
WinApi.Windows, System.Classes,
{$ELSE}
Windows, Classes,
{$ENDIF}
uCEFTypes, uCEFSchemeRegistrar;
type
ICefBrowser = interface;
ICefFrame = interface;
ICefRequest = interface;
ICefv8Value = interface;
ICefV8Exception = interface;
ICefV8StackTrace = interface;
ICefDomVisitor = interface;
ICefDomDocument = interface;
ICefDomNode = interface;
ICefv8Context = interface;
ICefListValue = interface;
ICefBinaryValue = interface;
ICefDictionaryValue = interface;
ICefClient = interface;
ICefUrlrequestClient = interface;
ICefBrowserHost = interface;
ICefTask = interface;
ICefTaskRunner = interface;
ICefFileDialogCallback = interface;
ICefPrintHandler = interface;
ICefPrintDialogCallback = interface;
ICefPrintJobCallback = interface;
ICefRequestContext = interface;
ICefAccessibilityHandler = interface;
ICefDragData = interface;
ICefNavigationEntry = interface;
ICefSslInfo = interface;
ICefSSLStatus = interface;
ICefImage = interface;
IChromiumEvents = interface;
ICefThread = interface;
ICefWaitableEvent = interface;
ICefX509CertPrincipal = interface;
ICefX509Certificate = interface;
ICefSelectClientCertificateCallback = interface;
ICefCommandLine = interface;
ICefRequestHandler = interface;
ICefResourceBundleHandler = interface;
ICefBrowserProcessHandler = interface;
ICefRenderProcessHandler = interface;
ICefProcessMessage = interface;
ICefLifeSpanHandler = interface;
ICefGetExtensionResourceCallback = interface;
ICefExtensionHandler = interface;
ICefExtension = interface;
ICefStreamReader = interface;
ICefLoadHandler = interface;
ICefServer = interface;
ICefServerHandler = interface;
TCefv8ValueArray = array of ICefv8Value;
TCefX509CertificateArray = array of ICefX509Certificate;
TCefBinaryValueArray = array of ICefBinaryValue;
TCefFrameIdentifierArray = array of int64;
TOnPdfPrintFinishedProc = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(const path: ustring; ok: Boolean);
TCefDomVisitorProc = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(const document: ICefDomDocument);
TCefDomVisitorProc2 = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(const browser : ICefBrowser; const document: ICefDomDocument);
TCefStringVisitorProc = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(const str: ustring);
TOnRegisterCustomSchemes = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(const registrar: TCefSchemeRegistrarRef) {$IFNDEF DELPHI12_UP}of object{$ENDIF};
TOnRenderThreadCreatedEvent = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(const extraInfo: ICefListValue) {$IFNDEF DELPHI12_UP}of object{$ENDIF};
TOnWebKitInitializedEvent = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure() {$IFNDEF DELPHI12_UP}of object{$ENDIF};
TOnBrowserCreatedEvent = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(const browser: ICefBrowser) {$IFNDEF DELPHI12_UP}of object{$ENDIF};
TOnBrowserDestroyedEvent = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(const browser: ICefBrowser) {$IFNDEF DELPHI12_UP}of object{$ENDIF};
TOnBeforeNavigationEvent = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; navigationType: TCefNavigationType; isRedirect: Boolean; var aStopNavigation : boolean) {$IFNDEF DELPHI12_UP}of object{$ENDIF};
TOnContextCreatedEvent = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(const browser: ICefBrowser; const frame: ICefFrame; const context: ICefv8Context) {$IFNDEF DELPHI12_UP}of object{$ENDIF};
TOnContextReleasedEvent = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(const browser: ICefBrowser; const frame: ICefFrame; const context: ICefv8Context) {$IFNDEF DELPHI12_UP}of object{$ENDIF};
TOnUncaughtExceptionEvent = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(const browser: ICefBrowser; const frame: ICefFrame; const context: ICefv8Context; const exception: ICefV8Exception; const stackTrace: ICefV8StackTrace) {$IFNDEF DELPHI12_UP}of object{$ENDIF};
TOnFocusedNodeChangedEvent = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(const browser: ICefBrowser; const frame: ICefFrame; const node: ICefDomNode) {$IFNDEF DELPHI12_UP}of object{$ENDIF};
TOnProcessMessageReceivedEvent = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(const browser: ICefBrowser; sourceProcess: TCefProcessId; const message: ICefProcessMessage; var aHandled : boolean) {$IFNDEF DELPHI12_UP}of object{$ENDIF};
TOnContextInitializedEvent = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure() {$IFNDEF DELPHI12_UP}of object{$ENDIF};
TOnBeforeChildProcessLaunchEvent = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(const commandLine: ICefCommandLine) {$IFNDEF DELPHI12_UP}of object{$ENDIF};
TOnRenderProcessThreadCreatedEvent = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(const extraInfo: ICefListValue) {$IFNDEF DELPHI12_UP}of object{$ENDIF};
TOnScheduleMessagePumpWorkEvent = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(const delayMs: Int64) {$IFNDEF DELPHI12_UP}of object{$ENDIF};
TOnGetDataResourceEvent = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(resourceId: Integer; out data: Pointer; out dataSize: NativeUInt; var aResult : Boolean);
TOnGetLocalizedStringEvent = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(stringId: Integer; out stringVal: ustring; var aResult : Boolean);
TOnGetDataResourceForScaleEvent = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(resourceId: Integer; scaleFactor: TCefScaleFactor; out data: Pointer; out dataSize: NativeUInt; var aResult : Boolean);
TCefCompletionCallbackProc = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure;
TCefSetCookieCallbackProc = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(success: Boolean);
TCefDeleteCookiesCallbackProc = {$IFDEF DELPHI12_UP}reference to{$ENDIF} procedure(numDeleted: Integer);
ICefBaseRefCounted = interface
['{1F9A7B44-DCDC-4477-9180-3ADD44BDEB7B}']
function Wrap: Pointer;
end;
ICefRunFileDialogCallback = interface(ICefBaseRefCounted)
['{59FCECC6-E897-45BA-873B-F09586C4BE47}']
procedure OnFileDialogDismissed(selectedAcceptFilter: Integer; filePaths: TStrings);
end;
TCefRunFileDialogCallbackProc = {$IFDEF DELPHI12_UP}reference to{$ENDIF}
procedure(selectedAcceptFilter: Integer; filePaths: TStrings);
ICefNavigationEntryVisitor = interface(ICefBaseRefCounted)
['{CC4D6BC9-0168-4C2C-98BA-45E9AA9CD619}']
function Visit(const entry: ICefNavigationEntry;
current: Boolean; index, total: Integer): Boolean;
end;
TCefNavigationEntryVisitorProc = {$IFDEF DELPHI12_UP}reference to{$ENDIF}
function(const entry: ICefNavigationEntry; current: Boolean; index, total: Integer): Boolean;
ICefPdfPrintCallback = interface(ICefBaseRefCounted)
['{F1CC58E9-2C30-4932-91AE-467C8D8EFB8E}']
procedure OnPdfPrintFinished(const path: ustring; ok: Boolean);
end;
TOnDownloadImageFinishedProc = {$IFDEF DELPHI12_UP}reference to{$ENDIF}
procedure(const imageUrl: ustring; httpStatusCode: Integer; const image: ICefImage);
ICefDownloadImageCallback = interface(ICefBaseRefCounted)
['{0C6E9032-27DF-4584-95C6-DC3C7CB63727}']
procedure OnDownloadImageFinished(const imageUrl: ustring;
httpStatusCode: Integer; const image: ICefImage);
end;
ICefBrowserHost = interface(ICefBaseRefCounted)
['{53AE02FF-EF5D-48C3-A43E-069DA9535424}']
function GetBrowser: ICefBrowser;
procedure CloseBrowser(forceClose: Boolean);
function TryCloseBrowser: Boolean;
procedure SetFocus(focus: Boolean);
function GetWindowHandle: TCefWindowHandle;
function GetOpenerWindowHandle: TCefWindowHandle;
function HasView: Boolean;
function GetRequestContext: ICefRequestContext;
function GetZoomLevel: Double;
procedure SetZoomLevel(zoomLevel: Double);
procedure RunFileDialog(mode: TCefFileDialogMode; const title, defaultFilePath: ustring; acceptFilters: TStrings; selectedAcceptFilter: Integer; const callback: ICefRunFileDialogCallback);
procedure RunFileDialogProc(mode: TCefFileDialogMode; const title, defaultFilePath: ustring; acceptFilters: TStrings; selectedAcceptFilter: Integer; const callback: TCefRunFileDialogCallbackProc);
procedure StartDownload(const url: ustring);
procedure DownloadImage(const imageUrl: ustring; isFavicon: Boolean; maxImageSize: Cardinal; bypassCache: Boolean; const callback: ICefDownloadImageCallback);
procedure Print;
procedure PrintToPdf(const path: ustring; settings: PCefPdfPrintSettings; const callback: ICefPdfPrintCallback);
procedure PrintToPdfProc(const path: ustring; settings: PCefPdfPrintSettings; const callback: TOnPdfPrintFinishedProc);
procedure Find(identifier: Integer; const searchText: ustring; forward, matchCase, findNext: Boolean);
procedure StopFinding(clearSelection: Boolean);
procedure ShowDevTools(const windowInfo: PCefWindowInfo; const client: ICefClient; const settings: PCefBrowserSettings; inspectElementAt: PCefPoint);
procedure CloseDevTools;
function HasDevTools: Boolean;
procedure GetNavigationEntries(const visitor: ICefNavigationEntryVisitor; currentOnly: Boolean);
procedure GetNavigationEntriesProc(const proc: TCefNavigationEntryVisitorProc; currentOnly: Boolean);
procedure SetMouseCursorChangeDisabled(disabled: Boolean);
function IsMouseCursorChangeDisabled: Boolean;
procedure ReplaceMisspelling(const word: ustring);
procedure AddWordToDictionary(const word: ustring);
function IsWindowRenderingDisabled: Boolean;
procedure WasResized;
procedure WasHidden(hidden: Boolean);
procedure NotifyScreenInfoChanged;
procedure Invalidate(kind: TCefPaintElementType);
procedure SendKeyEvent(const event: PCefKeyEvent);
procedure SendMouseClickEvent(const event: PCefMouseEvent; kind: TCefMouseButtonType; mouseUp: Boolean; clickCount: Integer);
procedure SendMouseMoveEvent(const event: PCefMouseEvent; mouseLeave: Boolean);
procedure SendMouseWheelEvent(const event: PCefMouseEvent; deltaX, deltaY: Integer);
procedure SendFocusEvent(setFocus: Boolean);
procedure SendCaptureLostEvent;
procedure NotifyMoveOrResizeStarted;
function GetWindowlessFrameRate(): Integer;
procedure SetWindowlessFrameRate(frameRate: Integer);
procedure IMESetComposition(const text: ustring; underlinesCount : NativeUInt; const underlines : PCefCompositionUnderline; const replacement_range, selection_range : PCefRange);
procedure IMECommitText(const text: ustring; const replacement_range : PCefRange; relative_cursor_pos : integer);
procedure IMEFinishComposingText(keep_selection : boolean);
procedure IMECancelComposition;
procedure DragTargetDragEnter(const dragData: ICefDragData; const event: PCefMouseEvent; allowedOps: TCefDragOperations);
procedure DragTargetDragOver(const event: PCefMouseEvent; allowedOps: TCefDragOperations);
procedure DragTargetDragLeave;
procedure DragTargetDrop(event: PCefMouseEvent);
procedure DragSourceEndedAt(x, y: Integer; op: TCefDragOperation);
procedure DragSourceSystemDragEnded;
function GetVisibleNavigationEntry : ICefNavigationEntry;
procedure SetAccessibilityState(accessibilityState: TCefState);
procedure SetAutoResizeEnabled(enabled: boolean; const min_size, max_size: PCefSize);
function GetExtension : ICefExtension;
function IsBackgroundHost : boolean;
property Browser: ICefBrowser read GetBrowser;
property WindowHandle: TCefWindowHandle read GetWindowHandle;
property OpenerWindowHandle: TCefWindowHandle read GetOpenerWindowHandle;
property ZoomLevel: Double read GetZoomLevel write SetZoomLevel;
property RequestContext: ICefRequestContext read GetRequestContext;
property VisibleNavigationEntry : ICefNavigationEntry read GetVisibleNavigationEntry;
end;
ICefProcessMessage = interface(ICefBaseRefCounted)
['{E0B1001A-8777-425A-869B-29D40B8B93B1}']
function IsValid: Boolean;
function IsReadOnly: Boolean;
function Copy: ICefProcessMessage;
function GetName: ustring;
function GetArgumentList: ICefListValue;
property Name: ustring read GetName;
property ArgumentList: ICefListValue read GetArgumentList;
end;
ICefBrowser = interface(ICefBaseRefCounted)
['{BA003C2E-CF15-458F-9D4A-FE3CEFCF3EEF}']
function GetHost: ICefBrowserHost;
function CanGoBack: Boolean;
procedure GoBack;
function CanGoForward: Boolean;
procedure GoForward;
function IsLoading: Boolean;
procedure Reload;
procedure ReloadIgnoreCache;
procedure StopLoad;
function GetIdentifier: Integer;
function IsSame(const that: ICefBrowser): Boolean;
function IsPopup: Boolean;
function HasDocument: Boolean;
function GetMainFrame: ICefFrame;
function GetFocusedFrame: ICefFrame;
function GetFrameByident(identifier: Int64): ICefFrame;
function GetFrame(const name: ustring): ICefFrame;
function GetFrameCount: NativeUInt;
function GetFrameIdentifiers(var aFrameCount : NativeUInt; var aFrameIdentifierArray : TCefFrameIdentifierArray) : boolean;
function GetFrameNames(var aFrameNames : TStrings) : boolean;
function SendProcessMessage(targetProcess: TCefProcessId; const ProcMessage: ICefProcessMessage): Boolean;
property MainFrame: ICefFrame read GetMainFrame;
property FocusedFrame: ICefFrame read GetFocusedFrame;
property FrameCount: NativeUInt read GetFrameCount;
property Host: ICefBrowserHost read GetHost;
property Identifier: Integer read GetIdentifier;
end;
ICefPostDataElement = interface(ICefBaseRefCounted)
['{3353D1B8-0300-4ADC-8D74-4FF31C77D13C}']
function IsReadOnly: Boolean;
procedure SetToEmpty;
procedure SetToFile(const fileName: ustring);
procedure SetToBytes(size: NativeUInt; bytes: Pointer);
function GetType: TCefPostDataElementType;
function GetFile: ustring;
function GetBytesCount: NativeUInt;
function GetBytes(size: NativeUInt; bytes: Pointer): NativeUInt;
end;
ICefPostData = interface(ICefBaseRefCounted)
['{1E677630-9339-4732-BB99-D6FE4DE4AEC0}']
function IsReadOnly: Boolean;
function HasExcludedElements: Boolean;
function GetCount: NativeUInt;
function GetElements(Count: NativeUInt): IInterfaceList; // list of ICefPostDataElement
function RemoveElement(const element: ICefPostDataElement): Integer;
function AddElement(const element: ICefPostDataElement): Integer;
procedure RemoveElements;
end;
ICefStringMap = interface
['{A33EBC01-B23A-4918-86A4-E24A243B342F}']
function GetHandle: TCefStringMap;
function GetSize: Integer;
function Find(const Key: ustring): ustring;
function GetKey(Index: Integer): ustring;
function GetValue(Index: Integer): ustring;
procedure Append(const Key, Value: ustring);
procedure Clear;
property Handle: TCefStringMap read GetHandle;
property Size: Integer read GetSize;
property Key[index: Integer]: ustring read GetKey;
property Value[index: Integer]: ustring read GetValue;
end;
ICefStringMultimap = interface
['{583ED0C2-A9D6-4034-A7C9-20EC7E47F0C7}']
function GetHandle: TCefStringMultimap;
function GetSize: Integer;
function FindCount(const Key: ustring): Integer;
function GetEnumerate(const Key: ustring; ValueIndex: Integer): ustring;
function GetKey(Index: Integer): ustring;
function GetValue(Index: Integer): ustring;
procedure Append(const Key, Value: ustring);
procedure Clear;
property Handle: TCefStringMap read GetHandle;
property Size: Integer read GetSize;
property Key[index: Integer]: ustring read GetKey;
property Value[index: Integer]: ustring read GetValue;
property Enumerate[const Key: ustring; ValueIndex: Integer]: ustring read GetEnumerate;
end;
ICefRequest = interface(ICefBaseRefCounted)
['{FB4718D3-7D13-4979-9F4C-D7F6C0EC592A}']
function IsReadOnly: Boolean;
function GetUrl: ustring;
function GetMethod: ustring;
function GetPostData: ICefPostData;
procedure GetHeaderMap(const HeaderMap: ICefStringMultimap);
procedure SetUrl(const value: ustring);
procedure SetMethod(const value: ustring);
procedure SetReferrer(const referrerUrl: ustring; policy: TCefReferrerPolicy);
function GetReferrerUrl: ustring;
function GetReferrerPolicy: TCefReferrerPolicy;
procedure SetPostData(const value: ICefPostData);
procedure SetHeaderMap(const HeaderMap: ICefStringMultimap);
function GetFlags: TCefUrlRequestFlags;
procedure SetFlags(flags: TCefUrlRequestFlags);
function GetFirstPartyForCookies: ustring;
procedure SetFirstPartyForCookies(const url: ustring);
procedure Assign(const url, method: ustring;
const postData: ICefPostData; const headerMap: ICefStringMultimap);
function GetResourceType: TCefResourceType;
function GetTransitionType: TCefTransitionType;
function GetIdentifier: UInt64;
property Url: ustring read GetUrl write SetUrl;
property Method: ustring read GetMethod write SetMethod;
property ReferrerUrl: ustring read GetReferrerUrl;
property ReferrerPolicy: TCefReferrerPolicy read GetReferrerPolicy;
property PostData: ICefPostData read GetPostData write SetPostData;
property Flags: TCefUrlRequestFlags read GetFlags write SetFlags;
property FirstPartyForCookies: ustring read GetFirstPartyForCookies write SetFirstPartyForCookies;
property ResourceType: TCefResourceType read GetResourceType;
property TransitionType: TCefTransitionType read GetTransitionType;
property Identifier: UInt64 read GetIdentifier;
end;
ICefStringVisitor = interface(ICefBaseRefCounted)
['{63ED4D6C-2FC8-4537-964B-B84C008F6158}']
procedure Visit(const str: ustring);
end;
ICefFrame = interface(ICefBaseRefCounted)
['{8FD3D3A6-EA3A-4A72-8501-0276BD5C3D1D}']
function IsValid: Boolean;
procedure Undo;
procedure Redo;
procedure Cut;
procedure Copy;
procedure Paste;
procedure Del;
procedure SelectAll;
procedure ViewSource;
procedure GetSource(const visitor: ICefStringVisitor);
procedure GetSourceProc(const proc: TCefStringVisitorProc);
procedure GetText(const visitor: ICefStringVisitor);
procedure GetTextProc(const proc: TCefStringVisitorProc);
procedure LoadRequest(const request: ICefRequest);
procedure LoadUrl(const url: ustring);
procedure LoadString(const str, url: ustring);
procedure ExecuteJavaScript(const code, scriptUrl: ustring; startLine: Integer);
function IsMain: Boolean;
function IsFocused: Boolean;
function GetName: ustring;
function GetIdentifier: Int64;
function GetParent: ICefFrame;
function GetUrl: ustring;
function GetBrowser: ICefBrowser;
function GetV8Context: ICefv8Context;
procedure VisitDom(const visitor: ICefDomVisitor);
procedure VisitDomProc(const proc: TCefDomVisitorProc);
property Name: ustring read GetName;
property Url: ustring read GetUrl;
property Browser: ICefBrowser read GetBrowser;
property Parent: ICefFrame read GetParent;
end;
ICefCustomStreamReader = interface(ICefBaseRefCounted)
['{BBCFF23A-6FE7-4C28-B13E-6D2ACA5C83B7}']
function Read(ptr: Pointer; size, n: NativeUInt): NativeUInt;
function Seek(offset: Int64; whence: Integer): Integer;
function Tell: Int64;
function Eof: Boolean;
function MayBlock: Boolean;
end;
ICefStreamReader = interface(ICefBaseRefCounted)
['{DD5361CB-E558-49C5-A4BD-D1CE84ADB277}']
function Read(ptr: Pointer; size, n: NativeUInt): NativeUInt;
function Seek(offset: Int64; whence: Integer): Integer;
function Tell: Int64;
function Eof: Boolean;
function MayBlock: Boolean;
end;
ICefWriteHandler = interface(ICefBaseRefCounted)
['{F2431888-4EAB-421E-9EC3-320BE695AF30}']
function Write(const ptr: Pointer; size, n: NativeUInt): NativeUInt;
function Seek(offset: Int64; whence: Integer): Integer;
function Tell: Int64;
function Flush: Integer;
function MayBlock: Boolean;
end;
ICefStreamWriter = interface(ICefBaseRefCounted)
['{4AA6C477-7D8A-4D5A-A704-67F900A827E7}']
function Write(const ptr: Pointer; size, n: NativeUInt): NativeUInt;
function Seek(offset: Int64; whence: Integer): Integer;
function Tell: Int64;
function Flush: Integer;
function MayBlock: Boolean;
end;
ICefResponse = interface(ICefBaseRefCounted)
['{E9C896E4-59A8-4B96-AB5E-6EA3A498B7F1}']
function IsReadOnly: Boolean;
function GetError: TCefErrorCode;
procedure SetError(error: TCefErrorCode);
function GetStatus: Integer;
procedure SetStatus(status: Integer);
function GetStatusText: ustring;
procedure SetStatusText(const StatusText: ustring);
function GetMimeType: ustring;
procedure SetMimeType(const mimetype: ustring);
function GetHeader(const name: ustring): ustring;
procedure GetHeaderMap(const headerMap: ICefStringMultimap);
procedure SetHeaderMap(const headerMap: ICefStringMultimap);
property Status: Integer read GetStatus write SetStatus;
property StatusText: ustring read GetStatusText write SetStatusText;
property MimeType: ustring read GetMimeType write SetMimeType;
property Error: TCefErrorCode read GetError write SetError;
end;
ICefDownloadItem = interface(ICefBaseRefCounted)
['{B34BD320-A82E-4185-8E84-B98E5EEC803F}']
function IsValid: Boolean;
function IsInProgress: Boolean;
function IsComplete: Boolean;
function IsCanceled: Boolean;
function GetCurrentSpeed: Int64;
function GetPercentComplete: Integer;
function GetTotalBytes: Int64;
function GetReceivedBytes: Int64;
function GetStartTime: TDateTime;
function GetEndTime: TDateTime;
function GetFullPath: ustring;
function GetId: Cardinal;
function GetUrl: ustring;
function GetOriginalUrl: ustring;
function GetSuggestedFileName: ustring;
function GetContentDisposition: ustring;
function GetMimeType: ustring;
property CurrentSpeed: Int64 read GetCurrentSpeed;
property PercentComplete: Integer read GetPercentComplete;
property TotalBytes: Int64 read GetTotalBytes;
property ReceivedBytes: Int64 read GetReceivedBytes;
property StartTime: TDateTime read GetStartTime;
property EndTime: TDateTime read GetEndTime;
property FullPath: ustring read GetFullPath;
property Id: Cardinal read GetId;
property Url: ustring read GetUrl;
property OriginalUrl: ustring read GetOriginalUrl;
property SuggestedFileName: ustring read GetSuggestedFileName;
property ContentDisposition: ustring read GetContentDisposition;
property MimeType: ustring read GetMimeType;
end;
ICefBeforeDownloadCallback = interface(ICefBaseRefCounted)
['{5A81AF75-CBA2-444D-AD8E-522160F36433}']
procedure Cont(const downloadPath: ustring; showDialog: Boolean);
end;
ICefDownloadItemCallback = interface(ICefBaseRefCounted)
['{498F103F-BE64-4D5F-86B7-B37EC69E1735}']
procedure Cancel;
procedure Pause;
procedure Resume;
end;
ICefDownloadHandler = interface(ICefBaseRefCounted)
['{3137F90A-5DC5-43C1-858D-A269F28EF4F1}']
procedure OnBeforeDownload(const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const suggestedName: ustring; const callback: ICefBeforeDownloadCallback);
procedure OnDownloadUpdated(const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const callback: ICefDownloadItemCallback);
end;
ICefV8Exception = interface(ICefBaseRefCounted)
['{7E422CF0-05AC-4A60-A029-F45105DCE6A4}']
function GetMessage: ustring;
function GetSourceLine: ustring;
function GetScriptResourceName: ustring;
function GetLineNumber: Integer;
function GetStartPosition: Integer;
function GetEndPosition: Integer;
function GetStartColumn: Integer;
function GetEndColumn: Integer;
property Message: ustring read GetMessage;
property SourceLine: ustring read GetSourceLine;
property ScriptResourceName: ustring read GetScriptResourceName;
property LineNumber: Integer read GetLineNumber;
property StartPosition: Integer read GetStartPosition;
property EndPosition: Integer read GetEndPosition;
property StartColumn: Integer read GetStartColumn;
property EndColumn: Integer read GetEndColumn;
end;
ICefv8Context = interface(ICefBaseRefCounted)
['{2295A11A-8773-41F2-AD42-308C215062D9}']
function GetTaskRunner: ICefTaskRunner;
function IsValid: Boolean;
function GetBrowser: ICefBrowser;
function GetFrame: ICefFrame;
function GetGlobal: ICefv8Value;
function Enter: Boolean;
function Exit: Boolean;
function IsSame(const that: ICefv8Context): Boolean;
function Eval(const code: ustring; const script_url: ustring; start_line: integer; var retval: ICefv8Value; var exception: ICefV8Exception): Boolean;
property Browser: ICefBrowser read GetBrowser;
property Frame: ICefFrame read GetFrame;
property Global: ICefv8Value read GetGlobal;
end;
ICefv8Handler = interface(ICefBaseRefCounted)
['{F94CDC60-FDCB-422D-96D5-D2A775BD5D73}']
function Execute(const name: ustring; const obj: ICefv8Value;
const arguments: TCefv8ValueArray; var retval: ICefv8Value;
var exception: ustring): Boolean;
end;
ICefV8Interceptor = interface(ICefBaseRefCounted)
['{B3B8FD7C-A916-4B25-93A2-2892AC324F21}']
function GetByName(const name: ustring; const obj: ICefv8Value; out retval: ICefv8Value; const exception: ustring): boolean;
function GetByIndex(index: integer; const obj: ICefv8Value; out retval: ICefv8Value; const exception: ustring): boolean;
function SetByName(const name: ustring; const obj: ICefv8Value; const value: ICefv8Value; const exception: ustring): boolean;
function SetByIndex(index: integer; const obj: ICefv8Value; const value: ICefv8Value; const exception: ustring): boolean;
end;
ICefV8Accessor = interface(ICefBaseRefCounted)
['{DCA6D4A2-726A-4E24-AA64-5E8C731D868A}']
function Get(const name: ustring; const obj: ICefv8Value; out retval: ICefv8Value; var exception: ustring): Boolean;
function Put(const name: ustring; const obj: ICefv8Value; const value: ICefv8Value; var exception: ustring): Boolean;
end;
ICefTask = interface(ICefBaseRefCounted)
['{0D965470-4A86-47CE-BD39-A8770021AD7E}']
procedure Execute;
end;
ICefTaskRunner = interface(ICefBaseRefCounted)
['{6A500FA3-77B7-4418-8EA8-6337EED1337B}']
function IsSame(const that: ICefTaskRunner): Boolean;
function BelongsToCurrentThread: Boolean;
function BelongsToThread(threadId: TCefThreadId): Boolean;
function PostTask(const task: ICefTask): Boolean; stdcall;
function PostDelayedTask(const task: ICefTask; delayMs: Int64): Boolean;
end;
ICefThread = interface(ICefBaseRefCounted)
['{26B30EA5-F44A-4C40-97DF-67FD9E73A4FF}']
function GetTaskRunner : ICefTaskRunner;
function GetPlatformThreadID : TCefPlatformThreadId;
procedure Stop;
function IsRunning : boolean;
end;
ICefWaitableEvent = interface(ICefBaseRefCounted)
['{965C90C9-3DAE-457F-AA64-E04FF508094A}']
procedure Reset;
procedure Signal;
function IsSignaled : boolean;
procedure Wait;
function TimedWait(max_ms: int64): boolean;
end;
ICefv8Value = interface(ICefBaseRefCounted)
['{52319B8D-75A8-422C-BD4B-16FA08CC7F42}']
function IsValid: Boolean;
function IsUndefined: Boolean;
function IsNull: Boolean;
function IsBool: Boolean;
function IsInt: Boolean;
function IsUInt: Boolean;
function IsDouble: Boolean;
function IsDate: Boolean;
function IsString: Boolean;
function IsObject: Boolean;
function IsArray: Boolean;
function IsFunction: Boolean;
function IsSame(const that: ICefv8Value): Boolean;
function GetBoolValue: Boolean;
function GetIntValue: Integer;
function GetUIntValue: Cardinal;
function GetDoubleValue: Double;
function GetDateValue: TDateTime;
function GetStringValue: ustring;
function IsUserCreated: Boolean;
function HasException: Boolean;
function GetException: ICefV8Exception;
function ClearException: Boolean;
function WillRethrowExceptions: Boolean;
function SetRethrowExceptions(rethrow: Boolean): Boolean;
function HasValueByKey(const key: ustring): Boolean;
function HasValueByIndex(index: Integer): Boolean;
function DeleteValueByKey(const key: ustring): Boolean;
function DeleteValueByIndex(index: Integer): Boolean;
function GetValueByKey(const key: ustring): ICefv8Value;
function GetValueByIndex(index: Integer): ICefv8Value;
function SetValueByKey(const key: ustring; const value: ICefv8Value;
attribute: TCefV8PropertyAttributes): Boolean;
function SetValueByIndex(index: Integer; const value: ICefv8Value): Boolean;
function SetValueByAccessor(const key: ustring; settings: TCefV8AccessControls;
attribute: TCefV8PropertyAttributes): Boolean;
function GetKeys(const keys: TStrings): Integer;
function SetUserData(const data: ICefv8Value): Boolean;
function GetUserData: ICefv8Value;
function GetExternallyAllocatedMemory: Integer;
function AdjustExternallyAllocatedMemory(changeInBytes: Integer): Integer;
function GetArrayLength: Integer;
function GetFunctionName: ustring;
function GetFunctionHandler: ICefv8Handler;
function ExecuteFunction(const obj: ICefv8Value; const arguments: TCefv8ValueArray): ICefv8Value;
function ExecuteFunctionWithContext(const context: ICefv8Context; const obj: ICefv8Value; const arguments: TCefv8ValueArray): ICefv8Value;
end;
ICefV8StackFrame = interface(ICefBaseRefCounted)
['{BA1FFBF4-E9F2-4842-A827-DC220F324286}']
function IsValid: Boolean;
function GetScriptName: ustring;
function GetScriptNameOrSourceUrl: ustring;
function GetFunctionName: ustring;
function GetLineNumber: Integer;
function GetColumn: Integer;
function IsEval: Boolean;
function IsConstructor: Boolean;
property ScriptName: ustring read GetScriptName;
property ScriptNameOrSourceUrl: ustring read GetScriptNameOrSourceUrl;
property FunctionName: ustring read GetFunctionName;
property LineNumber: Integer read GetLineNumber;
property Column: Integer read GetColumn;
end;
ICefV8StackTrace = interface(ICefBaseRefCounted)
['{32111C84-B7F7-4E3A-92B9-7CA1D0ADB613}']
function IsValid: Boolean;
function GetFrameCount: Integer;
function GetFrame(index: Integer): ICefV8StackFrame;
property FrameCount: Integer read GetFrameCount;
property Frame[index: Integer]: ICefV8StackFrame read GetFrame;
end;
ICefXmlReader = interface(ICefBaseRefCounted)
['{0DE686C3-A8D7-45D2-82FD-92F7F4E62A90}']
function MoveToNextNode: Boolean;
function Close: Boolean;
function HasError: Boolean;
function GetError: ustring;
function GetType: TCefXmlNodeType;
function GetDepth: Integer;
function GetLocalName: ustring;
function GetPrefix: ustring;
function GetQualifiedName: ustring;
function GetNamespaceUri: ustring;
function GetBaseUri: ustring;
function GetXmlLang: ustring;
function IsEmptyElement: Boolean;
function HasValue: Boolean;
function GetValue: ustring;
function HasAttributes: Boolean;
function GetAttributeCount: NativeUInt;
function GetAttributeByIndex(index: Integer): ustring;
function GetAttributeByQName(const qualifiedName: ustring): ustring;
function GetAttributeByLName(const localName, namespaceURI: ustring): ustring;
function GetInnerXml: ustring;
function GetOuterXml: ustring;
function GetLineNumber: Integer;
function MoveToAttributeByIndex(index: Integer): Boolean;
function MoveToAttributeByQName(const qualifiedName: ustring): Boolean;
function MoveToAttributeByLName(const localName, namespaceURI: ustring): Boolean;
function MoveToFirstAttribute: Boolean;
function MoveToNextAttribute: Boolean;
function MoveToCarryingElement: Boolean;
end;
ICefZipReader = interface(ICefBaseRefCounted)
['{3B6C591F-9877-42B3-8892-AA7B27DA34A8}']
function MoveToFirstFile: Boolean;
function MoveToNextFile: Boolean;
function MoveToFile(const fileName: ustring; caseSensitive: Boolean): Boolean;
function Close: Boolean;
function GetFileName: ustring;
function GetFileSize: Int64;
function GetFileLastModified: TCefTime;
function OpenFile(const password: ustring): Boolean;
function CloseFile: Boolean;
function ReadFile(buffer: Pointer; bufferSize: NativeUInt): Integer;
function Tell: Int64;
function Eof: Boolean;
end;
ICefDomNode = interface(ICefBaseRefCounted)
['{96C03C9E-9C98-491A-8DAD-1947332232D6}']
function GetType: TCefDomNodeType;
function IsText: Boolean;
function IsElement: Boolean;
function IsEditable: Boolean;
function IsFormControlElement: Boolean;
function GetFormControlElementType: ustring;
function IsSame(const that: ICefDomNode): Boolean;
function GetName: ustring;
function GetValue: ustring;
function SetValue(const value: ustring): Boolean;
function GetAsMarkup: ustring;
function GetDocument: ICefDomDocument;
function GetParent: ICefDomNode;
function GetPreviousSibling: ICefDomNode;
function GetNextSibling: ICefDomNode;
function HasChildren: Boolean;
function GetFirstChild: ICefDomNode;
function GetLastChild: ICefDomNode;
function GetElementTagName: ustring;
function HasElementAttributes: Boolean;
function HasElementAttribute(const attrName: ustring): Boolean;
function GetElementAttribute(const attrName: ustring): ustring;
procedure GetElementAttributes(const attrMap: ICefStringMap);
function SetElementAttribute(const attrName, value: ustring): Boolean;
function GetElementInnerText: ustring;
function GetElementBounds: TCefRect;
property NodeType: TCefDomNodeType read GetType;
property Name: ustring read GetName;
property AsMarkup: ustring read GetAsMarkup;
property Document: ICefDomDocument read GetDocument;
property Parent: ICefDomNode read GetParent;
property PreviousSibling: ICefDomNode read GetPreviousSibling;
property NextSibling: ICefDomNode read GetNextSibling;
property FirstChild: ICefDomNode read GetFirstChild;
property LastChild: ICefDomNode read GetLastChild;
property ElementTagName: ustring read GetElementTagName;
property ElementInnerText: ustring read GetElementInnerText;
property ElementBounds: TCefRect read GetElementBounds;
end;
ICefDomDocument = interface(ICefBaseRefCounted)
['{08E74052-45AF-4F69-A578-98A5C3959426}']
function GetType: TCefDomDocumentType;
function GetDocument: ICefDomNode;
function GetBody: ICefDomNode;
function GetHead: ICefDomNode;
function GetTitle: ustring;
function GetElementById(const id: ustring): ICefDomNode;
function GetFocusedNode: ICefDomNode;
function HasSelection: Boolean;
function GetSelectionStartOffset: Integer;
function GetSelectionEndOffset: Integer;
function GetSelectionAsMarkup: ustring;
function GetSelectionAsText: ustring;
function GetBaseUrl: ustring;
function GetCompleteUrl(const partialURL: ustring): ustring;
property DocType: TCefDomDocumentType read GetType;
property Document: ICefDomNode read GetDocument;
property Body: ICefDomNode read GetBody;
property Head: ICefDomNode read GetHead;
property Title: ustring read GetTitle;
property FocusedNode: ICefDomNode read GetFocusedNode;
property SelectionStartOffset: Integer read GetSelectionStartOffset;
property SelectionEndOffset: Integer read GetSelectionEndOffset;
property SelectionAsMarkup: ustring read GetSelectionAsMarkup;
property SelectionAsText: ustring read GetSelectionAsText;
property BaseUrl: ustring read GetBaseUrl;
end;
ICefDomVisitor = interface(ICefBaseRefCounted)
['{30398428-3196-4531-B968-2DDBED36F6B0}']
procedure visit(const document: ICefDomDocument);
end;
ICefCookieVisitor = interface(ICefBaseRefCounted)
['{8378CF1B-84AB-4FDB-9B86-34DDABCCC402}']
function visit(const name, value, domain, path: ustring; secure, httponly,
hasExpires: Boolean; const creation, lastAccess, expires: TDateTime;
count, total: Integer; out deleteCookie: Boolean): Boolean;
end;
ICefCommandLine = interface(ICefBaseRefCounted)
['{6B43D21B-0F2C-4B94-B4E6-4AF0D7669D8E}']
function IsValid: Boolean;
function IsReadOnly: Boolean;
function Copy: ICefCommandLine;
procedure InitFromArgv(argc: Integer; const argv: PPAnsiChar);
procedure InitFromString(const commandLine: ustring);
procedure Reset;
function GetCommandLineString: ustring;
procedure GetArgv(args: TStrings);
function GetProgram: ustring;
procedure SetProgram(const prog: ustring);
function HasSwitches: Boolean;
function HasSwitch(const name: ustring): Boolean;
function GetSwitchValue(const name: ustring): ustring;
procedure GetSwitches(switches: TStrings);
procedure AppendSwitch(const name: ustring);
procedure AppendSwitchWithValue(const name, value: ustring);
function HasArguments: Boolean;
procedure GetArguments(arguments: TStrings);
procedure AppendArgument(const argument: ustring);
procedure PrependWrapper(const wrapper: ustring);
property CommandLineString: ustring read GetCommandLineString;
end;
ICefResourceBundleHandler = interface(ICefBaseRefCounted)
['{09C264FD-7E03-41E3-87B3-4234E82B5EA2}']
function GetLocalizedString(stringId: Integer; var stringVal: ustring): Boolean;
function GetDataResource(resourceId: Integer; var data: Pointer; var dataSize: NativeUInt): Boolean;
function GetDataResourceForScale(resourceId: Integer; scaleFactor: TCefScaleFactor; var data: Pointer; var dataSize: NativeUInt): Boolean;
end;
ICefBrowserProcessHandler = interface(ICefBaseRefCounted)
['{27291B7A-C0AE-4EE0-9115-15C810E22F6C}']
procedure OnContextInitialized;
procedure OnBeforeChildProcessLaunch(const commandLine: ICefCommandLine);
procedure OnRenderProcessThreadCreated(const extraInfo: ICefListValue);
function GetPrintHandler : ICefPrintHandler;
procedure OnScheduleMessagePumpWork(const delayMs: Int64);
end;
ICefRenderProcessHandler = interface(ICefBaseRefCounted)
['{FADEE3BC-BF66-430A-BA5D-1EE3782ECC58}']
procedure OnRenderThreadCreated(const extraInfo: ICefListValue);
procedure OnWebKitInitialized;
procedure OnBrowserCreated(const browser: ICefBrowser);
procedure OnBrowserDestroyed(const browser: ICefBrowser);
function GetLoadHandler : ICefLoadHandler;
function OnBeforeNavigation(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; navigationType: TCefNavigationType; isRedirect: Boolean): Boolean;
procedure OnContextCreated(const browser: ICefBrowser; const frame: ICefFrame; const context: ICefv8Context);
procedure OnContextReleased(const browser: ICefBrowser; const frame: ICefFrame; const context: ICefv8Context);
procedure OnUncaughtException(const browser: ICefBrowser; const frame: ICefFrame; const context: ICefv8Context; const exception: ICefV8Exception; const stackTrace: ICefV8StackTrace);
procedure OnFocusedNodeChanged(const browser: ICefBrowser; const frame: ICefFrame; const node: ICefDomNode);
function OnProcessMessageReceived(const browser: ICefBrowser; sourceProcess: TCefProcessId; const aMessage: ICefProcessMessage): Boolean;
end;
ICefApp = interface(ICefBaseRefCounted)
['{970CA670-9070-4642-B188-7D8A22DAEED4}']
procedure OnBeforeCommandLineProcessing(const processType: ustring; const commandLine: ICefCommandLine);
procedure OnRegisterCustomSchemes(const registrar: TCefSchemeRegistrarRef);
procedure GetResourceBundleHandler(var aHandler : ICefResourceBundleHandler);
procedure GetBrowserProcessHandler(var aHandler : ICefBrowserProcessHandler);
procedure GetRenderProcessHandler(var aHandler : ICefRenderProcessHandler);
end;
TCefCookieVisitorProc = {$IFDEF DELPHI12_UP}reference to{$ENDIF} function(
const name, value, domain, path: ustring; secure, httponly,
hasExpires: Boolean; const creation, lastAccess, expires: TDateTime;
count, total: Integer; out deleteCookie: Boolean): Boolean;
ICefCompletionCallback = interface(ICefBaseRefCounted)
['{A8ECCFBB-FEE0-446F-AB32-AD69A7478D57}']
procedure OnComplete;
end;
ICefSetCookieCallback = interface(ICefBaseRefCounted)
['{16E14B6F-CB0A-4F9D-A008-239E0BC7B892}']
procedure OnComplete(success: Boolean);
end;
ICefDeleteCookiesCallback = interface(ICefBaseRefCounted)
['{758B79A1-B9E8-4F0D-94A0-DCE5AFADE33D}']
procedure OnComplete(numDeleted: Integer);
end;
ICefCookieManager = Interface(ICefBaseRefCounted)
['{CC1749E6-9AD3-4283-8430-AF6CBF3E8785}']
procedure SetSupportedSchemes(schemes: TStrings; const callback: ICefCompletionCallback);
procedure SetSupportedSchemesProc(schemes: TStrings; const callback: TCefCompletionCallbackProc);
function VisitAllCookies(const visitor: ICefCookieVisitor): Boolean;
function VisitAllCookiesProc(const visitor: TCefCookieVisitorProc): Boolean;
function VisitUrlCookies(const url: ustring;
includeHttpOnly: Boolean; const visitor: ICefCookieVisitor): Boolean;
function VisitUrlCookiesProc(const url: ustring;
includeHttpOnly: Boolean; const visitor: TCefCookieVisitorProc): Boolean;
function SetCookie(const url: ustring; const name, value, domain, path: ustring; secure, httponly,
hasExpires: Boolean; const creation, lastAccess, expires: TDateTime;
const callback: ICefSetCookieCallback): Boolean;
function SetCookieProc(const url: ustring; const name, value, domain, path: ustring; secure, httponly,
hasExpires: Boolean; const creation, lastAccess, expires: TDateTime;
const callback: TCefSetCookieCallbackProc): Boolean;
function DeleteCookies(const url, cookieName: ustring; const callback: ICefDeleteCookiesCallback): Boolean;
function DeleteCookiesProc(const url, cookieName: ustring; const callback: TCefDeleteCookiesCallbackProc): Boolean;
function SetStoragePath(const path: ustring; persistSessionCookies: Boolean; const callback: ICefCompletionCallback): Boolean;
function SetStoragePathProc(const path: ustring; persistSessionCookies: Boolean; const callback: TCefCompletionCallbackProc): Boolean;
function FlushStore(const handler: ICefCompletionCallback): Boolean;
function FlushStoreProc(const proc: TCefCompletionCallbackProc): Boolean;
end;
ICefWebPluginInfo = interface(ICefBaseRefCounted)
['{AA879E58-F649-44B1-AF9C-655FF5B79A02}']
function GetName: ustring;
function GetPath: ustring;
function GetVersion: ustring;
function GetDescription: ustring;
property Name: ustring read GetName;
property Path: ustring read GetPath;
property Version: ustring read GetVersion;
property Description: ustring read GetDescription;
end;
ICefCallback = interface(ICefBaseRefCounted)
['{1B8C449F-E2D6-4B78-9BBA-6F47E8BCDF37}']
procedure Cont;
procedure Cancel;
end;
ICefResourceHandler = interface(ICefBaseRefCounted)
['{BD3EA208-AAAD-488C-BFF2-76993022F2B5}']
function ProcessRequest(const request: ICefRequest; const callback: ICefCallback): Boolean;
procedure GetResponseHeaders(const response: ICefResponse;
out responseLength: Int64; out redirectUrl: ustring);
function ReadResponse(const dataOut: Pointer; bytesToRead: Integer;
var bytesRead: Integer; const callback: ICefCallback): Boolean;
function CanGetCookie(const cookie: PCefCookie): Boolean;
function CanSetCookie(const cookie: PCefCookie): Boolean;
procedure Cancel;
end;
ICefSchemeHandlerFactory = interface(ICefBaseRefCounted)
['{4D9B7960-B73B-4EBD-9ABE-6C1C43C245EB}']
function New(const browser: ICefBrowser; const frame: ICefFrame;
const schemeName: ustring; const request: ICefRequest): ICefResourceHandler;
end;
ICefAuthCallback = interface(ICefBaseRefCounted)
['{500C2023-BF4D-4FF7-9C04-165E5C389131}']
procedure Cont(const username, password: ustring);
procedure Cancel;
end;
ICefJsDialogCallback = interface(ICefBaseRefCounted)
['{187B2156-9947-4108-87AB-32E559E1B026}']
procedure Cont(success: Boolean; const userInput: ustring);
end;
ICefContextMenuParams = interface(ICefBaseRefCounted)
['{E31BFA9E-D4E2-49B7-A05D-20018C8794EB}']
function GetXCoord: Integer;
function GetYCoord: Integer;
function GetTypeFlags: TCefContextMenuTypeFlags;
function GetLinkUrl: ustring;
function GetUnfilteredLinkUrl: ustring;
function GetSourceUrl: ustring;
function HasImageContents: Boolean;
function GetTitleText: ustring;
function GetPageUrl: ustring;
function GetFrameUrl: ustring;
function GetFrameCharset: ustring;
function GetMediaType: TCefContextMenuMediaType;
function GetMediaStateFlags: TCefContextMenuMediaStateFlags;
function GetSelectionText: ustring;
function GetMisspelledWord: ustring;
function GetDictionarySuggestions(const suggestions: TStringList): Boolean;
function IsEditable: Boolean;
function IsSpellCheckEnabled: Boolean;
function GetEditStateFlags: TCefContextMenuEditStateFlags;
function IsCustomMenu: Boolean;
function IsPepperMenu: Boolean;
property XCoord: Integer read GetXCoord;
property YCoord: Integer read GetYCoord;
property TypeFlags: TCefContextMenuTypeFlags read GetTypeFlags;
property LinkUrl: ustring read GetLinkUrl;
property UnfilteredLinkUrl: ustring read GetUnfilteredLinkUrl;
property SourceUrl: ustring read GetSourceUrl;
property TitleText: ustring read GetTitleText;
property PageUrl: ustring read GetPageUrl;
property FrameUrl: ustring read GetFrameUrl;
property FrameCharset: ustring read GetFrameCharset;
property MediaType: TCefContextMenuMediaType read GetMediaType;
property MediaStateFlags: TCefContextMenuMediaStateFlags read GetMediaStateFlags;
property SelectionText: ustring read GetSelectionText;
property EditStateFlags: TCefContextMenuEditStateFlags read GetEditStateFlags;
end;
ICefMenuModel = interface(ICefBaseRefCounted)
['{40AF19D3-8B4E-44B8-8F89-DEB5907FC495}']
function IsSubMenu: Boolean;
function Clear: Boolean;
function GetCount: Integer;
function AddSeparator: Boolean;
function AddItem(commandId: Integer; const text: ustring): Boolean;
function AddCheckItem(commandId: Integer; const text: ustring): Boolean;
function AddRadioItem(commandId: Integer; const text: ustring; groupId: Integer): Boolean;
function AddSubMenu(commandId: Integer; const text: ustring): ICefMenuModel;
function InsertSeparatorAt(index: Integer): Boolean;
function InsertItemAt(index, commandId: Integer; const text: ustring): Boolean;
function InsertCheckItemAt(index, commandId: Integer; const text: ustring): Boolean;
function InsertRadioItemAt(index, commandId: Integer; const text: ustring; groupId: Integer): Boolean;
function InsertSubMenuAt(index, commandId: Integer; const text: ustring): ICefMenuModel;
function Remove(commandId: Integer): Boolean;
function RemoveAt(index: Integer): Boolean;
function GetIndexOf(commandId: Integer): Integer;
function GetCommandIdAt(index: Integer): Integer;
function SetCommandIdAt(index, commandId: Integer): Boolean;
function GetLabel(commandId: Integer): ustring;
function GetLabelAt(index: Integer): ustring;
function SetLabel(commandId: Integer; const text: ustring): Boolean;
function SetLabelAt(index: Integer; const text: ustring): Boolean;
function GetType(commandId: Integer): TCefMenuItemType;
function GetTypeAt(index: Integer): TCefMenuItemType;
function GetGroupId(commandId: Integer): Integer;
function GetGroupIdAt(index: Integer): Integer;
function SetGroupId(commandId, groupId: Integer): Boolean;
function SetGroupIdAt(index, groupId: Integer): Boolean;
function GetSubMenu(commandId: Integer): ICefMenuModel;
function GetSubMenuAt(index: Integer): ICefMenuModel;
function IsVisible(commandId: Integer): Boolean;
function isVisibleAt(index: Integer): Boolean;
function SetVisible(commandId: Integer; visible: Boolean): Boolean;
function SetVisibleAt(index: Integer; visible: Boolean): Boolean;
function IsEnabled(commandId: Integer): Boolean;
function IsEnabledAt(index: Integer): Boolean;
function SetEnabled(commandId: Integer; enabled: Boolean): Boolean;
function SetEnabledAt(index: Integer; enabled: Boolean): Boolean;
function IsChecked(commandId: Integer): Boolean;
function IsCheckedAt(index: Integer): Boolean;
function setChecked(commandId: Integer; checked: Boolean): Boolean;
function setCheckedAt(index: Integer; checked: Boolean): Boolean;
function HasAccelerator(commandId: Integer): Boolean;
function HasAcceleratorAt(index: Integer): Boolean;
function SetAccelerator(commandId, keyCode: Integer; shiftPressed, ctrlPressed, altPressed: Boolean): Boolean;
function SetAcceleratorAt(index, keyCode: Integer; shiftPressed, ctrlPressed, altPressed: Boolean): Boolean;
function RemoveAccelerator(commandId: Integer): Boolean;
function RemoveAcceleratorAt(index: Integer): Boolean;
function GetAccelerator(commandId: Integer; out keyCode: Integer; out shiftPressed, ctrlPressed, altPressed: Boolean): Boolean;
function GetAcceleratorAt(index: Integer; out keyCode: Integer; out shiftPressed, ctrlPressed, altPressed: Boolean): Boolean;
function SetColor(commandId: Integer; colorType: TCefMenuColorType; color: TCefColor): Boolean;
function SetColorAt(index: Integer; colorType: TCefMenuColorType; color: TCefColor): Boolean;
function GetColor(commandId: Integer; colorType: TCefMenuColorType; out color: TCefColor): Boolean;
function GetColorAt(index: Integer; colorType: TCefMenuColorType; out color: TCefColor): Boolean;
function SetFontList(commandId: Integer; const fontList: ustring): Boolean;
function SetFontListAt(index: Integer; const fontList: ustring): Boolean;
end;
ICefValue = interface(ICefBaseRefCounted)
['{66F9F439-B12B-4EC3-A945-91AE4EF4D4BA}']
function IsValid: Boolean;
function IsOwned: Boolean;
function IsReadOnly: Boolean;
function IsSame(const that: ICefValue): Boolean;
function IsEqual(const that: ICefValue): Boolean;
function Copy: ICefValue;
function GetType: TCefValueType;
function GetBool: Boolean;
function GetInt: Integer;
function GetDouble: Double;
function GetString: ustring;
function GetBinary: ICefBinaryValue;
function GetDictionary: ICefDictionaryValue;
function GetList: ICefListValue;
function SetNull: Boolean;
function SetBool(value: Integer): Boolean;
function SetInt(value: Integer): Boolean;
function SetDouble(value: Double): Boolean;
function SetString(const value: ustring): Boolean;
function SetBinary(const value: ICefBinaryValue): Boolean;
function SetDictionary(const value: ICefDictionaryValue): Boolean;
function SetList(const value: ICefListValue): Boolean;
end;
ICefBinaryValue = interface(ICefBaseRefCounted)
['{974AA40A-9C5C-4726-81F0-9F0D46D7C5B3}']
function IsValid: Boolean;
function IsOwned: Boolean;
function IsSame(const that: ICefBinaryValue): Boolean;
function IsEqual(const that: ICefBinaryValue): Boolean;
function Copy: ICefBinaryValue;
function GetSize: NativeUInt;
function GetData(buffer: Pointer; bufferSize, dataOffset: NativeUInt): NativeUInt;
end;
ICefDictionaryValue = interface(ICefBaseRefCounted)
['{B9638559-54DC-498C-8185-233EEF12BC69}']
function IsValid: Boolean;
function isOwned: Boolean;
function IsReadOnly: Boolean;
function IsSame(const that: ICefDictionaryValue): Boolean;
function IsEqual(const that: ICefDictionaryValue): Boolean;
function Copy(excludeEmptyChildren: Boolean): ICefDictionaryValue;
function GetSize: NativeUInt;
function Clear: Boolean;
function HasKey(const key: ustring): Boolean;
function GetKeys(const keys: TStrings): Boolean;
function Remove(const key: ustring): Boolean;
function GetType(const key: ustring): TCefValueType;
function GetValue(const key: ustring): ICefValue;
function GetBool(const key: ustring): Boolean;
function GetInt(const key: ustring): Integer;
function GetDouble(const key: ustring): Double;
function GetString(const key: ustring): ustring;
function GetBinary(const key: ustring): ICefBinaryValue;
function GetDictionary(const key: ustring): ICefDictionaryValue;
function GetList(const key: ustring): ICefListValue;
function SetValue(const key: ustring; const value: ICefValue): Boolean;
function SetNull(const key: ustring): Boolean;
function SetBool(const key: ustring; value: Boolean): Boolean;
function SetInt(const key: ustring; value: Integer): Boolean;
function SetDouble(const key: ustring; value: Double): Boolean;
function SetString(const key, value: ustring): Boolean;
function SetBinary(const key: ustring; const value: ICefBinaryValue): Boolean;
function SetDictionary(const key: ustring; const value: ICefDictionaryValue): Boolean;
function SetList(const key: ustring; const value: ICefListValue): Boolean;
end;
ICefListValue = interface(ICefBaseRefCounted)
['{09174B9D-0CC6-4360-BBB0-3CC0117F70F6}']
function IsValid: Boolean;
function IsOwned: Boolean;
function IsReadOnly: Boolean;
function IsSame(const that: ICefListValue): Boolean;
function IsEqual(const that: ICefListValue): Boolean;
function Copy: ICefListValue;
function SetSize(size: NativeUInt): Boolean;
function GetSize: NativeUInt;
function Clear: Boolean;
function Remove(index: NativeUInt): Boolean;
function GetType(index: NativeUInt): TCefValueType;
function GetValue(index: NativeUInt): ICefValue;
function GetBool(index: NativeUInt): Boolean;
function GetInt(index: NativeUInt): Integer;
function GetDouble(index: NativeUInt): Double;
function GetString(index: NativeUInt): ustring;
function GetBinary(index: NativeUInt): ICefBinaryValue;
function GetDictionary(index: NativeUInt): ICefDictionaryValue;
function GetList(index: NativeUInt): ICefListValue;
function SetValue(index: NativeUInt; const value: ICefValue): Boolean;
function SetNull(index: NativeUInt): Boolean;
function SetBool(index: NativeUInt; value: Boolean): Boolean;
function SetInt(index: NativeUInt; value: Integer): Boolean;
function SetDouble(index: NativeUInt; value: Double): Boolean;
function SetString(index: NativeUInt; const value: ustring): Boolean;
function SetBinary(index: NativeUInt; const value: ICefBinaryValue): Boolean;
function SetDictionary(index: NativeUInt; const value: ICefDictionaryValue): Boolean;
function SetList(index: NativeUInt; const value: ICefListValue): Boolean;
end;
ICefLifeSpanHandler = interface(ICefBaseRefCounted)
['{0A3EB782-A319-4C35-9B46-09B2834D7169}']
function OnBeforePopup(const browser: ICefBrowser; const frame: ICefFrame; const targetUrl, targetFrameName: ustring; targetDisposition: TCefWindowOpenDisposition; userGesture: Boolean; var popupFeatures: TCefPopupFeatures; var windowInfo: TCefWindowInfo; var client: ICefClient; var settings: TCefBrowserSettings; var noJavascriptAccess: Boolean): Boolean;
procedure OnAfterCreated(const browser: ICefBrowser);
procedure OnBeforeClose(const browser: ICefBrowser);
function DoClose(const browser: ICefBrowser): Boolean;
end;
ICefGetExtensionResourceCallback = interface(ICefBaseRefCounted)
['{579C8602-8252-40D0-9E0A-501F32C36C42}']
procedure cont(const stream: ICefStreamReader);
procedure cancel;
end;
ICefExtensionHandler = interface(ICefBaseRefCounted)
['{3234008F-D809-459D-963D-23BA50219648}']
procedure OnExtensionLoadFailed(result: TCefErrorcode);
procedure OnExtensionLoaded(const extension: ICefExtension);
procedure OnExtensionUnloaded(const extension: ICefExtension);
function OnBeforeBackgroundBrowser(const extension: ICefExtension; const url: ustring; var client: ICefClient; var settings: TCefBrowserSettings) : boolean;
function OnBeforeBrowser(const extension: ICefExtension; const browser, active_browser: ICefBrowser; index: Integer; const url: ustring; active: boolean; var windowInfo: TCefWindowInfo; var client: ICefClient; var settings: TCefBrowserSettings) : boolean;
function GetActiveBrowser(const extension: ICefExtension; const browser: ICefBrowser; include_incognito: boolean): ICefBrowser;
function CanAccessBrowser(const extension: ICefExtension; const browser: ICefBrowser; include_incognito: boolean; const target_browser: ICefBrowser): boolean;
function GetExtensionResource(const extension: ICefExtension; const browser: ICefBrowser; const file_: ustring; const callback: ICefGetExtensionResourceCallback): boolean;
end;
ICefExtension = interface(ICefBaseRefCounted)
['{D30D1C64-A26F-49C0-AEB7-C55EC68951CA}']
function GetIdentifier : ustring;
function GetPath : ustring;
function GetManifest : ICefDictionaryValue;
function IsSame(const that : ICefExtension) : boolean;
function GetHandler : ICefExtensionHandler;
function GetLoaderContext : ICefRequestContext;
function IsLoaded : boolean;
procedure unload;
property Identifier : ustring read GetIdentifier;
property Path : ustring read GetPath;
property Manifest : ICefDictionaryValue read GetManifest;
property Handler : ICefExtensionHandler read GetHandler;
property LoaderContext : ICefRequestContext read GetLoaderContext;
end;
ICefLoadHandler = interface(ICefBaseRefCounted)
['{2C63FB82-345D-4A5B-9858-5AE7A85C9F49}']
procedure OnLoadingStateChange(const browser: ICefBrowser; isLoading, canGoBack, canGoForward: Boolean);
procedure OnLoadStart(const browser: ICefBrowser; const frame: ICefFrame; transitionType: TCefTransitionType);
procedure OnLoadEnd(const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer);
procedure OnLoadError(const browser: ICefBrowser; const frame: ICefFrame; errorCode: Integer; const errorText, failedUrl: ustring);
end;
ICefRequestCallback = interface(ICefBaseRefCounted)
['{A35B8FD5-226B-41A8-A763-1940787D321C}']
procedure Cont(allow: Boolean);
procedure Cancel;
end;
ICefResponseFilter = interface(ICefBaseRefCounted)
['{5013BC3C-F1AE-407A-A571-A4C6B1D6831E}']
function InitFilter: Boolean;
function Filter(dataIn: Pointer; dataInSize : NativeUInt; dataInRead: PNativeUInt; dataOut: Pointer; dataOutSize : NativeUInt; dataOutWritten: PNativeUInt): TCefResponseFilterStatus;
end;
ICefRequestHandler = interface(ICefBaseRefCounted)
['{050877A9-D1F8-4EB3-B58E-50DC3E3D39FD}']
function OnBeforeBrowse(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; isRedirect: Boolean): Boolean;
function OnOpenUrlFromTab(const browser: ICefBrowser; const frame: ICefFrame; const targetUrl: ustring; targetDisposition: TCefWindowOpenDisposition; userGesture: Boolean): Boolean;
function OnBeforeResourceLoad(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const callback: ICefRequestCallback): TCefReturnValue;
function GetResourceHandler(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest): ICefResourceHandler;
procedure OnResourceRedirect(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse; var newUrl: ustring);
function OnResourceResponse(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse): Boolean;
function GetResourceResponseFilter(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse): ICefResponseFilter;
procedure OnResourceLoadComplete(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse; status: TCefUrlRequestStatus; receivedContentLength: Int64);
function GetAuthCredentials(const browser: ICefBrowser; const frame: ICefFrame; isProxy: Boolean; const host: ustring; port: Integer; const realm, scheme: ustring; const callback: ICefAuthCallback): Boolean;
function OnQuotaRequest(const browser: ICefBrowser; const originUrl: ustring; newSize: Int64; const callback: ICefRequestCallback): Boolean;
procedure OnProtocolExecution(const browser: ICefBrowser; const url: ustring; out allowOsExecution: Boolean);
function OnCertificateError(const browser: ICefBrowser; certError: TCefErrorcode; const requestUrl: ustring; const sslInfo: ICefSslInfo; const callback: ICefRequestCallback): Boolean;
function OnSelectClientCertificate(const browser: ICefBrowser; isProxy: boolean; const host: ustring; port: integer; certificatesCount: NativeUInt; const certificates: TCefX509CertificateArray; const callback: ICefSelectClientCertificateCallback): boolean;
procedure OnPluginCrashed(const browser: ICefBrowser; const pluginPath: ustring);
procedure OnRenderViewReady(const browser: ICefBrowser);
procedure OnRenderProcessTerminated(const browser: ICefBrowser; status: TCefTerminationStatus);
end;
ICefDisplayHandler = interface(ICefBaseRefCounted)
['{1EC7C76D-6969-41D1-B26D-079BCFF054C4}']
procedure OnAddressChange(const browser: ICefBrowser; const frame: ICefFrame; const url: ustring);
procedure OnTitleChange(const browser: ICefBrowser; const title: ustring);
procedure OnFaviconUrlChange(const browser: ICefBrowser; icon_urls: TStrings);
procedure OnFullScreenModeChange(const browser: ICefBrowser; fullscreen: Boolean);
function OnTooltip(const browser: ICefBrowser; var text: ustring): Boolean;
procedure OnStatusMessage(const browser: ICefBrowser; const value: ustring);
function OnConsoleMessage(const browser: ICefBrowser; const message, source: ustring; line: Integer): Boolean;
function OnAutoResize(const browser: ICefBrowser; const new_size: PCefSize): Boolean;
end;
ICefFocusHandler = interface(ICefBaseRefCounted)
['{BB7FA3FA-7B1A-4ADC-8E50-12A24018DD90}']
procedure OnTakeFocus(const browser: ICefBrowser; next: Boolean);
function OnSetFocus(const browser: ICefBrowser; source: TCefFocusSource): Boolean;
procedure OnGotFocus(const browser: ICefBrowser);
end;
ICefKeyboardHandler = interface(ICefBaseRefCounted)
['{0512F4EC-ED88-44C9-90D3-5C6D03D3B146}']
function OnPreKeyEvent(const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle; out isKeyboardShortcut: Boolean): Boolean;
function OnKeyEvent(const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle): Boolean;
end;
ICefJsDialogHandler = interface(ICefBaseRefCounted)
['{64E18F86-DAC5-4ED1-8589-44DE45B9DB56}']
function OnJsdialog(const browser: ICefBrowser; const originUrl: ustring; dialogType: TCefJsDialogType; const messageText, defaultPromptText: ustring; const callback: ICefJsDialogCallback; out suppressMessage: Boolean): Boolean;
function OnBeforeUnloadDialog(const browser: ICefBrowser; const messageText: ustring; isReload: Boolean; const callback: ICefJsDialogCallback): Boolean;
procedure OnResetDialogState(const browser: ICefBrowser);
procedure OnDialogClosed(const browser: ICefBrowser);
end;
ICefRunContextMenuCallback = interface(ICefBaseRefCounted)
['{44C3C6E3-B64D-4F6E-A318-4A0F3A72EB00}']
procedure Cont(commandId: Integer; eventFlags: TCefEventFlags);
procedure Cancel;
end;
ICefContextMenuHandler = interface(ICefBaseRefCounted)
['{C2951895-4087-49D5-BA18-4D9BA4F5EDD7}']
procedure OnBeforeContextMenu(const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel);
function RunContextMenu(const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel; const callback: ICefRunContextMenuCallback): Boolean;
function OnContextMenuCommand(const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; commandId: Integer; eventFlags: TCefEventFlags): Boolean;
procedure OnContextMenuDismissed(const browser: ICefBrowser; const frame: ICefFrame);
end;
ICefAccessibilityHandler = interface(ICefBaseRefCounted)
['{1878C3C7-7692-44AB-BFE0-6C387106816B}']
procedure OnAccessibilityTreeChange(const value: ICefValue);
procedure OnAccessibilityLocationChange(const value: ICefValue);
end;
ICefDialogHandler = interface(ICefBaseRefCounted)
['{7763F4B2-8BE1-4E80-AC43-8B825850DC67}']
function OnFileDialog(const browser: ICefBrowser; mode: TCefFileDialogMode; const title, defaultFilePath: ustring; acceptFilters: TStrings; selectedAcceptFilter: Integer; const callback: ICefFileDialogCallback): Boolean;
end;
ICefGeolocationCallback = interface(ICefBaseRefCounted)
['{272B8E4F-4AE4-4F14-BC4E-5924FA0C149D}']
procedure Cont(allow: Boolean);
end;
ICefGeolocationHandler = interface(ICefBaseRefCounted)
['{1178EE62-BAE7-4E44-932B-EAAC7A18191C}']
function OnRequestGeolocationPermission(const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer; const callback: ICefGeolocationCallback): Boolean;
procedure OnCancelGeolocationPermission(const browser: ICefBrowser; requestId: Integer);
end;
ICefRenderHandler = interface(ICefBaseRefCounted)
['{1FC1C22B-085A-4741-9366-5249B88EC410}']
procedure GetAccessibilityHandler(var aAccessibilityHandler : ICefAccessibilityHandler);
function GetRootScreenRect(const browser: ICefBrowser; var rect: TCefRect): Boolean;
function GetViewRect(const browser: ICefBrowser; var rect: TCefRect): Boolean;
function GetScreenPoint(const browser: ICefBrowser; viewX, viewY: Integer; var screenX, screenY: Integer): Boolean;
function GetScreenInfo(const browser: ICefBrowser; var screenInfo: TCefScreenInfo): Boolean;
procedure OnPopupShow(const browser: ICefBrowser; show: Boolean);
procedure OnPopupSize(const browser: ICefBrowser; const rect: PCefRect);
procedure OnPaint(const browser: ICefBrowser; kind: TCefPaintElementType; dirtyRectsCount: NativeUInt; const dirtyRects: PCefRectArray; const buffer: Pointer; width, height: Integer);
procedure OnCursorChange(const browser: ICefBrowser; cursor: TCefCursorHandle; CursorType: TCefCursorType; const customCursorInfo: PCefCursorInfo);
function OnStartDragging(const browser: ICefBrowser; const dragData: ICefDragData; allowedOps: TCefDragOperations; x, y: Integer): Boolean;
procedure OnUpdateDragCursor(const browser: ICefBrowser; operation: TCefDragOperation);
procedure OnScrollOffsetChanged(const browser: ICefBrowser; x, y: Double);
procedure OnIMECompositionRangeChanged(const browser: ICefBrowser; const selected_range: PCefRange; character_boundsCount: NativeUInt; const character_bounds: PCefRect);
end;
ICefClient = interface(ICefBaseRefCounted)
['{1D502075-2FF0-4E13-A112-9E541CD811F4}']
function GetContextMenuHandler: ICefContextMenuHandler;
function GetDisplayHandler: ICefDisplayHandler;
function GetDownloadHandler: ICefDownloadHandler;
function GetFocusHandler: ICefFocusHandler;
function GetGeolocationHandler: ICefGeolocationHandler;
function GetJsdialogHandler: ICefJsdialogHandler;
function GetKeyboardHandler: ICefKeyboardHandler;
function GetLifeSpanHandler: ICefLifeSpanHandler;
function GetLoadHandler: ICefLoadHandler;
function GetRenderHandler: ICefRenderHandler;
function GetRequestHandler: ICefRequestHandler;
function OnProcessMessageReceived(const browser: ICefBrowser;
sourceProcess: TCefProcessId; const message: ICefProcessMessage): Boolean;
end;
ICefUrlRequest = interface(ICefBaseRefCounted)
['{59226AC1-A0FA-4D59-9DF4-A65C42391A67}']
function GetRequest: ICefRequest;
function GetRequestStatus: TCefUrlRequestStatus;
function GetRequestError: Integer;
function GetResponse: ICefResponse;
procedure Cancel;
end;
ICefUrlrequestClient = interface(ICefBaseRefCounted)
['{114155BD-C248-4651-9A4F-26F3F9A4F737}']
procedure OnRequestComplete(const request: ICefUrlRequest);
procedure OnUploadProgress(const request: ICefUrlRequest; current, total: Int64);
procedure OnDownloadProgress(const request: ICefUrlRequest; current, total: Int64);
procedure OnDownloadData(const request: ICefUrlRequest; data: Pointer; dataLength: NativeUInt);
function OnGetAuthCredentials(isProxy: Boolean; const host: ustring; port: Integer;
const realm, scheme: ustring; const callback: ICefAuthCallback): Boolean;
end;
ICefWebPluginInfoVisitor = interface(ICefBaseRefCounted)
['{7523D432-4424-4804-ACAD-E67D2313436E}']
function Visit(const info: ICefWebPluginInfo; count, total: Integer): Boolean;
end;
ICefWebPluginUnstableCallback = interface(ICefBaseRefCounted)
['{67459829-EB47-4B7E-9D69-2EE77DF0E71E}']
procedure IsUnstable(const path: ustring; unstable: Boolean);
end;
ICefRegisterCDMCallback = interface(ICefBaseRefCounted)
['{6C39AB3B-F724-483F-ABA0-37F6E0AECF35}']
procedure OnCDMRegistrationComplete(result: TCefCDMRegistrationError; const error_message: ustring);
end;
ICefEndTracingCallback = interface(ICefBaseRefCounted)
['{79020EBE-9D1D-49A6-9714-8778FE8929F2}']
procedure OnEndTracingComplete(const tracingFile: ustring);
end;
ICefGetGeolocationCallback = interface(ICefBaseRefCounted)
['{ACB82FD9-3FFD-43F9-BF1A-A4849BF5B814}']
procedure OnLocationUpdate(const position: PCefGeoposition);
end;
ICefFileDialogCallback = interface(ICefBaseRefCounted)
['{1AF659AB-4522-4E39-9C52-184000D8E3C7}']
procedure Cont(selectedAcceptFilter: Integer; filePaths: TStrings);
procedure Cancel;
end;
ICefDragData = interface(ICefBaseRefCounted)
['{FBB6A487-F633-4055-AB3E-6619EDE75683}']
function Clone: ICefDragData;
function IsReadOnly: Boolean;
function IsLink: Boolean;
function IsFragment: Boolean;
function IsFile: Boolean;
function GetLinkUrl: ustring;
function GetLinkTitle: ustring;
function GetLinkMetadata: ustring;
function GetFragmentText: ustring;
function GetFragmentHtml: ustring;
function GetFragmentBaseUrl: ustring;
function GetFileName: ustring;
function GetFileContents(const writer: ICefStreamWriter): NativeUInt;
function GetFileNames(names: TStrings): Integer;
procedure SetLinkUrl(const url: ustring);
procedure SetLinkTitle(const title: ustring);
procedure SetLinkMetadata(const data: ustring);
procedure SetFragmentText(const text: ustring);
procedure SetFragmentHtml(const html: ustring);
procedure SetFragmentBaseUrl(const baseUrl: ustring);
procedure ResetFileContents;
procedure AddFile(const path, displayName: ustring);
function GetImage : ICefImage;
function GetImageHotspot : TCefPoint;
function HasImage : boolean;
end;
ICefDragHandler = interface(ICefBaseRefCounted)
['{59A89579-5B18-489F-A25C-5CC25FF831FC}']
function OnDragEnter(const browser: ICefBrowser; const dragData: ICefDragData; mask: TCefDragOperations): Boolean;
procedure OnDraggableRegionsChanged(const browser: ICefBrowser; regionsCount: NativeUInt; regions: PCefDraggableRegionArray);
end;
ICefFindHandler = interface(ICefBaseRefCounted)
['{F20DF234-BD43-42B3-A80B-D354A9E5B787}']
procedure OnFindResult(const browser: ICefBrowser; identifier, count: Integer; const selectionRect: PCefRect; activeMatchOrdinal: Integer; finalUpdate: Boolean);
end;
ICefRequestContextHandler = interface(ICefBaseRefCounted)
['{76EB1FA7-78DF-4FD5-ABB3-1CDD3E73A140}']
procedure OnRequestContextInitialized(const request_context: ICefRequestContext);
function GetCookieManager: ICefCookieManager;
function OnBeforePluginLoad(const mimeType, pluginUrl:ustring; isMainFrame : boolean; const topOriginUrl: ustring;
const pluginInfo: ICefWebPluginInfo; pluginPolicy: PCefPluginPolicy): Boolean;
end;
ICefResolveCallback = interface(ICefBaseRefCounted)
['{0C0EA252-7968-4163-A1BE-A1453576DD06}']
procedure OnResolveCompleted(result: TCefErrorCode; const resolvedIps: TStrings);
end;
ICefRequestContext = interface(ICefBaseRefCounted)
['{5830847A-2971-4BD5-ABE6-21451F8923F7}']
function IsSame(const other: ICefRequestContext): Boolean;
function IsSharingWith(const other: ICefRequestContext): Boolean;
function IsGlobal: Boolean;
function GetHandler: ICefRequestContextHandler;
function GetCachePath: ustring;
function GetDefaultCookieManager(const callback: ICefCompletionCallback): ICefCookieManager;
function GetDefaultCookieManagerProc(const callback: TCefCompletionCallbackProc): ICefCookieManager;
function RegisterSchemeHandlerFactory(const schemeName, domainName: ustring; const factory: ICefSchemeHandlerFactory): Boolean;
function ClearSchemeHandlerFactories: Boolean;
procedure PurgePluginListCache(reloadPages: Boolean);
function HasPreference(const name: ustring): Boolean;
function GetPreference(const name: ustring): ICefValue;
function GetAllPreferences(includeDefaults: Boolean): ICefDictionaryValue;
function CanSetPreference(const name: ustring): Boolean;
function SetPreference(const name: ustring; const value: ICefValue; out error: ustring): Boolean;
procedure ClearCertificateExceptions(const callback: ICefCompletionCallback);
procedure CloseAllConnections(const callback: ICefCompletionCallback);
procedure ResolveHost(const origin: ustring; const callback: ICefResolveCallback);
function ResolveHostCached(const origin: ustring; const resolvedIps: TStrings): TCefErrorCode;
procedure LoadExtension(const root_directory: ustring; const manifest: ICefDictionaryValue; const handler: ICefExtensionHandler);
function DidLoadExtension(const extension_id: ustring): boolean;
function HasExtension(const extension_id: ustring): boolean;
function GetExtensions(const extension_ids: TStringList): boolean;
function GetExtension(const extension_id: ustring): ICefExtension;
property CachePath : ustring read GetCachePath;
property IsGlobalContext : boolean read IsGlobal;
end;
ICefPrintSettings = Interface(ICefBaseRefCounted)
['{ACBD2395-E9C1-49E5-B7F3-344DAA4A0F12}']
function IsValid: Boolean;
function IsReadOnly: Boolean;
function Copy: ICefPrintSettings;
procedure SetOrientation(landscape: Boolean);
function IsLandscape: Boolean;
procedure SetPrinterPrintableArea(
const physicalSizeDeviceUnits: PCefSize;
const printableAreaDeviceUnits: PCefRect;
landscapeNeedsFlip: Boolean); stdcall;
procedure SetDeviceName(const name: ustring);
function GetDeviceName: ustring;
procedure SetDpi(dpi: Integer);
function GetDpi: Integer;
procedure SetPageRanges(const ranges: TCefRangeArray);
function GetPageRangesCount: NativeUInt;
procedure GetPageRanges(out ranges: TCefRangeArray);
procedure SetSelectionOnly(selectionOnly: Boolean);
function IsSelectionOnly: Boolean;
procedure SetCollate(collate: Boolean);
function WillCollate: Boolean;
procedure SetColorModel(model: TCefColorModel);
function GetColorModel: TCefColorModel;
procedure SetCopies(copies: Integer);
function GetCopies: Integer;
procedure SetDuplexMode(mode: TCefDuplexMode);
function GetDuplexMode: TCefDuplexMode;
property Landscape: Boolean read IsLandscape write SetOrientation;
property DeviceName: ustring read GetDeviceName write SetDeviceName;
property Dpi: Integer read GetDpi write SetDpi;
property SelectionOnly: Boolean read IsSelectionOnly write SetSelectionOnly;
property Collate: Boolean read WillCollate write SetCollate;
property ColorModel: TCefColorModel read GetColorModel write SetColorModel;
property Copies: Integer read GetCopies write SetCopies;
property DuplexMode: TCefDuplexMode read GetDuplexMode write SetDuplexMode;
end;
ICefPrintDialogCallback = interface(ICefBaseRefCounted)
['{1D7FB71E-0019-4A80-95ED-91DDD019253B}']
procedure cont(const settings: ICefPrintSettings);
procedure cancel;
end;
ICefPrintJobCallback = interface(ICefBaseRefCounted)
['{5554852A-052C-464B-A868-B618C7E7E2FD}']
procedure cont;
end;
ICefPrintHandler = interface(ICefBaseRefCounted)
['{2831D5C9-6E2B-4A30-A65A-0F4435371EFC}']
procedure OnPrintStart(const browser: ICefBrowser);
procedure OnPrintSettings(const browser: ICefBrowser; const settings: ICefPrintSettings; getDefaults: boolean);
function OnPrintDialog(const browser: ICefBrowser; hasSelection: boolean; const callback: ICefPrintDialogCallback): boolean;
function OnPrintJob(const browser: ICefBrowser; const documentName, PDFFilePath: ustring; const callback: ICefPrintJobCallback): boolean;
procedure OnPrintReset(const browser: ICefBrowser);
function GetPDFPaperSize(deviceUnitsPerInch: Integer): TCefSize;
end;
ICefNavigationEntry = interface(ICefBaseRefCounted)
['{D17B4B37-AA45-42D9-B4E4-AAB6FE2AB297}']
function IsValid: Boolean;
function GetUrl: ustring;
function GetDisplayUrl: ustring;
function GetOriginalUrl: ustring;
function GetTitle: ustring;
function GetTransitionType: TCefTransitionType;
function HasPostData: Boolean;
function GetCompletionTime: TDateTime;
function GetHttpStatusCode: Integer;
function GetSSLStatus: ICefSSLStatus;
property Url: ustring read GetUrl;
property DisplayUrl: ustring read GetDisplayUrl;
property OriginalUrl: ustring read GetOriginalUrl;
property Title: ustring read GetTitle;
property TransitionType: TCefTransitionType read GetTransitionType;
property CompletionTime: TDateTime read GetCompletionTime;
property HttpStatusCode: Integer read GetHttpStatusCode;
property SSLStatus: ICefSSLStatus read GetSSLStatus;
end;
ICefX509CertPrincipal = interface(ICefBaseRefCounted)
['{CD3621ED-7D68-4A1F-95B5-190C7001B65F}']
function GetDisplayName: ustring;
function GetCommonName: ustring;
function GetLocalityName: ustring;
function GetStateOrProvinceName: ustring;
function GetCountryName: ustring;
procedure GetStreetAddresses(addresses: TStrings);
procedure GetOrganizationNames(names: TStrings);
procedure GetOrganizationUnitNames(names: TStrings);
procedure GetDomainComponents(components: TStrings);
end;
ICefX509Certificate = interface(ICefBaseRefCounted)
['{C897979D-F068-4428-82DF-4221612FF7E0}']
function GetSubject: ICefX509CertPrincipal;
function GetIssuer: ICefX509CertPrincipal;
function GetSerialNumber: ICefBinaryValue;
function GetValidStart: TCefTime;
function GetValidExpiry: TCefTime;
function GetDerEncoded: ICefBinaryValue;
function GetPemEncoded: ICefBinaryValue;
function GetIssuerChainSize: NativeUInt;
procedure GetDEREncodedIssuerChain(chainCount: NativeUInt; var chain : TCefBinaryValueArray);
procedure GetPEMEncodedIssuerChain(chainCount: NativeUInt; var chain : TCefBinaryValueArray);
end;
ICefSslInfo = interface(ICefBaseRefCounted)
['{67EC86BD-DE7D-453D-908F-AD15626C514F}']
function GetCertStatus: TCefCertStatus;
function GetX509Certificate: ICefX509Certificate;
end;
ICefSSLStatus = interface(ICefBaseRefCounted)
['{E3F004F2-03D5-46A2-91D0-510C50F3B225}']
function IsSecureConnection: boolean;
function GetCertStatus: TCefCertStatus;
function GetSSLVersion: TCefSSLVersion;
function GetContentStatus: TCefSSLContentStatus;
function GetX509Certificate: ICefX509Certificate;
end;
ICefSelectClientCertificateCallback = interface(ICefBaseRefCounted)
['{003E3D09-ADE8-4C6E-A174-079D3D616608}']
procedure Select(const cert: ICefX509Certificate);
end;
ICefResourceBundle = interface(ICefBaseRefCounted)
['{3213CF97-C854-452B-B615-39192F8D07DC}']
function GetLocalizedString(stringId: Integer): ustring;
function GetDataResource(resourceId: Integer;
var data: Pointer; var dataSize: NativeUInt): Boolean;
function GetDataResourceForScale(resourceId: Integer; scaleFactor: TCefScaleFactor;
var data: Pointer; var dataSize: NativeUInt): Boolean;
end;
ICefImage = interface(ICefBaseRefCounted)
['{E2C2F424-26A2-4498-BB45-DA23219831BE}']
function IsEmpty: Boolean;
function IsSame(const that: ICefImage): Boolean;
function AddBitmap(scaleFactor: Single; pixelWidth, pixelHeight: Integer;
colorType: TCefColorType; alphaType: TCefAlphaType; pixelData: Pointer;
pixelDataSize: NativeUInt): Boolean;
function AddPng(scaleFactor: Single; const pngData: Pointer; pngDataSize: NativeUInt): Boolean;
function AddJpeg(scaleFactor: Single; const jpegData: Pointer; jpegDataSize: NativeUInt): Boolean;
function GetWidth: NativeUInt;
function GetHeight: NativeUInt;
function HasRepresentation(scaleFactor: Single): Boolean;
function RemoveRepresentation(scaleFactor: Single): Boolean;
function GetRepresentationInfo(scaleFactor: Single; actualScaleFactor: PSingle;
pixelWidth, pixelHeight: PInteger): Boolean;
function GetAsBitmap(scaleFactor: Single; colorType: TCefColorType;
alphaType: TCefAlphaType; pixelWidth, pixelHeight: PInteger): ICefBinaryValue;
function GetAsPng(scaleFactor: Single; withTransparency: Boolean;
pixelWidth, pixelHeight: PInteger): ICefBinaryValue;
function GetAsJpeg(scaleFactor: Single; quality: Integer;
pixelWidth, pixelHeight: PInteger): ICefBinaryValue;
property Width: NativeUInt read GetWidth;
property Height: NativeUInt read GetHeight;
end;
ICefMenuModelDelegate = interface(ICefBaseRefCounted)
['{1430D202-2795-433E-9A35-C79A0996F316}']
procedure ExecuteCommand(const menuModel: ICefMenuModel; commandId: Integer; eventFlags: TCefEventFlags);
procedure MouseOutsideMenu(const menuModel: ICefMenuModel; const screenPoint: PCefPoint);
procedure UnhandledOpenSubmenu(const menuModel: ICefMenuModel; isRTL: boolean);
procedure UnhandledCloseSubmenu(const menuModel: ICefMenuModel; isRTL: boolean);
procedure MenuWillShow(const menuModel: ICefMenuModel);
procedure MenuClosed(const menuModel: ICefMenuModel);
function FormatLabel(const menuModel: ICefMenuModel; const label_ : ustring) : boolean;
end;
IChromiumEvents = interface
['{0C139DB1-0349-4D7F-8155-76FEA6A0126D}']
procedure GetSettings(var settings: TCefBrowserSettings);
// ICefClient
function doOnProcessMessageReceived(const browser: ICefBrowser; sourceProcess: TCefProcessId; const message: ICefProcessMessage): Boolean;
// ICefLoadHandler
procedure doOnLoadingStateChange(const browser: ICefBrowser; isLoading, canGoBack, canGoForward: Boolean);
procedure doOnLoadStart(const browser: ICefBrowser; const frame: ICefFrame; transitionType: TCefTransitionType);
procedure doOnLoadEnd(const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer);
procedure doOnLoadError(const browser: ICefBrowser; const frame: ICefFrame; errorCode: Integer; const errorText, failedUrl: ustring);
// ICefFocusHandler
procedure doOnTakeFocus(const browser: ICefBrowser; next: Boolean);
function doOnSetFocus(const browser: ICefBrowser; source: TCefFocusSource): Boolean;
procedure doOnGotFocus(const browser: ICefBrowser);
// ICefContextMenuHandler
procedure doOnBeforeContextMenu(const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel);
function doRunContextMenu(const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel; const callback: ICefRunContextMenuCallback): Boolean;
function doOnContextMenuCommand(const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; commandId: Integer; eventFlags: TCefEventFlags): Boolean;
procedure doOnContextMenuDismissed(const browser: ICefBrowser; const frame: ICefFrame);
// ICefKeyboardHandler
function doOnPreKeyEvent(const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle; out isKeyboardShortcut: Boolean): Boolean;
function doOnKeyEvent(const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle): Boolean;
// ICefDisplayHandler
procedure doOnAddressChange(const browser: ICefBrowser; const frame: ICefFrame; const url: ustring);
procedure doOnTitleChange(const browser: ICefBrowser; const title: ustring);
procedure doOnFaviconUrlChange(const browser: ICefBrowser; iconUrls: TStrings);
procedure doOnFullScreenModeChange(const browser: ICefBrowser; fullscreen: Boolean);
function doOnTooltip(const browser: ICefBrowser; var text: ustring): Boolean;
procedure doOnStatusMessage(const browser: ICefBrowser; const value: ustring);
function doOnConsoleMessage(const browser: ICefBrowser; const message, source: ustring; line: Integer): Boolean;
function doOnAutoResize(const browser: ICefBrowser; const new_size: PCefSize): Boolean;
// ICefDownloadHandler
procedure doOnBeforeDownload(const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const suggestedName: ustring; const callback: ICefBeforeDownloadCallback);
procedure doOnDownloadUpdated(const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const callback: ICefDownloadItemCallback);
// ICefGeolocationHandler
function doOnRequestGeolocationPermission(const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer; const callback: ICefGeolocationCallback): Boolean;
procedure doOnCancelGeolocationPermission(const browser: ICefBrowser; requestId: Integer);
// ICefJsDialogHandler
function doOnJsdialog(const browser: ICefBrowser; const originUrl: ustring; dialogType: TCefJsDialogType; const messageText, defaultPromptText: ustring; const callback: ICefJsDialogCallback; out suppressMessage: Boolean): Boolean;
function doOnBeforeUnloadDialog(const browser: ICefBrowser; const messageText: ustring; isReload: Boolean; const callback: ICefJsDialogCallback): Boolean;
procedure doOnResetDialogState(const browser: ICefBrowser);
procedure doOnDialogClosed(const browser: ICefBrowser);
// ICefLifeSpanHandler
function doOnBeforePopup(const browser: ICefBrowser; const frame: ICefFrame; const targetUrl, targetFrameName: ustring; targetDisposition: TCefWindowOpenDisposition; userGesture: Boolean; var popupFeatures: TCefPopupFeatures; var windowInfo: TCefWindowInfo; var client: ICefClient; var settings: TCefBrowserSettings; var noJavascriptAccess: Boolean): Boolean;
procedure doOnAfterCreated(const browser: ICefBrowser);
procedure doOnBeforeClose(const browser: ICefBrowser);
function doOnClose(const browser: ICefBrowser): Boolean;
// ICefRequestHandler
function doOnBeforeBrowse(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; isRedirect: Boolean): Boolean;
function doOnOpenUrlFromTab(const browser: ICefBrowser; const frame: ICefFrame; const targetUrl: ustring; targetDisposition: TCefWindowOpenDisposition; userGesture: Boolean): Boolean;
function doOnBeforeResourceLoad(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const callback: ICefRequestCallback): TCefReturnValue;
function doOnGetResourceHandler(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest): ICefResourceHandler;
procedure doOnResourceRedirect(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse; var newUrl: ustring);
function doOnResourceResponse(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse): Boolean;
function doOnGetResourceResponseFilter(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse): ICefResponseFilter;
procedure doOnResourceLoadComplete(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse; status: TCefUrlRequestStatus; receivedContentLength: Int64);
function doOnGetAuthCredentials(const browser: ICefBrowser; const frame: ICefFrame; isProxy: Boolean; const host: ustring; port: Integer; const realm, scheme: ustring; const callback: ICefAuthCallback): Boolean;
function doOnQuotaRequest(const browser: ICefBrowser; const originUrl: ustring; newSize: Int64; const callback: ICefRequestCallback): Boolean;
procedure doOnProtocolExecution(const browser: ICefBrowser; const url: ustring; out allowOsExecution: Boolean);
function doOnCertificateError(const browser: ICefBrowser; certError: TCefErrorcode; const requestUrl: ustring; const sslInfo: ICefSslInfo; const callback: ICefRequestCallback): Boolean;
function doOnSelectClientCertificate(const browser: ICefBrowser; isProxy: boolean; const host: ustring; port: integer; certificatesCount: NativeUInt; const certificates: TCefX509CertificateArray; const callback: ICefSelectClientCertificateCallback): boolean;
procedure doOnPluginCrashed(const browser: ICefBrowser; const pluginPath: ustring);
procedure doOnRenderViewReady(const browser: ICefBrowser);
procedure doOnRenderProcessTerminated(const browser: ICefBrowser; status: TCefTerminationStatus);
// ICefDialogHandler
function doOnFileDialog(const browser: ICefBrowser; mode: TCefFileDialogMode; const title, defaultFilePath: ustring; acceptFilters: TStrings; selectedAcceptFilter: Integer; const callback: ICefFileDialogCallback): Boolean;
// ICefRenderHandler
procedure doOnGetAccessibilityHandler(var aAccessibilityHandler : ICefAccessibilityHandler);
function doOnGetRootScreenRect(const browser: ICefBrowser; var rect: TCefRect): Boolean;
function doOnGetViewRect(const browser: ICefBrowser; var rect: TCefRect): Boolean;
function doOnGetScreenPoint(const browser: ICefBrowser; viewX, viewY: Integer; var screenX, screenY: Integer): Boolean;
function doOnGetScreenInfo(const browser: ICefBrowser; var screenInfo: TCefScreenInfo): Boolean;
procedure doOnPopupShow(const browser: ICefBrowser; show: Boolean);
procedure doOnPopupSize(const browser: ICefBrowser; const rect: PCefRect);
procedure doOnPaint(const browser: ICefBrowser; kind: TCefPaintElementType; dirtyRectsCount: NativeUInt; const dirtyRects: PCefRectArray; const buffer: Pointer; width, height: Integer);
procedure doOnCursorChange(const browser: ICefBrowser; cursor: TCefCursorHandle; cursorType: TCefCursorType; const customCursorInfo: PCefCursorInfo);
function doOnStartDragging(const browser: ICefBrowser; const dragData: ICefDragData; allowedOps: TCefDragOperations; x, y: Integer): Boolean;
procedure doOnUpdateDragCursor(const browser: ICefBrowser; operation: TCefDragOperation);
procedure doOnScrollOffsetChanged(const browser: ICefBrowser; x, y: Double);
procedure doOnIMECompositionRangeChanged(const browser: ICefBrowser; const selected_range: PCefRange; character_boundsCount: NativeUInt; const character_bounds: PCefRect);
// ICefDragHandler
function doOnDragEnter(const browser: ICefBrowser; const dragData: ICefDragData; mask: TCefDragOperations): Boolean;
procedure doOnDraggableRegionsChanged(const browser: ICefBrowser; regionsCount: NativeUInt; regions: PCefDraggableRegionArray);
// ICefFindHandler
procedure doOnFindResult(const browser: ICefBrowser; identifier, count: Integer; const selectionRect: PCefRect; activeMatchOrdinal: Integer; finalUpdate: Boolean);
end;
ICefServer = interface(ICefBaseRefCounted)
['{41D41764-A74B-4552-B166-C77E70549047}']
function GetTaskRunner : ICefTaskRunner;
procedure Shutdown;
function IsRunning : boolean;
function GetAddress : ustring;
function HasConnection : boolean;
function IsValidConnection(connection_id: Integer) : boolean;
procedure SendHttp200response(connection_id: Integer; const content_type: ustring; const data: Pointer; data_size: NativeUInt);
procedure SendHttp404response(connection_id: Integer);
procedure SendHttp500response(connection_id: Integer; const error_message: ustring);
procedure SendHttpResponse(connection_id, response_code: Integer; const content_type: ustring; content_length: int64; const headerMap: ICefStringMultimap);
procedure SendRawData(connection_id: Integer; const data: Pointer; data_size: NativeUInt);
procedure CloseConnection(connection_id: Integer);
procedure SendWebSocketMessage(connection_id: Integer; const data: Pointer; data_size: NativeUInt);
end;
ICefServerHandler = interface(ICefBaseRefCounted)
['{AFB64A63-44C9-44CD-959B-D8E20F549879}']
procedure OnServerCreated(const server: ICefServer);
procedure OnServerDestroyed(const server: ICefServer);
procedure OnClientConnected(const server: ICefServer; connection_id: Integer);
procedure OnClientDisconnected(const server: ICefServer; connection_id: Integer);
procedure OnHttpRequest(const server: ICefServer; connection_id: Integer; const client_address: ustring; const request: ICefRequest);
procedure OnWebSocketRequest(const server: ICefServer; connection_id: Integer; const client_address: ustring; const request: ICefRequest; const callback: ICefCallback);
procedure OnWebSocketConnected(const server: ICefServer; connection_id: Integer);
procedure OnWebSocketMessage(const server: ICefServer; connection_id: Integer; const data: Pointer; data_size: NativeUInt);
end;
IServerEvents = interface
['{06A1B3C6-0967-4F6C-A751-8AA3A29E2FF5}']
procedure doOnServerCreated(const server: ICefServer);
procedure doOnServerDestroyed(const server: ICefServer);
procedure doOnClientConnected(const server: ICefServer; connection_id: Integer);
procedure doOnClientDisconnected(const server: ICefServer; connection_id: Integer);
procedure doOnHttpRequest(const server: ICefServer; connection_id: Integer; const client_address: ustring; const request: ICefRequest);
procedure doOnWebSocketRequest(const server: ICefServer; connection_id: Integer; const client_address: ustring; const request: ICefRequest; const callback: ICefCallback);
procedure doOnWebSocketConnected(const server: ICefServer; connection_id: Integer);
procedure doOnWebSocketMessage(const server: ICefServer; connection_id: Integer; const data: Pointer; data_size: NativeUInt);
end;
implementation
end.
|
{-------------------------------------------------------------------------------
Unit Name: gridimportfn
Author: Aaron Hochwimmer (hochwimmera@pbworld.com)
(derived from "karapiti" demo by Phil Scadden (p.scadden@gns.cri.nz)
Purpose: parsing data grids into an array of z(x,y) points.
Information on surfer can be found at
http://www.goldensoftware.com/products/surfer/surfer.shtml
-------------------------------------------------------------------------------}
unit Gridimportfn;
interface
uses
System.Classes, System.Sysutils,
Vcl.Dialogs;
type
TSingle1d = array of single;
TSingle2d = array of array of single;
TContourGridData = class(TObject)
points : TSingle2D; // stores z points: z=f(x,y)
xscale : TSingle1D; // array of x points
yscale : TSingle1D; // array of y points
private
fnx : smallint; // number of columns in the grid
fny : smallint; // number of rows in the grid
fxlo : single; // min x value of the grid
fxhi : single; // max x value of the grid
fxrange : single; // (xhi-xlo) - the x range
fxstep : single; // spacing between adjacent x nodes
fylo : single; // min y value of the grid
fyhi : single; // max y value of the grid
fyrange :single; // (yhi-ylo) - the y range
fystep : single; // spacing between adjacent y nodes
fzlo : single; // min z value of the grid
fzhi : single; // max z value of the grid
fzrange : single; // (zhi-zlo) - the z range
procedure CalcDerived;
procedure CalcDerivedNative;
procedure ConstructArrays;
{** attempts to open a surfer grid (.grd) in GS ASCII format.
Integer return code: 0 = file processed ok
1 = not a GS ASCII file}
function LoadSurferGSASCII(sFileName:string):integer;
{** attempts to open a surfer grid (.grd) in GS Binary format.
Integer return code: 0 = file processed ok
1 = not a GS Binary file}
function LoadSurferGSBinary(sFileName:string):integer;
{** attempts to open a surfer grid (.grd) in native binary format. This format
is used by default by both Surfer 7 and Surfer 8.
Integer return code: 0 = file processed ok
1 = not a Surfer Grid file}
function LoadSurferGridNative(sFileName:string):integer;
public
destructor Destroy;override;
{** attempts to open a surfer grid (.grd) in either GS ASCII, GS Binary, or
Surfer 7 GRD format.
Integer return code: 0 = file processed ok
1 = not a surfer grid of any format}
function LoadSurferGrid(sFileName:string):integer;
property nx : smallint read fnx write fnx;
property ny : smallint read fny write fny;
property xlo : single read fxlo write fxlo;
property xhi : single read fxhi write fxhi;
property xrange : single read fxrange write fxrange;
property xstep : single read fxstep write fxstep;
property ylo : single read fylo write fylo;
property yhi : single read fyhi write fyhi;
property yrange : single read fyrange write fyrange;
property ystep : single read fystep write fystep;
property zlo : single read fzlo write fzlo;
property zhi : single read fzhi write fzhi;
property zrange : single read fzrange write fzrange;
end;
implementation
uses
{** additional}
CommaSplit;
// ------ TContourGridData.CalcDerived -----------------------------------------
{** calculates derived quantities such as step sizes and ranges. Also sets up
the points array}
procedure TContourGridData.CalcDerived;
begin
xrange := xhi - xlo;
xstep := xrange/(nx-1);
yrange := yhi - ylo;
ystep := yrange/(ny-1);
zrange := zhi - zlo;
ConstructArrays;
end;
// ------ TContourGridData.CalcDerivedNative -----------------------------------
{** calculates derived quantities such as ranges. Different to CalcDerived
as the native Surfer Grid/Surfer 7 format has different parameters}
procedure TContourGridData.CalcDerivedNative;
begin
xrange := (nx-1)*xstep;
xhi := xlo + xrange;
yrange := (ny-1)*ystep;
yhi := ylo + yrange;
zrange := zhi - zlo;
ConstructArrays;
end;
// ------ TContourGridData.ConstructArrays -------------------------------------
procedure TContourGridData.ConstructArrays;
var
i:integer;
begin
SetLength(points,ny,nx);
SetLength(xscale,nx);
SetLength(yscale,ny);
xscale[0] := 0.0;
for i:=1 to nx-1 do
xscale[i] := xscale[i-1]+xstep;
yscale[0] := 0.0;
for i:=1 to ny-1 do
yscale[i] := yscale[i-1]+ystep;
end;
// ------ TContourGridData.LoadSurferGSASCII -----------------------------------
{GS ASCII Grid File Format:
GS ASCII GRid files [.grd] contain 5 header lines that provide information about
the size limits of the grid, followed by a list of z values. The fields within
a GS ASCII grid _must_ be space delimited.
The listing of z values follows the header information in the file. The z values
are stored in row-major order starting with the minimum Y coordinate. The first
z value of the grid corresponds to the lower left corner of the map (min X,Y).
When the maximum X value is reached in the row the list of z values continues
with the next highest row, until all the rows have been included.
General Format:
id = a four char id string "DSAA" which idicates GS ASCII grid file
nx ny = nx is the number of grid lines along the x axis (columns)
ny is the number of grid lines along the y axis (rows)
xlo xhi = xlo is the floating point minimum X value of the grid
xhi is the floating point maximum X value of the grid
ylo yhi = ylo is the floating point minimum Y value of the grid
yhi is the floating point maximum Y value of the grid
zlo zhi = zlo is the floating point minimum Z value of the grid
= xhi is the floating point maximum Z value of the grid
grid row 1
grid row 2
etc
NB: each grid row has a constant Y coordinate. Grid row 1 corresponds to ylo
and the last grid row corresponds to yhi. Within each row the Z values are
arranged from xlo to xhi. When an ASCII grid file is created in surfer the
program generates 10 z values per line for readability. This function will read
files with any number of values per line.
}
function TContourGridData.LoadSurferGSASCII(sFileName:string):integer;
var
// col = nx-1
// i = row counter
// j = column counter
// k = columns in line counter
// n = counter to increment through file
filestrings : TStringList;
col,i,j,k,n: integer;
cs : TCommaSplitter;
function ReadLine:string;
begin
result := filestrings[n];
Inc(n);
end;
begin
filestrings := TStringList.Create;
filestrings.LoadFromFile(sFileName);
n := 0;
cs := TCommaSplitter.Create(nil);
cs.Delimiter := ' ';
try
{** check for valid GS ASCII header}
if (Copy(ReadLine,1,4) <> 'DSAA') then
begin
filestrings.Free;
cs.Free;
result := 1;
exit;
end;
{** read nx,ny}
cs.Text := ReadLine;
nx := StrToInt(cs.Items[0]);
ny := StrToInt(cs.Items[1]);
{** read xlo,xhi}
cs.Text := ReadLine;
xlo := StrToFloat(cs.Items[0]);
xhi := StrToFloat(cs.Items[1]);
{** read ylo,yhi}
cs.Text := ReadLine;
ylo := StrToFloat(cs.Items[0]);
yhi := StrToFloat(cs.Items[1]);
{** read zlo,zhi}
cs.Text := ReadLine;
zlo := StrToFloat(cs.Items[0]);
zhi := StrToFloat(cs.Items[1]);
{** calculate the derived quantites - step sizes etc}
CalcDerived;
col := nx-1;
{** loop over the rows - i}
for i := 0 to ny-1 do
begin
j := 0;
{** keep reading lines until nx-1 (col) entries have been obtained}
while j <= col do
begin
cs.Text := ReadLine;
for k := 0 to cs.Items.Count-1 do
begin
if (j <= col) then
points[i,j] := StrToFloat(cs.Items[k]);
Inc(j);
end;
if (j > col) then
break;
end;
end;
finally
result := 0;
fileStrings.Free;
cs.Free;
end;
end;
// ------ TContourGridData.LoadSurferGSBinary ----------------------------------
{GS Binary Grid File Format:
GS Binary grid files [.grd] use a similar layout to the GS ASCII described
above. The difference is in the ID string and that the files are binary :)
Data types used:
char - single byte
smallint - 16 byte signed integer
single - 32 bit single precision floating point value
double - 64 bit double precision floating point value
General Format:
Element Type Description
id char 4 byte id string "DSBB" indicates GS Binary grid file
nx smallint number of grid lines along the x axis (columns)
ny smallint number of grid lines along the y axis (columns)
xlo double minimum X value of the grid
xhi double maximum X value of the grid
ylo double minimum Y value of the grid
yhi double maximum Y value of the grid
zlo double minimum Z value of the grid
zhi double maximum Z value of the grid
z11,z12,... single first row of the grid. Each row has constant Y coordinate
first row corresponds to ylo, and last corresponds to yhi
Within each row, the Z values are ordered from xlo -> xhi.
z21,z22,... single second row of the grid
z31,z32,... single third row of the grid
... single all other rows of the grid up to yhi
}
function TContourGridData.LoadSurferGSBinary(sFileName:string):integer;
var
binfile : file;
i,j : smallint;
d:double;
zval : single;
ndouble,nsingle,nsmallint,col:integer; // sizeof vars
sType : array[1..4] of char;
nread:integer; // number of bytes read - unused
begin
AssignFile(binfile,sFileName);
Reset(binfile,1); // record size of 1 byte
{** check to see if this is a GS Binary file}
BlockRead(binfile,sType,4,nread);
if (sType <> 'DSBB') then
begin
result := 1;
CloseFile(binfile);
end else
begin
ndouble := sizeof(d);
nsingle := sizeof(zval);
nsmallint := sizeof(i);
{** read nx,ny}
BlockRead(binfile,i,nsmallint,nRead);
nx := i;
BlockRead(binfile,i,nsmallint,nRead);
ny := i;
{** read xlo,xhi}
BlockRead(binfile,d,ndouble,nread);
xlo := d;
BlockRead(binfile,d,ndouble,nread);
xhi := d;
{** read ylo,yhi}
BlockRead(binfile,d,ndouble,nread);
ylo := d;
BlockRead(binfile,d,ndouble,nread);
yhi := d;
{** read zlo,zhi}
BlockRead(binfile,d,ndouble,nread);
zlo := d;
BlockRead(binfile,d,ndouble,nread);
zhi := d;
{** calculate the derived quantities - step sizes etc}
CalcDerived;
col := nx-1;
{** now read in the points}
for i := 0 to ny-1 do
for j := 0 to col do
begin
BlockRead(binfile,zval,nsingle,nRead);
points[i,j] := zval;
end;
result := 0;
CloseFile(binFile);
end;
end;
// ------ TContourGridData.LoadSurferGridNative --------------------------------
{ Surfer Grid and Surfer 7 Grid files [.GRD] use the same file format.
Uses tag-based binary file format (allow for future enhancements)
Each section is preceded by a tag structure - which indicates the type and size
of the following data.
If a program does not understand or want a type of data, it can read the tag
and skip to the next section. Sections can appear in any order than the first
(which must be the header section)
Data types used:
integer - 32 bit signed integer
double - 64 bit double precision floating point value
Each section is preceded by a tag structure with the following format:
Element Type Description
id integer The type of data in the following section.
size integer The number of bytes in the section (not including this
tag). Skipping this many bytes after reading this tag
aligns the file pointer on the next tag.
Tag Id values. The 0x prefix indicates a hexadecimal value:
id Description
0x42525344 Header section:
must be the first section within the file
0x44495247 Grid section:
describes a 2d matrix of Z values
0x41544144 Data section:
contains a variable amount of data.
0x49544c46 Fault Info section:
describes the fault traces used when creating a grid
** Header Section **
The header section must be the first section in the file and has the following
format.
Element Type Description
version integer Version number of the file format. Currently set to 1.
** Grid Section **
The grid section consists of a header that describes a 2D matrix of values,
followed by the matrix itself. This section encapsulates all of the data that
was traditionally referred to as a grid:
Element Type Description
ny integer number of rows in the grid (Y direction)
nx integer number of columns in the grid (X direction)
xlo double X coordinate of the lower left corner of the grid
ylo double Y coordinate of the lower right corner of the grid
xstep double spacing between adjacent nodes in the X direction
ystep double spacing between adjacent nodes in the Y direction
zlo double minimum Z value within the grid
zhi double maximum Z value within the grid
rotation double not currently used
blankval double nodes are blanked if >= this value
A Data section containing the 2d matrix of values (doubles) must immediately
follow a grid section. Within a data section the grid is stored in row-major
order, with the lowest row (min Y) first.
** Fault Info Section ** (NOT USED IN THIS CLASS)
Element Type Description
nTraces integer number of fault traces (polylines)
nVertices integer total number of vertices in all the traces
A Data section containing an array of Trace structures and an array of Vertex
structures must immediately follow a Fault Info section. The number of trace
structures in the array is nTraces and the number of vertex structures is
nVertices.
Trace Structure
Element Type Description
iFirst integer 0-based index into the vertex array for the first vertex
of this trace
nPts integer number of vertices in this trace
Vertex Structure
Element Type Description
x double X coordinate of the vertex
y double Y coordinate of the vertex
}
function TContourGridData.LoadSurferGridNative(sFileName:string):integer;
const
sHEADER = '42525344';
sFAULTINFO = '49544c46';
sGRIDSECT = '44495247';
sDATASECT = '41544144';
iSECTSIZE = 8;
var
binfile: file;
buf: array of byte;
dval : double;
col,i,iHeaderID,iSize,iVal,iVersion,j,nDouble,nInteger,nRead : integer;
sSectionID,sSectionID2 : string;
begin
AssignFile(binfile,sFileName);
Reset(binfile,1); {** set the default record size to 1 byte}
nInteger := SizeOf(iHeaderID); {** just size of integer variable}
{** read in the header}
BlockRead(binfile,iHeaderID,nInteger,nRead);
sSectionID := IntToHex(iHeaderID,iSECTSIZE);
{** check the header tag}
if (sSectionID <> sHEADER) then
begin
result := 1;
CloseFile(binfile);
end else
begin
nDouble := SizeOf(dVal); {** just size of double variable}
BlockRead(binfile,iSize,nInteger,nRead); {** size of header section}
BlockRead(binfile,iVersion,nInteger,nRead); {** file version}
{** the sections are in any order...}
while (not eof(binfile)) do
begin
{** what section is this?}
BlockRead(binfile,iHeaderID,nInteger,nRead);
sSectionID := IntToHex(iHeaderID,iSECTSIZE);
{** FAULT INFO SECTION}
if (sSectionID = sFAULTINFO) then
begin
BlockRead(binfile,iSize,nInteger,nRead); {** size of fault info section}
SetLength(buf,iSize); {** set up the temp buffer}
BlockRead(binfile,buf,iSize,nRead); {** skip the section}
{** from the specs a data section will follow - skip this one as well}
BlockRead(binfile,iHeaderID,nInteger,nRead);
sSectionID2 := IntToHex(iHeaderID,iSECTSIZE);
if (sSectionID2 = sDATASECT) then
begin
BlockRead(binfile,iSize,nInteger,nread);
SetLength(buf,iSize); {** set up the temp buffer}
BlockRead(binfile,buf,iSize,nRead); {** skip the section}
end;
{** GRID SECTION}
end else if (sSectionID = sGRIDSECT) then
begin
BlockRead(binfile,iSize,nInteger,nRead); {** size of grid section}
BlockRead(binfile,iVal,nInteger,nRead);
ny := iVal;
BlockRead(binFile,iVal,nInteger,nRead);
nx := iVal;
BlockRead(binfile,dVal,nDouble,nRead);
xlo := dval;
BlockRead(binfile,dVal,nDouble,nRead);
ylo := dval;
BlockRead(binFile,dVal,nDouble,nRead);
xstep := dval;
BlockRead(binfile,dVal,nDouble,nRead);
ystep := dval;
BlockRead(binfile,dval,nDouble,nread);
zlo := dval;
BlockRead(binfile,dval,nDouble,nread);
zhi := dval;
BlockRead(binfile,dval,nDouble,nread); {** rotation - not used here}
BlockRead(binfile,dval,nDouble,nread); {** blankvalue - not used here}
CalcDerivedNative;
{** from the specs a data section will follow - skip this one as well}
BlockRead(binfile,iHeaderID,nInteger,nRead);
sSectionID2 := IntToHex(iHeaderID,iSECTSIZE);
if (sSectionID2 = sDATASECT) then
begin
col := nx-1;
BlockRead(binfile,iSize,nInteger,nRead);
{** now read in the points}
for i := 0 to ny-1 do
begin
for j := 0 to col do
begin
BlockRead(binfile,dval,ndouble,nRead);
points[i,j] := dval;
end;
end;
end;
end; {while not eof}
end;
result := 0;
CloseFile(binFile);
end;
end;
// ------ TContourGridData.LoadSurferGrid --------------------------------------
function TContourGridData.LoadSurferGrid(sFileName:string):integer;
begin
{** native format first - Surfer 7 or 8}
if (LoadSurferGridNative(sFileName) = 0) then
begin
result := 0;
exit;
end;
{** check if the grd file is GS Binary}
if (LoadSurferGSBinary(sFileName) = 0) then
begin
result := 0;
exit;
end;
{** check if the grd file is GS ASCII}
if (LoadSurferGSASCII(sFileName) = 0) then
begin
result := 0;
exit;
end;
{** not a surfer grid file}
result := 1;
end;
// ------ TContourGridData.destroy ---------------------------------------------
destructor TContourGridData.destroy;
begin
points := nil;
xscale := nil;
yscale := nil;
inherited destroy;
end;
// =============================================================================
end.
|
{ ========================================================================
Unit: HexEdits
VCL: THexEdit
Version: 1.0
Copyright (C) 1996, Immo Wache
========================================================================}
unit HexEdits;
interface
uses WinTypes, WinProcs, Classes, StdCtrls, ExtCtrls, Controls, Messages,
SysUtils, Forms, Graphics, Menus, Buttons, Clipbrd, Dialogs;
type
// TEditBase =(ebHex, ebDec, ebOct, ebBin);
TEditBase =(ebDec, ebHex, ebBin, ebOct);
THexEdit = class(TCustomEdit)
private
FMinValue, FMaxValue: Longint;
FValidate: Boolean;
FNumBase: TEditBase;
procedure SetNumBase( NewValue: TEditBase);
procedure SetValue( NewValue : Longint );
function GetValue: Longint;
function CheckValue( NewValue: Longint): Longint;
procedure SetMaxValue( NewValue: Longint);
procedure SetMinValue( NewValue: Longint);
procedure SetValidate( B: Boolean);
function SyntaxOk(const S: string): Boolean;
procedure CMEnter(var Message: TCMGotFocus); message CM_ENTER;
procedure CMExit(var Message: TCMExit); message CM_EXIT;
function BaseStrToInt(const S: string): Longint;
function IntToBaseStr(Value: Longint): string;
protected
function IsValidChar( Key: Char) : Boolean; virtual;
procedure KeyDown(var Key: Word; Shift : TShiftState ); override;
procedure KeyPress(var Key: Char ); override;
function ValidCopy: Boolean;
function ValidPaste: Boolean;
function ValidCut: Boolean;
function ValidDelete: Boolean;
public
constructor Create( AOwner : TComponent ); override;
published
property AutoSelect;
property AutoSize;
property Anchors;
property BorderStyle;
property Color;
property NumBase: TEditBase read FNumBase write SetNumBase;
property Ctl3D;
property DragCursor;
property DragMode;
property Enabled;
property Font;
property HideSelection;
property MaxLength;
property MaxValue: Longint read FMaxValue write SetMaxValue;
property MinValue: Longint read FMinValue write SetMinValue;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ReadOnly;
property ShowHint;
property TabOrder;
property TabStop;
property Validate: Boolean read FValidate write SetValidate;
property Value: Longint read GetValue write SetValue;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
end;
procedure Register;
implementation
const
// Base: array[TEditBase] of Byte =(16, 10, 8, 2);
Base: array[TEditBase] of Byte =(10, 16, 2, 8);
constructor THexEdit.Create( AOwner : TComponent);
begin
inherited Create( AOwner);
{force Text to '0'}
SetValue( 0);
end;
function THexEdit.BaseStrToInt(const S: string): Longint;
var
Digit, I: Byte;
begin
Result :=0;
for I :=1 to Length( S) do
begin
Digit :=ord( S[I]) -ord('0');
if Digit >10 then Dec( Digit, 7);
Result :=Result *Base[NumBase] +Digit;
end;
end;
function THexEdit.IntToBaseStr(Value: Longint): string;
var
Ch: Char;
begin
Result :='';
repeat
Ch :='0';
Inc(Ch, Value mod Base[NumBase]);
if Ch >'9' then Inc(Ch, 7);
Insert( Ch, Result, 1);
Value :=Value div Base[NumBase];
until Value =0;
end;
function THexEdit.GetValue: Longint;
begin
Result :=BaseStrToInt( Text);
end;
procedure THexEdit.SetValue(NewValue: Longint);
begin
Text:=IntToBaseStr( CheckValue( NewValue));
end;
procedure THexEdit.SetNumBase( NewValue: TEditBase);
var
TempValue: LongInt;
begin
TempValue :=Value;
FNumBase :=NewValue;
SetValue( TempValue);
end;
function THexEdit.CheckValue( NewValue: Longint): Longint;
begin
if NewValue <0 then NewValue :=0;
Result :=NewValue;
if FValidate then
begin
if NewValue < FMinValue then Result:= FMinValue
else if NewValue > FMaxValue then Result:= FMaxValue;
end;
end;
procedure THexEdit.SetMaxValue( NewValue: Longint);
begin
if NewValue <0 then NewValue :=0;
FMaxValue := NewValue;
SetValue( Value);
end;
procedure THexEdit.SetMinValue( NewValue: Longint);
begin
if NewValue <0 then NewValue :=0;
FMinValue := NewValue;
SetValue( Value);
end;
procedure THexEdit.SetValidate( B: Boolean);
begin
FValidate :=B;
SetValue( Value);
end;
function THexEdit.SyntaxOk(const S: string): Boolean;
var
I: Byte;
NewValue: LongInt;
begin
{ syntax correct if all chars are valid }
Result := True;
for I :=1 to Length(S) do
begin
if not (S[I] in ['0'..'9', 'A'..'F']) or
(BaseStrToInt( S[I]) >=Base[NumBase]) then Result := False;
end;
{ syntax correct if Value inside bounds }
if Result and FValidate then
begin
NewValue :=BaseStrToInt( S);
if (NewValue < FMinValue) or (NewValue > FMaxValue) then Result:= False;
end;
end;
procedure THexEdit.CMEnter( var Message: TCMGotFocus);
begin
if AutoSelect and not( csLButtonDown in ControlState ) then SelectAll;
inherited;
end;
procedure THexEdit.CMExit( var Message: TCMExit);
begin
inherited;
SetValue( Value);
end;
function THexEdit.IsValidChar( Key: Char): Boolean;
begin
case Key of
'0'..'9', 'A'..'F':
Result := SyntaxOk( Copy( Text, 1, SelStart ) +
Key +
Copy( Text, SelStart+1+SelLength, 255 ));
^H: if SelLength = 0 then { ^H = Backspace }
Result := SyntaxOk( Copy( Text, 1, SelStart-1 ) +
Copy( Text, SelStart+1, 255 ))
else
Result := SyntaxOk( Copy( Text, 1, SelStart ) +
Copy( Text, SelStart+1+SelLength, 255 ));
else
Result := False;
end;{case}
end;
function THexEdit.ValidCopy: Boolean;
begin
Result :=True;
end;
function THexEdit.ValidPaste: Boolean;
begin
if Clipboard.HasFormat(CF_TEXT) then
Result :=SyntaxOk( Copy( Text, 1, SelStart ) +
Clipboard.AsText +
Copy( Text, SelStart+1, 255 ))
else
result:=FALSE;
end;
function THexEdit.ValidCut: Boolean;
begin
Result :=SyntaxOk( Copy( Text, 1, SelStart ) +
Copy( Text, SelStart+1+SelLength, 255 ));
end;
function THexEdit.ValidDelete: Boolean;
var
S: string;
begin
if SelLength =0 then
S :=Copy( Text, 1, SelStart ) +Copy( Text, SelStart+2, 255 )
else
S :=Copy( Text, 1, SelStart ) +Copy( Text, SelStart+1+SelLength, 255 );
Result :=SyntaxOk( S);
end;
procedure THexEdit.KeyDown(var Key: Word; Shift: TShiftState);
begin
{ handle Copy-, Paste-, Cut-, Delete-Keys}
if ssShift in Shift then
begin
if Key =VK_INSERT then begin if not ValidPaste then Key :=0 end
else if Key =VK_DELETE then begin if not ValidCut then Key :=0 end
end
else if ssCtrl in Shift then
begin
if Key =VK_INSERT then begin if not ValidCopy then Key :=0 end
else if Key =VK_DELETE then begin if not ValidDelete then Key :=0 end
end
else if Key =VK_DELETE then begin if not ValidDelete then Key :=0 end;
inherited KeyDown( Key, Shift);
end;
procedure THexEdit.KeyPress(var Key: Char);
begin
if FValidate then begin
{ handle Copy Paste Cut Keys}
if Key =^C then begin if not ValidCopy then Key :=#0 end
else if Key =^V then begin if not ValidPaste then Key :=#0 end
else if Key =^X then begin if not ValidCut then Key :=#0 end
else
begin
Key :=UpCase( Key); {transform a..f to A..F}
if not IsValidChar( Key) then Key := #0;
end;
if Key <>#0 then inherited KeyPress( Key);
end;
end;
procedure Register;
begin
RegisterComponents('Add-On''s', [THexEdit]);
end;
end.
|
unit DemoCustomFileSystemMain;
interface
uses
Windows, Classes, ShlObj, Types,
// API
apiPlugin, apiFileManager, apiMenu, apiCore, apiActions, apiPlaylists, apiObjects,
// Wrappers
AIMPCustomPlugin, apiWrappers;
type
{ TMenuItemHandler }
TMenuItemHandler = class(TInterfacedObject, IAIMPActionEvent)
strict private
FEvent: TNotifyEvent;
public
constructor Create(AEvent: TNotifyEvent);
procedure OnExecute(Data: IInterface); stdcall;
end;
{ TMyMusicFileSystem }
(*
Common idea of the TMyMusicFileSystem:
1. Replace path to "My Music" system folder with the "mymusic" scheme when adding it to playlist
2. Implement all file system commands that will be replace "mymusic" scheme by real path of the "MyMusic"
folder and forward call to the "default" file system handler
*)
TMyMusicFileSystem = class(TAIMPPropertyList,
IAIMPFileSystemCommandCopyToClipboard,
IAIMPFileSystemCommandDelete,
IAIMPFileSystemCommandDropSource,
IAIMPFileSystemCommandFileInfo,
IAIMPFileSystemCommandOpenFileFolder,
IAIMPFileSystemCommandStreaming,
IAIMPExtensionFileSystem)
strict private
FRootPath: UnicodeString;
function GetCommandForDefaultFileSystem(const IID: TGUID; out Obj): Boolean;
function TranslateFileName(const AFileName: IAIMPString): IAIMPString;
protected
// IAIMPExtensionFileSystem
procedure DoGetValueAsInt32(PropertyID: Integer; out Value: Integer; var Result: HRESULT); override;
function DoGetValueAsObject(PropertyID: Integer): IInterface; override;
// IAIMPFileSystemCommandCopyToClipboard
function CopyToClipboard(Files: IAIMPObjectList): HRESULT; stdcall;
// IAIMPFileSystemCommandDropSource
function CreateStream(FileName: IAIMPString; out Stream: IAIMPStream): HRESULT; overload; stdcall;
// IAIMPFileSystemCommandDelete
function IAIMPFileSystemCommandDelete.CanProcess = CanDelete;
function IAIMPFileSystemCommandDelete.Process = Delete;
function CanDelete(FileName: IAIMPString): HRESULT; stdcall;
function Delete(FileName: IAIMPString): HRESULT; stdcall;
// IAIMPFileSystemCommandFileInfo
function GetFileAttrs(FileName: IAIMPString; out Attrs: TAIMPFileAttributes): HRESULT; stdcall;
function GetFileSize(FileName: IAIMPString; out Size: Int64): HRESULT; stdcall;
function IsFileExists(FileName: IAIMPString): HRESULT; stdcall;
// IAIMPFileSystemCommandOpenFileFolder
function IAIMPFileSystemCommandOpenFileFolder.CanProcess = CanOpenFileFolder;
function IAIMPFileSystemCommandOpenFileFolder.Process = OpenFileFolder;
function CanOpenFileFolder(FileName: IAIMPString): HRESULT; stdcall;
function OpenFileFolder(FileName: IAIMPString): HRESULT; stdcall;
// IAIMPFileSystemCommandStreaming
function CreateStream(FileName: IAIMPString; const Offset, Size: Int64; Flags: Cardinal; out Stream: IAIMPStream): HRESULT; overload; stdcall;
public
constructor Create; virtual;
end;
{ TDemoCustomFileSystemPlugin }
TDemoCustomFileSystemPlugin = class(TAIMPCustomPlugin)
strict private
procedure HandlerMenuItemClick(Sender: TObject);
protected
function InfoGet(Index: Integer): PWideChar; override; stdcall;
function InfoGetCategories: Cardinal; override; stdcall;
function Initialize(Core: IAIMPCore): HRESULT; override; stdcall;
end;
implementation
uses
ActiveX, SysUtils, IOUtils;
const
sMyScheme = 'mymusic';
sMySchemePrefix = sMyScheme + ':\\';
function ShellGetSystemFolder(AFolder: Integer): UnicodeString;
var
ABuf: array[0..MAX_PATH] of WideChar;
begin
if SHGetSpecialFolderPathW(0, @ABuf[0], AFolder, False) then
Result := IncludeTrailingPathDelimiter(ABuf)
else
Result := '';
end;
function ShellGetMyMusic: UnicodeString;
begin
Result := ShellGetSystemFolder(CSIDL_MYMUSIC);
end;
{ TMenuItemHandler }
constructor TMenuItemHandler.Create(AEvent: TNotifyEvent);
begin
FEvent := AEvent;
end;
procedure TMenuItemHandler.OnExecute(Data: IInterface);
begin
FEvent(nil);
end;
{ TMyMusicFileSystem }
constructor TMyMusicFileSystem.Create;
begin
FRootPath := ShellGetMyMusic;
end;
procedure TMyMusicFileSystem.DoGetValueAsInt32(PropertyID: Integer; out Value: Integer; var Result: HRESULT);
begin
if PropertyID = AIMP_FILESYSTEM_PROPID_READONLY then
begin
Result := S_OK;
Value := 0;
end
else
inherited DoGetValueAsInt32(PropertyID, Value, Result);
end;
function TMyMusicFileSystem.DoGetValueAsObject(PropertyID: Integer): IInterface;
begin
if PropertyID = AIMP_FILESYSTEM_PROPID_SCHEME then
Result := MakeString(sMyScheme)
else
Result := inherited DoGetValueAsObject(PropertyID);
end;
function TMyMusicFileSystem.CopyToClipboard(Files: IAIMPObjectList): HRESULT;
var
AFileName: IAIMPString;
AIntf: IAIMPFileSystemCommandCopyToClipboard;
AList: IAIMPObjectList;
I: Integer;
begin
if GetCommandForDefaultFileSystem(IAIMPFileSystemCommandCopyToClipboard, AIntf) then
begin
CoreCreateObject(IAIMPObjectList, AList);
for I := 0 to Files.GetCount - 1 do
begin
if Succeeded(Files.GetObject(I, IAIMPString, AFileName)) then
AList.Add(TranslateFileName(AFileName));
end;
Result := AIntf.CopyToClipboard(AList);
end
else
Result := E_NOTIMPL;
end;
function TMyMusicFileSystem.CreateStream(FileName: IAIMPString; out Stream: IAIMPStream): HRESULT;
begin
Result := CreateStream(FileName, -1, -1, 0, Stream);
end;
function TMyMusicFileSystem.GetFileAttrs(FileName: IAIMPString; out Attrs: TAIMPFileAttributes): HRESULT;
var
AIntf: IAIMPFileSystemCommandFileInfo;
begin
if GetCommandForDefaultFileSystem(IAIMPFileSystemCommandFileInfo, AIntf) then
Result := AIntf.GetFileAttrs(TranslateFileName(FileName), Attrs)
else
Result := E_NOTIMPL;
end;
function TMyMusicFileSystem.GetFileSize(FileName: IAIMPString; out Size: Int64): HRESULT;
var
AIntf: IAIMPFileSystemCommandFileInfo;
begin
if GetCommandForDefaultFileSystem(IAIMPFileSystemCommandFileInfo, AIntf) then
Result := AIntf.GetFileSize(TranslateFileName(FileName), Size)
else
Result := E_NOTIMPL;
end;
function TMyMusicFileSystem.IsFileExists(FileName: IAIMPString): HRESULT;
var
AIntf: IAIMPFileSystemCommandFileInfo;
begin
if GetCommandForDefaultFileSystem(IAIMPFileSystemCommandFileInfo, AIntf) then
Result := AIntf.IsFileExists(TranslateFileName(FileName))
else
Result := E_NOTIMPL;
end;
function TMyMusicFileSystem.CanDelete(FileName: IAIMPString): HRESULT;
var
AIntf: IAIMPFileSystemCommandDelete;
begin
if GetCommandForDefaultFileSystem(IAIMPFileSystemCommandDelete, AIntf) then
Result := AIntf.CanProcess(TranslateFileName(FileName))
else
Result := E_NOTIMPL;
end;
function TMyMusicFileSystem.Delete(FileName: IAIMPString): HRESULT;
var
AIntf: IAIMPFileSystemCommandDelete;
begin
if GetCommandForDefaultFileSystem(IAIMPFileSystemCommandDelete, AIntf) then
Result := AIntf.Process(TranslateFileName(FileName))
else
Result := E_NOTIMPL;
end;
function TMyMusicFileSystem.CanOpenFileFolder(FileName: IAIMPString): HRESULT;
var
AIntf: IAIMPFileSystemCommandOpenFileFolder;
begin
if GetCommandForDefaultFileSystem(IAIMPFileSystemCommandOpenFileFolder, AIntf) then
Result := AIntf.CanProcess(TranslateFileName(FileName))
else
Result := E_NOTIMPL;
end;
function TMyMusicFileSystem.OpenFileFolder(FileName: IAIMPString): HRESULT;
var
AIntf: IAIMPFileSystemCommandOpenFileFolder;
begin
if GetCommandForDefaultFileSystem(IAIMPFileSystemCommandOpenFileFolder, AIntf) then
Result := AIntf.Process(TranslateFileName(FileName))
else
Result := E_NOTIMPL;
end;
function TMyMusicFileSystem.CreateStream(FileName: IAIMPString;
const Offset, Size: Int64; Flags: Cardinal; out Stream: IAIMPStream): HRESULT;
var
AIntf: IAIMPFileSystemCommandStreaming;
begin
if GetCommandForDefaultFileSystem(IAIMPFileSystemCommandStreaming, AIntf) then
Result := AIntf.CreateStream(TranslateFileName(FileName), Offset, Size, Flags, Stream)
else
Result := E_NOTIMPL;
end;
function TMyMusicFileSystem.GetCommandForDefaultFileSystem(const IID: TGUID; out Obj): Boolean;
var
AService: IAIMPServiceFileSystems;
begin
Result := CoreGetService(IAIMPServiceFileSystems, AService) and Succeeded(AService.GetDefault(IID, Obj));
end;
function TMyMusicFileSystem.TranslateFileName(const AFileName: IAIMPString): IAIMPString;
begin
CheckResult(AFileName.Clone(Result));
Result.Replace(MakeString(sMySchemePrefix), MakeString(FRootPath), AIMP_STRING_FIND_IGNORECASE);
end;
{ TDemoCustomFileSystemPlugin }
function TDemoCustomFileSystemPlugin.InfoGet(Index: Integer): PWideChar;
begin
case Index of
AIMP_PLUGIN_INFO_NAME:
Result := 'MyMusic - Custom File System Demo';
AIMP_PLUGIN_INFO_AUTHOR:
Result := 'Artem Izmaylov';
else
Result := '';
end;
end;
function TDemoCustomFileSystemPlugin.InfoGetCategories: Cardinal;
begin
Result := AIMP_PLUGIN_CATEGORY_ADDONS;
end;
function TDemoCustomFileSystemPlugin.Initialize(Core: IAIMPCore): HRESULT;
var
AMenuItem: IAIMPMenuItem;
AMenuServiceIntf: IAIMPServiceMenuManager;
AParentMenuItem: IAIMPMenuItem;
begin
Result := inherited Initialize(Core);
if Succeeded(Result) then
begin
// Create Menu item
if CoreGetService(IAIMPServiceMenuManager, AMenuServiceIntf) then
begin
if Succeeded(AMenuServiceIntf.GetBuiltIn(AIMP_MENUID_PLAYER_PLAYLIST_ADDING, AParentMenuItem)) then
begin
CoreCreateObject(IAIMPMenuItem, AMenuItem);
CheckResult(AMenuItem.SetValueAsObject(AIMP_MENUITEM_PROPID_NAME, MakeString('MyMusic: Add All Files')));
CheckResult(AMenuItem.SetValueAsObject(AIMP_MENUITEM_PROPID_EVENT, TMenuItemHandler.Create(HandlerMenuItemClick)));
CheckResult(AMenuItem.SetValueAsObject(AIMP_MENUITEM_PROPID_PARENT, AParentMenuItem));
Core.RegisterExtension(IAIMPServiceMenuManager, AMenuItem);
end;
end;
// Register custom file system
Core.RegisterExtension(IAIMPServiceFileSystems, TMyMusicFileSystem.Create);
end;
end;
procedure TDemoCustomFileSystemPlugin.HandlerMenuItemClick(Sender: TObject);
var
AFileFormatService: IAIMPServiceFileFormats;
AFileList: IAIMPObjectList;
AFiles: TStringDynArray;
APlaylist: IAIMPPlaylist;
APlaylistService: IAIMPServicePlaylistManager;
ARootPath: UnicodeString;
I: Integer;
begin
if CoreGetService(IAIMPServiceFileFormats, AFileFormatService) then
begin
// Get all files from MyMusic folder and sub-folders
ARootPath := ShellGetMyMusic;
AFiles := TDirectory.GetFiles(ARootPath, '*', TSearchOption.soAllDirectories, nil);
if Length(AFiles) = 0 then
Exit;
// Check the format type of returned files and replace the path of "My Music" folder by our scheme.
CoreCreateObject(IAIMPObjectList, AFileList);
for I := 0 to Length(AFiles) - 1 do
begin
if Succeeded(AFileFormatService.IsSupported(MakeString(AFiles[I]), AIMP_SERVICE_FILEFORMATS_CATEGORY_AUDIO)) then
AFileList.Add(MakeString(sMySchemePrefix + Copy(AFiles[I], Length(ARootPath) + 1, MaxInt)));
end;
// Put supported files to the playlist
if CoreGetService(IAIMPServicePlaylistManager, APlaylistService) then
begin
if Succeeded(APlaylistService.GetActivePlaylist(APlaylist)) then
APlaylist.AddList(AFileList, AIMP_PLAYLIST_ADD_FLAGS_NOCHECKFORMAT, -1);
end;
end;
end;
end.
|
Retiré de Elphy le 24 juin 2010
unit StmCube1;
interface
uses windows,DirectXGraphics,
D3DX81mo,
util1,Dgraphic,dibG,listG,
stmDef,stmObj,stmD3Dobj,stmPG;
type
Tcube=class (Tobject3D)
Fvalid:boolean;
Lx,Ly,Lz:single;
color0:integer;
dev:IDIRECT3DDEVICE8;
VB:IDIRECT3DVERTEXBUFFER8;
material:TD3Dmaterial8;
procedure initGeometry(D3dDevice:IDIRECT3DDEVICE8);
constructor create;override;
class function stmClassName:string;override;
procedure display3D(D3dDevice:IDIRECT3DDEVICE8;x,y,z,tx,ty,tz:single);override;
procedure releaseDevice;override;
end;
procedure proTcube_create(stName:String;dx,dy,dz:float;col:integer; var pu:typeUO);pascal;
procedure proTcube_color(col:integer; var pu:typeUO);pascal;
function fonctionTcube_color(var pu:typeUO):integer;pascal;
implementation
{ Tcube }
constructor Tcube.create;
begin
inherited;
Lx:=0.1;
Ly:=0.1;
Lz:=0.1;
color0:=rgb(255,0,0);
end;
type
TCUSTOMVERTEX=
record
position:TD3DVECTOR ; // The position
normal: TD3DVECTOR ; // The normal
color:TD3DCOLOR; // The color
end;
TCUSTOMVERTEXarray=array[0..1] of TCUSTOMVERTEX;
PCUSTOMVERTEXarray=^TCUSTOMVERTEXarray;
const
Vformat=D3DFVF_XYZ or D3DFVF_NORMAL or D3DFVF_DIFFUSE;
procedure Tcube.initGeometry(D3dDevice: IDIRECT3DDEVICE8);
var
n0, n1, n2, n3, n4, n5: TD3DVector;
pVertices:PCUSTOMVERTEXarray;
i:integer;
procedure setVertex(num:integer;x,y,z:single;n:TD3Dvector;col:integer);
begin
with pVertices[num] do
begin
position := D3DVECTOR( x,y, z );
normal := n;
color := col or $FF000000;
end;
end;
begin
Fvalid:=false;
if d3dDevice.CreateVertexBuffer( 24*sizeof(TCUSTOMVERTEX),
0, Vformat ,
D3DPOOL_DEFAULT, VB )<>0 then exit;
if FAILED( VB.Lock( 0, 0, windows.Pbyte(pVertices), 0 ) ) then exit;
// Define the normals for the cube
n0 := D3DVector( 0.0, 0.0,-1 ); // Front face
n1 := D3DVector( 0.0, 0.0, 1 ); // Back face
n2 := D3DVector( 0.0, 1.0, 0 ); // Top face
n3 := D3DVector( 0.0,-1.0, 0 ); // Bottom face
n4 := D3DVector( 1.0, 0.0, 0 ); // Right face
n5 := D3DVector(-1.0, 0.0, 0 ); // Left face
// Front face
setVertex(0,-lx/2, ly/2,-lz/2, n0, color0 );
setVertex(1, lx/2, ly/2,-lz/2, n0, color0 );
setVertex(2,-lx/2,-ly/2,-lz/2, n0, color0 );
setVertex(3, lx/2,-ly/2,-lz/2, n0, color0 );
// Back face
setVertex(4,-lx/2, ly/2, lz/2, n1, color0 );
setVertex(5,-lx/2,-ly/2, lz/2, n1, color0 );
setVertex(6, lx/2, ly/2, lz/2, n1, color0 );
setVertex(7, lx/2,-ly/2, lz/2, n1, color0 );
// Top face
setVertex(8,-lx/2, ly/2, lz/2, n2, color0 );
setVertex(9, lx/2, ly/2, lz/2, n2, color0 );
setVertex(10,-lx/2, ly/2,-lz/2, n2, color0 );
setVertex(11, lx/2, ly/2,-lz/2, n2, color0 );
// Bottom face
setVertex(12,-lx/2,-ly/2, lz/2, n3, color0 );
setVertex(13,-lx/2,-ly/2,-lz/2, n3, color0 );
setVertex(14, lx/2,-ly/2, lz/2, n3, color0 );
setVertex(15, lx/2,-ly/2,-lz/2, n3, color0 );
// Right face
setVertex(16, lx/2, ly/2,-lz/2, n4, color0 );
setVertex(17, lx/2, ly/2, lz/2, n4, color0 );
setVertex(18, lx/2,-ly/2,-lz/2, n4, color0 );
setVertex(19, lx/2,-ly/2, lz/2, n4, color0 );
// Left face
setVertex(20,-lx/2, ly/2,-lz/2, n5, color0 );
setVertex(21,-lx/2,-ly/2,-lz/2, n5, color0 );
setVertex(22,-lx/2, ly/2, lz/2, n5, color0 );
setVertex(23,-lx/2,-ly/2, lz/2, n5, color0 );
VB.Unlock;
fillchar( material,sizeof(material),0);
with material do
begin
Diffuse := rgbtoD3D(color0,1);
Ambient := rgbtoD3D(color0,1);
end;
Fvalid:=true;
end;
procedure Tcube.display3D(D3dDevice: IDIRECT3DDEVICE8; x, y, z, tx, ty,tz: single);
var
matWorld:TD3DMATRIX;
i:integer;
begin
D3DXMatrixTranslation(matWorld,x,y,z);
d3dDevice.SetTransform( D3DTS_WORLD, matWorld );
if (dev<>d3dDevice) or not Fvalid then initGeometry(D3Ddevice);
if not Fvalid then exit;
d3dDevice.setMaterial(material);
d3dDevice.lightEnable(0,true);
d3dDevice.SetRenderState( D3DRS_LIGHTING, 1 );
d3dDevice.SetRenderState(D3DRS_Ambient,rgb(128,128,128));
d3dDevice.SetStreamSource( 0, VB, sizeof(TCUSTOMVERTEX) );
d3dDevice.SetVertexShader( Vformat );
for i:=0 to 5 do
d3dDevice.DrawPrimitive( D3DPT_TRIANGLESTRIP, i*4, 2 );
dev:=d3dDevice;
end;
procedure Tcube.releaseDevice;
begin
inherited;
vb:=nil;
Fvalid:=false;
end;
class function Tcube.stmClassName: string;
begin
result:='Cube';
end;
{************************ Méthodes STM ****************************************}
procedure proTcube_create(stName:String;dx,dy,dz:float;col:integer; var pu:typeUO);
begin
createPgObject(stname,pu,Tcube);
with Tcube(pu) do
begin
Lx:=dx;
Ly:=dy;
Lz:=dz;
color0:=col;
end;
end;
procedure proTcube_color(col:integer; var pu:typeUO);
begin
verifierObjet(pu);
with Tcube(pu) do
begin
color0:=col;
Fvalid:=false;
end;
end;
function fonctionTcube_color(var pu:typeUO):integer;
begin
verifierObjet(pu);
with Tcube(pu) do
begin
result:=color0;
end;
end;
initialization
registerObject(Tcube,data);
end.
|
unit WaryLua;
{$M+}
interface
uses
VerySimple.Lua, VerySimple.Lua.Lib, System.SysUtils, Winapi.Windows,
ApplicationLua, FormLua, ConsoleLua;
type
// MyLua example class
TWaryLua = class(TVerySimpleLua)
private
pApplicationLua: TApplicationLua;
pFormLua: TFormLua;
pConSole: TConsoleLua;
protected
procedure DoPrint(Msg: string); override;
procedure DoError(Msg: String); override;
public
constructor Create; override;
destructor Destroy; override;
procedure Open; override;
published
// lua functions this published methods are automatically added
// to the lua function table if called with TLua.Create(True) or Create()
end;
implementation
uses GlobalDefine, cnConsole;
constructor TWaryLua.Create;
begin
inherited;
LibraryPath := LUA_LIBRARY;
pApplicationLua := TApplicationLua.Create();
pFormLua := TFormLua.Create();
pConSole := TConsoleLua.Create();
end;
destructor TWaryLua.Destroy;
begin
pApplicationLua.Free();
pFormLua.Free();
pConSole.Free();
inherited;
end;
procedure TWaryLua.DoError(Msg: String);
begin
if Assigned(g_Console) then
begin
g_console.SetTextColor(tfRed + tfIntensity);
Writeln(Msg);
g_console.SetTextColor(tfWhite);
end
else
begin
OutPutDebugString(PChar(Msg));
end;
end;
procedure TWaryLua.DoPrint(Msg: string);
begin
if Assigned(g_Console) then
begin
g_console.SetTextColor(tfGreen + tfIntensity);
Writeln(Msg);
g_console.SetTextColor(tfWhite);
end
else
begin
OutPutDebugString(PChar(Msg));
end;
end;
procedure TWaryLua.Open;
begin
inherited;
// and create a second package and auto register those package functions
RegisterPackage('vcl.Application', pApplicationLua);
RegisterPackage('vcl.Form', pFormLua);
RegisterPackage('vcl.Console', pConSole);
end;
end.
|
{*
FtermSSH : An SSH implementation in Delphi for FTerm2 by kxn@cic.tsinghua.edu.cn
Cryptograpical code from OpenSSL Project
*}
unit sshkex;
interface
uses Classes, sshbn, sshdh, sshutil, sshsha, sshcipher, sshmac, sshrsa;
type
TSSHKex = class
constructor Create(Owner: TObject); virtual;
end;
TSSH2Kex = class(TSSHKex)
private
Parent: TObject;
public
constructor Create(Owner: TObject); override;
destructor Destroy; override;
// function OnPacket(Packet:TSSHBuffer):boolean;virtual;
end;
TSSH1KexState = (BEFORE_PUBLICKEY, SESSIONKEY_SENT, KEYEX_OK);
TSSH1Kex = class(TSSHKex)
private
state: TSSH1KexState;
Session: TObject;
FirstKex: boolean;
HostKey, ServKey: TSSHRSA;
cookie: array [0..7] of byte;
servflag, sciphers, sauth: integer;
sessionid: array[0..15] of byte;
sessionkey: array [0..31] of byte;
procedure MakeSessionID;
public
constructor Create(Owner: TObject); override;
destructor Destroy; override;
function OnPacket(Packet: TSSH1PacketReceiver): boolean;
end;
TSSH2DHGSHA1KexState = (BEGIN_KEYEXCHANGE, KEYEX_INIT_SENT,
KEYEX_DH_INIT_SENT, KEYEX_NEWKEY_SENT, KEYEX_COMPLETE);
TSSH2DHGSHA1Kex = class(TSSH2Kex)
private
DHGroup: TSSHDH;
SHA1: TSSHSHA1;
state: TSSH2DHGSHA1KexState;
SVStr, CVStr: string;
HostKey: string;
SigData: string;
Mykex, HisKex: TSSHBuffer;
schmac, cshmac: TSSH2MAC;
sccipher, cscipher: TSSHCipher;
ExHash: array[1..20] of byte;
KeyBuf: array [1..40] of byte;
FirstKex: boolean;
K: BIGNUM;
procedure SetClientVer(const Value: string);
procedure SetServerVer(const Value: string);
procedure SSH2MkKey(K: BIGNUM; Hash: Pointer; sessionid: Pointer;
c: char; Key: Pointer);
public
constructor Create(Owner: TObject); override;
destructor Destroy; override;
function OnPacket(Packet: TSSH2PacketReceiver): boolean;
property ServerVersion: string write SetServerVer;
property ClientVersion: string write SetClientVer;
end;
implementation
uses SSHsession, sshconst, sshdes, sysutils, dialogs, sshmd5, sshwsock;
{ TSSH2Kex }
constructor TSSH2Kex.Create(Owner: TObject);
begin
Parent := Owner;
end;
destructor TSSH2Kex.Destroy;
begin
inherited;
end;
{ TSSH2DHGKEx }
constructor TSSH2DHGSHA1KEx.Create(Owner: TObject);
begin
inherited Create(Owner);
DHGroup := TSSHDH.Create(self);
SHA1 := TSSHSHA1.Create;
state := KEYEX_INIT_SENT;
FirstKex := True;
end;
{ TSSHKex }
constructor TSSHKex.Create(Owner: TObject);
begin
end;
destructor TSSH2DHGSHA1KEx.Destroy;
begin
if Assigned(DHGroup) then DHGroup.Free;
if Assigned(SHA1) then SHA1.Free;
if K <> nil then BN_free(K);
inherited;
end;
function TSSH2DHGSHA1Kex.OnPacket(Packet: TSSH2PacketReceiver): boolean;
var
Ss: TSSH2Session;
i: integer;
f: BIGNUM;
tempbuf: TSSHBuffer;
s: string;
begin
SS := TSSH2Session(Parent);
Result := False;
case state of
BEGIN_KEYEXCHANGE:
begin
ss.OutPacket.StartPacket(SSH2_MSG_KEXINIT);
for i := 1 to 16 do
ss.OutPacket.AddByte(random(256)); // cookie
ss.OutPacket.AddString('diffie-hellman-group1-sha1');
//TODO : more algorithms
ss.OutPacket.AddString('ssh-dss'); // Host Key
ss.OutPacket.AddString('3des-cbc'); // cs enc
ss.OutPacket.AddString('3des-cbc'); // sc enc
ss.OutPacket.AddString('hmac-sha1'); // cs hmac
ss.OutPacket.AddString('hmac-sha1'); // sc hmac
ss.OutPacket.AddString('none'); // cs comp
ss.OutPacket.AddString('none'); // sc comp
ss.OutPacket.AddString(''); // cs lang
ss.OutPacket.AddString(''); // sc lang
ss.OutPacket.AddByte(0); // follow
ss.OutPacket.AddInteger(0); // reserved;
MyKex := TSSHBuffer.Create(ss.OutPacket.Buffer.Length);
MyKex.Add(ss.OutPacket.Buffer.Data, ss.OutPacket.Buffer.Length);
ss.OutPacket.Write;
state := KEYEX_INIT_SENT;
Result := True; //handled
end;
KEYEX_INIT_SENT:
begin
if Packet.PacketType <> SSH2_MSG_KEXINIT then
raise ESSHError.Create('Protocol Error');
HisKex := TSSHBuffer.Create(Packet.Buffer.Length);
HisKex.AddByte(SSH2_MSG_KEXINIT);
HisKex.Add(Packet.Buffer.Data, Packet.Buffer.Length - Packet.padding);
// TODO: keyex method
// TODO Algorithm selection;
Packet.Buffer.Consume(16); // skip cookie
Packet.GetString(s); // key ex, assume ok
Packet.GetString(s); // host key
if Pos('ssh-dss', s) = 0 then raise ESSHError.Create('Can not agree hostkey');
Packet.GetString(s); // cs cipher
if Pos('3des-cbc', s) = 0 then raise ESSHError.Create('Can not agree cipher');
Packet.GetString(s); // sc cipher
if Pos('3des-cbc', s) = 0 then raise ESSHError.Create('Can not agree cipher');
Packet.GetString(s); // cs hmac
if Pos('hmac-sha1', s) = 0 then raise ESSHError.Create('Can not agree hmac');
Packet.GetString(s); // sc hmac
if Pos('hmac-sha1', s) = 0 then raise ESSHError.Create('Can not agree hmac');
Packet.GetString(s); // cs comp
if Pos('none', s) = 0 then raise ESSHError.Create('Can not agree compression');
Packet.GetString(s); // sc comp
if Pos('none', s) = 0 then raise ESSHError.Create('Can not agree compression');
ss.OutPacket.StartPacket(SSH2_MSG_KEXINIT);
for i := 1 to 16 do
ss.OutPacket.AddByte(random(256)); // cookie
ss.OutPacket.AddString('diffie-hellman-group1-sha1');
//TODO : more algorithms
ss.OutPacket.AddString('ssh-dss'); // Host Key
ss.OutPacket.AddString('3des-cbc'); // cs enc
ss.OutPacket.AddString('3des-cbc'); // sc enc
ss.OutPacket.AddString('hmac-sha1'); // cs hmac
ss.OutPacket.AddString('hmac-sha1'); // sc hmac
ss.OutPacket.AddString('none'); // cs comp
ss.OutPacket.AddString('none'); // sc comp
ss.OutPacket.AddString('en'); // cs lang
ss.OutPacket.AddString('en'); // sc lang
ss.OutPacket.AddByte(0); // follow
ss.OutPacket.AddInteger(0); // reserved;
MyKex := TSSHBuffer.Create(ss.OutPacket.Buffer.Length);
MyKex.Add(ss.OutPacket.Buffer.Data, ss.OutPacket.Buffer.Length);
ss.OutPacket.Write;
// state := KEYEX_INIT_SENT;
// agreed, proceeding on dh
// create the ciphers and macs
sccipher := TSSHDES3.Create;
cscipher := TSSHDES3.Create;
if TSSHWSocket(ss.Sock).Hmacbug then
begin
cshmac := TSSH2MACSHA1Buggy.Create;
schmac := TSSH2MACSHA1Buggy.Create;
end
else
begin
cshmac := TSSH2MACSHA1.Create;
schmac := TSSH2MACSHA1.Create;
end;
// TODO : only for 3DES
DHGroup.GenKey(2 * 160);
ss.OutPacket.StartPacket(SSH2_MSG_KEXDH_INIT);
ss.OutPacket.AddBN(DHGroup.dh.pub_key);
ss.OutPacket.Write;
state := KEYEX_DH_INIT_SENT;
Result := True;
end;
KEYEX_DH_INIT_SENT:
begin
if Packet.PacketType <> SSH2_MSG_KEXDH_REPLY then
raise ESSHError.Create('Protocol Error');
Packet.GetString(HostKey);
f := BN_new;
tempbuf := TSSHBuffer.Create(5000);
try
Packet.GetBN(f);
Packet.GetString(SigData);
k := DHGroup.FindK(f);
//calc the exchange hash
tempbuf.AddString2(CVStr);
tempbuf.AddString2(SVStr);
tempbuf.AddInteger(MyKex.Length);
tempbuf.Add(MyKex.Data, MyKex.Length);
tempbuf.AddInteger(HisKex.Length);
tempbuf.Add(HisKex.Data, HisKex.Length);
tempbuf.AddString2(HostKey);
tempbuf.AddSSH2BN(DHGroup.dh.pub_key);
tempbuf.AddSSH2BN(f);
tempbuf.AddSSH2BN(K);
SHA1.Free;
SHA1 := TSSHSHA1.Create;
SHA1.Update(tempbuf.Data, tempbuf.Length);
SHA1.Final(@ExHash);
SHA1.Free;
finally
tempbuf.Free;
BN_free(f);
end;
// BN_free(K); K is managed by DHGroup
ss.OutPacket.StartPacket(SSH2_MSG_NEWKEYS);
ss.OutPacket.Write;
// TODO : verify host key
// make new key and set them
Move(ExHash, ss.sessionid, 20);
SSH2MkKey(K, @ExHash, @ss.SessionId, 'A', @Keybuf);
cscipher.SetIV(@KeyBuf);
SSH2MkKey(K, @ExHash, @ss.SessionId, 'B', @Keybuf);
sccipher.SetIV(@KeyBuf);
SSH2MkKey(K, @ExHash, @ss.SessionId, 'C', @Keybuf);
cscipher.SetKey(@KeyBuf);
SSH2MkKey(K, @ExHash, @ss.SessionId, 'D', @Keybuf);
sccipher.SetKey(@KeyBuf);
SSH2MkKey(K, @ExHash, @ss.SessionId, 'E', @Keybuf);
cshmac.SetKey(@KeyBuf);
SSH2MkKey(K, @ExHash, @ss.SessionId, 'F', @Keybuf);
schmac.SetKey(@KeyBuf);
BN_free(K);
K := nil;
state := KEYEX_NEWKEY_SENT;
Result := True;
end;
KEYEX_NEWKEY_SENT:
begin
if Packet.PacketType <> SSH2_MSG_NEWKEYS then
raise ESSHError.Create('newkey failed');
// set ciphers to session
ss.cshmac := cshmac;
ss.cscipher := cscipher;
ss.schmac := schmac;
ss.sccipher := sccipher;
//from now on the packets are encrypted
state := KEYEX_COMPLETE;
if FirstKex then
begin
Result := False;
FirstKEx := False;
end
else
Result := True;
end;
KEYEX_COMPLETE:
begin
if Packet.PacketType = SSH2_MSG_KEXINIT then
begin
raise ESSHError.Create('server request keyexchange, i can not handle that by now');
state := BEGIN_KEYEXCHANGE;
Result := True;
exit;
end;
Result := False; // unhandled
end;
end;
end;
procedure TSSH2DHGSHA1Kex.SetClientVer(const Value: string);
begin
CVStr := Value;
end;
procedure TSSH2DHGSHA1Kex.SetServerVer(const Value: string);
begin
SVStr := Value;
end;
procedure TSSH2DHGSHA1Kex.SSH2MkKey(K: BIGNUM; Hash, sessionid: Pointer;
c: char; Key: Pointer);
var
sha: TSSHSHA1;
temp: TSSHBuffer;
begin
temp := TSSHBuffer.Create(500);
sha := TSSHSHA1.Create;
temp.AddSSH2BN(K);
temp.Add(Hash, 20);
temp.AddByte(Ord(c));
temp.Add(SessionId, 20);
sha.Update(temp.Data, temp.Length);
sha.Final(Key);
sha.Free;
temp.Free;
Sha := TSSHSHA1.Create;
temp := TSSHBuffer.Create(500);
temp.AddSSH2BN(K);
temp.Add(Hash, 20);
temp.Add(Key, 20);
sha.Update(temp.Data, temp.Length);
sha.Final(PChar(Key) + 20);
temp.Free;
sha.Free;
end;
{ TSSH1Kex }
constructor TSSH1Kex.Create(Owner: TObject);
begin
inherited;
state := BEFORE_PUBLICKEY;
Session := Owner;
FirstKex := True;
end;
destructor TSSH1Kex.Destroy;
begin
if Assigned(HostKey) then HostKey.Free;
if Assigned(ServKey) then ServKey.Free;
inherited;
end;
procedure TSSH1Kex.MakeSessionID;
var
P: PChar;
md5: TSSHMD5;
servlen, hostlen: integer;
begin
md5 := TSSHMd5.Create;
Servlen := BN_num_bytes(ServKey.rsa.n);
Hostlen := BN_num_bytes(HostKey.rsa.n);
GetMem(p, ServLen + HostLen);
BN_bn2bin(HostKey.rsa.n, p);
BN_bn2bin(ServKey.rsa.n, p + HostLen);
md5.Update(p, ServLen + HostLen);
md5.Update(@cookie, 8);
md5.Final(@sessionid);
md5.Free;
FreeMem(p);
end;
function TSSH1Kex.OnPacket(Packet: TSSH1PacketReceiver): boolean;
var
ss: TSSH1Session;
i: integer;
key: BIGNUM;
begin
ss := TSSH1Session(Session);
Result := False;
case state of
BEFORE_PUBLICKEY:
begin
if Packet.PacketType <> SSH1_SMSG_PUBLIC_KEY then
raise ESSHError.Create('First packet is not public key');
Packet.GetBuffer(@cookie, 8);
ServKey := TSSHRSA.Create;
MakeKey(Packet.Buffer, ServKey);
HostKey := TSSHRSA.Create;
MakeKey(Packet.Buffer, HostKey);
Packet.GetInteger(servflag);
Packet.GetInteger(sciphers);
Packet.GetInteger(sauth);
if sciphers and (1 shl SSH_CIPHER_3DES) = 0 then
raise ESSHError.Create('Server do not support my cipher');
// ssh1 always support password auth?
// BUG : hostkey verification
// SSH1 does not have signature on the hostkey,
// the client can only compare it againse local storage.
// I think this is not as much useful as it sounds, faint.
MakeSessionID;
for i := 0 to 31 do
sessionkey[i] := Random(256);
key := BN_new;
try
BN_set_word(key, 0);
for i := 0 to 31 do
begin
BN_lshift(key, key, 8);
if i < 16 then BN_add_word(key, sessionkey[i] xor sessionid[i])
else
BN_add_word(key, sessionkey[i]);
end;
if BN_cmp(ServKEy.rsa.n, HostKey.rsa.n) < 0 then
begin
// TODO: key length check
ServKey.PublicEncrypt(key, key);
HostKey.PublicEncrypt(key, key);
end
else
begin
HostKey.PublicEncrypt(key, key);
ServKey.PublicEncrypt(key, key);
end;
HostKey.Free;
HostKey := nil;
ServKey.Free;
ServKey := nil;
// TODO : cipher selection
ss.OutPacket.StartPacket(SSH1_CMSG_SESSION_KEY);
ss.OutPacket.AddByte(SSH_CIPHER_3DES);
ss.OutPacket.AddBuffer(@cookie, 8);
ss.OutPacket.AddBN(key);
finally
BN_free(key);
end;
ss.OutPacket.AddInteger(1); // SSH_PROTOFLAG_SCREEN_NUMBER
ss.OutPacket.Write;
state := SESSIONKEY_SENT;
// now create cipher and set the keys
ss.SCCipher := TSSH1DES3.Create;
ss.CSCipher := TSSH1DES3.Create;
ss.sccipher.SetIV(nil);
ss.sccipher.SetKey(@sessionkey);
ss.cscipher.SetIV(nil);
ss.cscipher.SetKey(@sessionkey);
Result := True; // handled
end;
SESSIONKEY_SENT:
begin
if Packet.PacketType <> SSH1_SMSG_SUCCESS then
raise ESSHError.Create('key exchange failed');
state := KEYEX_OK;
Result := False;
// don't handle this packet in order to trigger the auth state machine
end;
KEYEX_OK:
begin
Result := False;
end;
end;
end;
end.
|
unit CCJSO_ClientNotice_PayDetails;
{
© PgkSoft 25.08.2016
Механизм формирования и отправки клиенту реквизитов платежа
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UCCenterJournalNetZkz, ActnList, ExtCtrls, StdCtrls, ComCtrls,
ToolWin, DB, ADODB, uActionCore;
type
TfrmCCJSO_ClientNotice_PayDetails = class(TForm)
pnlControl: TPanel;
pnlControl_Tool: TPanel;
pnlControl_Show: TPanel;
pnlParm: TPanel;
aList: TActionList;
aExit: TAction;
aRegNotice: TAction;
lblOrder: TLabel;
lblPrefix: TLabel;
lblPharm: TLabel;
lblClient: TLabel;
lblPhone: TLabel;
lblEMail: TLabel;
lblSum: TLabel;
lblShipping: TLabel;
lblPayment: TLabel;
lblDetails: TLabel;
edOrder: TEdit;
edPrefix: TEdit;
edClient: TEdit;
edPhone: TEdit;
edEMail: TEdit;
edSum: TEdit;
edShipping: TEdit;
edPayment: TEdit;
edPharm: TEdit;
edDetails: TMemo;
tbarTool: TToolBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
edCheck: TMemo;
spGetPaymentDetails: TADOStoredProc;
aChange: TAction;
lblOrderAmount: TLabel;
edOrderAmount: TEdit;
spPayDetails: TADOStoredProc;
lblOrderAmountShipping: TLabel;
edOrderAmountShipping: TEdit;
lblCoolantSum: TLabel;
edCoolantSum: TEdit;
Label1: TLabel;
edOrderName: TEdit;
procedure FormCreate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure aExitExecute(Sender: TObject);
procedure aRegNoticeExecute(Sender: TObject);
procedure aChangeExecute(Sender: TObject);
private
{ Private declarations }
bSignActive : boolean;
Section : integer;
OrderPrefix : string;
RecSession : TUserSession;
RecHeaderItem : TJSO_OrderHeaderItem;
PhoneNorm : string;
PayDetails : string;
NoticeCheck : string;
FActionResult: TActionResult;
FSendDone: Boolean;
procedure ShowGets;
procedure GetPaymentDetails(
USER : integer;
CODE : string;
Prefix : string;
Order : integer;
Pharm : integer;
FullName : string;
Sum : string;
SignCheck : boolean;
OrderName : string;
var Details : string;
var Check : string
);
public
{ Public declarations }
procedure SetRecHeaderItem(Parm : TJSO_OrderHeaderItem);
procedure SetRecSession(Parm : TUserSession);
procedure SetSection(Parm : integer);
function ShowDialog: TActionResult;
end;
var
frmCCJSO_ClientNotice_PayDetails: TfrmCCJSO_ClientNotice_PayDetails;
implementation
uses UMAIN, CCJSO_DM, ExDBGRID;
{$R *.dfm}
procedure TfrmCCJSO_ClientNotice_PayDetails.FormCreate(Sender: TObject);
begin
{ Инициализация }
bSignActive := false;
Section := 0;
end;
procedure TfrmCCJSO_ClientNotice_PayDetails.FormActivate(Sender: TObject);
begin
{ Инициализация полей }
case Section of
cFSection_SiteApteka911: begin
OrderPrefix := RecHeaderItem.ExtSysPrefix;//DM_CCJSO.GetPrefNumbOrderApteka911;
lblPharm.Visible := false;
edPharm.Visible := false;
edOrder.Text := RecHeaderItem.SorderID;
edPrefix.Text := RecHeaderItem.ExtSysPrefix; //DM_CCJSO.GetPrefNumbOrderApteka911;
edClient.Text := RecHeaderItem.orderShipName;
edOrderAmount.Text := CurrToStrF(RecHeaderItem.orderAmount, ffFixed, 2);
edOrderAmountShipping.Text := CurrToStrF(RecHeaderItem.NOrderAmountShipping, ffFixed, 2);
edCoolantSum.Text := CurrToStrF(RecHeaderItem.NCoolantSum, ffFixed, 2);
edPhone.Text := RecHeaderItem.orderPhone;
edEMail.Text := RecHeaderItem.orderEmail;
edSUM.Text := CurrToStrF(RecHeaderItem.orderAmount + RecHeaderItem.NOrderAmountShipping + RecHeaderItem.NCoolantSum, ffFixed, 2);
edShipping.Text := RecHeaderItem.orderShipping;
edPayment.Text := RecHeaderItem.orderPayment;
edOrderName.Text := RecHeaderItem.orderName;
GetPaymentDetails(
RecSession.CurrentUser,
DM_CCJSO.GetCodeDetailsPrePaymentCourier,
DM_CCJSO.GetPrefNumbOrderApteka911,
RecHeaderItem.orderID,
0,
RecHeaderItem.orderShipName,
edSUM.Text,
true,
RecHeaderItem.orderName,
PayDetails,
NoticeCheck
);
edDetails.Text := PayDetails;
if length(NoticeCheck) <> 0 then begin
edCheck.Text := NoticeCheck;
end else begin
edCheck.Visible := false;
end;
end;
cFSection_OrderClients: begin
end;
end;
{ Форма активна }
bSignActive := true;
ShowGets;
edSUM.SetFocus;
end;
procedure TfrmCCJSO_ClientNotice_PayDetails.ShowGets;
begin
if bSignActive then begin
{ Контроль на пустые строки }
if length(trim(edSum.Text)) = 0 then edSum.Color := clYellow
else edSum.Color := clWindow;
if (length(trim(edPhone.Text)) = 0) and (length(trim(edEMAil.Text)) = 0) then begin
edPhone.Color := clYellow;
edEMAil.Color := clYellow;
end else begin
edPhone.Color := clWindow;
edEMAil.Color := clWindow;
end;
{ Управление доступом к выполнению }
if (
(length(trim(edSum.Text)) = 0)
or
(
(length(trim(edSum.Text)) > 0)
and
(not ufoTryStrToCurr(edSum.Text))
)
)
or (
(length(trim(edPhone.Text)) = 0)
and (length(trim(edEMAil.Text)) = 0)
)
then aRegNotice.Enabled := false
else aRegNotice.Enabled := true;
end;
end;
procedure TfrmCCJSO_ClientNotice_PayDetails.SetRecHeaderItem(Parm : TJSO_OrderHeaderItem); begin RecHeaderItem := Parm; end;
procedure TfrmCCJSO_ClientNotice_PayDetails.SetRecSession(Parm : TUserSession); begin RecSession := Parm; end;
procedure TfrmCCJSO_ClientNotice_PayDetails.SetSection(Parm : integer); begin Section := Parm; end;
procedure TfrmCCJSO_ClientNotice_PayDetails.aExitExecute(Sender: TObject);
begin
self.Close;
end;
procedure TfrmCCJSO_ClientNotice_PayDetails.aRegNoticeExecute(Sender: TObject);
var
MsgDetails : string;
begin
FSendDone := true;
FActionResult.IErr := 0;
FActionResult.ExecMsg := '';
MsgDetails := '';
if length(edPhone.Text) > 0 then MsgDetails := MsgDetails + 'СМС на телефон' + chr(10);
if length(edEMail.Text) > 0 then MsgDetails := MsgDetails + 'на EMail' + chr(10);
if MessageDLG('Подтвердите отправку реквизитов платежа'+chr(10)+MsgDetails,mtConfirmation,[mbYes,mbNo],0) = mrNo then exit;
try
spPayDetails.Parameters.ParamValues['@USER'] := RecSession.CurrentUser;
spPayDetails.Parameters.ParamValues['@Prefix'] := OrderPrefix;
spPayDetails.Parameters.ParamValues['@Order'] := RecHeaderItem.orderID;
spPayDetails.Parameters.ParamValues['@Pharm'] := 0;
spPayDetails.Parameters.ParamValues['@Cash'] := StrToCurr(edSum.Text);
spPayDetails.Parameters.ParamValues['@Phone'] := trim(edPhone.Text);
spPayDetails.Parameters.ParamValues['@EMail'] := trim(edEMail.Text);
spPayDetails.Parameters.ParamValues['@Details'] := PayDetails;
spPayDetails.ExecProc;
FActionResult.IErr := spPayDetails.Parameters.ParamValues['@RETURN_VALUE'];
if FActionResult.IErr <> 0 then begin
FActionResult.ExecMsg := spPayDetails.Parameters.ParamValues['@SErr'];
ShowMessage(FActionResult.ExecMsg);
end else self.Close;
except
on e:Exception do begin
FActionResult.ExecMsg := e.Message;
ShowMessage(FActionResult.ExecMsg);
end;
end;
end;
procedure TfrmCCJSO_ClientNotice_PayDetails.GetPaymentDetails(
USER : integer;
CODE : string;
Prefix : string;
Order : integer;
Pharm : integer;
FullName : string;
Sum : string;
SignCheck : boolean;
OrderName : string;
var Details : string;
var Check : string
);
var
IErr : integer;
SErr : string;
begin
IErr := 0;
SErr := '';
Details := '';
Check := '';
try
spGetPaymentDetails.Parameters.ParamValues['@USER'] := USER;
spGetPaymentDetails.Parameters.ParamValues['@CODE'] := CODE;
spGetPaymentDetails.Parameters.ParamValues['@Prefix'] := Prefix;
spGetPaymentDetails.Parameters.ParamValues['@Order'] := Order;
spGetPaymentDetails.Parameters.ParamValues['@Pharm'] := Pharm;
spGetPaymentDetails.Parameters.ParamValues['@FullName'] := FullName;
spGetPaymentDetails.Parameters.ParamValues['@Sum'] := Sum;
spGetPaymentDetails.Parameters.ParamValues['@SignCheck'] := SignCheck;
spGetPaymentDetails.Parameters.ParamValues['@OrderName'] := OrderName;
spGetPaymentDetails.ExecProc;
IErr := spGetPaymentDetails.Parameters.ParamValues['@RETURN_VALUE'];
if IErr = 0 then begin
Details := spGetPaymentDetails.Parameters.ParamValues['@Details'];
Check := spGetPaymentDetails.Parameters.ParamValues['@Check'];
end else begin
SErr := spGetPaymentDetails.Parameters.ParamValues['@SErr'];
ShowMessage(SErr);
end;
except
on e:Exception do begin
SErr := e.Message;
IErr := -1;
ShowMessage('Сбой при получении шаблона реквизитов платежа.' + chr(10)+SErr);
end;
end;
end;
procedure TfrmCCJSO_ClientNotice_PayDetails.aChangeExecute(Sender: TObject);
var
NameComponent : string;
TextOld : string;
TextNew : string;
SignTry : boolean;
begin
NameComponent := (Sender as TEdit).Name;
TextOld := (Sender as TEdit).Text;
TextNew := TextOld;
SignTry := false;
if NameComponent = 'edSum' then begin
(Sender as TEdit).Font.Color := clWindowText;
if not ufoTryStrToCurr(TextOld) then begin
{ Выполняем детальный анализ и пытаемся откорректировать точку или запятую }
upoTryStrToCurr(TextNew);
if TextOld <> TextNew then begin
(Sender as TEdit).Text := TextNew;
(Sender as TEdit).SelLength:=0;
(Sender as TEdit).SelLength := length((Sender as TEdit).Text);
end else begin
SignTry := true;
(Sender as TEdit).Font.Color := clRed;
end;
end;
if not SignTry then begin
GetPaymentDetails(
RecSession.CurrentUser,
DM_CCJSO.GetCodeDetailsPrePaymentCourier,
DM_CCJSO.GetPrefNumbOrderApteka911,
RecHeaderItem.orderID,
0,
RecHeaderItem.orderShipName,
edSUM.Text,
false,
RecHeaderItem.orderName,
PayDetails,
NoticeCheck
);
edDetails.Text := PayDetails;
end;
end else if NameComponent = 'edPhone' then begin
{--}
end else if NameComponent = 'edEMail' then begin
{--}
end;
ShowGets;
end;
function TfrmCCJSO_ClientNotice_PayDetails.ShowDialog: TActionResult;
begin
FSendDone := false;
ShowModal;
if not FSendDone then
begin
Result.IErr := -100;
Result.ExecMsg := 'Операция отменена пользователем';
end
else
begin
Result.IErr := FActionResult.IErr;
Result.ExecMsg := FActionResult.ExecMsg;
end;
end;
end.
|
namespace Sugar.Test;
interface
uses
Sugar,
Sugar.Collections,
Sugar.TestFramework;
type
HashSetTest = public class (Testcase)
private
Data: HashSet<String>;
public
method Setup; override;
method &Add;
method Clear;
method Contains;
method &Remove;
method Count;
method Enumerator;
method ForEach;
end;
implementation
method HashSetTest.Setup;
begin
Data := new HashSet<String>;
Data.Add("One");
Data.Add("Two");
Data.Add("Three");
end;
method HashSetTest.&Add;
begin
Assert.CheckBool(true,Data.Add("Four"));
Assert.CheckInt(4, Data.Count);
Assert.CheckBool(true, Data.Contains("Four"));
//no duplicates allowed
Assert.CheckBool(false, Data.Add("Four"));
Assert.CheckInt(4, Data.Count);
Assert.CheckBool(true, Data.Add(nil));
Assert.CheckInt(5, Data.Count);
end;
method HashSetTest.Clear;
begin
Assert.CheckInt(3, Data.Count);
Data.Clear;
Assert.CheckInt(0, Data.Count);
end;
method HashSetTest.Contains;
begin
Assert.CheckBool(true, Data.Contains("One"));
Assert.CheckBool(true, Data.Contains("Two"));
Assert.CheckBool(true, Data.Contains("Three"));
Assert.CheckBool(false, Data.Contains("one"));
Assert.CheckBool(false, Data.Contains(nil));
end;
method HashSetTest.&Remove;
begin
Assert.CheckBool(true, Data.Remove("One"));
Assert.CheckInt(2, Data.Count);
Assert.CheckBool(false, Data.Contains("One"));
Assert.CheckBool(false, Data.Remove("One"));
Assert.CheckBool(false, Data.Remove(nil));
Assert.CheckBool(false, Data.Remove("two"));
Assert.CheckInt(2, Data.Count);
Assert.CheckBool(true, Data.Contains("Two"));
end;
method HashSetTest.Count;
begin
Assert.CheckInt(3, Data.Count);
Assert.CheckBool(true, Data.Remove("One"));
Assert.CheckInt(2, Data.Count);
Data.Clear;
Assert.CheckInt(0, Data.Count);
end;
method HashSetTest.Enumerator;
begin
var Expected: HashSet<String> := new HashSet<String>;
Expected.Add("One");
Expected.Add("Two");
Expected.Add("Three");
var lCount: Integer := 0;
for Item: String in Data do begin
inc(lCount);
Assert.CheckBool(true, Expected.Contains(Item));
end;
Assert.CheckInt(3, lCount);
end;
method HashSetTest.ForEach;
begin
var Expected: HashSet<String> := new HashSet<String>;
Expected.Add("One");
Expected.Add("Two");
Expected.Add("Three");
var lCount: Integer := 0;
Data.ForEach(x -> begin
inc(lCount);
Assert.CheckBool(true, Expected.Contains(x));
end);
Assert.CheckInt(3, lCount);
end;
end. |
unit Forms.SelectState;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, AdvCombo, AdvGlowButton, Modules.Resources,
AdvStyleIF, AdvAppStyler, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async,
FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client;
type
TFrmSelectState = class(TForm)
cbStates: TAdvComboBox;
AdvGlowButton1: TAdvGlowButton;
AdvGlowButton2: TAdvGlowButton;
FormStyler: TAdvFormStyler;
private
{ Private declarations }
procedure InitCombo;
public
{ Public declarations }
function SelectState( ADefault : String ):String;
end;
var
FrmSelectState: TFrmSelectState;
implementation
{$R *.dfm}
uses Modules.Data;
{ TFrmSelectState }
procedure TFrmSelectState.InitCombo;
var
LQuery: TFDQuery;
begin
LQuery := TFDQuery.Create(nil);
try
LQuery.Connection := DBController.Connection;
LQuery.SQL.Text := 'select distinct state from coordinates order by state';
LQuery.Open;
cbStates.Items.Clear;
cbStates.Items.BeginUpdate;
while not LQuery.Eof do
begin
cbStates.Items.Add( LQuery['state'] );
LQuery.Next;
end;
finally
cbStates.Items.EndUpdate;
LQuery.Free;
end;
end;
function TFrmSelectState.SelectState(ADefault: String): String;
begin
InitCombo;
cbStates.ItemIndex := cbStates.Items.IndexOf(ADefault);
if self.ShowModal = mrOK then
begin
Result := self.cbStates.Text;
end
else
begin
Result := '';
end;
end;
end.
|
{------------=ð> Writes a BIG string on the screen <ð=-----------}
Procedure BigWrite(x, y : Word; s : String; Color: Byte);
Var a,b,c : Word;
Begin
Bar(x,y,x+length(s)*16,y+16,0);
a:=0;
Repeat
a:=a+1;
For i:=0 to 7 Do
Begin
For j:=0 to 7 Do
If Fonts^[Ord(s[a]),i,j]>0 Then
BigPixel(((a-1)*16)+x+(i*2),(y+(j*2)),Color);
End;
until a=length(s);
end;
{ ---------===ðð> Gives back the bitmap that the shape uses <ðð==---------- }
Function ShapeMap(Current:Byte):Byte;
Var c:Byte;
i,j:byte;
Begin
For i:=1 to 4 do
For j:=1 to 4 do
If ShapeData^[Current].Data[i,j]>0 then
c:=ShapeData^[Current].Data[i,j];
ShapeMap:=c;
End;
{------------=ð> Writes a string on the screen <ð=-----------}
Procedure WriteText(x, y : Word; s : String; Color: Byte);
Var a,b,c : Word;
Begin
Bar(x,y,x+length(s)*8,y+8,0);
a:=0;
Repeat
a:=a+1;
if ord(s[a])<127 then
For i:=0 to 7 Do
Begin
For j:=0 to 7 Do
If Fonts^[Ord(s[a]),i,j]>0 Then
PutPixel(((a-1)*8)+x+i,y+j,Color);
End;
Until a=length(s);
End;
{ --===ðð> Chooses the next shape acoording to what you've selected <ðð===--}
Function ChooseNextShape:Byte;
Function Ratio(R:Byte):Byte;
Begin
Ratio:=Random(R)+1;
End;
Begin
Case Options[1] of
0:ChooseNextShape:=Random(Normal);
3:ChooseNextShape:=Normal+Random(Deluxe-Normal);
8:ChooseNextShape:=Deluxe+Random(Crazy-Deluxe);
1:
Case ratio(4) of
1..3:ChooseNextShape:=Random(Normal);
4:ChooseNextShape:=Normal+Random(Deluxe-Normal);
End;
2:
Case ratio(10) of
1..6:ChooseNextShape:=Random(Normal);
7..9:ChooseNextShape:=Normal+Random(Deluxe-Normal);
10:ChooseNextShape:=Deluxe+Random(Crazy-Deluxe);
End;
5:
Case ratio(7) of
1..6:ChooseNextShape:=Random(Normal);
7:ChooseNextShape:=Deluxe+Random(Crazy-Deluxe);
End;
4:
Case ratio(4) of
1..3:ChooseNextShape:=Normal+Random(Deluxe-Normal);
4:ChooseNextShape:=Deluxe+Random(Crazy-Deluxe);
End;
6:
Case ratio(3) of
1:ChooseNextShape:=Random(Normal);
2:ChooseNextShape:=Normal+Random(Deluxe-Normal);
3:ChooseNextShape:=Deluxe+Random(Crazy-Deluxe);
End;
7:
Case ratio(6) of
1:ChooseNextShape:=Random(Normal);
2..3:ChooseNextShape:=Normal+Random(Deluxe-Normal);
4..6:ChooseNextShape:=Deluxe+Random(Crazy-Deluxe);
End;
End;
End;
{-----------------=ð> Saves the bios fonts <ð=-------------------}
Procedure Init_Fonts;
Var ad,c,k:word;
ch:byte;
Begin
New(Fonts);
For c:=0 to 126 do
Begin
ad := $fa6e + (c * 8); { Calc address of character image in ROM }
For i := 0 to 7 Do
Begin
ch := mem[$f000 : ad + i]; { Get a byte of the image }
j:=1;
k:=0;
Repeat
If (j and ch=j) then Fonts^[c,7-k,i]:=round(i*4.5)+185
else Fonts^[c,7-k,i]:=0;
{ j:=j shl 1;}
asm
shl j,1
end;
k:=k+1;
Until k=8;
End;
End;
End;
{ ----------------===ðð> Clears the keyboard buffer <ðð===----------------- }
Procedure ClearBuffer;
Begin
MemW[$0000:$041C] := MemW[$0000:$041A]; { flush keyboard buffer }
End;
Procedure WriteLevel;
Var s:String;
Begin
str(level,s);
BigWrite(12,20,s,87);
End;
Procedure WriteScore;
Var s:String;
Begin
str(score,s);
WriteText(1,60,s,1);
End;
Procedure WriteGoal;
Var s:String;
Begin
str(Goal,s);
WriteText(15,90,s,1);
End;
{ ----------------===ðð> Puts a bitmap on the screen <ðð===---------------- }
Procedure PutBitMap(Num:byte; x,y:Word);
Var i,j : Byte;
Begin
For i:=1 to Size do
For j:=1 to Size do
if num<>0 then PutPixel(x+j,y+i,BitMap^[2,i,j]) else
PutPixel(x+j,y+i,BitMap^[0,i,j]);
End;
{ ------===ðð> Puts random dots on screen for more Pleasure <ðð===--------- }
Procedure Init_Dots;
Var i,j,d:Byte;
Begin
For i:=MaxYPit-1 downto MaxYPit-Options[5] do
For j:=1 to MaxXPit div 2 do
Begin
d:=random(MaxXPit-1)+1;
Pit^[d,i]:={Random(MaxBitMaps)+1}1;
PutBitMap(Pit^[d,i],StX+(d*Size)+size,Sty+(i*Size)-Size);
End;
End;
{ ----------------===ðð> Draws the Shape On Screen <ðð===------------------ }
Procedure DrawShape(Current,x,y,mode:Byte);
Var a,b:Byte;
Begin
{ For i:=1 to 4 do
For j:=1 to 4 do
If ShapeData[Current].Data[i,j]>0 then
Begin
Pit[x+i-1,y+j-1]:=Mode;
PutBitMap(Mode,StX+((x*Size)+(i*Size)),Sty+(y*Size)+(j*size)-(2*Size));
End;}
If mode>0 then
Begin
For i:=1 to 4 do
For j:=1 to 4 do
If ShapeData^[Current].Data[i,j]>0 then
Begin
Pit^[x+i-1,y+j-1]:=Mode;
PutBitMap(Mode,StX+((x*Size)+(i*Size)),Sty+(y*Size)+(j*size)-(2*Size));
End;
End
Else
Begin
For i:=1 to 4 do
For j:=1 to 4 do
If ShapeData^[Current].Data[i,j]>0 then
Pit^[x+i-1,y+j-1]:=Mode;
For a:=1 to 4 do
For b:=1 to 4 do
If shapedata^[current].data[a,b]>0 then
For i:=0 to Size-1 do
For j:=1 to Size do
PutPixel((StX+((x*Size)+(a*Size))+i+1),(Sty+(y*Size)+(b*size)-(2*Size))+j,
bg^[((x*Size)+(a*Size))+i-14,((y*Size)+(b*size)-(2*Size))+j-1]);
End;
End;
{ ------------===ðð> Writes the next shape on screen <ðð===---------------- }
Procedure WriteNextShape(Next:Byte);
Var i,j:Byte;
Begin
If Options[2]=1 Then
For i:=1 to 4 do
For j:=1 to 4 do
Begin
PutBitMap(0,275+(i*Size),45+(j*Size));
If ShapeData^[Next].Data[i,j]>0 then
PutBitMap(ShapeData^[Next].Data[i,j],275+(i*Size),45+(j*Size));
End;
End;
Procedure CheckHighScores;
var highscoresfile:File of HighS;
filescores:array[1..10] of HighS;
TempString:String;
i:byte;
InTopTen:Byte;
Ch:Char;
Begin
Bar(0,0,319,199,0);
InTopTen:=0;
Assign(highscoresfile,'High.Scr');
{$I-}
Reset(highscoresfile);
{$I+}
If ioresult=0 then
For i:=10 downto 1 do
Begin
read(highscoresfile,filescores[i]);
If filescores[i].score<=PlayerScore.score then InTopTen:=i;
End
Else
For i:=1 to 10 do
Begin
With filescores[i] do
Begin
Name:='Empty';
Score:=0;
StartLevel:=0; EndLevel:=0;
ShapeForm:=0;
End;
InTopTen:=1;
End;
if (intopten<10) and (intopten>0) then
For i:=10 downto intopten+1 do
filescores[i]:=filescores[i-1];
If InTopTen>0 then
Begin
setrgb(1,16,12,8);
setrgb(2,32,24,16);
setrgb(3,48,36,24);
setrgb(4,63,48,32);
setrgb(5,12,8,16);
setrgb(6,24,16,32);
setrgb(7,36,24,48);
setrgb(8,48,32,63);
Font15('You are in the top ten',50,10,0,1,2,3,4,$A000);
Font15('Enter your name',80,40,0,1,2,3,4,$A000);
i:=1;
playerscore.name:=' ';
Repeat
Ch:=readkey;
If ch=#8 then if i>1 then
begin
dec(i);
Font15(playerscore.name,100,80,1,0,0,0,0,$A000);
playerscore.name[i]:=' ';
playerscore.name[0]:=chr(i);
Font15(playerscore.name,100,80,1,5,6,7,8,$A000);
end
else else
if (ch<>#13) and (i<11) then
begin
playerscore.name[i]:=ch;
playerscore.name[0]:=chr(i);
Font15(PlayerScore.name,100,80,1,5,6,7,8,$A000);
inc(i);
end;
Until Ch=#13;
filescores[InTopTen]:=PlayerScore;
End;
Bar(0,0,319,199,0);
rewrite(highscoresfile);
for i:=10 downto 1 do write(highscoresfile,filescores[i]);
Close(highscoresfile);
Font01('Name',10,10,100,$A000);
Font01('Score',100,10,100,$A000);
Font01('Start',165,0,100,$A000);
Font01('Level',165,10,100,$A000);
Font01('End',212,0,100,$A000);
Font01('Level',212,10,100,$A000);
Font01('Shape',262,0,100,$A000);
Font01('Form',262,10,100,$A000);
for i:=1 to 10 do
begin
{ WriteText(10,i*16+10,filescores[i].name,1);
str(filescores[i].score,tempstring);
WriteText(100,i*16+10,tempstring,1);
str(filescores[i].startlevel,tempstring);
WriteText(180,i*16+10,tempstring,1);
str(filescores[i].endlevel,tempstring);
WriteText(220,i*16+10,tempstring,1);
str(filescores[i].shapeform,tempstring);
WriteText(270,i*16+10,tempstring,1); }
str(i,tempstring);
Font01(tempstring,0,i*16+10,3,$A000);
Font01(filescores[i].name,15,i*16+10,1,$A000);
str(filescores[i].score,tempstring);
Font01(tempstring,100,i*16+10,1,$A000);
str(filescores[i].startlevel,tempstring);
Font01(tempstring,180,i*16+10,1,$A000);
str(filescores[i].endlevel,tempstring);
Font01(tempstring,220,i*16+10,1,$A000);
str(filescores[i].shapeform,tempstring);
Font01(tempstring,270,i*16+10,1,$A000);
end;
ch:=readkey;
End;
Function Menu:Byte;
var ch:char;
Item:Byte;
r,g,b:Byte;
Procedure Scale;
var r2,g2,b2:Byte;
original:Array[0..2,0..2] of byte;
Begin
Getrgb(item*3-2,r,g,b);
original[0,0]:=r; original[0,1]:=g; original[0,2]:=b;
Getrgb(item*3-1,r,g,b);
original[1,0]:=r; original[1,1]:=g; original[1,2]:=b;
GetRgb(item*3,r,g,b);
original[2,0]:=r; original[2,1]:=g; original[2,2]:=b;
ch:=' ';
Repeat
ScanRay;
delay(50);
GetRgb(item*3-1,r2,g2,b2);
SetRgb(item*3-1,r,g,b);
getRgb(item*3-2,r,g,b);
ScanRay;
delay(50);
Setrgb(item*3-2,r2,g2,b2);
setrgb(item*3,r,g,b);
getrgb(item*3,r,g,b);
ScanRay;
delay(50);
If keypressed then ch:=readkey;
Until (Ch=#13) or (Ch=#72) or (Ch=#80);
SetRgb(item*3-2,original[0,0],original[0,1],original[0,2]);
SetRgb(item*3-1,original[1,0],original[1,1],original[1,2]);
SetRgb(item*3,original[2,0],original[2,1],original[2,2]);
End;
Begin
GetRgb(7,r,g,b);
SetRgb(1,r,g,b);
SetRgb(4,r,g,b);
SetRgb(10,r,g,b);
SetRgb(13,r,g,b);
GetRgb(8,r,g,b);
SetRgb(2,r,g,b);
SetRgb(5,r,g,b);
SetRgb(11,r,g,b);
SetRgb(14,r,g,b);
GetRgb(15,r,g,b);
SetRgb(3,r,g,b);
SetRgb(6,r,g,b);
SetRgb(9,r,g,b);
SetRgb(12,r,g,b);
Item:=1;
Font11('New Game',40,10,1,2,3,0,$A000);
Font11('Options',45,45,4,5,6,0,$A000);
Font11('Top Ten',52,80,7,8,9,0,$A000);
Font11('Credits',45,115,10,11,12,0,$A000);
Font11('Quit',90,150,13,14,15,0,$A000);
Repeat
Scale;
Case ord(ch) of
80: Begin Inc(Item); if item>5 then item:=1; End;
72: Begin Dec(Item); If item<1 then item:=5; End;
end;
ClearBuffer;
Until ch=#13;
Menu:=Item;
End;
|
program Project1;
uses Math;
var x, sum, next: real;
continue, precision, k: integer;
begin
repeat
writeln('Enter the value of x: ');
readln(x);
writeln('Enter the precision of calculations: ');
readln(precision);
k:=1;
sum:=0;
repeat
next:= Power((-1)*x, k)/(Power(2, k)*k);
writeln('The value of the Next Term:'); //checking
writeln(next); //checking
writeln;//for comfort testing
sum:= sum+next;
writeln('The value of the sum together with this Next Term:'); //checking
writeln(sum); //checking
writeln;//for comfort testing
k:=k+1;
writeln('Counter: ', k); //checking
until (abs(next) < Power(0.1, precision+1));
writeln('Result: ', sum:3:precision);
writeln('Continue? If YES enter 1.');
readln(continue);
writeln;//for comfort testing
writeln;//for comfort testing
until(continue<>1);
end.
{Test1: x=1, sum = -0.40546510810816438197801311546434913657199042346249419761
В WolframAlfa вбить: sum[((-1)^n)/((2^n)*n)]
Test2: x=2 sum=-0.69314718055994530941723212145817656807550013436025525412
В WolframAlfa вбить: sum[((-2)^n)/((2^n)*n)]}
|
unit mrLookUpQuery;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
DB, DBTables, PowerADOQuery, ADODb, uSqlFunctions, uSystemTypes,
uStringFunctions;
type
TComboField = record
FieldName: String;
FieldValue: Variant;
end;
TComboFields = array of TComboField;
TClickButtonEvent = function (Sender : TPowerADOQuery;
ClickedButton : TBtnCommandType;
var PosID1, PosID2 : String) : Boolean of object;
TmrLookupQuery = class(TPowerADOQuery)
private
{ Private declarations }
FquFreeSQL : TADOQuery;
FListField, FLookUpField,
FSecondSQL, FCodeField, FSecondWildCard : String;
FSecondFieldType : TFieldType;
FOnClickButton : TClickButtonEvent;
MySpcWhereClause, MyFltWhereClause : String;
FLookUpFieldSearch, FCodeFieldSearch : Boolean;
function GetWhereClause(FFilterFields, FFilterValues : TStringList) : String;
function PutFltWhere(StrWhere, FltWhereClause,
SpcWhereClause : String;
MostraDesativado : TDesativadoState;
MostraHidden : THiddenState) : String;
procedure SaveOriginalSQL;
protected
{ Protected declarations }
public
{ Public declarations }
FOnBeforeOpenGrid : TNotifyEvent; {# Antes de abrir o grid }
IsFirst : Boolean;
ListValue, LookUpValue, CodeValue : String;
OriginalSQL : String; // Guarda o SQL original de procura
function CallLookUpForm(IsAddNew : Boolean) : Boolean;
procedure UpdateValues;
procedure ResetValues;
function LocateFirst(Value : String; IsListFiltered, IsLocate : Boolean;
FFilterFields, FFilterValues : TStringList;
FilterSugest : Boolean;
SpcWhereClause : String;
FilterEqual : Boolean;
MostraDesativado : TDesativadoState;
MostraHidden : THiddenState) : Boolean;
function LocateLast(IsListFiltered : Boolean;
FFilterFields, FFilterValues : TStringList;
FilterSugest : Boolean;
SpcWhereClause : String;
MostraDesativado : TDesativadoState;
MostraHidden : THiddenState) : Boolean;
function LocateNext (Value : String; IsListFiltered : Boolean;
nRowMove : integer;
FFilterFields, FFilterValues : TStringList;
FilterSugest : Boolean;
SpcWhereClause : String;
MostraDesativado : TDesativadoState;
MostraHidden : THiddenState) : Boolean;
function LocatePrior(Value : String; IsListFiltered : Boolean;
nRowMove : integer;
FFilterFields, FFilterValues : TStringList;
FilterSugest : Boolean;
SpcWhereClause : String;
MostraDesativado : TDesativadoState;
MostraHidden : THiddenState) : Boolean;
function DescLookUpField(Value : String;
IsLookUpField : Boolean;
FFilterFields, FFilterValues : TStringList;
FilterSugest : Boolean;
SpcWhereClause : String;
MostraDesativado : TDesativadoState;
MostraHidden : THiddenState) : Boolean;
constructor Create( AOwner: TComponent ); override;
published
{ Published declarations }
property SecondFieldType : TFieldType read FSecondFieldType write FSecondFieldType;
property SecondSQL : String read FSecondSQL write FSecondSQL;
property ListField : String read FListField write FListField;
property CodeField : String read FCodeField write FCodeField;
property CodeFieldSearch : Boolean read FCodeFieldSearch write FCodeFieldSearch default True;
property LookUpField : String read FLookUpField write FLookUpField;
property LookUpFieldSearch : Boolean read FLookUpFieldSearch write FLookUpFieldSearch default True;
property quFreeSQL : TADOQuery read FquFreeSQL write FquFreeSQL;
property SecondWildCard : String read FSecondWildCard write FSecondWildCard;
// Eventos
property OnClickButton : TClickButtonEvent read FOnClickButton write FOnClickButton;
property OnBeforeOpenGrid : TNotifyEvent read FOnBeforeOpenGrid write FOnBeforeOpenGrid;
end;
procedure Register;
implementation
uses xBase, uDataBaseFunctions;
const
MAX_ROWS = 200;
constructor TmrLookupQuery.Create( AOwner: TComponent );
begin
inherited Create( AOwner );
IsFirst := True;
FSecondSQL := '';
MySpcWhereClause := '';
MyFltWhereClause := '';
FSecondFieldType := ftString;
FSecondWildCard := '';
FLookUpFieldSearch := True;
FCodeFieldSearch := True;
ResetValues;
end;
procedure TmrLookupQuery.SaveOriginalSQL;
begin
if IsFirst then
begin
IsFirst := False;
OriginalSQL := CommandText;
end;
end;
function TmrLookupQuery.LocateFirst(Value : String; IsListFiltered, IsLocate : Boolean;
FFilterFields, FFilterValues : TStringList;
FilterSugest : Boolean;
SpcWhereClause : String;
FilterEqual : Boolean;
MostraDesativado : TDesativadoState;
MostraHidden : THiddenState) : Boolean;
var
NewSQL, WhereString : String;
MyValue, FltWhereClause, OldSQL : String;
OldPos : TBookMarkStr;
lFound : Boolean;
begin
SaveOriginalSQL;
MyValue := FixStrPlic(Value);
lFound := False;
if FilterSugest then
FltWhereClause := ''
else
FltWhereClause := GetWhereClause(FFilterFields, FFilterValues);
if (FltWhereClause <> MyFltWhereClause) or (SpcWhereClause <> MySpcWhereClause) then
begin
MyFltWhereClause := FltWhereClause;
MySpcWhereClause := FltWhereClause;
end
else
begin
if Active and ( (not IsListFiltered) or IsLocate) then
begin
// Tenta procurar em memoria
try
lFound := Locate(FListField, MyValue, [loPartialKey, loCaseInsensitive]);
except
on exception do
Result := False;
end;
end;
end;
// tenta procurar dando requery
if not lFound then
begin
try
DisableControls;
// Guarda antigo SQL
OldSQL := CommandText;
OldPos := BookMark;
if IsListFiltered then
begin
if FilterEqual then
{TESTE}
if FilterEqual or EOF then
WhereString := FListField + ' >= ' + Chr(39) + MyValue + Chr(39)
else
{/TESTE}
WhereString := FListField + ' > ' + Chr(39) + MyValue + Chr(39);
NewSQL := ChangeWhereClause(OriginalSQL, WhereString, False);
NewSQL := PutFltWhere(NewSQL, FltWhereClause, SpcWhereClause, MostraDesativado, MostraHidden);
if Active then Close;
CommandText := NewSQL;
Open;
RecordCount; // Forca trazer todo o recordset
lFound := not (Eof and Bof);
// Controle de quando se posicionar no maior que esta sendo procurado.
if FilterEqual then
begin
{TESTE
Locate(FListField, MyValue, [loPartialKey, loCaseInsensitive]);
{/TESTE}
lFound := lFound and ( UpperCase(LeftStr(Trim(FieldByName(FListField).AsString), Length(Value))) = UpperCase(Trim(Value)) )
{TESTEand (Value <> ''){/TESTE};
// Forca a continuar no mesmo lugar, quando filtrar o item e nao puder acha-lo
if not lFound then
begin
// nao achou, deve se manter no mesmo lugar que estava antes
if Active then Close;
CommandText := OldSQL;
Open;
RecordCount; // Forca trazer todo o recordset
BookMark := OldPos;
end;
end;
end
else
begin
if not Active then
begin
NewSQL := PutFltWhere(OriginalSQL, FltWhereClause, SpcWhereClause, MostraDesativado, MostraHidden);
if Active then Close;
CommandText := NewSQL;
Open;
RecordCount; // Forca trazer todo o recordset
lFound := not (Eof and Bof);
// Se nao esta no modo de IsListFiltered e existe itens no query deve dar locate
if lFound then
begin
try
lFound := Locate(FListField, MyValue, [loPartialKey, loCaseInsensitive]);
except
on exception do
Result := False;
end;
end;
end;
if MyValue = '' then
begin
// vai para o primeiro
First;
if not (Eof and Bof) then
lFound := True;
end;
end;
finally
EnableControls;
end;
end;
Result := lFound;
// Guarda os valores retornados
if lFound then
UpdateValues
else
ResetValues;
end;
function TmrLookupQuery.LocateNext(Value : String; IsListFiltered : Boolean;
nRowMove : integer;
FFilterFields, FFilterValues : TStringList;
FilterSugest : Boolean;
SpcWhereClause : String;
MostraDesativado : TDesativadoState;
MostraHidden : THiddenState) : Boolean;
var
lChange : Boolean;
OldPos : TBookMarkStr;
begin
lChange := False;
if Active then
begin
// Tenta procurar em memoria
OldPos := BookMark;
MoveBy(nRowMove);
lChange := (OldPos <> BookMark);
end;
if not lChange then
lChange := LocateFirst(Value, IsListFiltered, False,
FFilterFields, FFilterValues, FilterSugest,
SpcWhereClause, False, MostraDesativado, MostraHidden);
Result := lChange;
end;
function TmrLookupQuery.LocatePrior(Value : String; IsListFiltered : Boolean;
nRowMove : integer;
FFilterFields, FFilterValues : TStringList;
FilterSugest : Boolean;
SpcWhereClause : String;
MostraDesativado : TDesativadoState;
MostraHidden : THiddenState) : Boolean;
var
OldPos : TBookMarkStr;
lChange : Boolean;
NewSQL, WhereString, FltWhereClause, MyValue : String;
MySQLStatement : TSQlStatement;
begin
lChange := False;
if not Active then
LocateFirst(Value, IsListFiltered, False,
FFilterFields, FFilterValues, FilterSugest,
SpcWhereClause, True, MostraDesativado, MostraHidden);
// Tenta procurar em memoria
OldPos := BookMark;
MoveBy(-nRowMove);
lChange := (OldPos <> BookMark);
if not lChange and IsListFiltered then
begin
// Tenta procurar dando varios requeries
MyValue := FixStrPlic(Value);
if FilterSugest then
FltWhereClause := ''
else
FltWhereClause := GetWhereClause(FFilterFields, FFilterValues);
try
DisableControls;
MySQLStatement := UnMountSQL(OriginalSQL);
MySQLStatement[ST_ORDER] := GetFieldAlias(FListField, OriginalSQL) + FListField + ' DESC';
NewSQL := MountSQL(MySQLStatement);
NewSQL := PutFltWhere(NewSQL, FltWhereClause, SpcWhereClause, MostraDesativado, MostraHidden);
{TESTE}
if BOF then
WhereString := FListField + ' <= ' + Chr(39) + MyValue + Chr(39)
else
{/TESTE}
WhereString := FListField + ' < ' + Chr(39) + MyValue + Chr(39);
NewSQL := ChangeWhereClause(NewSQL, WhereString, False);
if Active then Close;
CommandText := NewSQL;
Open;
lChange := not (Eof and Bof);
if lChange then
begin
MoveBy(MAX_ROWS-50);
WhereString := FListField + ' >= ' + Chr(39) + Trim(FieldByName(FListField).AsString) + Chr(39);
NewSQL := ChangeWhereClause(OriginalSQL, WhereString, False);
NewSQL := PutFltWhere(NewSQL, FltWhereClause, SpcWhereClause, MostraDesativado, MostraHidden);
if Active then Close;
CommandText := NewSQL;
Open;
RecordCount;
Locate(FListField, Trim(Value), [loPartialKey, loCaseInsensitive]);
MoveBy(-nRowMove);
end;
finally
EnableControls;
end;
end;
Result := lChange;
end;
function TmrLookupQuery.LocateLast(IsListFiltered : Boolean;
FFilterFields, FFilterValues : TStringList;
FilterSugest : Boolean;
SpcWhereClause : String;
MostraDesativado : TDesativadoState;
MostraHidden : THiddenState) : Boolean;
var
MySQLStatement : TSQlStatement;
FltWhereClause, NewSQL : String;
begin
if not IsListFiltered then
begin
Result := True;
if not Active then
LocateFirst('', IsListFiltered, False,
FFilterFields, FFilterValues, FilterSugest,
SpcWhereClause, True, MostraDesativado, MostraHidden);
Last;
end
else
begin
// Descobre o ultimo da Lista
with FquFreeSQL do
begin
try
DisableControls;
if Active then Close;
if FilterSugest then
FltWhereClause := ''
else
FltWhereClause := GetWhereClause(FFilterFields, FFilterValues);
MySQLStatement := UnMountSQL(OriginalSQL);
MySQLStatement[ST_SELECT] := ' MAX( ' + FListField + ' ) ';
MySQLStatement[ST_ORDER] := '';
NewSQL := MountSQL(MySQLStatement);
NewSQL := PutFltWhere(NewSQL, FltWhereClause, SpcWhereClause, MostraDesativado, MostraHidden);
if Active then Close;
//CommandText := NewSQL;
SQL.Text := NewSQL;
Open;
Result := not (Eof and Bof);
if Result then
LocatePrior(Fields[0].AsString, IsListFiltered, 0,
FFilterFields, FFilterValues,
FilterSugest, SpcWhereClause, MostraDesativado, MostraHidden);
Close;
finally
EnableControls;
end;
end;
end;
end;
function TmrLookupQuery.DescLookUpField(Value : String;
IsLookUpField : Boolean;
FFilterFields, FFilterValues : TStringList;
FilterSugest : Boolean;
SpcWhereClause : String;
MostraDesativado : TDesativadoState;
MostraHidden : THiddenState): Boolean;
var
NewSQL, WhereString, FltWhereClause : String;
FoundSecond, FoundFirst : Boolean;
MyField, MyValue : String;
begin
FoundSecond := False;
FoundFirst := False;
MyValue := FixStrPlic(Value);
if IsLookUpField then
begin
MyField := FLookUpField;
MostraDesativado := STD_AMBOSDESATIVADO;
MostraHidden := STD_AMBOSHIDDEN;
end
else
MyField := FCodeField;
SaveOriginalSQL;
if FilterSugest then
FltWhereClause := ''
else
FltWhereClause := GetWhereClause(FFilterFields, FFilterValues);
// Testa se value e vazio
if MyValue = '' then
begin
ResetValues;
// Se nao existe nada digitado forca a trcoa para nulo
Result := True;
Exit;
end;
// Inicia procura no secondSQl se existir
if FSecondSQL <> '' then
begin
try
DisableControls;
// Teste se e necesario realizar a Query
if TestFieldQuery(FSecondFieldType, MyValue) then
begin
NewSQL := Format(FSecondSQL, [ConvTypeSQLValue(FSecondFieldType, MyValue+FSecondWildCard)]);
NewSQL := PutFltWhere(NewSQL, FltWhereClause, SpcWhereClause, MostraDesativado, MostraHidden);
if Active then Close;
CommandText := NewSQL;
try
Open;
FoundSecond := not (Eof and Bof);
except
FoundSecond := False;
end;
end
else
begin
FoundSecond := False;
end;
if FoundSecond then
UpdateValues
else
ResetValues;
Result := FoundSecond;
Close;
EnableControls;
except
on exception do
begin
EnableControls;
ResetValues;
FoundSecond := False;
end;
end;
end;
if not FoundSecond then
begin
// Testa se deve fazer a procura pelo CodeField
if IsLookUpField then
begin
{if not FLookUpFieldSearch then
begin
ResetValues;
Result := False;
Exit;
end
}
end
else
begin
if not FCodeFieldSearch then
begin
ResetValues;
Result := False;
Exit;
end;
end;
// Procura o LookUpField
try
DisableControls;
// Teste se e necesario realizar a Query
if TestFieldQuery(FieldByName(MyField).DataType, MyValue) then
begin
WhereString := MyField + ' = ' +
ConvSQLValue(FieldByName(MyField), MyValue);
NewSQL := ChangeWhereClause(OriginalSQL, WhereString, False);
NewSQL := PutFltWhere(NewSQL, FltWhereClause, SpcWhereClause, MostraDesativado, MostraHidden);
if Active then Close;
CommandText := NewSQL;
try
Open;
FoundFirst := not (Eof and Bof);
except
FoundFirst := False;
end;
end
else
begin
FoundFirst := False
end;
if FoundFirst then
UpdateValues
else
ResetValues;
Result := FoundFirst;
// ( Trim(UpperCase(LookUpValue)) = Trim(UpperCase(Value)) );
Close;
EnableControls;
except
on exception do
begin
ResetValues;
EnableControls;
end;
end;
end;
end;
function TmrLookupQuery.PutFltWhere(StrWhere, FltWhereClause,
SpcWhereClause : String;
MostraDesativado : TDesativadoState;
MostraHidden : THiddenState) : String;
begin
Result := strWhere;
if FltWhereClause <> '' then
Result := ChangeWhereClause(Result, FltWhereClause, False);
if SpcWhereClause <> '' then
Result := ChangeWhereClause(Result, SpcWhereClause, False);
case MostraDesativado of
STD_NAODESATIVADO : Result := ChangeWhereClause(Result, 'DESATIVADO = 0', False);
STD_DESATIVADO : Result := ChangeWhereClause(Result, 'DESATIVADO = 1', False);
end;
case MostraHidden of
STD_NAOHIDDEN : Result := ChangeWhereClause(Result, 'HIDDEN = 0', False);
STD_HIDDEN : Result := ChangeWhereClause(Result, 'HIDDEN = 1', False);
end;
end;
procedure TmrLookupQuery.UpdateValues;
begin
ListValue := FieldByName(FListField).AsString;
LookUpValue := FieldByName(FLookUpField).AsString;
CodeValue := FieldByName(FCodeField).AsString;
end;
procedure TmrLookupQuery.ResetValues;
begin
ListValue := '';
LookUpValue := '';
CodeValue := '';
end;
function TmrLookupQuery.CallLookUpForm(IsAddNew : Boolean): Boolean;
var
Ret : Boolean;
PosID1, PosID2, WhereString, NewSQL : String;
begin
SaveOriginalSQL;
Ret := False;
if Assigned(OnClickButton) then
begin
if IsAddNew then
Ret := FOnClickButton(Self, btInc, PosID1, PosID2)
else
Ret := FOnClickButton(Self, btAlt, PosID1, PosID2);
if Ret then
begin
try
DisableControls;
Close;
WhereString := FLookUpField + ' = ' + ConvSQLValue(FieldByName(FLookUpField), PosID1);
NewSQL := ChangeWhereClause(OriginalSQL, WhereString, False);
if Active then Close;
CommandText := NewSQL;
Open;
UpdateValues;
finally
EnableControls;
end;
end;
Result := Ret;
end;
end;
function TmrLookupQuery.GetWhereClause(FFilterFields, FFilterValues : TStringList) : String;
var
i : integer;
begin
Result := '';
for i := 0 to FFilterFields.Count - 1 do
begin
Result := Result + ' ( ' + FFilterFields[i] + ' = ' + FFilterValues[i] + ' ) ';
if i < FFilterFields.Count - 1 then
Result := Result + ' AND '
end;
end;
{
function TmrLookupQuery.LocatePrior(Value : String; FFilterFields, FFilterValues : TStringList;
FilterSugest : Boolean;
SpcWhereClause : String) : Boolean;
var
NewSQL, WhereString : String;
MyValue, FltWhereClause : String;
lFound : Boolean;
begin
SaveOriginalSQL;
MyValue := FixStrPlic(Value);
lFound := False;
if FilterSugest then
FltWhereClause := ''
else
FltWhereClause := GetWhereClause(FFilterFields, FFilterValues);
// tenta procurar dando requery
try
DisableControls;
if IsListFiltered then
begin
if FilterWithLike then
WhereString := FListField + ' like ' + Chr(39) + MyValue + '%' + Chr(39)
else
WhereString := FListField + ' > ' + Chr(39) + MyValue + Chr(39);
NewSQL := ChangeWhereClause(OriginalSQL, WhereString, False);
NewSQL := PutFltWhere(NewSQL, FltWhereClause, SpcWhereClause);
end
else
begin
NewSQL := PutFltWhere(OriginalSQL, FltWhereClause, SpcWhereClause);
end;
if Active then Close;
CommandText := NewSQL;
Open;
RecordCount; // Forca trazere todo o recordset
lFound := not (Eof and Bof);
finally
EnableControls;
end;
end;
Result := lFound;
// Guarda os valores retornados
if lFound then
UpdateValues
else
ResetValues;
end;
}
procedure Register;
begin
RegisterComponents('MainRetail', [TmrLookupQuery]);
end;
end.
|
unit TestUTemplateFcxController;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, DB, DBXJSON, UCondominioController, ConexaoBD, Generics.Collections,
UController, Classes, UTemplateFcxVO, SysUtils, DBClient, DBXCommon, SQLExpr,
UTemplateFcxController;
type
// Test methods for class TTemplateFcxController
TestTTemplateFcxController = class(TTestCase)
strict private
FTemplateFcxController: TTemplateFcxController;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestConsultarPorId;
procedure TestConsultaPorIdNaoEncontrado;
end;
implementation
procedure TestTTemplateFcxController.SetUp;
begin
FTemplateFcxController := TTemplateFcxController.Create;
end;
procedure TestTTemplateFcxController.TearDown;
begin
FTemplateFcxController.Free;
FTemplateFcxController := nil;
end;
procedure TestTTemplateFcxController.TestConsultaPorIdNaoEncontrado;
var
ReturnValue: TTemplateFcxVO;
begin
ReturnValue := FTemplateFcxController.ConsultarPorId(70);
if(returnvalue = nil) then
check(true,'Template Fcx pesquisado com sucesso!')
else
check(false,'Fcx não encontrado!');
end;
procedure TestTTemplateFcxController.TestConsultarPorId;
var
ReturnValue: TTemplateFcxVO;
begin
ReturnValue := FTemplateFcxController.ConsultarPorId(70);
if(returnvalue = nil) then
check(true,'Template Fcx pesquisado com sucesso!')
else
check(false,'Fcx não encontrado!');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTTemplateFcxController.Suite);
end.
|
unit UDebugLog;
(*====================================================================
Functions for sending debug messages to external debug receiver
======================================================================*)
interface
procedure Log(const FormatStr: String; const Args: array of const);
implementation
uses SysUtils,
{$ifdef mswindows}
WinTypes,WinProcs,
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
Messages;
var
g_hLogWindow: HWND;
g_bLoggingEnabled: boolean;
g_bLogFileAreadyChecked: boolean;
//---------------------------------------------------------------------
function FileLoggingEnabled: boolean;
begin
Result := g_bLoggingEnabled;
if g_bLogFileAreadyChecked then exit;
// find if the LOG FILE application is running
///g_hLogWindow := FindWindow('TFormDebugLog'#0, 'Debug LOG Messages Receiver'#0);
g_bLoggingEnabled := g_hLogWindow <> 0;
g_bLogFileAreadyChecked := true; // do not initialize twice
if not g_bLoggingEnabled then Result := false else Result := true;
end;
//---------------------------------------------------------------------
procedure Log(const FormatStr: String; const Args: array of const);
var
Msg: AnsiString;
{$ifdef mswindows}
CopyData: COPYDATASTRUCT;
{$endif}
begin
if not FileLoggingEnabled then exit;
Msg := Format (FormatStr, Args);
{$ifdef mswindows}
CopyData.dwData := 0;
CopyData.cbData := Length(Msg)+1;
CopyData.lpData := PChar(Msg);
SendMessage(g_hLogWindow, WM_COPYDATA, 0, integer(@CopyData));
{$else}
{$endif}
end;
//-------------------------------------------------------------------
begin
g_hLogWindow := 0;
g_bLoggingEnabled := false;
g_bLogFileAreadyChecked := false;
end.
|
unit PersenDanNilai;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls,
System.DateUtils;
type
TPersenDanNilai = class(TPanel)
private
FEPersen,
FENilai: TEdit;
FLabel: TLabel;
FPersen,
FValue: Double;
FNilaiDasar: Double;
FPemisahRibuan,
FPemisahPecahan: Char;
FonChange,
FOnPersenChange,
FOnNilaiDasarChanged,
FOnNilaiChange: TNotifyEvent;
FOnEnabled: TNotifyEvent;
procedure OnPersenChanged(Sender: TObject);
procedure OnValueChanged(Sender: TObject);
procedure OnNilaiDasarChanged(Sender: TObject);
procedure OnPersenExit(Sender: TObject);
procedure OnNilaiExit(Sender: TObject);
function GetPersen: DOuble;
function GetNilai: Double;
procedure SetPersen(Value: DOuble);
procedure SetNilai(Value: DOuble);
procedure SetNilaiDasar(Value: Double);
procedure SetPemisahRibuan(value: Char);
procedure SetPemisahPecahan(value: Char);
procedure DoNilaiDasarChange;
procedure DoPersenChange;
procedure DoNilaiChange;
procedure DoChange;
protected
function _FloatToStr(v: Double): String;
function _StrToFloat(v: String): Double;
procedure SetEnabled(Value: Boolean); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Change;
published
property Persen: Double read GetPersen write SetPersen;
property Nilai: Double read GetNilai write SetNilai;
property NilaiDasar: Double read FNilaiDasar write SetNilaiDasar;
property PemisahRibuan: char read FPemisahRibuan write SetPemisahRibuan;
property PemisahPecahan: char read FPemisahPecahan write SetPemisahPecahan;
property OnNilaiChange: TNotifyEvent read FOnNilaiChange write FOnNilaiChange;
property OnPersenChange: TNotifyEvent read FOnPersenChange write FOnPersenChange;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
TOnDualDateChange = procedure (Sender: TObject; DateBegin, DateEnd: TDateTime; JmlHari: Integer) of object;
TJangkaWaktu = class(TPanel)
private
FDP1,
FDP2: TDateTimePicker;
FDPJumlah: TEdit;
FDPLabel,
FDPLabel2: TLabel;
FTanggalAwal: TDateTime;
FTanggalAkhir: TDateTime;
FOnChange: TOnDualDateChange;
procedure onDateChanged(Sender: TObject);
procedure SetTanggalAwal(const Value: TDateTime);
procedure SetTanggalAkhir(const Value: TDateTime);
function GetJumlahHari: Integer;
procedure DoDateChange;
protected
procedure CreateWindowHandle(const Params: TCreateParams); override;
procedure CreateWnd; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AfterConstruction; override;
property JumlahHari: Integer read GetJumlahHari;
published
property TanggalAwal: TDateTime read FTanggalAwal write SetTanggalAwal;
property TanggalAkhir: TDateTime read FTanggalAkhir write SetTanggalAkhir;
property OnDateChange: TOnDualDateChange read FOnChange write FOnChange;
end;
procedure Register;
implementation
{ TPersenDanNilai }
procedure TPersenDanNilai.Change;
begin
DoChange;
end;
constructor TPersenDanNilai.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
self.ShowCaption := false;
self.Caption := '';
self.Height := 21;
self.Constraints.MaxHeight := 21;
self.Caption := '';
self.BevelOuter := bvNone;
self.Width := 230;
FEPersen := TEdit.Create(self);
FEPersen.Parent := self;
FEPersen.Align := alLeft;
FEPersen.Alignment := taRightJustify;
FEPersen.Width := 65;
FLabel := TLabel.Create(self);
FLabel.Align := alLeft;
FLabel.Left := FEPersen.Width;
FLabel.AlignWithMargins := true;
FLabel.Parent := self;
with FLabel.Margins do
begin
Left := 0;
top := 4;
Right := 0;
Bottom := 0;
end;
FLabel.Caption := ' % = Rp ';
FENilai := TEdit.Create(self);
FENilai.Parent := self;
FENilai.Color := clYellow;
FENilai.Alignment := taRightJustify;
FENilai.Align := alClient;
FENilai.Left := FLabel.Width;
FEPersen.OnChange := OnPersenChanged;
FENilai.OnChange := OnValueChanged;
FEPersen.OnExit := OnPersenExit;
FENilai.OnExit := OnNilaiExit;
self.PemisahPecahan := ',';
self.PemisahRibuan := '.';
SetNilaiDasar(0);
SetPersen(0);
// SetNilai(0);
end;
destructor TPersenDanNilai.Destroy;
begin
FEPersen.Free;
FENilai.Free;
FLabel.Free;
inherited Destroy;
end;
procedure TPersenDanNilai.DoChange;
begin
if Assigned(FonChange) then
FonChange(Self);
end;
procedure TPersenDanNilai.DoNilaiChange;
begin
if Assigned(FOnNilaiChange) then
FOnNilaiChange(self);
DoChange;
end;
procedure TPersenDanNilai.DoNilaiDasarChange;
begin
DoChange;
end;
procedure TPersenDanNilai.DoPersenChange;
begin
if Assigned(FOnPersenChange) then
FOnPersenChange(self);
DoChange;
end;
function TPersenDanNilai.GetNilai: Double;
begin
result := _StrToFloat(FENilai.Text);
end;
function TPersenDanNilai.GetPersen: DOuble;
begin
result := _StrToFloat(FEPersen.Text);
end;
procedure TPersenDanNilai.OnNilaiDasarChanged(Sender: TObject);
begin
DoNilaiDasarChange;
end;
procedure TPersenDanNilai.OnNilaiExit(Sender: TObject);
var
v: Double;
begin
FENilai.OnChange := nil;
try
v := _StrToFloat(FENilai.Text);
FENilai.Text := _FloatToStr(v);
finally
FENilai.OnChange := OnValueChanged;
end;
end;
procedure TPersenDanNilai.OnPersenChanged(Sender: TObject);
var
_persen: Double;
begin
FENilai.OnChange := nil;
try
_persen := _StrToFloat(FEPersen.Text);
if NilaiDasar <> 0 then
FENilai.Text := _FloatToStr(_persen/100*NilaiDasar)
else
FENilai.Text := _FloatToStr(0);
finally
FENilai.OnChange := OnValueChanged;
end;
DoPersenChange;
end;
procedure TPersenDanNilai.OnPersenExit(Sender: TObject);
var
v: Double;
begin
FEPersen.OnChange := nil;
try
v := _StrToFloat(FEPersen.Text);
FEPersen.Text := _FloatToStr(v);
finally
FEPersen.OnChange := OnPersenChanged;
end;
end;
procedure TPersenDanNilai.OnValueChanged(Sender: TObject);
var
_nilai: Double;
begin
FEPersen.OnChange := nil;
try
_nilai:= _StrToFloat(FENilai.Text);
if NilaiDasar <> 0 then
FEPersen.Text := _FloatToStr(_nilai/NilaiDasar*100)
else
FEPersen.Text := _FloatToStr(0);
finally
FEPersen.OnChange := OnPersenChanged;
end;
DoNilaiChange;
end;
procedure TPersenDanNilai.SetEnabled(Value: Boolean);
begin
inherited SetEnabled(value);
FEPersen.ReadOnly := Value;
FENilai.ReadOnly:= Value;
FEPersen.Font.Color := clBlack;
FENilai.Font.Color := clBlack;
if Value then
begin
FEPersen.Color := clWindow;
FENilai.Color := clYellow;
end
else
begin
FEPersen.Color := clSilver;
FENilai.Color := $007777BB;
end;
end;
procedure TPersenDanNilai.SetNilai(Value: DOuble);
begin
FEPersen.OnChange := nil;
try
FENilai.Text := _FloatToStr(Value);
finally
FEPersen.OnChange := OnValueChanged;
end;
OnValueChanged(FENilai);
end;
procedure TPersenDanNilai.SetNilaiDasar(Value: Double);
var
f: TNotifyEvent;
begin
if FNilaiDasar = value then
exit;
FNilaiDasar := Value;
FENilai.OnChange := nil;
FEPersen.OnChange := nil;
try
// if _StrToFloat(FEPersen.Text) = 0 then
// FEPersen.Text := _FloatToStr(Value);
finally
FENilai.OnChange := OnValueChanged;
FEPersen.OnChange := OnPersenChanged;
FENilai.OnChange := OnNilaiDasarChanged;
end;
// OnNilaiDasarChanged(self);
OnPersenChanged(FEPersen);
end;
procedure TPersenDanNilai.SetPemisahPecahan(value: Char);
begin
if FPemisahPecahan = value then
exit;
FPemisahPecahan := value;
OnPersenChanged(FEPersen);
end;
procedure TPersenDanNilai.SetPemisahRibuan(value: Char);
begin
if FPemisahRibuan = value then
exit;
FPemisahRibuan := value;
OnPersenChanged(FEPersen);
end;
procedure TPersenDanNilai.SetPersen(Value: DOuble);
begin
FENilai.OnChange := nil;
try
FEPersen.Text := _FloatToStr(Value);
finally
FENilai.OnChange := OnValueChanged;
end;
OnPersenChanged(FEPersen);
end;
function TPersenDanNilai._FloatToStr(v: Double): String;
var
d,t: CHar;
begin
d := FormatSettings.DecimalSeparator;
t:= FormatSettings.ThousandSeparator;
try
FormatSettings.DecimalSeparator := PemisahPecahan;
FormatSettings.ThousandSeparator := PemisahRibuan;
// Result := FloatToStr(v, FormatSettings);
Result := FormatFloat('#,#0.####;-#,#0.####;0', v, FormatSettings);
finally
FormatSettings.DecimalSeparator := d;
FormatSettings.ThousandSeparator := t;
end;
end;
function TPersenDanNilai._StrToFloat(v: String): Double;
var
s: String;
i: integer;
d,t: CHar;
begin
d := FormatSettings.DecimalSeparator;
t:= FormatSettings.ThousandSeparator;
try
s := v;
for i := length(s) downto 1 do
if not (s[i] in ['0'..'9',PemisahPecahan]) then
delete(s,i,1);
FormatSettings.DecimalSeparator := PemisahPecahan;
FormatSettings.ThousandSeparator := PemisahRibuan;
Result := StrToFloatDef(s, 0, FormatSettings);
finally
FormatSettings.DecimalSeparator := d;
FormatSettings.ThousandSeparator := t;
end;
end;
procedure Register;
begin
RegisterComponents('Andan TeknoMedia', [
TPersenDanNilai,
TJangkaWaktu
]);
end;
{ TJangkaWaktu }
procedure TJangkaWaktu.AfterConstruction;
begin
inherited;
end;
constructor TJangkaWaktu.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
procedure TJangkaWaktu.CreateWindowHandle(const Params: TCreateParams);
begin
inherited;
end;
procedure TJangkaWaktu.CreateWnd;
begin
inherited;
Height := 21;
with Constraints do
begin
MaxHeight := 21;
MinWidth := 270;
end;
Caption := '';
BevelOuter := bvNone;
Width := 270;
FDP1 := TDateTimePicker.Create(self);
FDP1.Parent := self;
FDP1.Width := 85;
FDP1.Format := 'dd/MM/yyyy';
FDP1.Align := alLeft;
FDP1.Kind := TDateTimeKind.dtkDate;
FDPLabel := TLabel.Create(self);
FDPLabel.Parent := self;
FDPLabel.Align := alLeft;
FDPLabel.Left := FDP1.Width;
FDPLabel.AlignWithMargins := true;
with FDPLabel.Margins do
begin
Left := 0;
top := 4;
Right := 0;
Bottom := 0;
end;
FDPLabel.Caption := ' s.d. ';
FDP2 := TDateTimePicker.Create(self);
FDP2.Parent := self;
FDP2.Left := FDPLabel.BoundsRect.Right;
FDP2.Width := 85;
FDP2.Align := alLeft;
FDP2.Format := 'dd/MM/yyyy';
FDP2.Kind := TDateTimeKind.dtkDate;
FDPLabel2 := TLabel.Create(self);
FDPLabel2.Parent := self;
FDPLabel2.Align := alLeft;
FDPLabel2.Left := FDP2.BoundsRect.Right;
FDPLabel2.AlignWithMargins := true;
with FDPLabel2.Margins do
begin
Left := 0;
top := 4;
Right := 0;
Bottom := 0;
end;
FDPLabel2.Caption := ' = ';
FDPJumlah := TEdit.Create(self);
FDPJumlah.Parent := self;
FDPJumlah.Alignment := taRightJustify;
FDPJumlah.Left := FDPLabel2.BoundsRect.Right;
FDPJumlah.Width := 40;
FDPJumlah.Align := alClient;
FDPJumlah.ReadOnly := true;
FDPJumlah.Color := clSilver;
FDPJumlah.tabstop := false;
FDP1.OnChange := onDateChanged;
FDP2.OnChange := onDateChanged;
TanggalAwal := Date;
TanggalAkhir := Date;
end;
destructor TJangkaWaktu.Destroy;
begin
FDP1.Free;
FDP2.Free;
FDPJumlah.free;
FDPLabel.Free;
FDPLabel2.Free;
inherited Destroy;
end;
procedure TJangkaWaktu.DoDateChange;
begin
if Assigned(FOnChange) then
FOnChange(self, FDP1.Date, FDP2.Date, GetJumlahHari);
end;
function TJangkaWaktu.GetJumlahHari: Integer;
begin
Result := 1 + DaysBetween(FDP1.Date, FDP2.Date);
end;
procedure TJangkaWaktu.onDateChanged(Sender: TObject);
begin
FDP1.OnChange := nil;
FDP2.OnChange := nil;
try
if FDP1.Date> FDP2.Date then
FDP2.Date := FDP1.Date;
FDPJumlah.Text := IntToStr(GetJumlahHari)+' Hari';
finally
FDP1.OnChange := onDateChanged;
FDP2.OnChange := onDateChanged;
end;
DoDateChange;
end;
procedure TJangkaWaktu.SetTanggalAkhir(const Value: TDateTime);
begin
if FTanggalAkhir = Value then exit;
FTanggalAkhir := Value;
FDP2.Date := Value;
onDateChanged(FDP2);
end;
procedure TJangkaWaktu.SetTanggalAwal(const Value: TDateTime);
begin
if FTanggalAwal = Value then exit;
FTanggalAwal := Value;
FDP1.Date := Value;
onDateChanged(FDP1);
end;
end.
|
unit TestMREWSynch;
{ This unit contains the test cases for the multi read aexclusive write synhronizer,
as alwasy this is work in progress, any problems you can demostrate or features you wish to see
are welcome, above all else I welcome test cases that will help me debug your problems. }
interface
uses
TestFramework,
sysutils,
{$IFDEF MSWINDOWS}
windows,
{$ENDIF}
uEvsSyncObjs, uEvsThreadTestUtils;
type
// Test methods for class TEvsSemaSynchronizer
TTestEvsMREWSynchronizer = class(TTestCase)
strict private
FSynchronizer: TEvsMREWS;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestStartRead;
procedure TestStartWrite;
procedure TestEndRead;
procedure TestEndWrite;
end;
implementation
procedure TTestEvsMREWSynchronizer.SetUp;
begin
FSynchronizer := TEvsMREWS.Create;
end;
procedure TTestEvsMREWSynchronizer.TearDown;
begin
FSynchronizer.Free;
FSynchronizer := nil;
end;
procedure TTestEvsMREWSynchronizer.TestStartRead;
var
vLock:Array[0..10] of Pointer;
begin
CheckTrue(FSynchronizer.TryAcquireRead(10), 'already locked?');
vLock[0] := ReadLock(FSynchronizer);
CheckEquals(StatusAcquired, LockStatus(vlock[0]),'This is multiple read and failed on the 2nd?');
CheckTrue(FSynchronizer.TryAcquireRead(10), 'Failed of the 3rd?');
vLock[1] := ReadLock(FSynchronizer);
CheckEquals(StatusAcquired, LockStatus(vlock[1]),'This is multiple read and failed on the 4Th?');
CheckTrue(FSynchronizer.TryAcquireRead(10), 'Failed of the 5th?');
vLock[2] := ReadLock(FSynchronizer);
CheckEquals(StatusAcquired, LockStatus(vlock[2]),'This is multiple read and failed on the 6th?');
CheckTrue(FSynchronizer.TryAcquireRead(10), 'Failed of the 7th?');
vLock[3] := ReadLock(FSynchronizer);
CheckEquals(StatusAcquired, LockStatus(vlock[3]),'This is multiple read and failed on the 8th?');
//reentrant on read? check the read count.
CheckEquals(8,FSynchronizer.ReadCounter,'erm 8 succesfull read locks and only '+IntToStr(FSynchronizer.ReadCounter)+' counted?');
//-------------------------------------
FSynchronizer.ReleaseRead; //1
CheckEquals(7, FSynchronizer.ReadCounter, '1st lock did not release?');
ReleaseLock(vLock[0]); //2
CheckEquals(6, FSynchronizer.ReadCounter, '2nd lock did not release?');
FSynchronizer.ReleaseRead; //3
CheckEquals(5, FSynchronizer.ReadCounter, '3rd lock did not release?');
ReleaseLock(vLock[1]); //4
CheckEquals(4, FSynchronizer.ReadCounter, '4th lock did not release?');
FSynchronizer.ReleaseRead; //5
CheckEquals(3, FSynchronizer.ReadCounter, '5th lock did not release?');
ReleaseLock(vLock[2]); //6
CheckEquals(2, FSynchronizer.ReadCounter, '6th lock did not release?');
FSynchronizer.ReleaseRead; //7
CheckEquals(1, FSynchronizer.ReadCounter, '7th lock did not release?');
ReleaseLock(vLock[3]); //8
CheckEquals(0, FSynchronizer.ReadCounter, '8th lock did not release?');
end;
procedure TTestEvsMREWSynchronizer.TestStartWrite;
var
vLock: Pointer;
begin
Fail('You need some write acquisition tests');
CheckTrue(FSynchronizer.TryAcquireWrite(10), 'First write lock and it failed?');
vLock := WriteLock(FSynchronizer);
CheckEquals(StatusFailed, LockStatus(vLock), 'Well, this suppose to be single writer.');
ReleaseLock(vLock);
FSynchronizer.ReleaseWrite;
end;
procedure TTestEvsMREWSynchronizer.TestEndRead;
var
vLock:Array[0..10] of Pointer;
begin
fail('Make sure that the release of read locks is in order');
FSynchronizer.AcquireWrite;
vLock[0] := WriteLock(FSynchronizer);
FSynchronizer.AcquireWrite;
vLock[1] := WriteLock(FSynchronizer);
FSynchronizer.AcquireWrite;
vLock[2] := WriteLock(FSynchronizer);
FSynchronizer.AcquireWrite;
vLock[3] := WriteLock(FSynchronizer);
//-------------------------------------
FSynchronizer.ReleaseWrite;
ReleaseLock(vLock[0]);
FSynchronizer.ReleaseWrite;
ReleaseLock(vLock[1]);
FSynchronizer.ReleaseWrite;
ReleaseLock(vLock[2]);
FSynchronizer.ReleaseWrite;
ReleaseLock(vLock[3]);
end;
procedure TTestEvsMREWSynchronizer.TestEndWrite;
var
vLock:Array[0..10] of Pointer;
begin
Fail('Make sure the Release of write locks is in order');
FSynchronizer.AcquireWrite;
vLock[0] := WriteLock(FSynchronizer);
FSynchronizer.AcquireWrite;
vLock[1] := WriteLock(FSynchronizer);
FSynchronizer.AcquireWrite;
vLock[2] := WriteLock(FSynchronizer);
FSynchronizer.AcquireWrite;
vLock[3] := WriteLock(FSynchronizer);
//-------------------------------------
FSynchronizer.ReleaseWrite;
ReleaseLock(vLock[0]);
FSynchronizer.ReleaseWrite;
ReleaseLock(vLock[1]);
FSynchronizer.ReleaseWrite;
ReleaseLock(vLock[2]);
FSynchronizer.ReleaseWrite;
ReleaseLock(vLock[3]);
end;
initialization
// Register any test cases with the test runner
RegisterTest(TTestEvsMREWSynchronizer.Suite);
end.
|
(*
Category: SWAG Title: FILE HANDLING ROUTINES
Original name: 0095.PAS
Description: Create plain ASCII data from binary file
Author: DIRK SCHWARZMANN
Date: 11-29-96 08:17
*)
PROGRAM BinToInclude; (* Version 1.0, 12.10.96 *)
(*
Author: Dirk "Rob!" Schwarzmann, (w) September 1996, Germany
E-Mail: rob@rbg.informatik.th-darmstadt.de
WWW : http://www.student.informatik.th-darmstadt.de/~rob/
About this small piece of code:
This program reads any type of file and writes it back as a include
file (text type for TurboPascal) where every byte read is written as
its value. So, if a .com file is read and byte #x is an @, BinToInclude
will write the number 64 for it.
In addition, it creates a header so that you can use the new data
file directly as an include file in your own programs. The binary file
is stored as an array of byte and you can write it back to disc by using
the small procedure shown below.
What's it all good for?
You can hold binary files of _any_ type in your own program and do not
have to take care that an external data (or program) file is truly there.
If it does not exist, you simple write it! No panic, if a user has
accidently deleted a file or a file is corrupted!
Using this program:
You have to specify at least one command line parameter giving the file
you like to read. If no second parameter (the target file name) is given,
BinToInclude will create an .INC file with the path and name similar to
the source file. Otherwise the given name is used.
Note that BinToInclude does very little error checking! It does not
assure that the source file exists nor does it prevent you from over-
writing existing include files! But because this program is only a small
quick-hacked utility for programmers, I guess this not very important.
If you include a file in your program, keep in mind that you may get
problems if you include files bigger than 64k!
There a some constants you can only change in this source code;
- COMPRESSED is a boolean flag and toggles the writing of data between
the well-to-read format:
001, 020, 234, 089, ...
and the space-saving format:
1, 20, 234, 89, ...
If you want to save even the blanks between comma and numbers, get
your editor, mark the whole area and do a search + replace. It's
that simple! It would have taken much more effort to do this here.
- ArrayFormat
Specify the number of rows the array definition should use. 65 - 70
rows are a good choice to keep a good readability.
- Ext2_Str
Here you can change the default data file suffix - but I think there
is no need to do so.
To write the data back in a file, you only need this small routine:
PROCEDURE WriteArrayToFile(TargetName:FILE OF BYTE);
VAR
i : LONGINT;
BEGIN
Assign(TargetFile,TargetName);
Rewrite(TargetFile);
FOR i := 1 TO BinFileSize DO
Write(TargetFile,BinFile[i]);
Close(TargetFile);
END;
That's all!
For any suggestions, please feel free to email me!
*)
USES DOS;
CONST
Compressed : BOOLEAN = FALSE; (* False: 010, 009, 255, ...
True: 10, 9, 255,...
If you want to have 10,9,255 you can
remove the blanks with search +
replace
in your editor! *)
ArrayFormat : BYTE = 65; (* The width of the array definition area
(number of rows) *)
Ext2_Str : ExtStr = '.INC'; (* The default suffix for the file to write *)
(* These lines are the header of the written include-file. After the
variable "BinFileSize =" the program will insert the file length
(=array length) and after the last header line the data will follow. *)
IncHeader1 : STRING = 'CONST';
IncHeader2 : STRING = ' BinFileSize = ';
IncHeader3 : STRING = ' BinFile : ARRAY[1..BinFileSize] OF BYTE = (';
VAR (* main.BinToInclude *)
SourceFile : FILE OF BYTE;
TargetFile : TEXT;
SourceName : STRING[128];
TargetName : STRING[128];
SourceByte : BYTE;
TgtByteStr : STRING[5];
TargetStr : STRING[80];
Dir_Str : DirStr;
Name_Str : NameStr;
Ext_Str : ExtStr;
BEGIN (* main.BinToInclude *)
(* The case statement is only to parse the command line: *)
CASE ParamCount OF
1: BEGIN
FSplit(FExpand(ParamStr(1)),Dir_Str,Name_Str,Ext_Str);
SourceName := Dir_Str + Name_Str + Ext_Str;
TargetName := Dir_Str + Name_Str + Ext2_Str;
END; (* case ParamCount of 1 *)
2: BEGIN
FSplit(FExpand(ParamStr(1)),Dir_Str,Name_Str,Ext_Str);
SourceName := Dir_Str + Name_Str + Ext_Str;
FSplit(FExpand(ParamStr(2)),Dir_Str,Name_Str,Ext_Str);
TargetName := Dir_Str + Name_Str + Ext_Str;
END; (* case ParamCount of 2 *)
ELSE (* case ParamCount *)
WriteLn('Please specify at least one Parameter as the source file.');
Write('If the optional second one is not given, <Source file>.INC is');
WriteLn(' assumed.');
Halt(1);
END; (* case ParamCount *)
Assign(SourceFile,SourceName);
Reset(SourceFile);
Assign(TargetFile,TargetName);
Rewrite(TargetFile);
WriteLn(TargetFile,IncHeader1);
WriteLn(TargetFile,IncHeader2,FileSize(SourceFile),';');
WriteLn(TargetFile,IncHeader3);
TargetStr := ' '; (* Set the left margin *)
Inc(ArrayFormat,2); (* This needs an explanation: because of the 4 blanks
on the left margin, we should add 4 to ArrayFormat.
But as every number will be followed by a comma
and a blank, we have to decrease it by 2. -> add 2 *)
WHILE NOT EoF(SourceFile) DO BEGIN
Read(SourceFile,SourceByte);
Str(Ord(SourceByte),TgtByteStr);
IF NOT Compressed THEN
TgtByteStr := Copy('00',1,3-Length(TgtByteStr)) + TgtByteStr;
IF (Length(TargetStr) + Length(TgtByteStr) > ArrayFormat) THEN BEGIN
WriteLn(TargetFile,TargetStr); (* Flush the string *)
TargetStr := ' ';
END;
TargetStr := TargetStr + TgtByteStr + ', ';
END; (* while not EoF(SourceFile) *)
(* Flush the buffer string but don't write the last comma: *)
Write(TargetFile,Copy(TargetStr,1,Length(TargetStr)-2));
WriteLn(TargetFile,');'); (* Close the array definition with the ")"
*)
Close(TargetFile);
Close(SourceFile);
END. (* main.BinToInclude *)
|
unit OTFEFreeOTFE_DriverHashAPI;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, // Required for DWORD
FreeOTFEDriverConsts,
DriverAPI; // Required for DEVICE_FREEOTFE_ROOT
// HASH DRIVER RELATED
const
MAX_HASH_NAME = 256;
type
// THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!!
// - i.e. it's not a "packed record"
PHASH = ^THASH;
THASH = record
HashGUID: TGUID;
Title: array [0..MAX_HASH_NAME-1] of Ansichar;
VersionID: DWORD;
Length: DWORD; // In bits
BlockSize: DWORD; // In bits
end;
// THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!!
// - i.e. it's not a "packed record"
PDIOC_HASH_IDENTIFYDRIVER = ^TDIOC_HASH_IDENTIFYDRIVER;
TDIOC_HASH_IDENTIFYDRIVER = record
DriverGUID: TGUID;
Title: array [0..MAX_HASH_NAME-1] of Ansichar;
VersionID: DWORD;
HashCount: DWORD;
end;
// THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!!
// - i.e. it's not a "packed record"
PDIOC_HASH_IDENTIFYSUPPORTED = ^TDIOC_HASH_IDENTIFYSUPPORTED;
TDIOC_HASH_IDENTIFYSUPPORTED = record
BufCount: DWORD;
Hashes: array [0..0] of THASH; // Variable length array of them
end;
// THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!!
// - i.e. it's not a "packed record"
PDIOC_HASH_DATA_IN = ^TDIOC_HASH_DATA_IN;
TDIOC_HASH_DATA_IN = record
HashGUID: TGUID;
DataLength: DWORD; // In bits
Data: array [0..0] of byte; // Variable length
end;
// THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!!
// - i.e. it's not a "packed record"
PDIOC_HASH_DATA_OUT = ^TDIOC_HASH_DATA_OUT;
TDIOC_HASH_DATA_OUT = record
HashLength: DWORD; // In bits
Hash: array [0..0] of byte; // Variable length
end;
const IOCTL_FREEOTFEHASH_IDENTIFYDRIVER =
(((FILE_DEVICE_UNKNOWN) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($800) * $4) OR (METHOD_BUFFERED));
const IOCTL_FREEOTFEHASH_IDENTIFYSUPPORTED =
(((FILE_DEVICE_UNKNOWN) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($801) * $4) OR (METHOD_BUFFERED));
const IOCTL_FREEOTFEHASH_HASHDATA =
(((FILE_DEVICE_UNKNOWN) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($802) * $4) OR (METHOD_BUFFERED));
const
DEVICE_HASH_BASE_NAME = '\FreeOTFEHash';
DEVICE_HASH_DIR_NAME = DEVICE_FREEOTFE_ROOT + '\Hash';
DEVICE_HASH_SYMLINK_DIR_NAME = DEVICE_SYMLINK_FREEOTFE_ROOT;
DEVICE_HASH_SYMLINK_PREFIX = DEVICE_HASH_SYMLINK_DIR_NAME + DEVICE_HASH_BASE_NAME;
implementation
END.
|
unit UDWindowStyle;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, UCrpe32;
type
TCrpeWindowStyleDlg = class(TForm)
pnlWindowStyle: TPanel;
lblWindowTitle: TLabel;
cbSystemMenu: TCheckBox;
cbMinButton: TCheckBox;
cbMaxButton: TCheckBox;
rgBorderStyle: TRadioGroup;
editTitle: TEdit;
cbDisabled: TCheckBox;
btnOk: TButton;
btnCancel: TButton;
btnClear: TButton;
procedure FormShow(Sender: TObject);
procedure UpdateWindowStyle;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnClearClick(Sender: TObject);
procedure cbSystemMenuClick(Sender: TObject);
procedure cbMinButtonClick(Sender: TObject);
procedure cbMaxButtonClick(Sender: TObject);
procedure cbDisabledClick(Sender: TObject);
procedure editTitleChange(Sender: TObject);
procedure rgBorderStyleClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
rSystemMenu : boolean;
rMinButton : boolean;
rMaxButton : boolean;
rBorderStyle : smallint;
rDisabled : boolean;
rTitle : string;
end;
var
CrpeWindowStyleDlg: TCrpeWindowStyleDlg;
bWindowStyle : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeWindowStyleDlg.FormCreate(Sender: TObject);
begin
bWindowStyle := True;
LoadFormPos(Self);
btnOk.Tag := 1;
btnCancel.Tag := 1;
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeWindowStyleDlg.FormShow(Sender: TObject);
begin
{Store current VCL Settings}
rSystemMenu := Cr.WindowStyle.SystemMenu;
rMinButton := Cr.WindowStyle.MinButton;
rMaxButton := Cr.WindowStyle.MaxButton;
rBorderStyle := Ord(Cr.WindowStyle.BorderStyle);
rDisabled := Cr.WindowStyle.Disabled;
rTitle := Cr.WindowStyle.Title;
UpdateWindowStyle;
end;
{------------------------------------------------------------------------------}
{ UpdateWindowStyle }
{------------------------------------------------------------------------------}
procedure TCrpeWindowStyleDlg.UpdateWindowStyle;
begin
cbSystemMenu.Checked := Cr.WindowStyle.SystemMenu;
cbMinButton.Checked := Cr.WindowStyle.MinButton;
cbMaxButton.Checked := Cr.WindowStyle.MaxButton;
rgBorderStyle.ItemIndex := Ord(Cr.WindowStyle.BorderStyle);
cbDisabled.Checked := Cr.WindowStyle.Disabled;
editTitle.Text := Cr.WindowStyle.Title;
{Enable the applicable controls}
cbMinButton.Enabled := True;
cbMaxButton.Enabled := True;
cbSystemMenu.Enabled := True;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeWindowStyleDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TCheckBox then
TCheckBox(Components[i]).Enabled := OnOff;
if Components[i] is TRadioGroup then
TRadioGroup(Components[i]).Enabled := OnOff;
if Components[i] is TEdit then
begin
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ cbSystemMenuClick }
{------------------------------------------------------------------------------}
procedure TCrpeWindowStyleDlg.cbSystemMenuClick(Sender: TObject);
begin
Cr.WindowStyle.SystemMenu := cbSystemMenu.Checked;
end;
{------------------------------------------------------------------------------}
{ cbMinButtonClick }
{------------------------------------------------------------------------------}
procedure TCrpeWindowStyleDlg.cbMinButtonClick(Sender: TObject);
begin
Cr.WindowStyle.MinButton := cbMinButton.Checked;
end;
{------------------------------------------------------------------------------}
{ cbMaxButtonClick }
{------------------------------------------------------------------------------}
procedure TCrpeWindowStyleDlg.cbMaxButtonClick(Sender: TObject);
begin
Cr.WindowStyle.MaxButton := cbMaxButton.Checked;
end;
{------------------------------------------------------------------------------}
{ cbDisabledClick }
{------------------------------------------------------------------------------}
procedure TCrpeWindowStyleDlg.cbDisabledClick(Sender: TObject);
begin
Cr.WindowStyle.Disabled := cbDisabled.Checked;
end;
{------------------------------------------------------------------------------}
{ rgBorderStyleClick }
{------------------------------------------------------------------------------}
procedure TCrpeWindowStyleDlg.rgBorderStyleClick(Sender: TObject);
begin
Cr.WindowStyle.BorderStyle := TCrFormBorderStyle(rgBorderStyle.ItemIndex);
UpdateWindowStyle;
end;
{------------------------------------------------------------------------------}
{ editTitleChange }
{------------------------------------------------------------------------------}
procedure TCrpeWindowStyleDlg.editTitleChange(Sender: TObject);
begin
Cr.WindowStyle.Title := editTitle.Text;
end;
{------------------------------------------------------------------------------}
{ btnClearClick }
{------------------------------------------------------------------------------}
procedure TCrpeWindowStyleDlg.btnClearClick(Sender: TObject);
begin
Cr.WindowStyle.Clear;
UpdateWindowStyle;
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeWindowStyleDlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ btnCancelClick }
{------------------------------------------------------------------------------}
procedure TCrpeWindowStyleDlg.btnCancelClick(Sender: TObject);
begin
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeWindowStyleDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if ModalResult = mrCancel then
begin
{Restore Settings}
Cr.WindowStyle.SystemMenu := rSystemMenu;
Cr.WindowStyle.MinButton := rMinButton;
Cr.WindowStyle.MaxButton := rMaxButton;
Cr.WindowStyle.BorderStyle := TCrFormBorderStyle(rBorderStyle);
Cr.WindowStyle.Disabled := rDisabled;
Cr.WindowStyle.Title := rTitle;
end;
bWindowStyle := False;
Release;
end;
end.
|
unit E_Threads;
//------------------------------------------------------------------------------
// Модуль реализует классы потоков
//------------------------------------------------------------------------------
//
// Поток непрерывной работы - TThreadInfinite
// - вызывает заданную процедуру непрерывно
// Поток запускаемой работы - TThreadActivated
// - вызывает заданную процедуру по требованию (метод Work)
//
// Есть 2 процедуры, вызываемые при работе потока:
// - TThCallbackFunc - собственно процедура работы, вызывается при каждом цикле
// - TThErrorFunc - процедура ошибки, вызывается при возникновении исключительной ситуации (может быть опущена)
// ! обе процедуры вызываются в контексте потока !
//
// !ВАЖНЫЕ ЗАМЕЧАНИЯ!
// 1) классы потоков работают не так, как наследник TThread;
// они не имеют процедуры Terminate(), поэтому вручную завершить выполнение потока
// можно только уничтожив экземпляр класса, т.е. вызвав Free();
// ОДНАКО при возникновении исключительной ситуации поток будет автоматически завершён,
// причём это произойдёт после вызова процедуры TThErrorFunc (если она назначена);
// - ! уничтожать экземпляр класса потока всё равно надо вручную (впрочем, не обязательно делать это немедленно)
//
// 2) потоки не могут быть приостановлены (Suspended)
//
// 3) все вызываемые процедуры TThreadActivated имеют параметр AData;
// его значение каждый раз передаётся при вызове Work, т.е. при запросе на отработку
// этот параметр может быть равен nil;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
SysUtils, Classes, RTLConsts, Windows;
//------------------------------------------------------------------------------
type
//------------------------------------------------------------------------------
//! рабочая процедура потока
//------------------------------------------------------------------------------
TThCallback = procedure(
//! ссылка на данные
const AData: Pointer
);
//------------------------------------------------------------------------------
//! ошибка потока
//------------------------------------------------------------------------------
TThError = procedure(
//! ссылка на данные
const AData: Pointer;
//! ссылка на класс исключения
var AException: Exception;
//! windows ID потока
const AThreadID: TThreadID
);
//------------------------------------------------------------------------------
//! внутренний класс потока непрерывной работы (!не предназначен для использования напрямую!)
//------------------------------------------------------------------------------
TInternalInfiniteThread = class sealed( TThread )
strict private
//! ссылка на процедуру обратного вызова
FCallbackFunc: TThCallback;
//! ссылка на процедуру ошибки
FErrorFunc: TThError;
//! ссылка на данные
FData: Pointer;
protected
//!
procedure Execute(); override;
public
//!
constructor Create(
const ACallbackFunc: TThCallback;
const AErrorFunc: TThError;
const AData: Pointer
);
//!
destructor Destroy(); override;
end;
//------------------------------------------------------------------------------
//! внутренний класс потока запускаемой работы (!не предназначен для использования напрямую!)
//------------------------------------------------------------------------------
TInternalActivatedThread = class sealed( TThread )
strict private
//! ссылка на процедуру обратного вызова
FCallbackFunc: TThCallback;
//! ссылка на процедуру ошибки
FErrorFunc: TThError;
//! ссылка на данные
FData: Pointer;
//! событие прокрутки цикла
FCicleEvent: THandle;
protected
//!
procedure Execute(); override;
public
//! ссылка на данные (для записи)
property DataRef: Pointer write FData;
//!
constructor Create(
const ACallbackFunc: TThCallback;
const AErrorFunc: TThError
);
//!
destructor Destroy(); override;
//! выполнить один цикл
procedure Process();
end;
//------------------------------------------------------------------------------
//! класс потока непрерывной работы
//------------------------------------------------------------------------------
TThreadInfinite = class sealed
strict private
//!
FThread: TInternalInfiniteThread;
public
//!
constructor Create(
const ACallbackFunc: TThCallback;
const AErrorFunc: TThError;
const AData: Pointer
);
//!
destructor Destroy(); override;
//!
function IsTerminated(): Boolean;
end;
//------------------------------------------------------------------------------
//! класс потока запускаемой работы
//------------------------------------------------------------------------------
TThreadActivated = class sealed
strict private
//!
FThread: TInternalActivatedThread;
public
//!
constructor Create(
const ACallbackFunc: TThCallback;
const AErrorFunc: TThError
);
//!
destructor Destroy(); override;
//!
procedure Work(
const AData: Pointer
);
//!
function IsTerminated(): Boolean;
end;
//------------------------------------------------------------------------------
implementation
const
//------------------------------------------------------------------------------
//! сообщения
//------------------------------------------------------------------------------
cTNoWorkProc: string = 'Не назначена рабочая процедура потока';
//------------------------------------------------------------------------------
// TInternalInfiniteThread
//------------------------------------------------------------------------------
constructor TInternalInfiniteThread.Create(
const ACallbackFunc: TThCallback;
const AErrorFunc: TThError;
const AData: Pointer
);
begin
inherited Create( True );
//
if not Assigned( ACallbackFunc )
then raise EThread.CreateResFmt( @SThreadCreateError, [cTNoWorkProc] );
FreeOnTerminate := False;
FCallbackFunc := ACallbackFunc;
FErrorFunc := AErrorFunc;
FData := AData;
end;
destructor TInternalInfiniteThread.Destroy();
begin
inherited Destroy(); // Terminate и WaitFor внутри
end;
procedure TInternalInfiniteThread.Execute();
begin
while not Terminated
do begin
Windows.Sleep( 0 ); // не забываем давать работать другим
try
FCallbackFunc( FData );
except
on Ex: Exception
do begin
if Assigned( FErrorFunc )
then FErrorFunc( FData, Ex, ThreadID );
Terminate();
end;
end;
end;
end;
//------------------------------------------------------------------------------
// TInternalActivatedThread
//------------------------------------------------------------------------------
constructor TInternalActivatedThread.Create(
const ACallbackFunc: TThCallback;
const AErrorFunc: TThError
);
begin
inherited Create( True );
//
if not Assigned( ACallbackFunc )
then raise EThread.CreateResFmt( @SThreadCreateError, [cTNoWorkProc] );
FCicleEvent := CreateEvent( nil, True, False, nil );
if ( FCicleEvent = 0 )
then raise EThread.CreateResFmt( @SThreadCreateError, [SysErrorMessage( GetLastError )] );
FreeOnTerminate := False;
FCallbackFunc := ACallbackFunc;
FErrorFunc := AErrorFunc;
end;
destructor TInternalActivatedThread.Destroy();
begin
Terminate(); // ставим флаг завершения
SetEvent( FCicleEvent ); // запускаем с точки ожидания (если поток не в работе)
WaitFor(); // ожидаем завершения потока
CloseHandle( FCicleEvent ); // освобождаем ресурсы
//
inherited Destroy();
end;
procedure TInternalActivatedThread.Process();
begin
SetEvent( FCicleEvent );
end;
procedure TInternalActivatedThread.Execute();
begin
repeat
if Terminated
then Break;
WaitForSingleObject( FCicleEvent, INFINITE ); // в этой точке мы ждём
if Terminated
then Break;
ResetEvent( FCicleEvent );
try
FCallbackFunc( FData );
except
on Ex: Exception
do begin
if Assigned( FErrorFunc )
then FErrorFunc( FData, Ex, ThreadID );
Terminate();
end;
end;
until False;
end;
//------------------------------------------------------------------------------
// TThreadInfinite
//------------------------------------------------------------------------------
constructor TThreadInfinite.Create(
const ACallbackFunc: TThCallback;
const AErrorFunc: TThError;
const AData: Pointer
);
begin
inherited Create();
//
FThread := TInternalInfiniteThread.Create( ACallbackFunc, AErrorFunc, AData );
FThread.Start(); // автозапуск
end;
destructor TThreadInfinite.Destroy();
begin
FThread.Free();
//
inherited Destroy();
end;
function TThreadInfinite.IsTerminated(): Boolean;
begin
Result := FThread.Terminated;
end;
//------------------------------------------------------------------------------
// TThreadActivated
//------------------------------------------------------------------------------
constructor TThreadActivated.Create(
const ACallbackFunc: TThCallback;
const AErrorFunc: TThError
);
begin
inherited Create();
//
FThread := TInternalActivatedThread.Create( ACallbackFunc, AErrorFunc );
FThread.Start();
end;
destructor TThreadActivated.Destroy();
begin
FThread.Free();
//
inherited Destroy();
end;
procedure TThreadActivated.Work(
const AData: Pointer
);
begin
if FThread.Terminated
then Exit;
FThread.DataRef := AData;
FThread.Process();
end;
function TThreadActivated.IsTerminated(): Boolean;
begin
Result := FThread.Terminated;
end;
end.
|
(*
Category: SWAG Title: SORTING ROUTINES
Original name: 0011.PAS
Description: IMROVSRT.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:57
*)
{
MARK OUELLET
> I code these things this way:
>
> for I := 1 to MAX-1 do
> for J := I+1 to MAX do
> if A[I] < A[J] then
> begin
> ( swap code )
> end
this can be improved even more. By limiting the MAX value on each
successive loop by keeping track of the highest swaped pair.
If on a particular loop, no swap is performed from element MAX-10
onto the end. Then the next loop does not need to go anyhigher than
MAX-11. Remember you are moving the highest value up, if no swap is
performed from MAX-10 on, it means all values above MAX-11 are in order
and all values below MAX-10 are smaller than MAX-10.
}
{$X+}
program MKOSort;
USES
Crt;
Const
MAX = 1000;
var
A : Array[1..MAX] of word;
Loops : word;
procedure Swap(Var A1, A2 : word);
var
Temp : word;
begin
Temp := A1;
A1 := A2;
A2 := Temp;
end;
procedure working;
const
cursor : array[0..3] of char = '\|/-';
CurrentCursor : byte = 1;
Update : word = 0;
begin
update := (update + 1) mod 2500;
if update = 0 then
begin
DirectVideo := False;
write(Cursor[CurrentCursor], #13);
CurrentCursor := ((CurrentCursor + 1) mod 4);
DirectVideo := true;
end;
end;
procedure Bubble;
var
Highest,
Limit, I : word;
NotSwaped : boolean;
begin
Limit := MAX;
Loops := 0;
repeat
I := 1;
Highest := 2;
NotSwaped := true;
repeat
working;
if A[I] > A[I + 1] then
begin
Highest := I;
NotSwaped := False;
Swap(A[I], A[I + 1]);
end;
Inc(I);
until (I = Limit);
Limit := Highest;
Inc(Loops);
until (NotSwaped) or (Limit <= 2);
end;
procedure InitArray;
var
I, J : word;
{Temp : word;}
begin
randomize;
for I := 1 to MAX do
A[I] := I;
for I := MAX - 1 downto 1 do
begin
J := random(I) + 1;
Swap(A[I + 1], A[J]);
end;
end;
procedure Pause;
begin
writeln;
writeln('Press any key to continue...');
while keypressed do
readkey;
while not keypressed do;
readkey;
end;
procedure PrintOut;
var
I : word;
begin
ClrScr;
For I := 1 to MAX do
begin
if WhereY >= 22 then
begin
Pause;
ClrScr;
end;
if (WhereX >= 70) then
Writeln(A[I] : 5)
else
Write(A[I] : 5);
end;
writeln;
Pause;
end;
begin
ClrScr;
InitArray;
PrintOut;
Bubble;
PrintOut;
writeln;
writeln('Took ', Loops, ' Loops to complete');
end.
|
unit NtQuotation;
// Note! This need to be in UTF8
// http://cldr.unicode.org/development/development-process/design-proposals/delimiter-quotation-mark-proposal
interface
uses
Generics.Collections;
type
TQuotationKind =
(
qkAscii, // "..."
qkEnglish, // “...”
qkSwedish, // ”...”
qkGerman, // „...“
qkPolish, // „...”
gkFrench, // «...»
qkDanish, // »...«
qkChinese // 「...」
);
TQuotationFixer = class(TObject)
private
class var FLanguages: TDictionary<String, TQuotationKind>;
procedure Populate;
public
function IsQuote(c: Char): Boolean;
function GetKind(const id: String): TQuotationKind;
function GetStartQuote(kind: TQuotationKind): Char;
function GetEndQuote(kind: TQuotationKind): Char;
function Fix(
const originalLanguage, translatedLanguage, originalText: String;
var translatedText: String): Integer;
end;
var
QuotationFixer: TQuotationFixer;
implementation
uses
NtBase;
type
TQuoteData = record
StartChar: Char;
EndChar: Char;
Languages: array of String;
end;
const
QUOTES_C: array[TQuotationKind] of TQuoteData =
(
// ASCII
(
StartChar: '"';
EndChar: '"';
Languages: []
),
// English
(
StartChar: '“';
EndChar: '”';
Languages:
[
'en', 'ar', 'hy', 'as', 'bn', 'bs', 'my', 'chr', 'zh-Hans', 'zh', 'kw', 'eo', 'fo', 'fil', 'gl', 'haw', 'id', 'ga', 'kl',
'kn', 'kk-Cyrl', 'kk', 'km', 'kok', 'mgh', 'ms', 'ml', 'mt', 'gv', 'mfe', 'nb', 'nus', 'or', 'om', 'ps', 'pt', 'pa-Arab',
'pa-Guru', 'pa', 'sr-Cyrl', 'ii', 'si', 'so', 'ta', 'te', 'th', 'bo', 'ti', 'tr', 'uz-Arab', 'uz-Cyrl', 'uz-Latn', 'uz', 'vi', 'cy',
'af',
'he',
'kea', 'khq', 'ses', 'twq', 'to', 'dje',
'seh', 'sw', 'yo',
'brx', 'gu', 'hi', 'mr', 'ne',
'bem', 'ee', 'ha-Latn', 'ha', 'jmc', 'rof', 'rwk', 'vun',
'asa', 'ebu', 'lg', 'ig', 'kln', 'kam', 'ki', 'ln', 'kde', 'mer', 'naq', 'nd', 'saq', 'sbp', 'ksb', 'dav',
'cgg', 'nyn', 'xog',
'guz',
'teo',
'lu',
'ak', 'bez', 'tzm-Latn', 'tzm', 'nl', 'ko', 'luo', 'vai-Latn', 'vai-Vaii', 'vai', 'zu',
'ur',
'swc', 'mas'
]
),
// Swedish
(
StartChar: '”';
EndChar: '”';
Languages:
[
'sv', 'fi',
'lag',
'rn', 'sn'
]
),
// German
(
StartChar: '„';
EndChar: '“';
Languages:
[
'de', 'cs', 'is',
'bg',
'et', 'lt',
'luy',
'hr',
'sk',
'sq', 'ka', 'mk', 'sr', 'sr-Latn',
'sl'
]
),
// Polish
(
StartChar: '„';
EndChar: '”';
Languages: [
'pl',
'ro',
'ff',
'hu',
'agq',
'nmg'
]
),
// French
(
StartChar: '«';
EndChar: '»';
Languages: [
'fr',
'am', 'fa', 'rm', 'gsw',
'bm', 'ewo', 'dyo', 'kab', 'mg', 'mua',
'ru', 'uk',
'shi-Latn', 'shi-Tfng', 'shi',
'yav',
'dua',
'nn',
'el',
'sg',
'bas',
'ksf',
'rw',
'it-CH',
'az-Cyrl', 'az-Latn', 'az', 'eu', 'br',
'de-CH',
'be',
'pt-PT',
'lv',
//'nb',
'it', 'es', 'ca'
]
),
// Danish
(
StartChar: '»';
EndChar: '«';
Languages: ['da']
),
// Chinese
(
StartChar: '「';
EndChar: '」';
Languages: ['zh-Hant', 'ja']
)
);
function TQuotationFixer.IsQuote(c: Char): Boolean;
var
k: TQuotationKind;
begin
for k := Low(k) to High(k) do
begin
Result := (QUOTES_C[k].StartChar = c) or (QUOTES_C[k].EndChar = c);
if Result then
Exit;
end;
Result := False;
end;
function TQuotationFixer.GetKind(const id: String): TQuotationKind;
function GetValue(const id: String): TQuotationKind;
begin
if FLanguages.ContainsKey(id) then
Result := FLanguages[id]
else
Result := qkAscii;
end;
var
language, script, country, variant: String;
begin
Populate;
Result := GetValue(id);
if Result <> qkAscii then
Exit;
TNtBase.ParseLocaleId(id, language, script, country, variant);
if language = id then
Exit;
if script <> '' then
Result := FLanguages[language + '-' + script];
if Result <> qkAscii then
Exit;
Result := FLanguages[language];
end;
function TQuotationFixer.GetStartQuote(kind: TQuotationKind): Char;
begin
Result := QUOTES_C[kind].StartChar;
end;
function TQuotationFixer.GetEndQuote(kind: TQuotationKind): Char;
begin
Result := QUOTES_C[kind].EndChar;
end;
function TQuotationFixer.Fix(
const originalLanguage, translatedLanguage, originalText: String; //FI:O804
var translatedText: String): Integer; //FI:O804
begin
Result := 0;
end;
procedure TQuotationFixer.Populate;
procedure Process(values: array of String; kind: TQuotationKind);
var
i: Integer;
begin
for i := Low(values) to High(values) do
FLanguages.Add(values[i], kind);
end;
var
k: TQuotationKind;
begin
if FLanguages.Count > 0 then
Exit;
for k := Low(k) to High(k) do
Process(QUOTES_C[k].Languages, k);
end;
initialization
TQuotationFixer.FLanguages := TDictionary<String, TQuotationKind>.Create;
QuotationFixer := TQuotationFixer.Create;
finalization
QuotationFixer.Free;
TQuotationFixer.FLanguages.Free;
end.
|
unit DataModule;
interface
uses
SysUtils, Classes, DB, ADODB, IniFiles;
type
TDM = class(TDataModule)
ADOconn: TADOConnection;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
procedure ADOconnBeforeConnect(Sender: TObject);
private
FQry_Temp:TADOQuery;
{ Private declarations }
Procedure ErrSaveToFile(ErrSQL:TStrings);
public
{ Public declarations }
Procedure QueryWork(SQLStream:String; SelAct:Boolean = True); Overload;
Procedure QueryWork(SQLStream:TStrings; SelAct:Boolean = True); Overload;
procedure QueryWork(SQLStream:String; RunQuery:TADOQuery; SelAct:Boolean = True); Overload;
Property DefQuery:TADOQuery Read FQry_Temp Write FQry_Temp;
end;
var
DM: TDM;
implementation
{$R *.dfm}
{ TDM }
procedure TDM.QueryWork(SQLStream: String; SelAct: Boolean);
begin
with DefQuery do
Begin
if Active then Close;
SQL.Clear;
SQL.Add(SQLStream);
try
if SelAct then Open
else ExecSQL;
except
// ErrSaveToFile(DefQuery.SQL);
end;
end;
end;
procedure TDM.QueryWork(SQLStream: TStrings; SelAct: Boolean);
begin
with DefQuery do
Begin
if Active then Close;
SQL.Clear;
SQL.Assign(SQLStream);
Try
if SelAct then Open
else ExecSQL;
except
//ErrSaveToFile(DefQuery.SQL);
end;
end;
end;
procedure TDM.QueryWork(SQLStream: String; RunQuery: TADOQuery; SelAct: Boolean);
begin
with RunQuery do
Begin
if Active then Close;
SQL.Clear;
SQL.Add(SQLStream);
try
if SelAct then Open
else ExecSQL;
except
//ErrSaveToFile(DefQuery.SQL);
end;
end;
end;
procedure TDM.DataModuleCreate(Sender: TObject);
begin
FQry_Temp := TADOQuery.Create(Nil);
FQry_Temp.Connection := ADOconn;
ADOconn.Open;
end;
procedure TDM.DataModuleDestroy(Sender: TObject);
begin
if FQry_Temp.Active then
FQry_Temp.Close;
FQry_Temp.Free;
end;
procedure TDM.ADOconnBeforeConnect(Sender: TObject);
Var
PassDB:TIniFile;
ConnStr:WideString;
begin
PassDB := TIniFile.Create('.\DBC.CON');
try
ConnStr := Trim(PassDB.ReadString('DataBase','Connection',''));
if ConnStr = '' then ConnStr := PromptDataSource(0,Connstr);
//if ConnStr = '' then Terminate
//else
Begin
ADOconn.ConnectionString := ConnStr;
PassDB.WriteString('DataBase','Connection',ConnStr);//
end;
finally
PassDB.Free;
end;
end;
procedure TDM.ErrSaveToFile(ErrSQL: TStrings);
begin
//ErrSQL.SaveToFile(FormatDateTime('"ErrSQL "YYYY-MM-DD HH:MM:SSS',Now));
end;
end.
|
unit OperationEndUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, FIBQuery, pFIBQuery,
pFIBStoredProc, FIBDatabase, pFIBDatabase,IBase,ZMessages, pFIBErrorHandler,ZProc,
PackageLoad, cxControls, cxContainer, cxEdit, cxLabel, ExtCtrls;
type
TOperationEndForm = class(TForm)
MainDatabase: TpFIBDatabase;
WriteTransaction: TpFIBTransaction;
WorkProc: TpFIBStoredProc;
Panel1: TPanel;
SaveAccountBtn: TcxButton;
RemoveAccountBtn: TcxButton;
UvBtn: TcxButton;
CancelBtn: TcxButton;
Panel2: TPanel;
Label1: TLabel;
procedure SaveAccountBtnClick(Sender: TObject);
procedure RemoveAccountBtnClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure UvBtnClick(Sender: TObject);
private
pIsRollback:boolean;
function ExecuteWorkProc(Commit:Boolean):Boolean;
public
constructor Create(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE;IS_rollback:boolean);reintroduce;
end;
function ShowOperationEndForm(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE;IS_rollback:boolean):Variant;stdcall;
exports ShowOperationEndForm;
implementation
function ShowOperationEndForm(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE;IS_Rollback:boolean):Variant;stdcall;
var
form: TOperationEndForm;
begin
form:=TOperationEndForm.Create(AOwner,DB_HANDLE,IS_rollback);
form.ShowModal;
ShowOperationEndForm:=null;
form.FreeNotification(form);
end;
{$R *.dfm}
{ TOperationEndForm }
constructor TOperationEndForm.Create(AOwner: TComponent;DB_HANDLE: TISC_DB_HANDLE;Is_Rollback:boolean);
var kod_op:variant;
DONT_SAVE_CALC:Variant;
begin
inherited Create(AOwner);
MainDataBase.Handle:=DB_HANDLE;
pIsRollback:=IS_rollback;
if pIsRollback
then begin
Label1.Caption:='УВАГА! ВИ ХОЧЕТЕ ПЕРЕВЕСТИ СИСТЕМУ У ПОПЕРЕДНІЙ ПЕРІОД?'
end
else begin
kod_op:=ValueFieldZSetup(MainDatabase.Handle,'UV_Z_KOD_ACTION');
if kod_op<>null
then begin
if kod_op = 1
then Label1.Caption:='УВАГА! ВИ ХОЧЕТЕ ЗБЕРЕГТИ РОЗРАХУНОК ЗАРОБІТНОЇ ПЛАТИ ТА ПЕРЕВЕСТИ СИСТЕМУ У НАСТУПНИЙ ПЕРІОД?'
else Label1.Caption:='УВАГА! ВИ ХОЧЕТЕ ЗБЕРЕГТИ РОЗРАХУНОК?';
DONT_SAVE_CALC:=NULL;
DONT_SAVE_CALC:=ValueFieldZSetup(MainDatabase.Handle, 'DONT_SAVE_CALC');
if DONT_SAVE_CALC=1
then SaveAccountBtn.Enabled:=false;
end
else Label1.Caption:='УВАГА! ВИ ХОЧЕТЕ ЗБЕРЕГТИ РОЗРАХУНОК?';
end;
if pIsRollback
then begin
SaveAccountBtn.Visible:=False;
UvBtn.Visible:=False;
RemoveAccountBtn.Caption:='Перевести період';
end;
self.Color := Application.MainForm.Color;
end;
function TOperationEndForm.ExecuteWorkProc(Commit:Boolean): Boolean;
begin
if (not WriteTransaction.InTransaction) then WriteTransaction.StartTransaction;
try
WorkProc.ExecProc;
except
on E:Exception do
begin
WriteTransaction.Rollback;
ZShowMessage('Помилка!', PChar(E.Message),mtInformation, [mbOk]);
ExecuteWorkProc:=False;
Exit;
end;
end;
if Commit then WriteTransaction.Commit;
ExecuteWorkProc:=True;
end;
procedure TOperationEndForm.SaveAccountBtnClick(Sender: TObject);
begin
WorkProc.SQL.Text:='EXECUTE PROCEDURE Z_PAYMENT_COUNT_OPERATION_END(''F'')';
if ExecuteWorkProc(True)
then begin
ZShowMessage('Вдале завершення', 'Розрахунок збережений!', mtInformation,[mbOk]);
ZProc.SetBeginAction(MainDataBase.Handle,0);
end;
end;
procedure TOperationEndForm.RemoveAccountBtnClick(Sender: TObject);
begin
if pIsRollback then WorkProc.SQL.Text:='EXECUTE PROCEDURE Z_PAYMENT_COUNT_OPERATION_END(''O'')'
else WorkProc.SQL.Text:='EXECUTE PROCEDURE Z_PAYMENT_COUNT_OPERATION_END(''T'')';
if ExecuteWorkProc(True) then
begin
if not pIsRollback then ZShowMessage('Вдале завершення','Розрахунок вилучено!',mtInformation,[mbOk])
else ZShowMessage('Вдале завершення','Переведення системи завершено!!',mtInformation,[mbOk]);
ZProc.SetBeginAction(MainDataBase.Handle,0);
end;
end;
procedure TOperationEndForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if WriteTransaction.InTransaction then WriteTransaction.Commit;
end;
procedure TOperationEndForm.UvBtnClick(Sender: TObject);
var kodAction:variant;
SumLimit:variant;
begin
kodAction := ValueFieldZSetup(MainDatabase.Handle,'UV_Z_KOD_ACTION');
SumLimit := ValueFieldZSetup(MainDatabase.Handle,'UV_Z_LIMIT');
if VarIsNull(kodAction) then
begin
ZShowMessage('Помилка','Не можливо переформувати!',mtInformation,[mbOk]);
exit;
end;
WorkProc.Sql.Text:='EXECUTE PROCEDURE UV_END_OF_OPERATION(''F'',''F'')';
if ExecuteWorkProc(True) then uvFormSheet(self,MainDatabase.Handle,kodAction,SumLimit);
end;
end.
|
unit UBookList;
interface
var
booksLen: Integer = 0;
type
// Язык издания книги
TLang = (RU, EN, CH, BY, JP, SP);
// Запись о книге
TBook = packed record
code: Integer;
authorSurname: String[30];
bookTitle: String[20];
publishYear: Integer;
publishLang: TLang;
end;
TBooks = array of TBook;
// Конструктор TBook
function toBook(const code: Integer;
const authorSurname, bookTitle: String;
const publishYear: Integer;
const publishLang: TLang):TBook;
// Добавление книги
procedure addBook(book: TBook);
// Удаление книги по коду
procedure deleteByCode(code: Integer);
// Поиск книги по имени автора
function findByAuthor(name: String):TBooks;
// Поиск книги по названию
function findByTitle(title: String):TBooks;
// Поиск книги по коду
function findByCode(code: Integer):TBook;
// Изменение книги по коду
procedure changeByCode(code: Integer; newBook: TBook);
// Возвращает все книги библиотеки
function returnAllBooks:TBooks;
// Переводит TLang в строку
function langToStr(lang: TLang):String;
// Проверяет, существует ли книга с кодом
function bookExist(code: Integer):Boolean;
implementation
uses
UMain;
type
// Список книг в библиотеке
TBookList = ^TBookElem;
TBookElem = packed record
book: TBook;
next: TBookList;
end;
var
books: TBookList;
// Переводит TLang в строку
function langToStr(lang: TLang):String;
begin
case lang of
RU:
result := sLANG_RU;
EN:
result := sLANG_EN;
CH:
result := sLANG_CH;
BY:
result := sLANG_BY;
JP:
result := sLANG_JP;
SP:
result := sLANG_SP;
end;
end;
// Конструктор TBook
function toBook(const code: Integer;
const authorSurname, bookTitle: String;
const publishYear: Integer;
const publishLang: TLang):TBook;
begin
result.code := code;
result.authorSurname := authorSurname;
result.bookTitle := bookTitle;
result.publishYear := publishYear;
result.publishLang := publishLang;
end;
// Добавление элемента в список
procedure insert(list: TBookList; book: TBook);
var
temp: TBookList;
begin
new(temp);
temp^.book := book;
temp^.next := list^.next;
list^.next := temp;
end;
// Добавление книги
procedure addBook(book: TBook);
var
list: TBookList;
begin
list := books;
while (list^.next <> nil) and (list^.next^.book.bookTitle < book.bookTitle) do
list := list^.next;
insert(list, book);
if book.code > booksLen then
booksLen := book.code;
end;
// Изменение книги по коду
procedure changeByCode(code: Integer; newBook: TBook);
var
list: TBookList;
begin
list := books;
while (list^.next <> nil) and (list^.next^.book.code <> code) do
list := list^.next;
if list^.next <> nil then
list^.next^.book := newBook;
end;
// Поиск книги по имени автора
function findByAuthor(name: String):TBooks;
var
list: TBookList;
begin
list := books;
SetLength(result, 0);
while list^.next <> nil do
begin
list := list^.next;
if list^.book.authorSurname = name then
begin
SetLength(result, length(result) + 1);
result[length(result) - 1] := list^.book;
end;
end;
end;
// Поиск книги по названию
function findByTitle(title: String):TBooks;
var
list: TBookList;
begin
list := books;
SetLength(result, 0);
while list^.next <> nil do
begin
list := list^.next;
if list^.book.bookTitle = title then
begin
SetLength(result, length(result) + 1);
result[length(result) - 1] := list^.book;
end;
end;
end;
// Поиск книги по коду
function findByCode(code: Integer):TBook;
var
list: TBookList;
begin
list := books;
result.code := code - 1;
while list^.next <> nil do
begin
list := list^.next;
if list^.book.code = code then
result := list^.book;
end;
end;
// Удаление элемента списка
procedure delete(list: TBookList);
var
temp: TBookList;
begin
if list^.next <> nil then
begin
temp := list^.next;
list^.next := temp^.next;
dispose(temp);
end;
end;
// Удаление книги по коду
procedure deleteByCode(code: Integer);
var
list: TBookList;
begin
list := books;
while list^.next <> nil do
begin
if list^.next^.book.code = code then
delete(list)
else
list := list^.next;
end;
end;
// Возвращает все книги библиотеки
function returnAllBooks:TBooks;
var
list: TBookList;
begin
list := books;
SetLength(result, 0);
while list^.next <> nil do
begin
list := list^.next;
SetLength(result, length(result) + 1);
result[length(result) - 1] := list^.book;
end;
end;
// Проверяет, существует ли книга с кодом
function bookExist(code: Integer):Boolean;
var
list: TBookList;
begin
list := books;
result := false;
while list^.next <> nil do
begin
list := list^.next;
if list^.book.code = code then
result := true;
end;
end;
// Очистка списков
procedure clear(list: TBookList);
begin
while list^.next <> nil do
delete(list);
end;
// Создание списка
procedure create(var list: TBookList);
begin
new(list);
list^.next := nil;
end;
// Удаление списка
procedure destroy(var list: TBookList);
begin
clear(list);
dispose(list);
list := nil;
end;
initialization
create(books);
finalization
destroy(books);
end.
|
unit FD.Compiler.Environment;
interface
uses
System.SysUtils, System.Classes, System.Generics.Collections,
FD.Compiler.Exceptions;
type
(* TCompilerEnvironment represents a single compilation environment process, and
contains things like "Environment Defines", "Search Paths", etc...
*)
TCompilerEnvironment = class(TObject)
private
procedure SetBasePath(const Value: String);
protected
FSearchPath: TList<String>;
FBasePath: String;
public
constructor Create;
destructor Destroy; override;
procedure AddSearchPath(SearchPath: String); virtual;
function ExpandFileName(FileName: String; var AbsoluteFileName: String): Boolean;
function OpenFileForRead(FileName: String): TStream;
property BasePath: String read FBasePath write SetBasePath;
end;
implementation
uses
System.IOUtils;
{ TCompilerEnvironment }
procedure TCompilerEnvironment.AddSearchPath(SearchPath: String);
begin
FSearchPath.Add(IncludeTrailingPathDelimiter(SearchPath));
end;
constructor TCompilerEnvironment.Create;
begin
FSearchPath := TList<String>.Create;
end;
destructor TCompilerEnvironment.Destroy;
begin
FSearchPath.Free;
inherited;
end;
function TCompilerEnvironment.ExpandFileName(FileName: String;
var AbsoluteFileName: String): Boolean;
var
i: Integer;
function TryExpandWithASearchPath(const SP: String): Boolean;
var
FullFileName: String;
begin
// Try expand without the Base Path
FullFileName := TPath.GetFullPath(TPath.Combine(SP, FileName));
if TFile.Exists(FullFileName) then
begin
AbsoluteFileName := FullFileName;
Exit(True);
end;
// Try expand with the Base Path
FullFileName := TPath.GetFullPath(TPath.Combine(TPath.Combine(BasePath, SP), FileName));
if TFile.Exists(FullFileName) then
begin
AbsoluteFileName := FullFileName;
Exit(True);
end;
Result := False;
end;
begin
if TryExpandWithASearchPath('') then
Exit(True);
for i := 0 to FSearchPath.Count - 1 do
if TryExpandWithASearchPath(FSearchPath[i]) then
Exit(True);
Result := False;
end;
function TCompilerEnvironment.OpenFileForRead(FileName: String): TStream;
var
AbsFileName: String;
begin
if not Self.ExpandFileName(FileName, AbsFileName) then
raise EFDFileNotFound.Create('File not found: "' + FileName + '"');
Result := TFileStream.Create(AbsFileName, fmOpenRead or fmShareDenyNone);
end;
procedure TCompilerEnvironment.SetBasePath(const Value: String);
begin
FBasePath := TPath.GetFullPath(IncludeTrailingPathDelimiter(Value));
end;
end.
|
unit URegraCRUDTipoMovimentacao;
interface
uses
URegraCRUD
,URepositorioDB
,URepositorioTipoMovimentacao
,UEntidade
,UTipoMovimentacao
;
type
TRegraCrudTipoMovimentacao = class (TRegraCRUD)
protected
procedure ValidaInsercao (const coENTIDADE: TENTIDADE); override;
public
constructor Create; override;
end;
implementation
{ TRegraCrudTipoMovimentacao }
uses
SysUtils
,UUtilitarios
,UMensagens
,UConstantes
;
{ TRegraCrudTipoMovimentacao }
constructor TRegraCrudTipoMovimentacao.Create;
begin
inherited;
FRepositorioDB := TRepositorioDB<TENTIDADE>(TRepositorioTipoMovimentacao.Create);
end;
procedure TRegraCrudTipoMovimentacao.ValidaInsercao(
const coENTIDADE: TENTIDADE);
begin
inherited;
if Trim (TTIPOMOVIMENTACAO(coENTIDADE).FNOME) = EmptyStr then
raise EValidacaoNegocio.Create(STR_TIPO_MOVIMENTACAO_NAO_INFORMADO);
end;
end.
|
unit Buffer;
interface
uses
System.AnsiStrings, System.SysUtils;
const
BUF_MINSIZE = 64;
BUF_REALLOCSIZE = 64;
type
TBuffer = object
protected
FAutoExtention: Boolean;
FData: PByte;
FSize: Integer;
FOffset: Integer;
public
property Data: PByte read FData;
property Position: Integer read FOffset;
constructor Create(Size: Integer);
destructor Destroy;
procedure Seek(Size: Integer);
procedure CheckBounds(IncomingSize: Integer);
procedure Write(const A; Size: Integer); overload;
procedure Write<T>(A: T); overload;
procedure SaveToFile(const FileName: string);
end;
implementation
{ TBuffer }
procedure TBuffer.CheckBounds(IncomingSize: Integer);
begin
if FOffset + IncomingSize > FSize then
begin
if FAutoExtention then
begin
Inc(FSize, IncomingSize + BUF_REALLOCSIZE);
ReallocMem(FData, FSize);
end
else
raise Exception.Create('TBuffer: Overflowed.');
end;
end;
constructor TBuffer.Create(Size: Integer);
begin
if Size = 0 then
begin
GetMem(FData, BUF_MINSIZE);
FSize := BUF_MINSIZE;
FAutoExtention := True;
end
else
begin
GetMem(FData, Size);
FSize := Size;
FAutoExtention := False;
end;
FOffset := 0;
end;
destructor TBuffer.Destroy;
begin
FreeMem(FData);
end;
procedure TBuffer.SaveToFile(const FileName: string);
var
F: File;
begin
if (FData = nil) or (FOffset <= 0) then
Exit;
AssignFile(F, FileName);
ReWrite(F, 1);
BlockWrite(F, FData^, FOffset);
CloseFile(F);
end;
procedure TBuffer.Seek(Size: Integer);
begin
Inc(FOffset, Size);
end;
procedure TBuffer.Write(const A; Size: Integer);
begin
Move(A, PByte(Integer(FData) + FOffset)^, Size);
Inc(FOffset, Size);
end;
procedure TBuffer.Write<T>(A: T);
var
Len: Integer;
PValue: Pointer;
begin
PValue := PPointer(@A)^;
if IsManagedType(A) then // interface, string or dynamic array
begin
Len := PInteger(Integer(PValue) - SizeOf(Integer))^;
CheckBounds(Len);
Write(PValue^, Len);
end
else
if TypeInfo(T) = TypeInfo(PAnsiChar) then
begin
Len := System.AnsiStrings.StrLen(PAnsiChar(PValue));
CheckBounds(Len);
Write(PValue^, Len);
end
else
if TypeInfo(T) = TypeInfo(PWideChar) then
begin
Len := StrLen(PWideChar(PValue));
CheckBounds(Len);
Write(PValue^, Len);
end
else
begin
CheckBounds(SizeOf(A));
Write(A, SizeOf(A));
end;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Label0: TLabel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label11: TLabel;
Label21: TLabel;
Label101: TLabel;
Label111: TLabel;
InfoLabel0: TLabel;
InfoLabel1: TLabel;
InfoLabel2: TLabel;
InfoLabel3: TLabel;
InfoLabel4: TLabel;
InfoLabel5: TLabel;
InfoLabel11: TLabel;
InfoLabel21: TLabel;
InfoLabel101: TLabel;
InfoLabel111: TLabel;
ZeroCheckBox: TCheckBox;
LanguageButton: TButton;
procedure FormCreate(Sender: TObject);
procedure ZeroCheckBoxClick(Sender: TObject);
procedure LanguageButtonClick(Sender: TObject);
private
procedure UpdateValues;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
NtPattern, NtLanguageDlg;
procedure TForm1.UpdateValues;
resourcestring
// Contains two patterns: one and other.
SMessagePlural = '{plural, one {%d file} other {%d files}}'; //loc 0: Amount of files
// Contains three patterns: zero, one and other.
SZeroMessagePlural = '{plural, zero {No files} one {%d file} other {%d files}}'; //loc 0: Amount of files
procedure Process(count: Integer; messageLabel, infoLabel: TLabel);
var
str, pattern: String;
form, customForm: TPlural;
begin
// Update message label
if ZeroCheckBox.Checked then
pattern := SZeroMessagePlural
else
pattern := SMessagePlural;
messageLabel.Caption := TMultiPattern.Format(pattern, count, [count]);
// Update info label
TMultiPattern.GetMatchingPlural(count, pattern, form, customForm);
str := TMultiPattern.GetPluralName(customForm);
if form <> customForm then
infoLabel.Font.Style := [fsBold]
else
infoLabel.Font.Style := [];
infoLabel.Caption := str;
end;
begin
Process(0, Label0, InfoLabel0);
Process(1, Label1, InfoLabel1);
Process(2, Label2, InfoLabel2);
Process(3, Label3, InfoLabel3);
Process(4, Label4, InfoLabel4);
Process(5, Label5, InfoLabel5);
Process(11, Label11, InfoLabel11);
Process(21, Label21, InfoLabel21);
Process(101, Label101, InfoLabel101);
Process(111, Label111, InfoLabel111);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
UpdateValues;
end;
procedure TForm1.ZeroCheckBoxClick(Sender: TObject);
begin
UpdateValues;
end;
procedure TForm1.LanguageButtonClick(Sender: TObject);
begin
if TNtLanguageDialog.Select then
UpdateValues;
end;
// If your original language is not English remove comments and set the default language here.
{
initialization
DefaultLocale := 'de';
}
end.
|
// ###################################################################
// #### This file is part of the mathematics library project, and is
// #### offered under the licence agreement described on
// #### http://www.mrsoft.org/
// ####
// #### Copyright:(c) 2020, Michael R. . All rights reserved.
// ####
// #### 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 ufrmMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, WebAuthn;
type
TfrmWebAuthnTest = class(TForm)
btnVersion: TButton;
memLog: TMemo;
btnUserVerifyAvail: TButton;
btnCredential: TButton;
btnCheckJSON: TButton;
btnAssert: TButton;
procedure btnVersionClick(Sender: TObject);
procedure btnUserVerifyAvailClick(Sender: TObject);
procedure btnCredentialClick(Sender: TObject);
procedure btnCheckJSONClick(Sender: TObject);
procedure btnAssertClick(Sender: TObject);
private
procedure WriteCredAttest(pCred : PWEBAUTHN_CREDENTIAL_ATTESTATION);
procedure WriteAssertion( pAssert : PWEBAUTHN_ASSERTION; clientData : UTF8String );
{ Private-Deklarationen }
public
{ Public-Deklarationen }
end;
var
frmWebAuthnTest: TfrmWebAuthnTest;
implementation
uses IdHashSha, cbor, AuthData, SuperObject;
{$R *.dfm}
// just one example. for testing fidotest.com can point to localhost via the hosts file ;)
const cClientData : UTF8String = '{' +
'"hashAlgorithm": "SHA-256",' +
'"challenge": "fzjg31IEKi6ZxKqsQ9S_XHG9WvdmcXPah5EXd11p1bU",' +
'"origin": "https:\/\/fidotest.com",' +
'"clientExtensions": {},' +
'"type": "webauthn.create"' +
'}';
cRefHost = 'fidotest.com';
procedure TfrmWebAuthnTest.btnVersionClick(Sender: TObject);
begin
memLog.Lines.Add('Web Auth Version: ' + IntToStr( WebAuthNGetApiVersionNumber ) );
end;
procedure TfrmWebAuthnTest.btnAssertClick(Sender: TObject);
var webauthJSON : ISuperObject;
WebAuthNClientData : TWebAuthnClientData; // _In_
WebAtuhNGetAssertionOption : TWebAuthNAuthenticatorGetAsserrtionOptions;
hr : HRESULT;
pWebAuthNAssertion : PWebAutNAssertion;
credList : Array[0..0] of TWebAuthNCredential;
credIDBuf : TBytes;
cancellationID : TGuid;
soClData : ISuperObject;
challange : Array[0..63] of byte;
i: Integer;
clientData : UTF8String;
begin
if not FileExists('webauth.json') then
raise Exception.Create('Cannot find original credential file');
with TStringLIst.Create do
try
LoadFromFile('webauth.json');
webauthJSON := SO(Text);
finally
Free;
end;
// ################################################
// #### Client data
soClData := SO(String(cClientData));
// create new challange
for i := 0 to Length(challange) - 1 do
challange[i] := random( 255 );
soClData.S['challenge'] := Base64URLEncode(@challange[0], Length(challange) );
clientData := UTF8String(soCLData.AsJSon);
FillChar(WebAuthNClientData, sizeof(WebAuthNClientData), 0);
WebAuthNClientData.dwVersion := WEBAUTHN_CLIENT_DATA_CURRENT_VERSION;
WebAuthNClientData.cbClientDataJSON := Length(clientData);
WebAuthNClientData.pbClientDataJSON := PAnsiChar(clientData);
WebAuthNClientData.pwszHashAlgId := WEBAUTHN_HASH_ALGORITHM_SHA_256;
// ###########################################
// #### Prepare credential list
credIDBuf := Base64URLDecodeToBytes(webauthJSON.S['id']);
credList[0].dwVersion := WEBAUTHN_CREDENTIAL_CURRENT_VERSION;
credList[0].cbId := Length(credIDBuf);
credList[0].pbId := @credIDBuf[0];
credList[0].pwszCredentialType := WEBAUTHN_CREDENTIAL_TYPE_PUBLIC_KEY;
// ###########################################
// #### Fill in params
assert( WebAuthNGetCancellationId(cancellationID) = S_OK, 'Cancellation ID failed');
FillChar(WebAtuhNGetAssertionOption, sizeof(WebAtuhNGetAssertionOption), 0);
WebAtuhNGetAssertionOption.dwVersion := WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_CURRENT_VERSION;
WebAtuhNGetAssertionOption.dwTimeoutMilliseconds := 20000;
WebAtuhNGetAssertionOption.CredentialList.cCredentials := Length(credList);
WebAtuhNGetAssertionOption.CredentialList.pCredentials := @credList;
WebAtuhNGetAssertionOption.Extensions.cExtensions := 0;
WebAtuhNGetAssertionOption.Extensions.pExtensions := nil;
WebAtuhNGetAssertionOption.dwAuthenticatorAttachment := WEBAUTHN_AUTHENTICATOR_ATTACHMENT_CROSS_PLATFORM;
WebAtuhNGetAssertionOption.dwUserVerificationRequirement := WEBAUTHN_USER_VERIFICATION_REQUIREMENT_DISCOURAGED; //WEBAUTHN_USER_VERIFICATION_REQUIREMENT_REQUIRED;
WebAtuhNGetAssertionOption.dwFlags := 0;
WebAtuhNGetAssertionOption.pwszU2fAppId := nil;
WebAtuhNGetAssertionOption.pbU2fAppId := nil;
WebAtuhNGetAssertionOption.pCancellationId := nil;
WebAtuhNGetAssertionOption.pCancellationId := @cancellationID;
pWebAuthNAssertion := nil;
hr := WebAuthNAuthenticatorGetAssertion( Handle,
PChar(cRefHost),
@WebAuthNClientData,
@WebAtuhNGetAssertionOption,
pWebAuthNAssertion );
if hr = S_OK then
begin
ShowMessage( 'Successfully created assertion');
memLog.Lines.Add('Created assertion -> now it would be time to validate on the host');
WriteAssertion( pWebAuthNAssertion, clientData );
WebAuthNFreeAssertion( pWebAuthNAssertion );
end;
end;
procedure TfrmWebAuthnTest.btnCheckJSONClick(Sender: TObject);
var webauthJSON : ISuperObject;
attest : TCborMap;
authData : TAuthData;
begin
with TStringLIst.Create do
try
LoadFromFile('webauth.json');
webauthJSON := SO(Text);
finally
Free;
end;
attest := TCborDecoding.DecodeBase64Url(webauthJSON.S['response.attestationObject']) as TCborMap;
try
memLog.Lines.Add(attest.ToString);
authData := TAuthData.Create((attest.ValueByName['authData'] as TCborByteString).ToBytes);
memLog.Lines.Add('');
memLog.Lines.Add('AuthData:' );
if authData <> nil then
memLog.Lines.Add(authData.ToString);
authData.Free;
finally
attest.Free;
end;
end;
procedure TfrmWebAuthnTest.WriteAssertion(pAssert: PWEBAUTHN_ASSERTION; clientData : UTF8String);
var jsonOut : ISuperObject;
begin
jsonout := SO;
jsonout.S['response.authenticatorData'] := Base64URLEncode( pAssert^.pbAuthenticatorData, pAssert^.cbAuthenticatorData );
jsonout.S['resopnse.signature'] := Base64URLEncode( pAssert^.pbSignature, pAssert^.cbSignature );
jsonout.S['response.userHandle'] := Base64URLEncode( pAssert^.pbUserId, pAssert^.cbUserId );
jsonout.S['response.clientDataJSON'] := Base64URLEncode( @clientData[1], Length(clientData) );
jsonout.S['id'] := Base64URLEncode( pAssert^.Credential.pbId, pAssert^.Credential.cbId );
jsonout.S['rawId'] := Base64URLEncode( pAssert^.Credential.pbId, pAssert^.Credential.cbId );
jsonout.S['type'] := pAssert^.Credential.pwszCredentialType;
jsonout.SaveTo('webauthn_assert.json');
memLog.Lines.Add('');
memLog.Lines.Add('Assertion json: ' );
memLog.Lines.Add(jsonout.AsJSon(True, True));
end;
procedure TfrmWebAuthnTest.WriteCredAttest(
pCred: PWEBAUTHN_CREDENTIAL_ATTESTATION);
var jsonOut : ISuperObject;
begin
jsonout := SO;
jsonout.S['type'] := pCred^.pwszFormatType;
jsonout.S['response.attestationObject'] := Base64URLEncode( pCred^.pbAttestationObject, pCred^.cbAttestationObject );
jsonout.S['response.clientDataJSON'] := Base64URLEncode( @cClientData[1], Length(cClientData) );
jsonout.S['id'] := Base64URLEncode( pCred^.pbCredentialId, pCred^.cbCredentialId );
jsonout.S['rawid'] := Base64URLEncode( pCred^.pbCredentialId, pCred^.cbCredentialId );
// additional fields not used e.g. on webauthn.io
if (pCred^.dwUsedTransport and WEBAUTHN_CTAP_TRANSPORT_FLAGS_MASK) = WEBAUTHN_CTAP_TRANSPORT_USB then
jsonout.s['transport'] := 'USB';
if (pCred^.dwUsedTransport and WEBAUTHN_CTAP_TRANSPORT_FLAGS_MASK) = WEBAUTHN_CTAP_TRANSPORT_BLE then
jsonout.s['transport'] := 'BLE';
if (pCred^.dwUsedTransport and WEBAUTHN_CTAP_TRANSPORT_FLAGS_MASK) = WEBAUTHN_CTAP_TRANSPORT_TEST then
jsonout.s['transport'] := 'Test';
if (pCred^.dwUsedTransport and WEBAUTHN_CTAP_TRANSPORT_FLAGS_MASK) = WEBAUTHN_CTAP_TRANSPORT_INTERNAL then
jsonout.s['transport'] := 'Internal';
jsonout.S['debug.authData'] := Base64URLEncode( pCred^.pbAuthenticatorData, pCred^.cbAuthenticatorData );
jsonout.S['debug.attestation'] := Base64URLEncode( pCred^.pbAttestation, pCred^.cbAttestation );
jsonout.SaveTo('webauth.json');
end;
procedure TfrmWebAuthnTest.btnUserVerifyAvailClick(Sender: TObject);
var isAvail : BOOL;
hr : HRESULT;
begin
hr := WebAuthNIsUserVerifyingPlatformAuthenticatorAvailable( isAvail );
if hr = S_OK then
begin
memLog.Lines.Add('Verifying Platform Avail: ' + BoolToStr(isAvail, True ) );
end
else
memLog.Lines.Add('Call Failed');
end;
procedure TfrmWebAuthnTest.btnCredentialClick(Sender: TObject);
var RpInformation : TWebAuthnRPEntityInformation; // _In_
UserInformation : TWebAuthUserEntityInformation; // _In_
PubKeyCredParams : TWebauthnCoseCredentialParameters; // _In_
WebAuthNClientData : TWebAuthnClientData; // _In_
WebAuthNMakeCredentialOptions : TWebAuthnAuthenticatorMakeCredentialOptions; // _In_opt_
pWebAuthNCredentialAttestation : PWEBAUTHN_CREDENTIAL_ATTESTATION; // _Outptr_result_maybenull_
hr : HRESULT;
coseParams : Array[0..1] of WEBAUTHN_COSE_CREDENTIAL_PARAMETER;
i : integer;
uid : Array[0..31] of byte;
cancellationID : TGuid;
bufClientData : UTF8String;
begin
// ################################################
// #### relying party
FillChar(RpInformation, sizeof(RpInformation), 0);
RpInformation.dwVersion := WEBAUTHN_RP_ENTITY_INFORMATION_CURRENT_VERSION;
RpInformation.pwszId := cRefHost;
RpInformation.pwszName := 'Sweet home localhost';
RpInformation.pwszIcon := nil;
// ################################################
// #### user information
FillChar(UserInformation, sizeof(UserInformation), 0);
UserInformation.dwVersion := WEBAUTHN_USER_ENTITY_INFORMATION_CURRENT_VERSION;
UserInformation.cbId := sizeof( uid );
Randomize;
// create credentials
for i := 0 to Length(uid) - 1 do
begin
uid[i] := Byte( Random(High(byte) + 1) );
end;
UserInformation.pbId := @uid[0];
UserInformation.pwszName := 'test';
UserInformation.pwszIcon := niL;
UserInformation.pwszDisplayName := 'Test display name';
// ################################################
// #### Client data
bufClientData := Copy( cClientData, 1, Length(cClientData));
FillChar(WebAuthNClientData, sizeof(WebAuthNClientData), 0);
WebAuthNClientData.dwVersion := WEBAUTHN_CLIENT_DATA_CURRENT_VERSION;
WebAuthNClientData.cbClientDataJSON := Length(cClientData);
WebAuthNClientData.pbClientDataJSON := PAnsiChar(bufClientData);
WebAuthNClientData.pwszHashAlgId := WEBAUTHN_HASH_ALGORITHM_SHA_256;
// ################################################
// #### pub ked credential params
PubKeyCredParams.cCredentialParameters := Length(coseParams);
PubKeyCredParams.pCredentialParameters := @coseParams[0];
coseParams[0].dwVersion := WEBAUTHN_COSE_CREDENTIAL_PARAMETER_CURRENT_VERSION;
coseParams[0].pwszCredentialType := WEBAUTHN_CREDENTIAL_TYPE_PUBLIC_KEY;
coseParams[0].lAlg := WEBAUTHN_COSE_ALGORITHM_ECDSA_P256_WITH_SHA256;
coseParams[1].dwVersion := WEBAUTHN_COSE_CREDENTIAL_PARAMETER_CURRENT_VERSION;
coseParams[1].pwszCredentialType := WEBAUTHN_CREDENTIAL_TYPE_PUBLIC_KEY;
coseParams[1].lAlg := WEBAUTHN_COSE_ALGORITHM_RSASSA_PKCS1_V1_5_WITH_SHA256;
// ###########################################
// #### Fill in params
FillChar(WebAuthNMakeCredentialOptions, sizeof(WebAuthNMakeCredentialOptions), 0);
WebAuthNMakeCredentialOptions.dwVersion := WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_CURRENT_VERSION;
WebAuthNMakeCredentialOptions.dwTimeoutMilliseconds := 20000;
WebAuthNMakeCredentialOptions.bRequireResidentKey := False;
WebAuthNMakeCredentialOptions.dwAuthenticatorAttachment := WEBAUTHN_AUTHENTICATOR_ATTACHMENT_CROSS_PLATFORM;
WebAuthNMakeCredentialOptions.dwUserVerificationRequirement := WEBAUTHN_USER_VERIFICATION_REQUIREMENT_REQUIRED;
WebAuthNMakeCredentialOptions.dwAttestationConveyancePreference := WEBAUTHN_ATTESTATION_CONVEYANCE_PREFERENCE_DIRECT;
// ###########################################
// #### Cancellation
assert( WebAuthNGetCancellationId(cancellationID) = S_OK, 'Cancellation ID failed');
WebAuthNMakeCredentialOptions.pCancellationId := @cancellationID;
// ###########################################
// #### do the magic
pWebAuthNCredentialAttestation := nil;
hr := WebAuthNAuthenticatorMakeCredential( Handle,
@RpInformation,
@UserInformation,
@PubKeyCredParams,
@WebAuthNClientData,
@WebAuthNMakeCredentialOptions,
pWebAuthNCredentialAttestation );
if hr = S_OK then
begin
WriteCredAttest( pWebAuthNCredentialAttestation );
WebAuthNFreeCredentialAttestation( pWebAuthNCredentialAttestation );
memLog.Lines.Add('Finished');
end
else
begin
memLog.Lines.Add('Make Cred failed with: ' + WebAuthNGetErrorName( hr ));
end;
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.Console.Writer.Windows;
interface
uses
DPM.Console.Writer;
type
//TODO : Make thread safe!
TWindowsConsole = class(TConsoleBase)
private
FDefaultForeground : Word;
FDefaultBackground : Word;
FLastForeground : TConsoleColor;
FLastBackground : TConsoleColor;
FStdOut : THandle;
function GetForegroundColourCode(const cc: TConsoleColor): Word;
function GetBackgroundColourCode(const cc: TConsoleColor): Word;
function ConsoleAttributesToConsoleColor(const value : word; const background : boolean = false) : TConsoleColor;
protected
function GetConsoleWidth : Integer;override;
procedure InternalWriteLn(const s : String); override;
procedure InternalWrite(const s : String); override;
function GetCurrentForegroundColor : TConsoleColor; override;
function GetCurrentBackgroundColor : TConsoleColor; override;
procedure SetForegroundColor(const foreground : TConsoleColor);override;
procedure SetColour(const foreground: TConsoleColor; const background: TConsoleColor = ccDefault); override;
public
constructor Create;override;
destructor Destroy; override;
end;
implementation
uses
WinAPI.Windows,
DPM.Core.Utils.Strings;
constructor TWindowsConsole.Create;
var
dummy : Cardinal;
consoleInfo : _CONSOLE_SCREEN_BUFFER_INFO;
begin
inherited;
FStdOut := GetStdHandle(STD_OUTPUT_HANDLE);
if not GetConsoleMode(FStdOut, dummy) then // Not a console handle
Self.RedirectedStdOut := True;
Self.ConsoleWidth := GetConsoleWidth;
//Save the current console colour settings so we can restore them:
if GetConsoleScreenBufferInfo(FStdOut, consoleInfo) then
begin
FDefaultForeground := consoleInfo.wAttributes and (FOREGROUND_BLUE or FOREGROUND_GREEN or FOREGROUND_RED or FOREGROUND_INTENSITY);
FDefaultBackground := consoleInfo.wAttributes and (BACKGROUND_BLUE or BACKGROUND_GREEN or BACKGROUND_RED or BACKGROUND_INTENSITY);
end
else
begin
FDefaultForeground := GetForegroundColourCode(ccWhite);
FDefaultBackground := GetBackgroundColourCode(ccBlack);
end;
// FLastForeground := ccDarkYellow; // Just to ensure the first colour change goes through
// FLastBackground := ccDarkYellow;
FLastForeground := ConsoleAttributesToConsoleColor(FDefaultForeground);
FLastBackground := ConsoleAttributesToConsoleColor(FDefaultBackground);
end;
function TWindowsConsole.ConsoleAttributesToConsoleColor(const value : Word; const background : boolean = false) : TConsoleColor;
var
intensity : boolean;
red : boolean;
blue : boolean;
green : boolean;
begin
if background then
begin
red := (value and BACKGROUND_RED) > 0;
green := (value and BACKGROUND_GREEN) > 0;
blue := (value and BACKGROUND_BLUE) > 0;
intensity := (value and BACKGROUND_INTENSITY) > 0;
result := TConsoleColor.ccBlack;
end
else
begin
red := (value and FOREGROUND_RED) > 0;
green := (value and FOREGROUND_GREEN) > 0;
blue := (value and FOREGROUND_GREEN) > 0;
intensity := (value and FOREGROUND_INTENSITY) > 0;
result := TConsoleColor.ccWhite;
end;
//red only
if red then
begin
//test with blue and green
if blue and green then
result := ccWhite
else if blue then
result := ccDarkPurple
else if green then
result := ccDarkYellow
else
result := ccDarkRed;
end
else if blue then
begin
//test with green only since red&blue is tested under red
if green then
result := ccDarkAqua
else
result := ccDarkBlue;
end
else if green then
begin
result := ccDarkGreen;
end
else if not (red or blue or green) then
begin
if intensity then
result := ccGrey
else
result := ccBlack;
end;
if intensity then
begin
case result of
ccDarkRed: result := ccBrightRed;
ccDarkBlue: result := ccBrightBlue;
ccDarkGreen: result := ccBrightGreen;
ccDarkYellow: result := ccBrightYellow;
ccDarkAqua: result := ccBrightAqua;
ccDarkPurple: result := ccBrightPurple;
ccBlack: result := ccGrey ;
ccWhite: result := ccBrightWhite;
else
//fi
end;
end;
end;
procedure TWindowsConsole.SetColour(const foreground, background: TConsoleColor);
begin
if (FLastForeground <> foreground) or (FLastBackground <> background) then
begin
SetConsoleTextAttribute(FStdOut,
GetForegroundColourCode(foreground) or
GetBackgroundColourCode(background));
FLastForeground := foreground;
FLastBackground := background;
end;
end;
procedure TWindowsConsole.SetForegroundColor(const foreground: TConsoleColor);
begin
SetColour(foreground,FLastBackground);
end;
function TWindowsConsole.GetForegroundColourCode(const cc : TConsoleColor) : Word;
begin
Result := 0;
case cc of
ccDefault : Result := FDefaultForeground;
ccBrightRed : Result := FOREGROUND_RED or FOREGROUND_INTENSITY;
ccDarkRed : Result := FOREGROUND_RED;
ccBrightBlue : Result := FOREGROUND_BLUE or FOREGROUND_INTENSITY;
ccDarkBlue : Result := FOREGROUND_BLUE;
ccBrightGreen : Result := FOREGROUND_GREEN or FOREGROUND_INTENSITY;
ccDarkGreen : Result := FOREGROUND_GREEN;
ccBrightYellow : Result := FOREGROUND_GREEN or FOREGROUND_RED or FOREGROUND_INTENSITY;
ccDarkYellow : Result := FOREGROUND_GREEN or FOREGROUND_RED;
ccBrightAqua : Result := FOREGROUND_GREEN or FOREGROUND_BLUE or FOREGROUND_INTENSITY;
ccDarkAqua : Result := FOREGROUND_GREEN or FOREGROUND_BLUE;
ccBrightPurple : Result := FOREGROUND_BLUE or FOREGROUND_RED or FOREGROUND_INTENSITY;
ccDarkPurple : Result := FOREGROUND_BLUE or FOREGROUND_RED;
ccGrey : Result := FOREGROUND_INTENSITY;
ccBlack : Result := 0;
ccBrightWhite : Result := FOREGROUND_BLUE or FOREGROUND_GREEN or FOREGROUND_RED or FOREGROUND_INTENSITY;
ccWhite : Result := FOREGROUND_BLUE or FOREGROUND_GREEN or FOREGROUND_RED;
end;
end;
procedure TWindowsConsole.InternalWrite(const s: String);
var
output : string;
dummy : Cardinal;
begin
//Add the indenting.
output := TStringUtils.PadString(s, length(s)+ Self.CurrentIndentLevel, True, ' ');
if Self.RedirectedStdOut then
System.Write(output)
else
WriteConsoleW(FStdOut, PWideChar(output), Length(output), dummy, nil);
end;
procedure TWindowsConsole.InternalWriteLn(const s: String);
var
output : string;
dummy : Cardinal;
begin
//Add the indenting.
output := TStringUtils.PadString(s, length(s)+ Self.CurrentIndentLevel, True, ' ');
//If we are already going to wrap around to the next line. No need to add CRLF
if Length(output) < ConsoleWidth then
output := output + #13#10;
if Self.RedirectedStdOut then
System.Write(output)
else
WriteConsoleW(FStdOut, PWideChar(output), Length(output), dummy, nil);
end;
destructor TWindowsConsole.Destroy;
begin
SetColour(ccDefault); // Restore default console colours
inherited;
end;
function TWindowsConsole.GetBackgroundColourCode(const cc : TConsoleColor) : Word;
begin
Result := 0;
case cc of
ccDefault : Result := FDefaultBackground;
ccBrightRed : Result := BACKGROUND_RED or BACKGROUND_INTENSITY;
ccDarkRed : Result := BACKGROUND_RED;
ccBrightBlue : Result := BACKGROUND_BLUE or BACKGROUND_INTENSITY;
ccDarkBlue : Result := BACKGROUND_BLUE;
ccBrightGreen : Result := BACKGROUND_GREEN or BACKGROUND_INTENSITY;
ccDarkGreen : Result := BACKGROUND_GREEN;
ccBrightYellow : Result := BACKGROUND_GREEN or BACKGROUND_RED or BACKGROUND_INTENSITY;
ccDarkYellow : Result := BACKGROUND_GREEN or BACKGROUND_RED;
ccBrightAqua : Result := BACKGROUND_GREEN or BACKGROUND_BLUE or BACKGROUND_INTENSITY;
ccDarkAqua : Result := BACKGROUND_GREEN or BACKGROUND_BLUE;
ccBrightPurple : Result := BACKGROUND_BLUE or BACKGROUND_RED or BACKGROUND_INTENSITY;
ccDarkPurple : Result := BACKGROUND_BLUE or BACKGROUND_RED;
ccGrey : Result := BACKGROUND_INTENSITY;
ccBlack : Result := 0;
ccBrightWhite : Result := BACKGROUND_BLUE or BACKGROUND_GREEN or BACKGROUND_RED or BACKGROUND_INTENSITY;
ccWhite : Result := BACKGROUND_BLUE or BACKGROUND_GREEN or BACKGROUND_RED;
end;
end;
function TWindowsConsole.GetConsoleWidth: Integer;
var
info : CONSOLE_SCREEN_BUFFER_INFO;
begin
Result := High(Integer); // Default is unlimited width
if GetConsoleScreenBufferInfo(FStdOut, info) then
Result := info.dwSize.X;
end;
function TWindowsConsole.GetCurrentBackgroundColor: TConsoleColor;
begin
result := FLastBackground;
end;
function TWindowsConsole.GetCurrentForegroundColor: TConsoleColor;
begin
result := FLastForeground;
end;
end.
|
{-------------------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-------------------------------------------------------------------------------}
{===============================================================================
WinSyncObjs - set of classes encapsulating windows synchronization objects
©František Milt 2017-07-17
Version 1.0.2
Dependencies:
AuxTypes - github.com/ncs-sniper/Lib.AuxTypes
AuxClasses - github.com/ncs-sniper/Lib.AuxClasses
StrRect - github.com/ncs-sniper/Lib.StrRect
===============================================================================}
unit WinSyncObjs;
{$IF not(defined(MSWINDOWS) or defined(WINDOWS))}
{$MESSAGE FATAL 'Unsupported operating system.'}
{$IFEND}
{$IFDEF FPC}
{$MODE Delphi}
{$DEFINE FPC_DisableWarns}
{$MACRO ON}
{$ENDIF}
{$IF Declared(CompilerVersion)}
{$IF CompilerVersion >= 20} // Delphi 2009+
{$DEFINE DeprecatedCommentDelphi}
{$IFEND}
{$IFEND}
{$IF Defined(FPC) or Defined(DeprecatedCommentDelphi)}
{$DEFINE DeprecatedComment}
{$ELSE}
{$UNDEF DeprecatedComment}
{$IFEND}
interface
uses
Windows, AuxClasses;
const
SEMAPHORE_MODIFY_STATE = $00000002;
SEMAPHORE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED or SYNCHRONIZE or $3;
TIMER_MODIFY_STATE = $00000002;
TIMER_QUERY_STATE = $00000001;
TIMER_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED or SYNCHRONIZE or
TIMER_QUERY_STATE or TIMER_MODIFY_STATE;
type
TWaitResult = (wrSignaled, wrTimeout, wrAbandoned, wrError);
//==============================================================================
//-- TCriticalSection declaration --------------------------------------------
//==============================================================================
TCriticalSection = class(TCustomObject)
private
fCriticalSectionObj: TRTLCriticalSection;
fSpinCount: DWORD;
procedure _SetSpinCount(Value: DWORD);
public
constructor Create; overload;
constructor Create(SpinCount: DWORD); overload;
destructor Destroy; override;
Function SetSpinCount(SpinCount: DWORD): DWORD;
Function TryEnter: Boolean;
procedure Enter;
procedure Leave;
property SpinCount: DWORD read fSpinCount write _SetSpinCount;
end;
//==============================================================================
//-- TWinSyncObject declaration ----------------------------------------------
//==============================================================================
TWinSyncObject = class(TCustomObject)
private
fHandle: THandle;
fLastError: Integer;
fName: String;
protected
Function SetAndRectifyName(const Name: String): Boolean; virtual;
procedure SetAndCheckHandle(Handle: THandle); virtual;
public
destructor Destroy; override;
Function WaitFor(Timeout: DWORD = INFINITE): TWaitResult; virtual;
property Handle: THandle read fHandle;
property LastError: Integer read fLastError;
property Name: String read fName;
end;
//==============================================================================
//-- TEvent declaration ------------------------------------------------------
//==============================================================================
TEvent = class(TWinSyncObject)
public
constructor Create(SecurityAttributes: PSecurityAttributes; ManualReset, InitialState: Boolean; const Name: String); overload;
constructor Create(const Name: String); overload;
constructor Create; overload;
constructor Open(DesiredAccess: DWORD; InheritHandle: Boolean; const Name: String); overload;
constructor Open(const Name: String); overload;
Function WaitForAndReset(Timeout: DWORD = INFINITE): TWaitResult;
Function SetEvent: Boolean;
Function ResetEvent: Boolean;
{
Function PulseEvent is unreliable and should not be used. More info here:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms684914
}
Function PulseEvent: Boolean; deprecated {$IFDEF DeprecatedComment}'Unreliable, do not use.'{$ENDIF};
end;
//==============================================================================
//-- TMutex declaration ------------------------------------------------------
//==============================================================================
TMutex = class(TWinSyncObject)
public
constructor Create(SecurityAttributes: PSecurityAttributes; InitialOwner: Boolean; const Name: String); overload;
constructor Create(const Name: String); overload;
constructor Create; overload;
constructor Open(DesiredAccess: DWORD; InheritHandle: Boolean; const Name: String); overload;
constructor Open(const Name: String); overload;
Function WaitForAndRelease(TimeOut: DWORD = INFINITE): TWaitResult;
Function ReleaseMutex: Boolean;
end;
//==============================================================================
//-- TSemaphore declaration --------------------------------------------------
//==============================================================================
TSemaphore = class(TWinSyncObject)
public
constructor Create(SecurityAttributes: PSecurityAttributes; InitialCount, MaximumCount: Integer; const Name: String); overload;
constructor Create(InitialCount, MaximumCount: Integer; const Name: String); overload;
constructor Create(InitialCount, MaximumCount: Integer); overload;
constructor Open(DesiredAccess: LongWord; InheritHandle: Boolean; const Name: String); overload;
constructor Open(const Name: String); overload;
Function WaitForAndRelease(TimeOut: LongWord = INFINITE): TWaitResult;
Function ReleaseSemaphore(ReleaseCount: Integer; out PreviousCount: Integer): Boolean; overload;
Function ReleaseSemaphore: Boolean; overload;
end;
//==============================================================================
//-- TWaitableTimer declaration ----------------------------------------------
//==============================================================================
TTimerAPCRoutine = procedure(ArgToCompletionRoutine: Pointer; TimerLowValue, TimerHighValue: DWORD); stdcall;
PTimerAPCRoutine = ^TTimerAPCRoutine;
TWaitableTimer = class(TWinSyncObject)
public
constructor Create(SecurityAttributes: PSecurityAttributes; ManualReset: Boolean; const Name: String); overload;
constructor Create(const Name: String); overload;
constructor Create; overload;
constructor Open(DesiredAccess: DWORD; InheritHandle: Boolean; const Name: String); overload;
constructor Open(const Name: String); overload;
Function SetWaitableTimer(DueTime: Int64; Period: Integer; CompletionRoutine: TTimerAPCRoutine; ArgToCompletionRoutine: Pointer; Resume: Boolean): Boolean; overload;
Function SetWaitableTimer(DueTime: Int64; Period: Integer = 0): Boolean; overload;
Function SetWaitableTimer(DueTime: TDateTime; Period: Integer; CompletionRoutine: TTimerAPCRoutine; ArgToCompletionRoutine: Pointer; Resume: Boolean): Boolean; overload;
Function SetWaitableTimer(DueTime: TDateTime; Period: Integer = 0): Boolean; overload;
Function CancelWaitableTimer: Boolean;
end;
implementation
uses
SysUtils, StrRect;
{$IFDEF FPC_DisableWarns}
{$DEFINE FPCDWM}
{$DEFINE W5057:={$WARN 5057 OFF}} // Local variable "$1" does not seem to be initialized
{$DEFINE W5058:={$WARN 5058 OFF}} // Variable "$1" does not seem to be initialized
{$ENDIF}
//==============================================================================
//-- TCriticalSection implementation -----------------------------------------
//==============================================================================
//------------------------------------------------------------------------------
// TCriticalSection - private methods
//------------------------------------------------------------------------------
procedure TCriticalSection._SetSpinCount(Value: DWORD);
begin
fSpinCount := Value;
SetSpinCount(fSpinCount);
end;
//------------------------------------------------------------------------------
// TCriticalSection - public methods
//------------------------------------------------------------------------------
constructor TCriticalSection.Create;
begin
inherited Create;
fSpinCount := 0;
InitializeCriticalSection(fCriticalSectionObj);
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor TCriticalSection.Create(SpinCount: DWORD);
begin
inherited Create;
fSpinCount := SpinCount;
InitializeCriticalSectionAndSpinCount(fCriticalSectionObj,SpinCount);
end;
//------------------------------------------------------------------------------
destructor TCriticalSection.Destroy;
begin
DeleteCriticalSection(fCriticalSectionObj);
inherited;
end;
//------------------------------------------------------------------------------
Function TCriticalSection.SetSpinCount(SpinCount: DWORD): DWORD;
begin
fSpinCount := SpinCount;
Result := SetCriticalSectionSpinCount(fCriticalSectionObj,SpinCount);
end;
//------------------------------------------------------------------------------
Function TCriticalSection.TryEnter: Boolean;
begin
Result := TryEnterCriticalSection(fCriticalSectionObj);
end;
//------------------------------------------------------------------------------
procedure TCriticalSection.Enter;
begin
EnterCriticalSection(fCriticalSectionObj);
end;
//------------------------------------------------------------------------------
procedure TCriticalSection.Leave;
begin
LeaveCriticalSection(fCriticalSectionObj);
end;
//==============================================================================
//-- TWinSyncObject implementation -------------------------------------------
//==============================================================================
//------------------------------------------------------------------------------
// TWinSyncObject - proteted methods
//------------------------------------------------------------------------------
Function TWinSyncObject.SetAndRectifyName(const Name: String): Boolean;
begin
fName := Name;
If Length(fName) > MAX_PATH then SetLength(fName,MAX_PATH);
Result := Length(fName) > 0;
end;
//------------------------------------------------------------------------------
procedure TWinSyncObject.SetAndCheckHandle(Handle: THandle);
begin
fHandle := Handle;
If fHandle = 0 then
begin
fLastError := GetLastError;
RaiseLastOSError;
end;
end;
//------------------------------------------------------------------------------
// TWinSyncObject - public methods
//------------------------------------------------------------------------------
destructor TWinSyncObject.Destroy;
begin
CloseHandle(fHandle);
inherited;
end;
//------------------------------------------------------------------------------
Function TWinSyncObject.WaitFor(Timeout: DWORD = INFINITE): TWaitResult;
begin
case WaitForSingleObject(fHandle,Timeout) of
WAIT_ABANDONED: Result := wrAbandoned;
WAIT_OBJECT_0: Result := wrSignaled;
WAIT_TIMEOUT: Result := wrTimeout;
WAIT_FAILED: begin
Result := wrError;
FLastError := GetLastError;
end;
else
Result := wrError;
FLastError := GetLastError;
end;
end;
//==============================================================================
//-- TEvent implementation ---------------------------------------------------
//==============================================================================
//------------------------------------------------------------------------------
// TEvent - public methods
//------------------------------------------------------------------------------
constructor TEvent.Create(SecurityAttributes: PSecurityAttributes; ManualReset, InitialState: Boolean; const Name: String);
begin
inherited Create;
If SetAndRectifyName(Name) then
SetAndCheckHandle(CreateEvent(SecurityAttributes,ManualReset,InitialState,PChar(StrToWin(fName))))
else
SetAndCheckHandle(CreateEvent(SecurityAttributes,ManualReset,InitialState,nil));
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor TEvent.Create(const Name: String);
begin
Create(nil,True,False,Name);
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor TEvent.Create;
begin
Create(nil,True,False,'');
end;
//------------------------------------------------------------------------------
constructor TEvent.Open(DesiredAccess: DWORD; InheritHandle: Boolean; const Name: String);
begin
inherited Create;
SetAndRectifyName(Name);
SetAndCheckHandle(OpenEvent(DesiredAccess,InheritHandle,PChar(StrToWin(fName))));
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor TEvent.Open(const Name: String);
begin
Open(SYNCHRONIZE or EVENT_MODIFY_STATE,False,Name);
end;
//------------------------------------------------------------------------------
Function TEvent.WaitForAndReset(Timeout: DWORD = INFINITE): TWaitResult;
begin
Result := WaitFor(Timeout);
If Result = wrSignaled then ResetEvent;
end;
//------------------------------------------------------------------------------
Function TEvent.SetEvent: Boolean;
begin
Result := Windows.SetEvent(fHandle);
If not Result then
fLastError := GetLastError;
end;
//------------------------------------------------------------------------------
Function TEvent.ResetEvent: Boolean;
begin
Result := Windows.ResetEvent(fHandle);
If not Result then
fLastError := GetLastError;
end;
//------------------------------------------------------------------------------
{$WARN SYMBOL_DEPRECATED OFF}
Function TEvent.PulseEvent: Boolean;
{$WARN SYMBOL_DEPRECATED ON}
begin
Result := Windows.PulseEvent(fHandle);
If not Result then
fLastError := GetLastError;
end;
//==============================================================================
//-- TMutex implementation ---------------------------------------------------
//==============================================================================
//------------------------------------------------------------------------------
// TMutex - public methods
//------------------------------------------------------------------------------
constructor TMutex.Create(SecurityAttributes: PSecurityAttributes; InitialOwner: Boolean; const Name: String);
begin
inherited Create;
If SetAndRectifyName(Name) then
SetAndCheckHandle(CreateMutex(SecurityAttributes,InitialOwner,PChar(StrToWin(fName))))
else
SetAndCheckHandle(CreateMutex(SecurityAttributes,InitialOwner,nil));
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor TMutex.Create(const Name: String);
begin
Create(nil,False,Name);
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor TMutex.Create;
begin
Create(nil,False,'');
end;
//------------------------------------------------------------------------------
constructor TMutex.Open(DesiredAccess: DWORD; InheritHandle: Boolean; const Name: String);
begin
inherited Create;
SetAndRectifyName(Name);
SetAndCheckHandle(OpenMutex(DesiredAccess,InheritHandle,PChar(StrToWin(fName))));
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor TMutex.Open(const Name: String);
begin
Open(SYNCHRONIZE or MUTEX_MODIFY_STATE,False,Name);
end;
//------------------------------------------------------------------------------
Function TMutex.WaitForAndRelease(TimeOut: DWORD = INFINITE): TWaitResult;
begin
Result := WaitFor(Timeout);
If Result in [wrSignaled,wrAbandoned] then ReleaseMutex;
end;
//------------------------------------------------------------------------------
Function TMutex.ReleaseMutex: Boolean;
begin
Result := Windows.ReleaseMutex(fHandle);
If not Result then
fLastError := GetLastError;
end;
//==============================================================================
//-- TSemaphore implementation -----------------------------------------------
//==============================================================================
//------------------------------------------------------------------------------
// TSemaphore - public methods
//------------------------------------------------------------------------------
constructor TSemaphore.Create(SecurityAttributes: PSecurityAttributes; InitialCount, MaximumCount: Integer; const Name: String);
begin
inherited Create;
If SetAndRectifyName(Name) then
SetAndCheckHandle(CreateSemaphore(SecurityAttributes,InitialCount,MaximumCount,PChar(StrToWin(fName))))
else
SetAndCheckHandle(CreateSemaphore(SecurityAttributes,InitialCount,MaximumCount,nil));
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor TSemaphore.Create(InitialCount, MaximumCount: Integer; const Name: String);
begin
Create(nil,InitialCount,MaximumCount,Name);
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor TSemaphore.Create(InitialCount, MaximumCount: Integer);
begin
Create(nil,InitialCount,MaximumCount,'');
end;
//------------------------------------------------------------------------------
constructor TSemaphore.Open(DesiredAccess: LongWord; InheritHandle: Boolean; const Name: String);
begin
inherited Create;
SetAndRectifyName(Name);
SetAndCheckHandle(OpenSemaphore(DesiredAccess,InheritHandle,PChar(StrToWin(fName))));
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor TSemaphore.Open(const Name: String);
begin
Open(SYNCHRONIZE or SEMAPHORE_MODIFY_STATE,False,Name);
end;
//------------------------------------------------------------------------------
Function TSemaphore.WaitForAndRelease(TimeOut: LongWord = INFINITE): TWaitResult;
begin
Result := WaitFor(Timeout);
If Result in [wrSignaled,wrAbandoned] then ReleaseSemaphore;
end;
//------------------------------------------------------------------------------
Function TSemaphore.ReleaseSemaphore(ReleaseCount: Integer; out PreviousCount: Integer): Boolean;
begin
Result := Windows.ReleaseSemaphore(fHandle,ReleaseCount,@PreviousCount);
If not Result then
fLastError := GetLastError;
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
Function TSemaphore.ReleaseSemaphore: Boolean;
var
Dummy: Integer;
begin
Result := ReleaseSemaphore(1,Dummy);
end;
//==============================================================================
//-- TWaitableTimer implementation -------------------------------------------
//==============================================================================
//------------------------------------------------------------------------------
// TWaitableTimer - public methods
//------------------------------------------------------------------------------
constructor TWaitableTimer.Create(SecurityAttributes: PSecurityAttributes; ManualReset: Boolean; const Name: String);
begin
inherited Create;
If SetAndRectifyName(Name) then
SetAndCheckHandle(CreateWaitableTimer(SecurityAttributes,ManualReset,PChar(StrToWin(fName))))
else
SetAndCheckHandle(CreateWaitableTimer(SecurityAttributes,ManualReset,nil));
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor TWaitableTimer.Create(const Name: String);
begin
Create(nil,True,Name);
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor TWaitableTimer.Create;
begin
Create(nil,True,'');
end;
//------------------------------------------------------------------------------
constructor TWaitableTimer.Open(DesiredAccess: DWORD; InheritHandle: Boolean; const Name: String);
begin
inherited Create;
SetAndRectifyName(Name);
SetAndCheckHandle(OpenWaitableTimer(DesiredAccess,InheritHandle,PChar(StrToWin(fName))));
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor TWaitableTimer.Open(const Name: String);
begin
Open(SYNCHRONIZE or TIMER_MODIFY_STATE,False,Name);
end;
//------------------------------------------------------------------------------
{$IFDEF FPCDWM}{$PUSH}W5058{$ENDIF}
Function TWaitableTimer.SetWaitableTimer(DueTime: Int64; Period: Integer; CompletionRoutine: TTimerAPCRoutine; ArgToCompletionRoutine: Pointer; Resume: Boolean): Boolean;
begin
Result := Windows.SetWaitableTimer(fHandle,DueTime,Period,@CompletionRoutine,ArgToCompletionRoutine,Resume);
If not Result then
fLastError := GetLastError;
end;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
// --- --- --- --- --- --- --- --- --- --- --- --- ---
Function TWaitableTimer.SetWaitableTimer(DueTime: Int64; Period: Integer = 0): Boolean;
begin
Result := SetWaitableTimer(DueTime,Period,nil,nil,False);
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
{$IFDEF FPCDWM}{$PUSH}W5057{$ENDIF}
Function TWaitableTimer.SetWaitableTimer(DueTime: TDateTime; Period: Integer; CompletionRoutine: TTimerAPCRoutine; ArgToCompletionRoutine: Pointer; Resume: Boolean): Boolean;
Function DateTimeToFileTime(DateTime: TDateTime): FileTime;
var
LocalTime: TFileTime;
SystemTime: TSystemTime;
begin
Result.dwLowDateTime := 0;
Result.dwHighDateTime := 0;
DateTimeToSystemTime(DateTime,SystemTime);
If SystemTimeToFileTime(SystemTime,LocalTime) then
begin
If not LocalFileTimeToFileTime(LocalTime,Result) then
raise Exception.CreateFmt('LocalFileTimeToFileTime failed with error 0x%.8x.',[GetLastError]);
end
else raise Exception.CreateFmt('SystemTimeToFileTime failed with error 0x%.8x.',[GetLastError]);
end;
begin
Result := SetWaitableTimer(Int64(DateTimeToFileTime(DueTime)),Period,CompletionRoutine,ArgToCompletionRoutine,Resume);
If not Result then
fLastError := GetLastError;
end;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
// --- --- --- --- --- --- --- --- --- --- --- --- ---
Function TWaitableTimer.SetWaitableTimer(DueTime: TDateTime; Period: Integer = 0): Boolean;
begin
Result := SetWaitableTimer(DueTime,Period,nil,nil,False);
end;
//------------------------------------------------------------------------------
Function TWaitableTimer.CancelWaitableTimer: Boolean;
begin
Result := Windows.CancelWaitableTimer(fHandle);
If not Result then
fLastError := GetLastError;
end;
end.
|
namespace com.example.android.snake;
{*
* Copyright (C) 2007 The Android Open Source Project
*
* 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.
*}
interface
uses
java.beans,
java.util,
android.content,
android.content.res,
android.os,
android.util,
android.view,
android.widget,
javax.crypto;
type
/// <summary>
/// SnakeView: implementation of a simple game of Snake
/// </summary>
SnakeView = public class(TileView)
private
const TAG = 'SnakeView';
// Current mode of application: READY to run, RUNNING, or you have already
// lost. static final ints are used instead of an enum for performance
// reasons.
var mMode: Integer := READY;
// Current direction the snake is headed.
var mDirection: Integer := NORTH;
var mNextDirection: Integer := NORTH;
const NORTH = 1;
const SOUTH = 2;
const EAST = 3;
const WEST = 4;
// Labels for the drawables that will be loaded into the TileView class
const RED_STAR = 1;
const YELLOW_STAR = 2;
const GREEN_STAR = 3;
// Gesture detector
var mGestureDetector: GestureDetector;
// mScore: used to track the number of apples captured mMoveDelay: number of
// milliseconds between snake movements. This will decrease as apples are
// captured.
var mScore: Int64 := 0;
var mMoveDelay: Int64 := 600;
// mLastMove: tracks the absolute time when the snake last moved, and is used
// to determine if a move should be made based on mMoveDelay.
var mLastMove: Int64;
// mStatusText: text shows to the user in some run states
var mStatusText: TextView;
// mSnakeTrail: a list of Coordinates that make up the snake's body
// mAppleList: the secret location of the juicy apples the snake craves.
var mSnakeTrail: ArrayList<Coordinate> := new ArrayList<Coordinate>();
var mAppleList: ArrayList<Coordinate> := new ArrayList<Coordinate>();
var mRedrawHandler: RefreshHandler := new RefreshHandler(self);
// Everyone needs a little randomness in their life
class var RNG: Random := new Random; readonly;
method initSnakeView;
method initNewGame;
method coordArrayListToArray(cvec: ArrayList<Coordinate>): array of Integer;
method coordArrayToArrayList(rawArray: array of Integer): ArrayList<Coordinate>;
method addRandomApple;
method updateWalls;
method updateApples;
method updateSnake;
public
const PAUSE = 0;
const READY = 1;
const RUNNING = 2;
const LOSE = 3;
constructor (ctx: Context; attrs: AttributeSet);
constructor (ctx: Context; attrs: AttributeSet; defStyle: Integer);
method saveState: Bundle;
method restoreState(icicle: Bundle);
method onKeyDown(keyCode: Integer; msg: KeyEvent): Boolean; override;
method onTouchEvent(&event: MotionEvent): Boolean; override;
method setTextView(newView: TextView);
method setMode(newMode: Integer);
method update;
end;
/// <summary>
/// Simple class containing two integer values and a comparison function.
/// There's probably something I should use instead, but this was quick and
/// easy to build.
/// </summary>
Coordinate nested in SnakeView = private class
public
x, y: Integer;
constructor(newX, newY: Integer);
method &equals(other: Coordinate): Boolean;
method toString: String; override;
end;
/// <summary>
/// Create a simple handler that we can use to cause animation to happen. We
/// set ourselves as a target and we can use the sleep()
/// function to cause an update/invalidate to occur at a later date.
/// </summary>
RefreshHandler nested in SnakeView = public class(Handler)
private
mSnakeView: SnakeView;
public
constructor (aSnakeView: SnakeView);
method handleMessage(msg: Message); override;
method sleep(delayMillis: Int64);
end;
implementation
/// <summary>
/// Constructs a SnakeView based on inflation from XML
/// </summary>
/// <param name="ctx"></param>
/// <param name="attrs"></param>
constructor SnakeView(ctx: Context; attrs: AttributeSet);
begin
inherited;
initSnakeView;
end;
constructor SnakeView(ctx: Context; attrs: AttributeSet; defStyle: Integer);
begin
inherited;
initSnakeView;
end;
method SnakeView.initSnakeView;
begin
Focusable := true;
var res: Resources := Context.Resources;
resetTiles(4);
loadTile(RED_STAR, res.Drawable[R.drawable.redstar]);
loadTile(YELLOW_STAR, res.Drawable[R.drawable.yellowstar]);
loadTile(GREEN_STAR, res.Drawable[R.drawable.greenstar]);
// Set up gesture detector
mGestureDetector := new GestureDetector(Context, new SnakeGestureListener(self));
end;
method SnakeView.initNewGame;
begin
mSnakeTrail.clear;
mAppleList.clear;
// For now we're just going to load up a short default eastbound snake
// that's just turned north
mSnakeTrail.&add(new Coordinate(7, 7));
mSnakeTrail.&add(new Coordinate(6, 7));
mSnakeTrail.&add(new Coordinate(5, 7));
mSnakeTrail.&add(new Coordinate(4, 7));
mSnakeTrail.&add(new Coordinate(3, 7));
mSnakeTrail.&add(new Coordinate(2, 7));
mNextDirection := NORTH;
// Two apples to start with
addRandomApple;
addRandomApple;
mMoveDelay := 600;
mScore := 0;
end;
/// <summary>
/// Given a ArrayList of coordinates, we need to flatten them into an array of
/// ints before we can stuff them into a map for flattening and storage.
/// </summary>
/// <param name="cvec">a ArrayList of Coordinate objects</param>
/// <returns>a simple array containing the x/y values of the coordinates as [x1,y1,x2,y2,x3,y3...]</returns>
method SnakeView.coordArrayListToArray(cvec: ArrayList<Coordinate>): array of Integer;
begin
var count: Integer := cvec.size;
var rawArray: array of Integer := new Integer[count * 2];
for &index: Integer := 0 to pred(count) do
begin
var c: Coordinate := cvec.get(&index);
rawArray[(2 * &index)] := c.x;
rawArray[((2 * &index) + 1)] := c.y;
end;
exit rawArray;
end;
/// <summary>
/// Given a flattened array of ordinate pairs, we reconstitute them into a
/// ArrayList of Coordinate objects
/// </summary>
/// <param name="rawArray">[x1,y1,x2,y2,...]</param>
/// <returns>a ArrayList of Coordinates</returns>
method SnakeView.coordArrayToArrayList(rawArray: array of Integer): ArrayList<Coordinate>;
begin
var coordArrayList: ArrayList<Coordinate> := new ArrayList<Coordinate>();
var coordCount: Integer := rawArray.length;
var &index: Integer := 0;
while &index < coordCount do
begin
var c: Coordinate := new Coordinate(rawArray[&index], rawArray[&index + 1]);
coordArrayList.&add(c);
inc(&index, 2)
end;
exit coordArrayList;
end;
/// <summary>
/// Selects a random location within the garden that is not currently covered
/// by the snake. Currently _could_ go into an infinite loop if the snake
/// currently fills the garden, but we'll leave discovery of this prize to a
/// truly excellent snake-player.
/// </summary>
method SnakeView.addRandomApple;
begin
var newCoord: Coordinate := nil;
var found: Boolean := false;
while not found do
begin
// Choose a new location for our apple
var newX: Integer := 1 + RNG.nextInt(mXTileCount - 2);
var newY: Integer := 1 + RNG.nextInt(mYTileCount - 2);
newCoord := new Coordinate(newX, newY);
// Make sure it's not already under the snake
var collision: Boolean := false;
var snakelength: Integer := mSnakeTrail.size;
for &index: Integer := 0 to pred(snakelength) do
if mSnakeTrail.get(&index).&equals(newCoord) then
collision := true;
// if we're here and there's been no collision, then we have
// a good location for an apple. Otherwise, we'll circle back
// and try again
found := not collision
end;
if newCoord = nil then
Log.e(TAG, 'Somehow ended up with a null newCoord!');
mAppleList.&add(newCoord);
end;
/// <summary>
/// Draws some walls.
/// </summary>
method SnakeView.updateWalls;
begin
for x: Integer := 0 to pred(mXTileCount) do
begin
setTile(GREEN_STAR, x, 0);
setTile(GREEN_STAR, x, mYTileCount - 1);
end;
for y: Integer := 0 to pred(mYTileCount) do
begin
setTile(GREEN_STAR, 0, y);
setTile(GREEN_STAR, mXTileCount - 1, y);
end;
end;
/// <summary>
/// Draws some apples.
/// </summary>
method SnakeView.updateApples;
begin
for c: Coordinate in mAppleList do
setTile(YELLOW_STAR, c.x, c.y)
end;
/// <summary>
/// Figure out which way the snake is going, see if he's run into anything (the
/// walls, himself, or an apple). If he's not going to die, we then add to the
/// front and subtract from the rear in order to simulate motion. If we want to
/// grow him, we don't subtract from the rear.
/// </summary>
method SnakeView.updateSnake;
begin
var growSnake: Boolean := false;
// grab the snake by the head
var head: Coordinate := mSnakeTrail.get(0);
var newHead: Coordinate := new Coordinate(1, 1);
mDirection := mNextDirection;
case mDirection of
EAST: newHead := new Coordinate(head.x + 1, head.y);
WEST: newHead := new Coordinate(head.x - 1, head.y);
NORTH: newHead := new Coordinate(head.x, head.y - 1);
SOUTH: newHead := new Coordinate(head.x, head.y + 1);
end;
// Collision detection
// For now we have a 1-square wall around the entire arena
if (newHead.x < 1) or (newHead.y < 1) or (newHead.x > mXTileCount - 2)
or (newHead.y > mYTileCount - 2) then
begin
setMode(LOSE);
exit
end;
// Look for collisions with itself
var snakelength: Integer := mSnakeTrail.size;
for snakeindex: Integer := 0 to pred(snakelength) do
begin
var c: Coordinate := mSnakeTrail.get(snakeindex);
if c.&equals(newHead) then
begin
setMode(LOSE);
exit
end;
end;
// Look for apples
var applecount: Integer := mAppleList.size();
for appleindex: Integer := 0 to pred(applecount) do
begin
var c: Coordinate := mAppleList.get(appleindex);
if c.&equals(newHead) then
begin
mAppleList.&remove(c);
addRandomApple;
inc(mScore);
mMoveDelay := Int64(mMoveDelay * 0.9);
growSnake := true
end;
end;
// push a new head onto the ArrayList and pull off the tail
mSnakeTrail.&add(0, newHead);
// except if we want the snake to grow
if not growSnake then
mSnakeTrail.&remove(mSnakeTrail.size - 1);
var &index: Integer := 0;
for each c: Coordinate in mSnakeTrail do
begin
if &index = 0 then
setTile(YELLOW_STAR, c.x, c.y)
else
setTile(RED_STAR, c.x, c.y);
inc(&index)
end;
end;
method SnakeView.saveState: Bundle;
begin
var map: Bundle := new Bundle;
map.putIntArray('mAppleList', coordArrayListToArray(mAppleList));
map.putInt('mDirection', Integer.valueOf(mDirection));
map.putInt('mNextDirection', Integer.valueOf(mNextDirection));
map.putLong('mMoveDelay', Long.valueOf(mMoveDelay));
map.putLong('mScore', Long.valueOf(mScore));
map.putIntArray('mSnakeTrail', coordArrayListToArray(mSnakeTrail));
exit map;
end;
/// <summary>
/// Restore game state if our process is being relaunched
/// </summary>
/// <param name="icicle">a Bundle containing the game state</param>
method SnakeView.restoreState(icicle: Bundle);
begin
setMode(PAUSE);
mAppleList := coordArrayToArrayList(icicle.getIntArray('mAppleList'));
mDirection := icicle.Int['mDirection'];
mNextDirection := icicle.Int['mNextDirection'];
mMoveDelay := icicle.Long['mMoveDelay'];
mScore := icicle.Long['mScore'];
mSnakeTrail := coordArrayToArrayList(icicle.IntArray['mSnakeTrail']);
end;
/// <summary>
/// handles key events in the game. Update the direction our snake is traveling
/// based on the DPAD. Ignore events that would cause the snake to immediately
/// turn back on itself.
/// </summary>
/// <param name="keyCode"></param>
/// <param name="msg"></param>
/// <returns></returns>
method SnakeView.onKeyDown(keyCode: Integer; msg: KeyEvent): Boolean;
begin
if keyCode = KeyEvent.KEYCODE_DPAD_UP then
begin
if mMode in [READY, LOSE] then
begin
// At the beginning of the game, or the end of a previous one,
// we should start a new game.
initNewGame;
setMode(RUNNING);
update;
exit true
end;
if mMode = PAUSE then
begin
// If the game is merely paused, we should just continue where
// we left off.
setMode(RUNNING);
update;
exit true
end;
if mDirection <> SOUTH then
mNextDirection := NORTH;
exit true
end;
if keyCode = KeyEvent.KEYCODE_DPAD_DOWN then
begin
if mDirection <> NORTH then
mNextDirection := SOUTH;
exit true
end;
if keyCode = KeyEvent.KEYCODE_DPAD_LEFT then
begin
if mDirection <> EAST then
mNextDirection := WEST;
exit true
end;
if keyCode = KeyEvent.KEYCODE_DPAD_RIGHT then
begin
if mDirection <> WEST then
mNextDirection := EAST;
exit true
end;
exit inherited onKeyDown(keyCode, msg);
end;
/// <summary>
/// additional code to detect swipe gestures to move the snake
/// in the absence of a D-Pad
/// </summary>
/// <param name="event"></param>
/// <returns></returns>
method SnakeView.onTouchEvent(&event: MotionEvent): Boolean;
begin
exit mGestureDetector.onTouchEvent(&event);
end;
/// <summary>
/// Sets the TextView that will be used to give information (such as "Game
/// Over" to the user.
/// </summary>
/// <param name="newView"></param>
method SnakeView.setTextView(newView: TextView);
begin
mStatusText := newView;
end;
/// <summary>
/// Updates the current mode of the application (RUNNING or PAUSED or the like)
/// as well as sets the visibility of textview for notification
/// </summary>
/// <param name="newMode"></param>
method SnakeView.setMode(newMode: Integer);
begin
var oldMode: Integer := mMode;
mMode := newMode;
if (newMode = RUNNING) and (oldMode <> RUNNING) then
begin
mStatusText.Visibility := View.INVISIBLE;
update;
exit
end;
var res: Resources := Context.Resources;
var str: CharSequence := '';
if newMode = PAUSE then
str := res.Text[R.string.mode_pause];
if newMode = READY then
str := res.Text[R.string.mode_ready];
if newMode = LOSE then
str := res.String[R.string.mode_lose_prefix] + mScore + res.String[R.string.mode_lose_suffix];
mStatusText.Text := str;
mStatusText.Visibility := View.VISIBLE;
end;
/// <summary>
/// Handles the basic update loop, checking to see if we are in the running
/// state, determining if a move should be made, updating the snake's location.
/// </summary>
method SnakeView.update;
begin
if mMode = RUNNING then
begin
var now: Int64 := System.currentTimeMillis;
if now - mLastMove > mMoveDelay then
begin
clearTiles;
updateWalls;
updateSnake;
updateApples;
mLastMove := now
end;
mRedrawHandler.sleep(mMoveDelay)
end;
end;
constructor SnakeView.Coordinate(newX: Integer; newY: Integer);
begin
x := newX;
y := newY
end;
method SnakeView.Coordinate.&equals(other: Coordinate): Boolean;
begin
exit (x = other.x) and (y = other.y)
end;
method SnakeView.Coordinate.toString: String;
begin
exit 'Coordinate: [' + x + ',' + y + ']'
end;
constructor SnakeView.RefreshHandler(aSnakeView: SnakeView);
begin
inherited constructor;
mSnakeView := aSnakeView;
end;
method SnakeView.RefreshHandler.handleMessage(msg: Message);
begin
mSnakeView.update;
mSnakeView.invalidate;
end;
method SnakeView.RefreshHandler.sleep(delayMillis: Int64);
begin
removeMessages(0);
sendMessageDelayed(obtainMessage(0), delayMillis)
end;
end. |
unit VolumeGreyIntData;
interface
uses Windows, Graphics, Abstract3DVolumeData, AbstractDataSet, IntDataSet,
dglOpenGL, Math;
type
T3DVolumeGreyIntData = class (TAbstract3DVolumeData)
private
// Gets
function GetData(_x, _y, _z: integer):integer;
function GetDataUnsafe(_x, _y, _z: integer):integer;
// Sets
procedure SetData(_x, _y, _z: integer; _value: integer);
procedure SetDataUnsafe(_x, _y, _z: integer; _value: integer);
protected
// Constructors and Destructors
procedure Initialize; override;
// Gets
function GetBitmapPixelColor(_Position: longword):longword; override;
function GetRPixelColor(_Position: longword):byte; override;
function GetGPixelColor(_Position: longword):byte; override;
function GetBPixelColor(_Position: longword):byte; override;
function GetAPixelColor(_Position: longword):byte; override;
function GetRedPixelColor(_x,_y,_z: integer):single; override;
function GetGreenPixelColor(_x,_y,_z: integer):single; override;
function GetBluePixelColor(_x,_y,_z: integer):single; override;
function GetAlphaPixelColor(_x,_y,_z: integer):single; override;
// Sets
procedure SetBitmapPixelColor(_Position, _Color: longword); override;
procedure SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); override;
procedure SetRedPixelColor(_x,_y,_z: integer; _value:single); override;
procedure SetGreenPixelColor(_x,_y,_z: integer; _value:single); override;
procedure SetBluePixelColor(_x,_y,_z: integer; _value:single); override;
procedure SetAlphaPixelColor(_x,_y,_z: integer; _value:single); override;
// Copies
procedure CopyData(const _Data: TAbstractDataSet; _DataXSize, _DataYSize, _DataZSize: integer); override;
public
// Gets
function GetOpenGLFormat:TGLInt; override;
// Misc
procedure ScaleBy(_Value: single); override;
procedure Invert; override;
procedure Fill(_value: integer);
// properties
property Data[_x,_y,_z:integer]:integer read GetData write SetData; default;
property DataUnsafe[_x,_y,_z:integer]:integer read GetDataUnsafe write SetDataUnsafe;
end;
implementation
// Constructors and Destructors
procedure T3DVolumeGreyIntData.Initialize;
begin
FData := TIntDataSet.Create;
end;
// Gets
function T3DVolumeGreyIntData.GetData(_x, _y,_z: integer):integer;
begin
if IsPixelValid(_x,_y,_z) then
begin
Result := (FData as TIntDataSet).Data[(_z * FYxXSize) + (_y * FXSize) + _x];
end
else
begin
Result := 0;
end;
end;
function T3DVolumeGreyIntData.GetDataUnsafe(_x, _y,_z: integer):integer;
begin
// Use with care, otherwise you'll get an access violation
Result := (FData as TIntDataSet).Data[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
function T3DVolumeGreyIntData.GetBitmapPixelColor(_Position: longword):longword;
begin
Result := RGB((FData as TIntDataSet).Data[_Position],(FData as TIntDataSet).Data[_Position],(FData as TIntDataSet).Data[_Position]);
end;
function T3DVolumeGreyIntData.GetRPixelColor(_Position: longword):byte;
begin
Result := (FData as TIntDataSet).Data[_Position] and $FF;
end;
function T3DVolumeGreyIntData.GetGPixelColor(_Position: longword):byte;
begin
Result := (FData as TIntDataSet).Data[_Position] and $FF;
end;
function T3DVolumeGreyIntData.GetBPixelColor(_Position: longword):byte;
begin
Result := (FData as TIntDataSet).Data[_Position] and $FF;
end;
function T3DVolumeGreyIntData.GetAPixelColor(_Position: longword):byte;
begin
Result := 0;
end;
function T3DVolumeGreyIntData.GetRedPixelColor(_x,_y,_z: integer):single;
begin
Result := (FData as TIntDataSet).Data[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
function T3DVolumeGreyIntData.GetGreenPixelColor(_x,_y,_z: integer):single;
begin
Result := 0;
end;
function T3DVolumeGreyIntData.GetBluePixelColor(_x,_y,_z: integer):single;
begin
Result := 0;
end;
function T3DVolumeGreyIntData.GetAlphaPixelColor(_x,_y,_z: integer):single;
begin
Result := 0;
end;
function T3DVolumeGreyIntData.GetOpenGLFormat:TGLInt;
begin
Result := GL_RGB;
end;
// Sets
procedure T3DVolumeGreyIntData.SetBitmapPixelColor(_Position, _Color: longword);
begin
(FData as TIntDataSet).Data[_Position] := Round(((0.299 * GetRValue(_Color)) + (0.587 * GetGValue(_Color)) + (0.114 * GetBValue(_Color))) * 255);
end;
procedure T3DVolumeGreyIntData.SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte);
begin
(FData as TIntDataSet).Data[_Position] := Round(((0.299 * _r) + (0.587 * _g) + (0.114 * _b)) * 255);
end;
procedure T3DVolumeGreyIntData.SetRedPixelColor(_x,_y,_z: integer; _value:single);
begin
(FData as TIntDataSet).Data[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value) and $FF;
end;
procedure T3DVolumeGreyIntData.SetGreenPixelColor(_x,_y,_z: integer; _value:single);
begin
// Do nothing
end;
procedure T3DVolumeGreyIntData.SetBluePixelColor(_x,_y,_z: integer; _value:single);
begin
// Do nothing
end;
procedure T3DVolumeGreyIntData.SetAlphaPixelColor(_x,_y,_z: integer; _value:single);
begin
// Do nothing
end;
procedure T3DVolumeGreyIntData.SetData(_x, _y, _z: integer; _value: integer);
begin
if IsPixelValid(_x,_y,_z) then
begin
(FData as TIntDataSet).Data[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
end;
end;
procedure T3DVolumeGreyIntData.SetDataUnsafe(_x, _y, _z: integer; _value: integer);
begin
(FData as TIntDataSet).Data[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
end;
// Copies
procedure T3DVolumeGreyIntData.CopyData(const _Data: TAbstractDataSet; _DataXSize, _DataYSize, _DataZSize: integer);
var
x,y,z,ZPos,ZDataPos,Pos,maxPos,DataPos,maxX, maxY, maxZ: integer;
begin
maxX := min(FXSize,_DataXSize)-1;
maxY := min(FYSize,_DataYSize)-1;
maxZ := min(FZSize,_DataZSize)-1;
for z := 0 to maxZ do
begin
ZPos := z * FYxXSize;
ZDataPos := z * _DataYSize * _DataXSize;
for y := 0 to maxY do
begin
Pos := ZPos + (y * FXSize);
DataPos := ZDataPos + (y * _DataXSize);
maxPos := Pos + maxX;
for x := Pos to maxPos do
begin
(FData as TIntDataSet).Data[x] := (_Data as TIntDataSet).Data[DataPos];
inc(DataPos);
end;
end;
end;
end;
// Misc
procedure T3DVolumeGreyIntData.ScaleBy(_Value: single);
var
x,maxx: integer;
begin
maxx := (FYxXSize * FZSize) - 1;
for x := 0 to maxx do
begin
(FData as TIntDataSet).Data[x] := Round((FData as TIntDataSet).Data[x] * _Value);
end;
end;
procedure T3DVolumeGreyIntData.Invert;
var
x,maxx: integer;
begin
maxx := (FYxXSize * FZSize) - 1;
for x := 0 to maxx do
begin
(FData as TIntDataSet).Data[x] := 255 - (FData as TIntDataSet).Data[x];
end;
end;
procedure T3DVolumeGreyIntData.Fill(_value: integer);
var
x,maxx: integer;
begin
maxx := (FYxXSize * FZSize) - 1;
for x := 0 to maxx do
begin
(FData as TIntDataSet).Data[x] := _value;
end;
end;
end.
|
unit UAuxClaveAut;
interface
function isANumber(const aNumString: String): Boolean;
function testClaveAutoriza(const aKey: String): Boolean;
function getClaveAutErrorMsg: String;
implementation
uses
SysUtils,
rxStrUtils;
var
theErrorMsg: String;
function isANumber(const aNumString: String): Boolean;
var
iPos,
lenStr: Integer;
begin
Result := TRUE;
lenStr := length(aNumString);
iPos := 1;
while ((iPos <= lenStr) and Result) do
begin
if (aNumString[iPos] < '0') or (aNumString[iPos] > '9') then
Result := FALSE;
inc(iPos);
end;
end;
function testEntOficDC(const aEntOfic, aDigCont: String): Boolean;
const
kPesos: array [1..8] of integer =
( 4,8,5,10,9,7,3,6 );
var
theEntOfic: String;
iPos,
digCont: Integer;
sumaPesos: int64;
begin
theEntOfic := AddCharR('0', Trim(aEntOfic), 8);
sumaPesos := 0;
for iPos := 1 to 8 do
sumaPesos := sumaPesos + (strToInt(theEntOfic[iPos]) * kPesos[iPos]);
digCont := 11- (sumaPesos mod 11);
if digCont = 10 then digCont := 1;
if digCont = 11 then digCont := 0;
Result := (digCont = StrToInt(AddChar('0',Trim( aDigCont), 1)))
end;
function testClaveAutoriza(const aKey: String): Boolean;
var
theKey: String;
numKey: Int64;
resto,
digCont: Integer;
begin
Result := FALSE;
theKey := AddCharR('0', Trim(aKey), 18);
if not isANumber(theKey) then
theErrorMsg := 'La clave no es numérica.'
else
begin
// se prueba que el dígito de la Entidad-Oficina es correcto
if not testEntOficDC(Copy(theKey, 4, 8), Copy(theKey, 12, 1)) then
theErrorMsg := 'El dígito de control interno asociado a la Entidad-Oficina no es correcto.'
else
begin
numKey := StrToInt64(Copy(theKey, 1, 17));
digCont := strToInt(Copy(theKey, 18, 1));
resto := numKey mod 7;
if resto <> digCont then
theErrorMsg := 'La Clave de Autorización no es válida.'
else
Result := TRUE;
end
end;
end;
function getClaveAutErrorMsg: String;
begin
Result := theErrorMsg;
end;
end.
|
unit LiteEdit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, uColorTheme, uParser;
{
Used to specify behavior for Lite Edit
}
type VT = (VT_NONE, VT_NOT_EMPTY_TEXT, VT_FLOAT, VT_INT);
{
Lite Edit
}
type TLiteEdit = class(TEdit, IUnknown, IThemeSupporter)
private
theme: ColorTheme;
isActive, warn: boolean;
valueType: VT;
procedure DoEnter(); override;
procedure DoExit(); override;
procedure Change(); override;
protected
public
constructor Create(AOwner: TComponent); override;
// IThemeSupporter
procedure setTheme(theme: ColorTheme);
function getTheme(): ColorTheme;
procedure updateColors();
{
Specifies the behaviour of isValid function
}
procedure setValueType(valueType: VT);
{
Returns true if Edit if empty
}
function isEmpty(): boolean;
{
Returns true if Edit value is valid according to current behaviour
}
function isValid(): boolean;
{
Updates state of edit
}
procedure validateState();
published
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Lite', [TLiteEdit]);
end;
// Override
constructor TLiteEdit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
isActive := false;
warn := false;
valueType := VT_NONE;
theme := CT_DEFAULT_THEME;
updateColors();
// other
BorderStyle := bsNone;
Font.Size := 15;
Font.Name := 'Consolas';
Autosize := false;
Width := 160;
Height := 24;
end;
// Override
procedure TLiteEdit.DoEnter();
begin
inherited DoEnter();
isActive := true;
updateColors();
end;
// Override
procedure TLiteEdit.DoExit();
begin
inherited DoExit();
isActive := false;
updateColors();
end;
// Override
procedure TLiteEdit.Change();
begin
validateState();
inherited Change();
updateColors();
end;
// Override
procedure TLiteEdit.setTheme(theme: ColorTheme);
begin
self.theme := theme; // link
end;
// Override
function TLiteEdit.getTheme(): ColorTheme;
begin
getTheme := theme;
end;
// Override
procedure TLiteEdit.updateColors();
begin
Font.Color := theme.text;
if ReadOnly then
Color := theme.textfield
else if warn then
Color := theme.warn
else if isActive then
Color := theme.active
else
Color := theme.interact;
end;
// TLiteEdit
procedure TLiteEdit.validateState();
var
i: integer;
f: real;
begin
if valueType = VT_NOT_EMPTY_TEXT then begin
if isEmpty() then
warn := true
else
warn := false;
end else if valueType = VT_FLOAT then begin
if not isFloat(Text, f) then
warn := true
else
warn := false;
end else if valueType = VT_INT then begin
if not isInt(Text, i) then
warn := true
else
warn := false;
end;
end;
// TLiteEdit
procedure TLiteEdit.setValueType(valueType: VT);
begin
self.valueType := valueType;
validateState();
updateColors();
end;
// TLiteEdit
function TLiteEdit.isEmpty(): boolean;
begin
isEmpty := Length(Text) = 0;
end;
// TLiteEdit
function TLiteEdit.isValid(): boolean;
begin
isValid := not warn;
end;
end.
|
unit JO9_Options;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxClasses, cxControls,
cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, ExtCtrls, ComCtrls, cxMemo, cxCheckBox,
cxLookAndFeelPainters, StdCtrls, cxButtons, cxGridBandedTableView,
TagTypes, FIBQuery, pFIBQuery, FIBDatabase, pFIBDatabase, FIBDataSet,
pFIBDataSet, IBase, pFIBStoredProc, cxContainer, cxTextEdit, cxMaskEdit,
cxButtonEdit, cxDropDownEdit, cxCalendar, cxCurrencyEdit, report_settings;
type
TJO9_Options_Form = class(TForm)
MainPanel: TPanel;
PageControl: TPageControl;
RepTabSheet: TTabSheet;
RepGrid: TcxGrid;
RepTableView: TcxGridTableView;
is_Active_Column: TcxGridColumn;
id_Report_Column: TcxGridColumn;
Name_Report_Column: TcxGridColumn;
is_Active_Old_Column: TcxGridColumn;
RepGridLevel: TcxGridLevel;
TabSheet1: TTabSheet;
Shape5: TShape;
Label1: TLabel;
Shape1: TShape;
Label7: TLabel;
Undef_Cust_Edit: TcxButtonEdit;
Show_Mng_Panel: TcxCheckBox;
Not_Dif_Bdg: TcxCheckBox;
Wizard_Form_Sh: TcxCheckBox;
Use_Sec_Prov: TcxCheckBox;
TabSheet2: TTabSheet;
Shape6: TShape;
Shape4: TShape;
Shape3: TShape;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Name_Sys_Edit: TcxTextEdit;
Sys_BegDateEdit: TcxDateEdit;
GroupDocView: TcxButtonEdit;
GroupDocAdd: TcxButtonEdit;
RepPanel: TPanel;
Shape2: TShape;
ApplyButton: TcxButton;
CancelButton: TcxButton;
StyleRepository: TcxStyleRepository;
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;
cxStyle17: TcxStyle;
cxStyle18: TcxStyle;
cxStyle19: TcxStyle;
cxStyle20: TcxStyle;
cxStyle21: TcxStyle;
cxStyle22: TcxStyle;
cxStyle23: TcxStyle;
cxStyle24: TcxStyle;
cxStyle25: TcxStyle;
cxStyle26: TcxStyle;
cxStyle27: TcxStyle;
cxStyle28: TcxStyle;
GridTableViewStyleSheet: TcxGridTableViewStyleSheet;
GridBandedTableViewStyleSheet: TcxGridBandedTableViewStyleSheet;
Database: TpFIBDatabase;
DataSet: TpFIBDataSet;
ReadTransaction: TpFIBTransaction;
WriteTransaction: TpFIBTransaction;
Query: TpFIBQuery;
StoredProc: TpFIBStoredProc;
ShowMonthEdit: TcxCurrencyEdit;
MainBookEdit: TcxCurrencyEdit;
cxButton1: TcxButton;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CancelButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ShowMonthEditKeyPress(Sender: TObject; var Key: Char);
procedure Undef_Cust_EditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormResize(Sender: TObject);
procedure GroupDocViewPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure GroupDocAddPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure ApplyButtonClick(Sender: TObject);
procedure cxButton1Click(Sender: TObject);
procedure RepTableViewFocusedRecordChanged(
Sender: TcxCustomGridTableView; APrevFocusedRecord,
AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
private
{ Private declarations }
public
id_Undef_Cust : variant;
id_Main_Book_Reg_Uch : variant;
id_Group_Doc_View : variant;
id_Group_Doc_Add : variant;
procedure InitConnection(DBhandle: TISC_DB_HANDLE; RTransaction: TISC_TR_HANDLE);
procedure SelectReports;
procedure SelectData;
procedure SaveOptions;
end;
function DoShowOptions(AOwner : TComponent; DBHandle : TISC_DB_HANDLE; RTrans : TISC_TR_HANDLE;
INFO : Pjo9_SYS_INFO; fs : TFormStyle) : boolean; stdcall;
exports DoShowOptions;
var
JO9_Options_Form: TJO9_Options_Form;
SYS_INFO : Pjo9_SYS_INFO;
implementation
uses DogLoaderUnit, LoadDogManedger, tagLibUnit, Rep_Setting_akt_sverki;
{$R *.dfm}
function DoShowOptions(AOwner : TComponent; DBHandle : TISC_DB_HANDLE; RTrans : TISC_TR_HANDLE;
INFO : Pjo9_SYS_INFO; fs : TFormStyle) : boolean; stdcall;
var
f : TJO9_Options_Form;
begin
SYS_INFO := INFO;
if fs = fsNormal then begin
JO9_Options_Form := TJO9_Options_Form.Create(AOwner);
JO9_Options_Form.InitConnection(DBHandle, RTrans);
JO9_Options_Form.FormStyle := fs;
GetFormParams(JO9_Options_Form);
JO9_Options_Form.ShowModal;
SetFormParams(JO9_Options_Form);
end
else begin
f := TJO9_Options_Form.Create(AOwner);
f.InitConnection(DBHandle, RTrans);
f.FormStyle := fs;
GetFormParams(f);
if fs = fsNormal then f.ShowModal
else f.Show;
end;
Result := True;
end;
procedure TJO9_Options_Form.FormCreate(Sender: TObject);
begin
is_Active_Column.DataBinding.ValueTypeClass := TcxIntegerValueType;
is_Active_Old_Column.DataBinding.ValueTypeClass := TcxIntegerValueType;
id_Report_Column.DataBinding.ValueTypeClass := TcxIntegerValueType;
Name_Report_Column.DataBinding.ValueTypeClass := TcxStringValueType;
PageControl.ActivePageIndex := 0;
end;
procedure TJO9_Options_Form.InitConnection(DBhandle: TISC_DB_HANDLE;
RTransaction: TISC_TR_HANDLE);
begin
Database.Handle := DBhandle;
ReadTransaction.Handle := RTransaction;
end;
procedure TJO9_Options_Form.SelectReports;
begin
RepTableView.DataController.RecordCount := 0;
DataSet.SelectSQL.Text := 'select * from JO9_REPORTS';
DataSet.Open;
while not DataSet.Eof do begin
with RepTableView.DataController do begin
RecordCount := RecordCount + 1;
Values[RecordCount - 1, 1] := DataSet.FieldByName('ID_REPORT').AsInteger;
Values[RecordCount - 1, 2] := DataSet.FieldByName('NAME_REPORT').AsString;
Query.SQL.Text := 'select * from JO9_REPORTS_SYS where ID_REPORT='
+ IntToStr(DataSet.FieldByName('ID_REPORT').AsInteger) + ' and KOD_SYS='
+ IntToStr(SYS_INFO^._id_Reg_Uch);
Query.ExecQuery;
if not Query.Eof then begin
Values[RecordCount - 1, 0] := 1;
Values[RecordCount - 1, 3] := 1;
end
else begin
Values[RecordCount - 1, 0] := 0;
Values[RecordCount - 1, 3] := 0;
end;
Query.Close;
end;
DataSet.Next;
end;
DataSet.Close;
end;
procedure TJO9_Options_Form.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if not (fsModal in FormState) then SetFormParams(Self);
Action := caFree;
end;
procedure TJO9_Options_Form.CancelButtonClick(Sender: TObject);
begin
if fsModal in FormState then ModalResult := mrCancel
else Close;
end;
procedure TJO9_Options_Form.FormShow(Sender: TObject);
begin
SelectReports;
SelectData;
end;
procedure TJO9_Options_Form.ShowMonthEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
GroupDocView.SetFocus;
Key := #0;
Exit;
end;
if not (Key in ['0'..'9', #8]) then begin
Key := #0;
Exit;
end;
end;
procedure TJO9_Options_Form.Undef_Cust_EditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
i, o : TSpravParams;
begin
i := TSpravParams.Create;
o := TSpravParams.Create;
i['DataBase'] := Integer(Database.Handle);
i['FormStyle'] := fsNormal;
i['bMultiSelect'] := false;
i['id_session'] := -1;
i['SelectMode'] := selCustomer;
LoadSprav('Customer\CustPackage.bpl', Self, i, o);
id_Undef_Cust := o['id_Customer'];
Undef_Cust_Edit.Text := o['Name_Customer'];
i.Free;
o.Free;
end;
procedure TJO9_Options_Form.SelectData;
begin
//////// INI
DataSet.SelectSQL.Text := 'select * from JO9_INI_SEL';
DataSet.Open;
if not DataSet.Eof then begin
id_Undef_Cust := DataSet.FieldByName('UNDEF_ID_CUST').AsVariant;
Undef_Cust_Edit.Text := DataSet.FieldByName('UNDEF_NAME_CUST').AsString;
SHOW_MNG_PANEL.Checked := DataSet.FieldByName('SHOW_MNG_PANEL').AsInteger = 1;
NOT_DIF_BDG.Checked := DataSet.FieldByName('NOT_DIF_BDG_FG').AsInteger = 1;
WIZARD_FORM_SH.Checked := DataSet.FieldByName('WIZARD_FORM_SH').AsInteger = 1;
USE_SEC_PROV.Checked := DataSet.FieldByName('USE_SECOND_PROVS').AsInteger = 1;
ID_MAIN_BOOK_REG_UCH := DataSet.FieldByName('MAIN_BOOK_REG_UCH').AsVariant;
MainBookEdit.Text := DataSet.FieldByName('MAIN_BOOK_REG_UCH').AsString;
end;
DataSet.Close;
///////// INST
DataSet.SelectSQL.Text := 'select * from JO9_INST_SEL(' + IntToStr(SYS_INFO^._id_Reg_Uch) + ')';
DataSet.Open;
if not DataSet.Eof then begin
Name_Sys_Edit.Text := DataSet.FieldByName('NAME_SYS').AsString;
if not VarIsNull(DataSet.FieldByName('SYS_BEGIN').AsVariant) then Sys_BegDateEdit.Date := DataSet.FieldByName('SYS_BEGIN').AsDateTime;
if not VarIsNull(DataSet.FieldByName('SHOW_MONTHS').AsVariant) then ShowMonthEdit.Text := DataSet.FieldByName('SHOW_MONTHS').AsString;
id_Group_Doc_View := DataSet.FieldByName('ID_GROUP_DOG').AsVariant;
id_Group_Doc_Add := DataSet.FieldByName('ID_GROUP_DOG_ADD').AsVariant;
GroupDocView.Text := DataSet.FieldByName('NAME_GROUP_DOC').AsString;
GroupDocAdd.Text := DataSet.FieldByName('NAME_GROUP_DOC_ADD').AsString;
end;
DataSet.Close;
end;
procedure TJO9_Options_Form.FormResize(Sender: TObject);
begin
MainPanel.Left := (Width - MainPanel.Width - 7) div 2;
MainPanel.Top := (Height - MainPanel.Height - 32) div 2;
end;
procedure TJO9_Options_Form.GroupDocViewPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
f : variant;
begin
f := null;
f := WorkGroupDoc(Self, Database.Handle, fsNormal, 'tip_dog');
if VarIsNull(f) then Exit;
if VarArrayDimCount(f) <= 0 then Exit;
if VarIsNull(f[0]) then Exit;
if VarArrayDimCount(f[0]) <= 0 then Exit;
id_Group_Doc_View := f[0][0];
GroupDocView.Text := f[0][1];
end;
procedure TJO9_Options_Form.GroupDocAddPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
f : variant;
begin
f := null;
f := WorkGroupDoc(Self, Database.Handle, fsNormal, 'tip_dog');
if VarIsNull(f) then Exit;
if VarArrayDimCount(f) <= 0 then Exit;
if VarIsNull(f[0]) then Exit;
if VarArrayDimCount(f[0]) <= 0 then Exit;
id_Group_Doc_Add := f[0][0];
GroupDocAdd.Text := f[0][1];
end;
procedure TJO9_Options_Form.SaveOptions;
var
ShowMngPanel,
WizardFormSh,
NotDifBdg,
UseSecProv : byte;
i : integer;
begin
StoredProc.Transaction.StartTransaction;
if Show_Mng_Panel.Checked then ShowMngPanel := 1 else ShowMngPanel := 0;
if Wizard_Form_Sh.Checked then WizardFormSh := 1 else WizardFormSh := 0;
if Not_Dif_Bdg.Checked then NotDifBdg := 1 else NotDifBdg := 0;
if Use_Sec_Prov.Checked then UseSecProv := 1 else UseSecProv := 0;
StoredProc.ExecProcedure('JO9_INI_MOD', [id_Undef_Cust, ShowMngPanel,
WizardFormSh, NotDifBdg, UseSecProv, MainBookEdit.Value]);
StoredProc.ExecProcedure('JO9_INST_MOD', [SYS_INFO._id_Reg_Uch, Name_Sys_Edit.Text,
Sys_BegDateEdit.Date, ShowMonthEdit.Value, id_Group_Doc_View, id_Group_Doc_Add]);
with RepTableView.DataController do begin
for i := 0 to RecordCount - 1 do begin
if Values[i, 0] <> Values[i, 3] then begin
if Values[i, 0] = 0 then
StoredProc.ExecProcedure('JO9_REPORTS_SYS_DEL', [Values[i, 1], SYS_INFO^._id_Reg_Uch])
else
StoredProc.ExecProcedure('JO9_REPORTS_SYS_ADD', [Values[i, 1], SYS_INFO^._id_Reg_Uch]);
end;
end;
end;
StoredProc.Transaction.Commit;
ShowMessage('Зміни успішно збережено!' + #13 + #13 + 'Але вони набудуть сили з наступним запуском системи!');
end;
procedure TJO9_Options_Form.ApplyButtonClick(Sender: TObject);
begin
SaveOptions;
Close;
end;
procedure TJO9_Options_Form.cxButton1Click(Sender: TObject);
var
Report_Settings_Form: TReport_Settings_Form;
f:TSetPropAktForm;
begin
if RepTableView.DataController.Values[RepTableView.DataController.FocusedRecordIndex,1]=15 then
begin
f:=TSetPropAktForm.Create(Self);
f.pkod_sys:=SYS_INFO._kod_Sys;
f.db.Handle:= Database.Handle;
f.ShowModal;
f.Free;
end
else
begin
// ShowMessage(SYS_INFO._kod_Sys);
Report_Settings_Form:=TReport_Settings_Form.Create(self, Database.Handle, 14,SYS_INFO._kod_Sys);
Report_Settings_Form.ShowModal;
end;
end;
procedure TJO9_Options_Form.RepTableViewFocusedRecordChanged(
Sender: TcxCustomGridTableView; APrevFocusedRecord,
AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
begin
if((AFocusedRecord.Index=13)or (AFocusedRecord.Index=14)or (AFocusedRecord.Index=15)) then
cxButton1.Enabled:=true
else
cxButton1.Enabled:=false;
end;
end.
|
{*
* hnb2olol - utility that converts hnb files to olol files
* Copyright (C) 2011 Kostas Michalopoulos
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
* Kostas Michalopoulos <badsector@runtimelegend.com>
*}
program hnb2olol;
{$MODE OBJFPC}{$H+}
uses SysUtils;
const
Spaces = [#8, #9, #10, #13, ' '];
type
TAttribute = record
Name: string;
Value: string;
end;
TAttributes = array of TAttribute;
var
f: File;
Ch: Char;
LastOpenTag: string = '';
AddTickable, AddTick: Boolean;
procedure ParseCode; forward;
procedure HandleOpenTag(Name: string; Attr: TAttributes);
var
i: Integer;
begin
if Name='node' then begin
Write('NODE ');
AddTickable:=False;
AddTick:=False;
for i:=0 to Length(Attr)-1 do begin
if (Attr[i].Name='type') and (Attr[i].Value='todo') then begin
AddTickable:=True;
continue;
end;
if (Attr[i].Name='done') and (Attr[i].Value='yes') then begin
AddTick:=True;
continue;
end;
end;
end;
LastOpenTag:=Name;
end;
procedure HandleCloseTag(Name: string);
begin
if Name='node' then WriteLn('DONE');
end;
procedure HandleContent(Content: string);
begin
if LastOpenTag='data' then begin
WriteLn(Content);
if AddTickable then
WriteLn('TYPE TICKABLE')
else
WriteLn('TYPE NORMAL');
if AddTick then WriteLn('TICK');
end;
end;
procedure Next;
begin
if not Eof(f) then BlockRead(f, Ch, 1) else Ch:=#0;
end;
procedure SkipSpaces;
begin
while Ch in Spaces do Next;
end;
procedure SkipSpecialTag;
var
Counter: Integer;
InString: Boolean;
begin
Counter:=1;
InString:=False;
while not Eof(f) do begin
if Ch='"' then InString:=not InString;
if not InString then begin
if Ch='>' then begin
Dec(Counter);
if Counter=0 then begin
Next;
break;
end;
end;
if Ch='<' then Inc(Counter);
end;
Next;
end;
end;
function ParseName: string;
begin
Result:='';
SkipSpaces;
while Ch in ['a'..'z', 'A'..'Z', '-', '_', '0'..'9'] do begin
Result:=Result + Ch;
Next;
end;
end;
function NextXMLChar: Char;
var
Name: string;
begin
if Ch='&' then begin
Next;
Name:=ParseName;
if Name='amp' then Result:='&'
else if Name='quot' then Result:='"'
else if Name='lt' then Result:='<'
else if Name='gt' then Result:='>'
else Result:='?';
if Ch=';' then Next;
end else begin
Result:=Ch;
Next;
end;
end;
function ParseValue: string;
begin
Result:='';
SkipSpaces;
if Ch='"' then begin
Next;
while not Eof(f) do begin
if Ch='"' then begin
Next;
SkipSpaces;
break;
end;
Result:=Result + NextXMLChar;
end;
end else exit(ParseName);
end;
procedure ParseOpenTag;
var
Name: string;
Attr: TAttributes;
Attrs: Integer;
begin
Name:=ParseName;
SkipSpaces;
SetLength(Attr, 0);
Attrs:=0;
while not Eof(f) do begin
SkipSpaces;
if Eof(f) or (Ch='>') then begin
if Ch='>' then Next;
break;
end;
SetLength(Attr, Attrs + 1);
Attr[Attrs].Name:=ParseName;
SkipSpaces;
if Ch <> '>' then begin
if Ch='=' then begin
Next;
Attr[Attrs].Value:=ParseValue;
end;
Inc(Attrs);
SkipSpaces;
end;
end;
HandleOpenTag(Name, Attr);
ParseCode;
end;
procedure ParseCloseTag;
var
Name: string;
begin
Next;
Name:=ParseName;
SkipSpaces;
if Ch='>' then begin
Next;
SkipSpaces;
end;
HandleCloseTag(Name);
end;
procedure ParseTagBracket;
begin
Next;
if Eof(f) then exit;
if Ch in ['?', '!'] then
SkipSpecialTag
else if Ch='/' then
ParseCloseTag
else
ParseOpenTag;
end;
procedure ParseCode;
var
Content: string;
begin
SkipSpaces;
Content:='';
while not Eof(f) do begin
if Ch='<' then begin
Content:=Trim(Content);
if Content <> '' then HandleContent(Content);
Content:='';
ParseTagBracket;
end else if Ch in Spaces then begin
SkipSpaces;
Content:=Content + ' ';
end else begin
Content:=Content + NextXMLChar;
end;
end;
Content:=Trim(Content);
if Content <> '' then HandleContent(Content);
end;
begin
if ParamCount < 1 then begin
WriteLn('Usage: hnb2olol <filename.hnb>');
exit;
end;
Assign(f, ParamStr(1));
{$I-}
Reset(f, 1);
{$I+}
if IOResult <> 0 then begin
WriteLn('Failed to open ', ParamStr(1), ' for input');
exit;
end;
WriteLn('NOTE');
WriteLn('NOTE Converted from ', ParamStr(1), ' using hnb2olol');
WriteLn('NOTE');
WriteLn('NODE');
WriteLn('TYPE NORMAL');
Next;
ParseCode;
WriteLn('DONE');
WriteLn('STOP');
Close(f);
end.
|
unit AirplaneFrm;
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.Imaging.pngimage, ImageFrm;
type
TAirplaneForm = class(TImageForm)
ComboBox1: TComboBox;
Label2: TLabel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
AirplaneForm: TAirplaneForm;
implementation
{$R *.dfm}
procedure TAirplaneForm.FormCreate(Sender: TObject);
resourcestring
SText = 'Airplane';
SDescription = 'This is am airplane. It is very fast way to travel.';
begin
TextLabel.Caption := SText;
DescriptionLabel.Caption := SDescription;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.