text stringlengths 14 6.51M |
|---|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLTrail<p>
Creates a trail-like mesh.
Based on Jason Lanford's demo. <p>
<b>History : </b><font size=-1><ul>
<li>23/08/10 - Yar - Added OpenGLTokens to uses, replaced OpenGL1x functions to OpenGLAdapter
<li>03/04/07 - DaStr - Added default values to some properties
Added TGLTrail.AntiZFightOffset
Subscribed for Notification in TGLTrail.SetTrailObject
<li>28/03/07 - DaStr - Renamed parameters in some methods
(thanks Burkhard Carstens) (Bugtracker ID = 1678658)
<li>19/12/06 - DaS - msRight (TMarkStyle) support added
<li>09/12/04 - LR - Suppress windows uses
<li>12/10/04 - Mrqzzz - Creation (Based on Jason Lanford's demo - june 2003)
</ul></font>
}
unit GLTrail;
interface
{$I GLScene.inc}
uses
System.Classes, System.SysUtils,
// GLS
GLScene, GLVectorTypes, GLMeshUtils, GLVectorGeometry, GLVectorFileObjects,
GLMesh, GLObjects, GLMaterial, GLStrings, GLBaseClasses;
const cMaxVerts = 2000;
type
TMarkStyle = (msUp, msDirection, msFaceCamera, msRight);
TGLTrail = class(TGlMesh)
private
fVertLimit: integer;
fTimeLimit: single;
fMinDistance: single;
fAlpha: single;
fAlphaFade: Boolean;
fUVScale: Single;
fVerts: array[1..cMaxVerts] of TVector3f;
fUVs: array[1..cMaxVerts] of TTexpoint;
fTimeStamps: array[1..cMaxVerts] of Double;
fVertStart,fVertEnd,fVertCount: integer;
fLastV0Pos,fLastPos, fLastDir, fLastUp: TVector3f;
FLastUVs: single;
// used for UV scaling
fLastP1,fLastP2: TVector3f;
FTrailObject: TGLBaseSceneObject;
FMarkStyle: TMarkStyle;
FMarkWidth: single;
FEnabled: boolean;
FAntiZFightOffset: Single;
procedure SetTrailObject(const Value: TGLBaseSceneObject);
procedure SetMarkStyle(const Value: TMarkStyle);
procedure SetAlpha(const Value: single);
procedure SetAlphaFade(const Value: Boolean);
procedure SetMinDistance(const Value: single);
procedure SetTimeLimit(const Value: single);
procedure SetUVScale(const Value: single);
procedure SetVertLimit(const Value: integer);
procedure SetMarkWidth(const Value: single);
procedure SetEnabled(const Value: boolean);
function StoreAntiZFightOffset: Boolean;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
//EnableUVmapping: boolean; // generate UV's or not
procedure DoProgress(const progressTime : TProgressTimes); override;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CreateMark(obj: TGlBaseSceneObject; width: single;CurrentTime : Double); overload;
procedure CreateMark(APos,ADir,AUp: TVector3f; AWidth: single;ACurrentTime : Double); overload;
function CreateMark(p1,p2: TVector3f;CurrentTime : Double):boolean; overload;
procedure ClearMarks;
published
{: Add a tiny bit of offset to help prevent z-fighting..
Need a better solution here as this will get out of whack on really
long trails and is dependant on scene scale. }
property AntiZFightOffset: Single read FAntiZFightOffset write FAntiZFightOffset stored StoreAntiZFightOffset;
property VertLimit: integer read FVertLimit write SetVertLimit default 150;
property TimeLimit: single read FTimeLimit write SetTimeLimit;
{: Don't create mark unless moved at least this distance. }
property MinDistance: single read FMinDistance write SetMinDistance;
property Alpha: single read FAlpha write SetAlpha;
property AlphaFade: Boolean read FAlphaFade write SetAlphaFade default True;
property UVScale: single read FUVScale write SetUVScale;
property MarkStyle : TMarkStyle read FMarkStyle write SetMarkStyle default msFaceCamera;
property TrailObject : TGLBaseSceneObject read FTrailObject write SetTrailObject default nil;
property MarkWidth : single read FMarkWidth write SetMarkWidth;
property Enabled : boolean read FEnabled write SetEnabled default True;
end;
implementation
constructor TGLTrail.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
vertices.Clear; // inherited tglmesh makes a triangle... remove it.
Mode := mmTriangleStrip;
FAntiZFightOffset := 0.0000266;
VertexMode := vmVNCT;
fVertStart := 1;
fVertEnd := 0;
fVertCount := 0;
fVertLimit := 150;
fTimeLimit := 0.5;
fMinDistance := 0.05;
fAlphaFade := True;
fAlpha := 1.0;
fLastUVs := 0;
fUVScale := 1.0;
FMarkWidth := 0.5;
FEnabled := True;
FMarkStyle := msFaceCamera;
Material.BlendingMode := bmAdditive;
Material.FaceCulling := fcNoCull;
end;
destructor TGLTrail.Destroy;
begin
// notta?
inherited Destroy;
end;
procedure TGLTrail.DoProgress(const progressTime: TProgressTimes);
begin
inherited;
if Enabled and Assigned(TrailObject) then
begin
CreateMark(TrailObject,MarkWidth,progressTime.NewTime);
end;
end;
procedure TGLTrail.ClearMarks;
begin
Vertices.Clear;
fVertCount := 0;
fVertEnd := 0;
fVertStart := 1;
end;
procedure TGLTrail.CreateMark(obj: TGlBaseSceneObject; width: single;CurrentTime : Double);
var
v0,dv,p1,p2 : TVector3f;
v: TVector3f;
c: TGLCamera;
begin
case MarkStyle of
msUp: begin
v := AffinevectorMake(obj.AbsoluteUp);
end;
msDirection: begin
v := AffinevectorMake(obj.AbsoluteDirection);
end;
msRight: begin
v := AffinevectorMake(obj.AbsoluteRight);
end;
msFaceCamera: begin
c := Scene.CurrentGLCamera;
if c<>nil then
begin
dv := VectorSubtract(fLastV0Pos,AffinevectorMake(obj.AbsolutePosition));
v := VectorCrossProduct(AffinevectorMake(VectorSubtract(c.AbsolutePosition,obj.AbsolutePosition)),dv);
NormalizeVector(v);
end;
end;
else Assert(False, glsErrorEx + glsUnknownType);
end;
v0 := AffinevectorMake(Obj.AbsolutePosition);
VectorScale(v,width,v);
p1:=VectorSubtract(v0,v);
p2:=VectorAdd(v0,v);
// PREVENT REFLAT
if not PointIsInHalfSpace(p1,fLastV0Pos,VectorSubtract(v0,fLastV0Pos)) then
p1 := fLastp1;
if not PointIsInHalfSpace(p2,fLastV0Pos,VectorSubtract(v0,fLastV0Pos)) then
p2 := fLastp2;
if CreateMark(p1,p2,CurrentTime) then
begin
fLastV0Pos := v0;
end;
end;
function TGLTrail.CreateMark(p1,p2: TVector3f; CurrentTime : Double): boolean;
var
diff: integer;
uv1,uv2: TTexPoint;
apoint1,apoint2: TVector3f;
currentvert: integer;
i: integer;
color: tVector4f;
ramp: single;
distance: single;
uvsize: single;
tinyoffset: TVector3f;
MustRebuild : Boolean;
begin
Result := false;
apoint1 := p1;
apoint2 := p2;
// get distance moved, based on average of 2 point movement;
distance := ( VectorDistance(fLastp1,p1) + VectorDistance(fLastp2,p2) ) / 2;
if distance = 0 then
begin
apoint1 := AffineVectorMake(fLastp1.V[0],fLastp1.V[1],fLastp1.V[2]);
apoint2 := AffineVectorMake(fLastp2.V[0],fLastp2.V[1],fLastp2.V[2]);
end;
uvsize := distance / fUVScale; // scale UV's
uv2.S := 0+fLastUVs+uvsize; uv2.T := 0;
uv1.S := 0+fLastUVs+uvsize; uv1.T := 1;
// process verts, then send them to .vertices for rendering
if fVertEnd >= cMaxVerts then
fVertEnd := 0;
fVerts[fVertEnd+1] := apoint2;
fVerts[fVertEnd+2] := apoint1;
fUVs[fVertEnd+1] := uv2;
fUVs[fVertEnd+2] := uv1;
//tstamp := GetTickCount; // win api
fTimeStamps[fVertEnd+1] := CurrentTime;
fTimeStamps[fVertEnd+2] := CurrentTime;
MustRebuild := false;
if distance >= fMinDistance then
begin
inc(fVertCount,2);
inc(fVertEnd,2);
// remember stuff
fLastUVs := fLastUVs + uvsize;
fLastp1 := p1; fLastp2 := p2;
MustRebuild := true;
Result := true;
end;
// remove expired verts over VertLimit
if fVertCount > fVertLimit then
begin
diff := fVertCount - fVertLimit;
inc(fVertStart,diff); // inc start, reducing count to fit in limit - rollover handled later
dec(fVertCount,diff);
end;
// remove time expired verts over TimeLimit
//currentvert := fVertStart;
for i := 0 to fVertCount-1 do
begin
if (i + fVertStart) > cMaxVerts then
currentvert := (i + fVertStart) - cMaxVerts // rollover
else
currentvert := (i + fVertStart);
if fTimeLimit > 0 then
if CurrentTime - fTimeStamps[ currentvert ] > fTimeLimit then
begin
inc(fVertStart,1); // inc start, reducing count to fit in limit - rollover handled later
dec(fVertCount,1);
MustRebuild := true;
end;
end;
// handle rollover
if fVertStart > cMaxVerts then fVertStart := 0 + ( fVertStart - cMaxVerts); // adjust if rollover
if MustRebuild then
begin
// give to .vertices, from start to count
//currentvert := fVertStart;
ramp := fAlpha / (fVertCount) ;
color := material.FrontProperties.Diffuse.Color;
Vertices.Clear;
for i := 0 to fVertCount-1 do
begin
if (i + fVertStart) > cMaxVerts then
currentvert := (i + fVertStart) - cMaxVerts // rollover
else
currentvert := (i + fVertStart);
if fAlphaFade then
color.V[3] := (ramp * i)
else
color.V[3] := fAlpha;
// add a tiny bit of offset to help prevent z-fighting..
// need a better solution here
// as this will get out of whack on really long trails
// and is dependant on scene scale
TinyOffset.V[0] := FAntiZFightOffset * i;
TinyOffset.V[1] := FAntiZFightOffset * i;
TinyOffset.V[2] := FAntiZFightOffset * i;
TinyOffset := VectorAdd( fVerts[ currentvert ],Tinyoffset);
//TinyOffset := fVerts[ currentvert]; // bypass
Vertices.AddVertex( TinyOffset, NullVector, Color, fUVs[currentvert] );
end;
end;
end;
procedure TGLTrail.CreateMark(APos,ADir,AUp: TVector3f; AWidth: single;ACurrentTime : Double);
var
apoint1,apoint2,crossp: TVector3f;
begin
if fMinDistance > 0 then
if vectorDistance(APos,fLastPos) < fMinDistance then
exit;
fLastPos := APos;
fLastDir := ADir;
fLastUp := AUp;
apoint1 := APos;
apoint2 := APos;
crossp := vectorcrossproduct(ADir,AUp);
CombineVector( apoint1,vectornormalize(crossp),AWidth);
CombineVector( apoint2,vectornormalize(VectorNegate(crossp)),AWidth);
CreateMark( apoint1, apoint2,ACurrentTime);
end;
// NOTES and stuff:
{ // UV mapped 4x4 square for refrence /debug
uv.S := 0; uv.T := 0;
Vertices.AddVertex( AffineVectorMake(1, 1, 1), NullVector, NullHmgVector, UV );
uv.S := 0; uv.T := 1;
Vertices.AddVertex( AffineVectorMake(1, 1, 4), NullVector, NullHmgVector, UV );
uv.S := 1; uv.T := 0;
Vertices.AddVertex( AffineVectorMake(4, 1, 1), NullVector, NullHmgVector, UV );
uv.S := 1; uv.T := 1;
Vertices.AddVertex( AffineVectorMake(4, 1, 4), NullVector, NullHmgVector, UV );
// Directmode: append .vertices only, no way to process/delete except .clear;
// else we manage vertices/UV in our own arrays then dump them all to .vertices
// I don't know if directmode is that much faster, but could be considerably?
if directmode then
begin
if fUVTop then // start a new UV tile
begin
uv2.S := 0; uv2.T := 0;
Vertices.AddVertex( AffineVectorMake(apoint2[0], apoint2[1],apoint2[2]), NullVector, NullHmgVector, UV2 );
uv1.S := 0; uv1.T := 1;
Vertices.AddVertex( AffineVectorMake(apoint1[0],apoint1[1],apoint1[2]), NullVector, NullHmgVector, UV1 );
end
else // finish a UV tile
begin
uv2.S := 1; uv2.T := 0;
Vertices.AddVertex( AffineVectorMake(apoint2[0], apoint2[1],apoint2[2]), NullVector, NullHmgVector, UV2 );
uv1.S := 1; uv1.T := 1;
Vertices.AddVertex( AffineVectorMake(apoint1[0],apoint1[1],apoint1[2]), NullVector, NullHmgVector, UV1 );
end;
end
}
procedure TGLTrail.SetTrailObject(const Value: TGLBaseSceneObject);
begin
if FTrailObject <> nil then FTrailObject.RemoveFreeNotification(Self);
FTrailObject := Value;
if FTrailObject <> nil then FTrailObject.FreeNotification(Self);
end;
procedure TGLTrail.SetMarkStyle(const Value: TMarkStyle);
begin
FMarkStyle := Value;
end;
procedure TGLTrail.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if (Operation = opRemove) and (AComponent = FTrailObject) then
TrailObject:=nil;
inherited;
end;
procedure TGLTrail.SetAlpha(const Value: single);
begin
FAlpha := Value;
end;
procedure TGLTrail.SetAlphaFade(const Value: Boolean);
begin
FAlphaFade := Value;
end;
procedure TGLTrail.SetMinDistance(const Value: single);
begin
FMinDistance := Value;
end;
procedure TGLTrail.SetTimeLimit(const Value: single);
begin
FTimeLimit := Value;
end;
procedure TGLTrail.SetUVScale(const Value: single);
begin
FUVScale := Value;
end;
procedure TGLTrail.SetVertLimit(const Value: integer);
begin
FVertLimit := Value;
end;
procedure TGLTrail.SetMarkWidth(const Value: single);
begin
FMarkWidth := Value;
end;
procedure TGLTrail.SetEnabled(const Value: boolean);
begin
FEnabled := Value;
end;
function TGLTrail.StoreAntiZFightOffset: Boolean;
begin
Result := FAntiZFightOffset <> 0.0000266;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// class registrations
RegisterClasses([TGLTrail]);
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/.
*
* Autor: Brovin Y.D.
* E-mail: y.brovin@gmail.com
*
********************************************************************}
unit FGX.ItemsReg;
interface
procedure Register;
implementation
uses
DesignIntf, FMX.Header, FMX.Menus, FMX.TreeView, FMX.SearchBox, FMX.ListBox, FMX.Edit, FMX.Grid, FGX.GradientEdit,
FGX.Editor.Items, FGX.Items, FGX.Toolbar;
procedure Register;
begin
{ Registration Class of Items for Item Editor }
TfgItemsManager.RegisterItems(TfgToolBar, [TfgToolBarButton, TfgToolBarPopupButton, TfgToolBarSeparator,
TfgToolBarDivider, TfgToolBarComboBox]);
TfgItemsManager.RegisterItems(TfgToolBarComboBox, [TListBoxItem, TMetropolisUIListBoxItem,
TListBoxHeader, TSearchBox, TListBoxGroupHeader,
TListBoxGroupFooter]);
{ Register Items designer for standard controls }
TfgItemsManager.RegisterItems(TListBox, [TListBoxItem, TMetropolisUIListBoxItem, TListBoxHeader, TSearchBox,
TListBoxGroupHeader, TListBoxGroupFooter]);
TfgItemsManager.RegisterItem(TTreeView, TfgItemInformation.Create(TTreeViewItem, True));
TfgItemsManager.RegisterItems(TEdit, [TEditButton, TClearEditButton, TPasswordEditButton, TSearchEditButton,
TEllipsesEditButton, TDropDownEditButton, TSpinEditButton]);
TfgItemsManager.RegisterItems(TComboBox, [TListBoxItem, TMetropolisUIListBoxItem, TListBoxHeader, TSearchBox,
TListBoxGroupHeader, TListBoxGroupFooter]);
TfgItemsManager.RegisterItems(TStringGrid, [TStringColumn]);
TfgItemsManager.RegisterItems(TGrid, [TColumn, TCheckColumn, TStringColumn, TProgressColumn, TPopupColumn,
TImageColumn, TDateColumn, TTimeColumn]);
TfgItemsManager.RegisterItems(THeader, [THeaderItem]);
TfgItemsManager.RegisterItem(TPopupMenu, TfgItemInformation.Create(TMenuItem, True));
TfgItemsManager.RegisterItem(TMenuBar, TfgItemInformation.Create(TMenuItem, True));
TfgItemsManager.RegisterItem(TMainMenu, TfgItemInformation.Create(TMenuItem, True));
{ Component Editors }
RegisterComponentEditor(TfgToolBar, TfgItemsEditor);
RegisterComponentEditor(TfgToolBarComboBox, TfgItemsEditor);
{$IFDEF REGISTER_ITEMS_DESIGNER}
{ Component Editors }
RegisterComponentEditor(TListBox, TfgItemsEditor);
RegisterComponentEditor(TTreeView, TfgItemsEditor);
RegisterComponentEditor(TEdit, TfgItemsEditor);
RegisterComponentEditor(TComboBox, TfgItemsEditor);
RegisterComponentEditor(TStringGrid, TfgItemsEditor);
RegisterComponentEditor(TGrid, TfgItemsEditor);
RegisterComponentEditor(THeader, TfgItemsEditor);
RegisterComponentEditor(TPopupMenu, TfgItemsEditor);
RegisterComponentEditor(TMenuBar, TfgItemsEditor);
RegisterComponentEditor(TMainMenu, TfgItemsEditor);
{$ENDIF}
end;
end.
|
{
Eulerian Tour
Flory Algorithm O(N2)
Input:
G: Directed (not nessecerily simple) connected eulerian graph
N: Number of vertices
Output:
CLength: Length of tour
C: Eulerian tour
Reference:
West
By Ali
}
program
EulerianTour;
const
MaxN = 50 + 2;
var
N: Integer;
G: array[1 .. MaxN, 1 .. MaxN] of Integer;
CLength: Integer;
C: array[1 .. MaxN * MaxN] of Integer;
Lcl: Integer;
Lc: array[1 .. MaxN] of Integer;
Tb: array[1 .. MaxN * MaxN, 1 .. 2] of Integer;
Mark, MMark: array[1 .. MaxN] of Boolean;
MainV: Integer;
function DFS(v: Integer): boolean;
var
i: Integer;
begin
if Mark[v] and (v <> MainV) then
begin
DFS := false;
exit;
end;
Mark[v] := true;
Inc(Lcl);
Lc[Lcl] := v;
DFS := true;
if (v = Mainv) and (Lcl > 1) then
exit;
for i := 1 to N do
if G[v, i] > 0 then
begin
Dec(G[v, i]);
{ Dec(G[j, i]); // if graph is undirected!!!}
if DFS(i) then
exit;
Inc(G[v, i]);
{ Inc(G[j, i]); // if graph is undirected!!!}
end;
Dec(Lcl);
DFS := false;
end;
function FindACycle(v: Integer): Boolean;
var
i, j: Integer;
begin
FindACycle := false;
if MMark[v] then
exit;
FillChar(Mark, SizeOf(Mark), 0);
Lcl := 0;
MainV := v;
DFS(v);
if Lcl < 2 then
begin
MMark[v] := true;
exit;
end;
FindACycle := true;
end;
procedure Euler(v: Integer);
var
i, j, k, u: Integer;
begin
Tb[1, 1] := v;
Tb[1, 2] := 0;
FillChar(MMark, SizeOf(MMark), 0);
if not FindACycle(v) then
begin
CLength := 0;
exit;
end;
for i := 1 to Lcl do begin
Tb[i, 1] := Lc[i];
Tb[i, 2] := i + 1;
end;
Tb[Lcl, 2] := 0;
k := Lcl;
u := 1;
repeat
while FindACycle(Tb[u, 1]) do begin
j := Tb[u, 2];
Tb[u, 2] := k + 1;
for i := 2 to Lcl do begin
Inc(k);
Tb[k, 1] := Lc[i];
Tb[k, 2] := k + 1;
end;
Tb[k, 2] := j;
end;
u := Tb[u, 2];
until u = 0;
u := 1;
k := 0;
repeat
Inc(k);
C[k] := Tb[u, 1];
u := Tb[u, 2];
until u = 0;
CLength := k;
end;
begin
Euler(1); {Starting vertex}
end.
|
unit lib_db;
interface
uses Windows, Messages, SysUtils, Variants, Classes, ADODB, uDmConexao, DBClient, Provider, DB, ADOInt;
type
TMapaValor = class
protected
FChave : String;
FValor : Variant;
FAdicional : String;
public
constructor create(const chave : string; valor : variant; Adicional : String = '');
destructor destroy;override;
end;
TListaMapaValor = class
private
FlistaValor : TList;
public
procedure Add(const chave : string; valor : Variant; Adicional : String = '');
procedure Remove(const index : Integer); overload;
procedure Remove(const chave : string); overload;
function GetValue(const index : Integer): Variant; overload;
function GetValue(const chave : string): Variant; overload;
function GetKey(const index : integer): string;
function GetAdicional(const index : integer) : string; overload;
function GetAdicional(const chave : string) : string; overload;
function Count : Integer;
procedure Clear;
constructor create; virtual;
destructor destroy; override;
end;
TObjetoDB = class(Tobject)
private
Fquery : TADOQuery;
FTabela : String;
FParametros : TListaMapaValor;
FParametrosNewValue : TListaMapaValor;
Fdsp : TDataSetProvider;
FSqlAdicional : TStringList;
FIgnoreParams : TStringList;
function GetSQLWhere : string;
function GetSQlInsert : string;
function GetSQLUpdate : string;
function GetSQLDelete : string;
procedure SetParams;
procedure SetNewValueParamUp;
public
FNomesParamAdic: array of string;
FValoresParamAdic: array of Variant;
procedure AddIgnoreParam(Param : String);
procedure ClearIgnoreParam;
procedure AddParametro(const field : string; valor : variant; comparador : String = '=');
procedure AddParametroNewValueUp(const field : string; valor : variant);
procedure RemoverParametro(const index : Integer); overload;
procedure RemoverParametro(const chave : String); overload;
procedure RemoverTodosParametros;
procedure AddSqlAdicional(sql : String);
procedure ClearSqlAdicional;
procedure Reset;
procedure Select(fields : array of string);
procedure Insert;
procedure Update;
procedure Delete;
procedure ChangeValue(const field : String; newvalue : Variant);
procedure SaveChanges;
procedure Next;
procedure Prior;
procedure Last;
procedure First;
procedure SetParamsToNewValueUp(const onlyIgnored : Boolean);
function ParamCount: Integer;
function IsEmpty : Boolean;
function Eof : Boolean;
function Find(Field : String; Value : Variant) : Boolean;
function GetVal(const field : String): variant;
function GetData: OleVariant;
constructor create(const NomeTabela : String);
destructor destroy; override;
end;
implementation
{ TObjetoDB }
procedure TObjetoDB.AddParametro(const field: string; valor: variant; comparador : String = '=');
begin
FParametros.Add(field, valor, comparador);
end;
constructor TObjetoDB.create(const NomeTabela : String);
begin
FTabela := NomeTabela;
Fquery := TADOQuery.Create(nil);
Fquery.Connection := dmConexao.adoConexaoBd;
Fdsp := TDataSetProvider.Create(nil);
Fdsp.DataSet := Fquery;
FSqlAdicional := TStringList.Create;
FParametros := TListaMapaValor.create;
FParametrosNewValue := TListaMapaValor.create;
FIgnoreParams := TStringList.Create;
end;
destructor TObjetoDB.destroy;
begin
Fquery.Close;
FreeAndNil(Fquery);
FreeAndNil(FParametros);
FreeAndNil(fdsp);
FSqlAdicional.Clear;
FreeAndNil(FSqlAdicional);
FreeAndNil(FIgnoreParams);
FreeAndNil(FParametrosNewValue);
inherited destroy;
end;
procedure TObjetoDB.RemoverParametro(const index: Integer);
begin
FParametros.Remove(index);
end;
function TObjetoDB.GetSQLWhere: String;
var
contador : Integer;
sql : string;
key : string;
comparador : string;
begin
Result := EmptyStr;
for contador := 0 to FParametros.Count - 1 do
begin
key := FParametros.GetKey(contador);
if FIgnoreParams.IndexOf(key) = -1 then
begin
comparador := FParametros.GetAdicional(contador);
sql := sql + Format(' %s %s :%s AND ', [key, comparador, key]);
end
end;
if sql <> EmptyStr then
sql := ' WHERE ' + sql;
Result := sql;
Result := Copy(Result, 1, Length(Result) - 4);
end;
procedure TObjetoDB.RemoverParametro(const chave : String);
begin
FParametros.Remove(chave);
end;
procedure TObjetoDB.Select(fields: array of string);
var
contador : Integer;
sql_fields : string;
begin
Fquery.Close;
Fquery.SQL.Clear;
for contador := 0 to Length(fields) - 1 do
begin
sql_fields := sql_fields + fields[contador] + ', ';
end;
sql_fields := Copy(sql_fields, 1, length(sql_fields) - 2);
Fquery.SQL.Add(Format('SELECT %s', [sql_fields]));
Fquery.SQL.Add(Format(' FROM %S', [FTabela]));
Fquery.SQL.Add(GetSQLWhere);
if FSqlAdicional.Count > 0 then
Fquery.SQL.AddStrings(FSqlAdicional);
SetParams;
Fquery.Open;
end;
procedure TObjetoDB.SetParams;
var
contador : Integer;
key : string;
begin
for contador := 0 to FParametros.Count - 1 do
begin
key := FParametros.GetKey(contador);
if FIgnoreParams.IndexOf(key) = -1 then
begin
case VarType(FParametros.GetValue(contador)) of
varDate: Fquery.Parameters.ParamByName(key).ParameterObject.Type_:= adDBTimeStamp;
varCurrency: Fquery.Parameters.ParamByName(Key).DataType := ftCurrency;
varDouble: Fquery.Parameters.ParamByName(key).DataType:= ftFloat;
varInteger: Fquery.Parameters.ParamByName(key).DataType:= ftInteger;
varSmallint: Fquery.Parameters.ParamByName(key).DataType:= ftSmallint;
varString: Fquery.Parameters.parambyname(key).DataType:= ftString;
end;
Fquery.Parameters.ParamByName(key).Value := FParametros.GetValue(contador);
end
end;
for contador:= 0 to Length(FNomesParamAdic) - 1 do
begin
case VarType(FValoresParamAdic[contador]) of
varDate: Fquery.Parameters.ParamByName(FNomesParamAdic[contador]).ParameterObject.Type_:= adDBTimeStamp ;
end;
Fquery.Parameters.ParamByName(FNomesParamAdic[contador]).Value := FValoresParamAdic[contador];
end;
end;
function TObjetoDB.GetSQlInsert: String;
var
contador : Integer;
sql_fields, sql_param, field : string;
begin
if (FSqlAdicional.Count > 0) then
begin
Result := FSqlAdicional.GetText;
Exit;
end;
sql_fields := Format('INSERT INTO %s( ', [FTabela]);
sql_param := 'values( ';
for contador := 0 to FParametros.Count - 1 do
begin
field := FParametros.GetKey(contador);
sql_fields := sql_fields + field + ', ';
sql_param := sql_param + ':' + field + ', ';
end;
sql_fields := Copy(sql_fields, 1, Length(sql_fields) - 2) + ')';
sql_param := Copy(sql_param, 1, Length(sql_param) - 2) + ')';
Result := sql_fields + sql_param;
end;
procedure TObjetoDB.Insert;
begin
if (FParametros.Count = 0) and (FSqlAdicional.Count = 0) then
raise Exception.Create('Não será possível inserir, pois nenhum parametro foi fornecido');
Fquery.close;
Fquery.SQL.Clear;
Fquery.SQL.Text := GetSQlInsert;
SetParams;
Fquery.ExecSQL;
FParametros.Clear;
end;
procedure TObjetoDB.RemoverTodosParametros;
begin
FParametros.Clear;
end;
function TObjetoDB.GetVal(const field: String): variant;
begin
Result := Fquery.FieldByName(field).Value;
end;
procedure TObjetoDB.AddSqlAdicional(sql: String);
begin
FSqlAdicional.Add(sql);
end;
procedure TObjetoDB.ClearSqlAdicional;
begin
FSqlAdicional.Clear;
end;
procedure TObjetoDB.Reset;
begin
ClearSqlAdicional;
RemoverTodosParametros;
Fquery.Close;
end;
procedure TObjetoDB.ChangeValue(const field: String; newvalue: Variant);
begin
if Fquery.State in [dsBrowse, dsInactive] then
begin
Fquery.Edit;
end;
Fquery.FieldByName(field).Value := newvalue;
end;
procedure TObjetoDB.SaveChanges;
begin
if Fquery.State in [dsInsert, dsEdit] then
begin
Fquery.Post;
end
end;
procedure TObjetoDB.Next;
begin
Fquery.Next;
end;
procedure TObjetoDB.Prior;
begin
Fquery.Prior;
end;
procedure TObjetoDB.Last;
begin
Fquery.Last;
end;
procedure TObjetoDB.First;
begin
Fquery.First;
end;
function TObjetoDB.IsEmpty : Boolean;
begin
Result := Fquery.IsEmpty;
end;
function TObjetoDB.Find(Field: String; Value: Variant): Boolean;
begin
Result := Fquery.Locate(Field, Value, [loCaseInsensitive]);
end;
procedure TObjetoDB.AddIgnoreParam(Param : String);
begin
FIgnoreParams.Add(Param);
end;
procedure TObjetoDB.ClearIgnoreParam;
begin
FIgnoreParams.Clear;
end;
procedure TObjetoDB.AddParametroNewValueUp(const field: string;
valor: variant);
begin
FParametrosNewValue.Add(field, valor, '');
end;
procedure TObjetoDB.Update;
begin
if (FParametrosNewValue.Count = 0) then
raise Exception.Create('Não será possível inserir, pois nenhum parametro foi fornecido');
Fquery.close;
Fquery.Parameters.Clear;
Fquery.SQL.Clear;
Fquery.SQL.Text := GetSQLUpdate;
SetParams;
SetNewValueParamUp;
Fquery.ExecSQL;
FParametros.Clear;
FParametrosNewValue.Clear;
end;
function TObjetoDB.GetSQLUpdate: string;
var
contador : Integer;
sql_param, field : string;
begin
sql_param := Format('update %s set ', [FTabela]);
for contador := 0 to FParametrosNewValue.Count - 1 do
begin
field := FParametrosNewValue.GetKey(contador);
sql_param := sql_param + Format(' %s = :new_%s, ', [field, field ])
end;
sql_param := Copy(sql_param, 1, Length(sql_param) - 2);
sql_param := sql_param + GetSQLWhere;
Result := sql_param;
end;
procedure TObjetoDB.SetNewValueParamUp;
var
contador : Integer;
key : string;
begin
for contador := 0 to FParametrosNewValue.Count - 1 do
begin
key := FParametrosNewValue.GetKey(contador);
Fquery.Parameters.ParamByName('new_' + key).Value := FParametrosNewValue.GetValue(contador);
end;
end;
procedure TObjetoDB.SetParamsToNewValueUp(const onlyIgnored: Boolean);
var
contador : Integer;
key : string;
begin
FParametrosNewValue.Clear;
for contador := 0 to FParametros.Count - 1 do
begin
key := FParametros.GetKey(contador);
FParametrosNewValue.Add(key, FParametros.GetValue(contador), '');
end;
end;
function TObjetoDB.Eof: Boolean;
begin
Result:= Fquery.Eof;
end;
function TObjetoDB.ParamCount: Integer;
begin
Result:= FParametros.Count + Length(FNomesParamAdic)
end;
function TObjetoDB.GetData: OleVariant;
begin
Result:= Fdsp.Data;
end;
function TObjetoDB.GetSQLDelete: string;
begin
Result:= Format('DELETE FROM %s %s ', [FTabela, GetSQLWhere]);
end;
procedure TObjetoDB.Delete;
begin
Fquery.Close;
Fquery.SQL.Text:= GetSQLDelete;
SetParams;
Fquery.ExecSQL;
FParametros.Clear;
end;
{ TMapaValor }
constructor TMapaValor.create(const chave: string; valor: variant; Adicional : string = '');
begin
FChave := chave;
FValor := valor;
FAdicional := Adicional;
end;
destructor TMapaValor.destroy;
begin
inherited destroy;
end;
{ TListaMapaValor }
procedure TListaMapaValor.Add(const chave: string; valor: Variant; Adicional : String = '');
var
Mapa : TMapaValor;
begin
Mapa := TMapaValor.create(chave, valor, Adicional);
FlistaValor.Add(Mapa);
end;
function TListaMapaValor.Count : Integer;
begin
Result := FlistaValor.Count;
end;
constructor TListaMapaValor.create;
begin
FlistaValor := TList.Create;
end;
destructor TListaMapaValor.destroy;
begin
FreeAndNil(FlistaValor);
inherited destroy;
end;
procedure TListaMapaValor.Remove(const index : Integer);
begin
FlistaValor.Delete(index);
end;
function TListaMapaValor.GetValue(const index: Integer): Variant;
var
mapa : TMapaValor;
begin
mapa := FlistaValor.Items[index];
Result := mapa.FValor;
end;
procedure TListaMapaValor.Remove(const chave: string);
var
contador : Integer;
mapa : TMapaValor;
begin
for contador := 0 to FlistaValor.Count do
begin
mapa := FlistaValor.Items[contador];
if UpperCase(mapa.FChave) = UpperCase(chave) then
begin
FlistaValor.Delete(contador);
end;
end;
end;
function TListaMapaValor.GetValue(const chave: string): Variant;
var
contador : Integer;
mapa : TMapaValor;
begin
for contador := 0 to FlistaValor.Count - 1 do
begin
mapa := FlistaValor.Items[contador];
if UpperCase(mapa.FChave) = UpperCase(chave) then
begin
Result := mapa.FValor;
Break;
end;
end;
end;
function TListaMapaValor.GetKey(const index: integer): string;
var
mapa : TMapaValor;
begin
mapa := FlistaValor.Items[index];
Result := mapa.FChave;
end;
procedure TListaMapaValor.Clear;
begin
FlistaValor.Clear;
end;
function TListaMapaValor.GetAdicional(const index : integer): string;
var
mapa : TMapaValor;
begin
mapa := FlistaValor.Items[index];
Result := mapa.FAdicional;
end;
function TListaMapaValor.GetAdicional(const chave: string): string;
var
contador : Integer;
mapa : TMapaValor;
begin
for contador := 0 to FlistaValor.Count - 1 do
begin
mapa := FlistaValor.Items[contador];
if UpperCase(mapa.FChave) = UpperCase(chave) then
begin
Result := mapa.FAdicional;
Break;
end;
end;
end;
end.
|
unit IdRawBase;
interface
uses
Classes,
IdComponent, IdGlobal, IdSocketHandle,
IdStackConsts;
const
Id_TIdRawBase_Port = 0;
Id_TIdRawBase_BufferSize = 8192;
GReceiveTimeout = 0;
GFTTL = 128;
type
TIdRawBase = class(TIdComponent)
protected
FBinding: TIdSocketHandle;
FBuffer: TMemoryStream;
FHost: string;
FPort: integer;
FReceiveTimeout: integer;
FProtocol: integer;
FTTL: Integer;
function GetBinding: TIdSocketHandle;
function GetBufferSize: Integer;
procedure SetBufferSize(const AValue: Integer);
procedure SetTTL(const Value: Integer);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property TTL: Integer read FTTL write SetTTL default GFTTL;
property Binding: TIdSocketHandle read GetBinding;
property ReceiveTimeout: integer read FReceiveTimeout write FReceiveTimeout
default GReceiveTimeout;
function ReceiveBuffer(var ABuffer; const AByteCount: Integer; ATimeOut:
integer = -1): integer;
procedure Send(AData: string); overload;
procedure Send(AHost: string; const APort: Integer; AData: string);
overload;
procedure Send(AHost: string; const APort: integer; var ABuffer; const
ABufferSize: integer); overload;
published
property BufferSize: Integer read GetBufferSize write SetBufferSize default
Id_TIdRawBase_BufferSize;
property Host: string read FHost write FHost;
property Port: Integer read FPort write FPort default Id_TIdRawBase_Port;
property Protocol: Integer read FProtocol write FProtocol default
Id_IPPROTO_RAW;
end;
implementation
uses
IdResourceStrings, IdStack, SysUtils;
constructor TIdRawBase.Create(AOwner: TComponent);
begin
inherited;
FBinding := TIdSocketHandle.Create(nil);
BufferSize := Id_TIdRawBase_BufferSize;
ReceiveTimeout := GReceiveTimeout;
FPort := Id_TIdRawBase_Port;
FProtocol := Id_IPPROTO_RAW;
FTTL := GFTTL;
end;
destructor TIdRawBase.Destroy;
begin
FreeAndNil(FBinding);
FreeAndNil(FBuffer);
inherited;
end;
function TIdRawBase.GetBinding: TIdSocketHandle;
begin
if not FBinding.HandleAllocated then
begin
FBinding.AllocateSocket(Id_SOCK_RAW, FProtocol);
end;
FBinding.SetSockOpt(Id_IPPROTO_IP, Id_IP_TTL, PChar(@FTTL), SizeOf(FTTL));
Result := FBinding;
end;
function TIdRawBase.GetBufferSize: Integer;
begin
Result := FBuffer.Size;
end;
procedure TIdRawBase.SetBufferSize(const AValue: Integer);
begin
if (FBuffer = nil) then
FBuffer := TMemoryStream.Create;
FBuffer.Size := AValue;
end;
function TIdRawBase.ReceiveBuffer(var ABuffer; const AByteCount: Integer;
ATimeOut: integer = -1): integer;
begin
if (AByteCount > 0) and (@ABuffer <> nil) then
begin
if ATimeOut < 0 then
ATimeOut := FReceiveTimeout;
if Binding.Readable(ATimeOut) then
Result := Binding.Recv(ABuffer, AByteCount, 0)
else
begin
result := 0;
end;
end
else
result := 0;
end;
procedure TIdRawBase.Send(AHost: string; const APort: Integer; AData: string);
begin
AHost := GStack.ResolveHost(AHost);
Binding.SendTo(AHost, APort, AData[1], Length(AData));
end;
procedure TIdRawBase.Send(AData: string);
begin
Send(Host, Port, AData);
end;
procedure TIdRawBase.Send(AHost: string; const APort: integer; var ABuffer; const
ABufferSize: integer);
begin
AHost := GStack.ResolveHost(AHost);
Binding.SendTo(AHost, APort, ABuffer, ABufferSize);
end;
procedure TIdRawBase.SetTTL(const Value: Integer);
var
data: pointer;
begin
FTTL := Value;
Data := @FTTL;
Binding.SetSockOpt(Id_IPPROTO_IP, Id_IP_TTL, PChar(Data), SizeOf(FTTL));
end;
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Fmx.Bind.Navigator;
interface
uses
System.Classes, System.SysUtils, System.Types, System.UITypes, FMX.Types, FMX.Objects, FMX.Layouts, FMX.Edit,
FMX.Controls, FMX.ExtCtrls, FMX.Dialogs, Data.Bind.Components;
const
InitRepeatPause = 400; { pause before repeat timer (ms) }
RepeatPause = 100; { pause before hint window displays (ms)}
SpaceSize = 5; { size of space between special buttons }
type
EBindNavException = class(Exception);
TBindNavButton = class;
TBindNavGlyph = (ngEnabled, ngDisabled);
TBindNavigateBtn = (nbFirst, nbPrior, nbNext, nbLast,
nbInsert, nbDelete, nbEdit, nbPost, nbCancel, nbRefresh);
TBindNavButtonSet = set of TBindNavigateBtn;
TBindNavButtonStyle = set of (nsAllowTimer, nsFocusRect);
EBindNavClick = procedure (Sender: TObject; Button: TBindNavigateBtn) of object;
TBindNavigatorController = class(TComponent)
private
FDataSource: TBaseBindScopeComponent;
FScopeNavigator: IScopeNavigator;
FScopeState: IScopeState;
FScopeEditor: IScopeEditor;
FOnDataChanged: TNotifyEvent;
FOnEditingChanged: TNotifyEvent;
FOnActiveChanged: TNotifyEvent;
function GetActive: Boolean;
function GetBOF: Boolean;
function GetEOF: Boolean;
function GetSelected: Boolean;
function GetEditing: Boolean;
procedure SetDataSource(const Value: TBaseBindScopeComponent);
function GetCanModify: Boolean;
procedure DoOnEditingChanged(Sender: TObject);
procedure DoOnDataChanged(Sender: TObject);
procedure DoOnDataScrolled(Sender: TObject; Distance: Integer);
procedure DoOnActiveChanged(Sender: TObject);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AComponent: TComponent); override;
destructor Destroy; override;
procedure Next;
procedure Prior;
procedure First;
procedure Last;
procedure Insert;
procedure Delete;
procedure Cancel;
procedure Post;
procedure Refresh;
procedure Edit;
property Active: Boolean read GetActive;
property Editing: Boolean read GetEditing;
property Eof: Boolean read GetEOF; {Upper case EOF conflicts with C++}
property BOF: Boolean read GetBOF;
property Selected: Boolean read GetSelected;
property DataSource: TBaseBindScopeComponent read FDataSource write SetDataSource;
property CanModify: Boolean read GetCanModify;
property OnEditingChanged: TNotifyEvent read FOnEditingChanged write FOnEditingChanged;
property OnDataChanged: TNotifyEvent read FOnDataChanged write FOnDataChanged;
property OnActiveChanged: TNotifyEvent read FOnActiveChanged write FOnActiveChanged;
end;
{ TvgDBNavigator }
TCustomBindNavigator = class (TLayout)
private
FController: TBindNavigatorController;
FVisibleButtons: TBindNavButtonSet;
FHints: TStrings;
FDefHints: TStrings;
ButtonWidth: Integer;
MinBtnSize: TPoint;
FOnNavClick: EBindNavClick;
FBeforeAction: EBindNavClick;
FocusedButton: TBindNavigateBtn;
FConfirmDelete: Boolean;
FyRadius: single;
FxRadius: single;
FCornerType: TCornerType;
FCorners: TCorners;
procedure BtnMouseDown (Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: single);
procedure ClickHandler(Sender: TObject);
function GetBindScope: TBaseBindScopeComponent;
function GetHints: TStrings;
procedure HintsChanged(Sender: TObject);
procedure InitButtons;
procedure InitHints;
procedure SetBindScope(Value: TBaseBindScopeComponent);
procedure SetHints(Value: TStrings);
procedure SetSize(var W: single;var H: single);
procedure SetVisible(Value: TBindNavButtonSet); reintroduce;
procedure SetCornerType(const Value: TCornerType);
procedure SetxRadius(const Value: single);
procedure SetyRadius(const Value: single);
function IsCornersStored: Boolean;
procedure SetCorners(const Value: TCorners);
procedure OnActiveChanged(Sender: TObject);
procedure OnDataChanged(Sender: TObject);
procedure OnEditingChanged(Sender: TObject);
protected
Buttons: array[TBindNavigateBtn] of TBindNavButton;
procedure DataChanged;
procedure EditingChanged;
procedure ActiveChanged;
procedure Loaded; override;
procedure KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure CalcMinSize(var W, H: single);
property Hints: TStrings read GetHints write SetHints;
property ShowHint;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Realign; override;
procedure BtnClick(Index: TBindNavigateBtn); virtual;
property BindScope: TBaseBindScopeComponent read GetBindScope write SetBindScope;
property VisibleButtons: TBindNavButtonSet read FVisibleButtons write SetVisible
default [nbFirst, nbPrior, nbNext, nbLast, nbInsert, nbDelete,
nbEdit, nbPost, nbCancel, nbRefresh];
property Align;
property Enabled;
property CornerType: TCornerType read FCornerType write SetCornerType default TCornerType.ctRound;
property Corners: TCorners read FCorners write SetCorners stored IsCornersStored;
property xRadius: single read FxRadius write SetxRadius;
property yRadius: single read FyRadius write SetyRadius;
// property Hints: TStrings read GetHints write SetHints;
property ConfirmDelete: Boolean read FConfirmDelete write FConfirmDelete default True;
// property ShowHint;
property Visible;
property BeforeAction: EBindNavClick read FBeforeAction write FBeforeAction;
property OnClick: EBindNavClick read FOnNavClick write FOnNavClick;
end;
TBindNavigator = class(TCustomBindNavigator)
protected
property Hints;
property ShowHint;
published
property BindScope;
property VisibleButtons;
property Align;
property Enabled;
property CornerType;
property Corners;
property xRadius;
property yRadius;
// property Hints;
property ConfirmDelete;
// property ShowHint;
property Visible;
property BeforeAction;
property OnClick;
end;
{ TvgNavButton }
TBindNavButton = class(TCornerButton)
private
FIndex: TBindNavigateBtn;
FNavStyle: TBindNavButtonStyle;
FRepeatTimer: TTimer;
FPath: TPath;
procedure TimerExpired(Sender: TObject);
protected
procedure ApplyStyle; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: single); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: single); override;
property NavStyle: TBindNavButtonStyle read FNavStyle write FNavStyle;
property Index : TBindNavigateBtn read FIndex write FIndex;
end;
implementation {===============================================================}
uses System.Math, Data.Bind.Consts;
const
MaxMapSize = (MaxInt div 2) div SizeOf(Integer); { 250 million }
{ TvgDBNavigator }
var
BtnTypeName: array[TBindNavigateBtn] of PChar = ('FIRST', 'PRIOR', 'NEXT',
'LAST', 'INSERT', 'DELETE', 'EDIT', 'POST', 'CANCEL', 'REFRESH');
BtnTypePath: array[TBindNavigateBtn] of string = (
'M 361.374,349.551 L 325.968,315.176 L 361.374,280.801 Z M 323.202,349.551 L 287.797,315.176 L 323.202,280.801 Z M 286.357,349.551 L 279.277,349.551 L 279.277,280.801 L 286.357,280.801 Z',
'M 327.076,346.113 L 291.667,311.738 L 327.076,277.363 Z ',
'M 341.236,311.738 L 305.830,346.113 L 305.830,277.363 Z ',
'M 361.374,349.551 L 354.294,349.551 L 354.294,280.801 L 361.374,280.801 Z M 352.854,315.176 L 317.448,349.551 L 317.448,280.801 Z M 314.682,315.176 L 279.277,349.551 L 279.277,280.801 Z',
// plus
'M 315.303,336.714 L 315.303,315.122 L 293.228,315.122 L 293.228,306.099 L 315.303,306.099 L 315.303,284.668 L 324.706,284.668 L 324.706,306.099 L 346.781,306.099 L 346.781,315.122 L '+
'324.706,315.122 L 324.706,336.714 Z ',
// minus
'M 286.766,375.304 L 286.766,364.321 L 352.763,364.321 L 352.763,375.304 Z ',
// edit
'M 350.074,271.455 L 350.074,350.947 L 289.995,350.947 L 289.995,271.455 Z M 347.362,274.087 L 292.704,274.087 L 292.704,348.315 L 347.362,348.315 Z M 300.892,337.681 L 300.892,335.049'+
' L 339.121,335.049 L 339.121,337.681 Z M 300.892,327.100 L 300.892,324.468 L 339.121,324.468 L 339.121,327.100 Z M 300.892,316.519 L 300.892,313.887 L 339.121,313.887 L 339.121,316.519 '+
'Z M 300.892,305.884 L 300.892,303.252 L 339.121,303.252 L 339.121,305.884 Z M 300.892,295.249 L 300.892,292.617 L 339.121,292.617 L 339.121,295.249 Z M 300.892,284.668 L 300.892,282.036 L'+
' 339.121,282.036 L 339.121,284.668 Z ',
// post
'M 358.467,266.729 L '+
'360.400,269.414 C 352.512,275.181 '+
'343.733,284.064 334.069,296.058 L '+
'334.069,296.058 C 324.407,308.056 '+
'317.029,319.261 311.940,329.678 L '+
'311.940,329.678 L 307.844,332.363 '+
'C 304.454,334.659 302.148,336.358 '+
'300.929,337.466 L 300.929,337.466 '+
'C 300.452,335.787 299.402,333.028 '+
'297.777,329.194 L 297.777,329.194 '+
'L 296.229,325.703 C '+
'294.017,320.695 291.959,316.989 '+
'290.059,314.588 L 290.059,314.588 '+
'C 288.159,312.191 286.031,310.597 '+
'283.671,309.805 L 283.671,309.805 '+
'C 287.656,305.726 291.308,303.685 '+
'294.625,303.682 L 294.625,303.682 '+
'C 297.465,303.685 300.620,307.428 '+
'304.085,314.907 L 304.085,314.907 '+
'L 305.800,318.667 C '+
'312.034,308.465 320.037,298.549 '+
'329.809,288.915 L 329.809,288.915 '+
'C 339.584,279.283 349.135,271.888 '+
'358.467,266.729 L 358.467,266.729 '+
'Z ',
// cancel
'M 319.704,321.353 L 318.875,322.480 C 313.121,330.933 308.402,335.160 304.712,335.156 L 304.712,335.156 C 300.472,335.160 296.306,331.813 292.211,325.112 L 292.211,325.112 C 292.765,325.153 293.171,325.169 293.426,325.166 L 293.426,325.166 '+
'C 298.260,325.169 '+
'303.645,321.588 309.580,314.424 L 309.580,314.424 L 311.074,312.598 L 309.140,310.557 C 303.719,304.974 301.006,300.231 301.006,296.323 L 301.006,296.323 C 301.006,293.141 303.977,289.381 309.912,285.044 L 309.912,285.044 C 310.761,290.596 '+
'313.289,296.004 '+
'317.492,301.265 L 317.492,301.265 L 319.150,303.306 L 320.480,301.641 C 326.640,294.017 332.226,290.204 337.241,290.200 L 337.241,290.200 C 341.152,290.204 344.123,293.087 346.150,298.848 L 346.150,298.848 C 345.559,298.781 345.136,298.744 '+
'344.878,298.740 '+
'L 344.878,298.740 C 343.109,298.744 340.618,299.898 337.409,302.208 L 337.409,302.208 C 334.200,304.518 331.490,307.123 329.275,310.020 L 329.275,310.020 L 327.617,312.222 L 329.221,313.726 C 335.160,319.315 341.357,322.108 347.809,322.104 '+
'L 347.809,322.104 '+
'C 344.344,328.912 340.729,332.313 336.966,332.310 L 336.966,332.310 C 333.575,332.313 328.667,329.413 322.249,323.608 L 322.249,323.608 Z ',
// refresh
'M 354.848,307.012 C 354.848,312.779 353.633,318.224 351.196,323.340 L 351.196,323.340 C '+
'348.614,328.677 344.999,332.994 340.353,336.284 L 340.353,336.284 L 346.493,340.957 L '+
'326.744,346.113 L 328.570,327.046 L 334.102,331.289 C 339.819,326.388 342.676,319.567 '+
'342.676,310.825 L 342.676,310.825 C 342.676,299.620 337.180,290.865 326.190,284.561 L '+
'326.190,284.561 L 333.159,271.401 C 339.947,274.590 345.298,279.515 349.205,286.172 L '+
'349.205,286.172 C 352.968,292.550 354.848,299.496 354.848,307.012 L 354.848,307.012 Z M '+
'312.581,332.954 L 305.609,346.113 C 298.861,342.931 293.530,338.006 289.623,331.343 L '+
'289.623,331.343 C 285.823,324.971 283.923,318.026 283.923,310.503 L 283.923,310.503 C '+
'283.923,304.742 285.158,299.297 287.629,294.175 L 287.629,294.175 C 290.214,288.844 '+
'293.809,284.527 298.418,281.230 L 298.418,281.230 L 292.278,276.504 L 312.027,271.401 L '+
'310.201,290.469 L 304.669,286.226 C 298.955,291.133 296.095,297.955 296.095,306.689 L '+
'296.095,306.689 C 296.095,317.902 301.590,326.656 312.581,332.954 L 312.581,332.954 Z '
);
constructor TCustomBindNavigator.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCorners := AllCorners;
FxRadius := 4;
FyRadius := 4;
FController := TBindNavigatorController.Create(Self);
FController.OnEditingChanged := OnEditingChanged;
FController.OnDataChanged := OnDataChanged;
FController.OnActiveChanged := OnActiveChanged;
FVisibleButtons := [nbFirst, nbPrior, nbNext, nbLast, nbInsert,
nbDelete, nbEdit, nbPost, nbCancel, nbRefresh];
FHints := TStringList.Create;
TStringList(FHints).OnChange := HintsChanged;
InitButtons;
InitHints;
Width := 241;
Height := 25;
ButtonWidth := 0;
FocusedButton := nbFirst;
FConfirmDelete := True;
end;
destructor TCustomBindNavigator.Destroy;
begin
FDefHints.Free;
FController.Free;
FHints.Free;
inherited Destroy;
end;
procedure TCustomBindNavigator.OnEditingChanged(Sender: TObject);
begin
Self.EditingChanged;
end;
procedure TCustomBindNavigator.OnActiveChanged(Sender: TObject);
begin
Self.ActiveChanged;
end;
procedure TCustomBindNavigator.OnDataChanged(Sender: TObject);
begin
Self.DataChanged;
end;
procedure TCustomBindNavigator.InitButtons;
var
I: TBindNavigateBtn;
Btn: TBindNavButton;
X: single;
ResName: string;
begin
MinBtnSize := TPoint.Create(20, 18);
X := 0;
for I := Low(Buttons) to High(Buttons) do
begin
Btn := TBindNavButton.Create (Self);
Btn.Index := I;
Btn.Visible := I in FVisibleButtons;
Btn.Enabled := True;
Btn.SetBounds(X, 0, MinBtnSize.X, MinBtnSize.Y);
FmtStr(ResName, 'dbn_%s', [BtnTypeName[I]]);
// Btn.Glyph.LoadFromResourceName(HInstance, ResName);
// Btn.NumGlyphs := 2;
Btn.Enabled := False;
Btn.Enabled := True;
Btn.OnClick := ClickHandler;
Btn.OnMouseDown := BtnMouseDown;
Btn.Parent := Self;
Buttons[I] := Btn;
X := X + MinBtnSize.X;
Btn.FPath := TPath.Create(Self);
Btn.FPath.Parent := Btn;
Btn.FPath.Width := 18;
Btn.FPath.Height := 18;
Btn.FPath.Align := TAlignLayout.alCenter;
Btn.FPath.HitTest := false;
Btn.FPath.Locked := true;
Btn.FPath.Stored := false;
Btn.FPath.Data.Data := AnsiString(BtnTypePath[I]);
Btn.FPath.WrapMode := TPathWrapMode.pwFit;
Btn.FPath.Stroke.Kind := TBrushKind.bkNone;
end;
Buttons[nbPrior].NavStyle := Buttons[nbPrior].NavStyle + [nsAllowTimer];
Buttons[nbNext].NavStyle := Buttons[nbNext].NavStyle + [nsAllowTimer];
end;
procedure TCustomBindNavigator.InitHints;
//var
// I: Integer;
// J: TBindNavigateBtn;
begin
(* if not Assigned(FDefHints) then
begin
FDefHints := TStringList.Create;
for J := Low(Buttons) to High(Buttons) do
FDefHints.Add(LoadResString(BtnHintId[J]));
end;
for J := Low(Buttons) to High(Buttons) do
Buttons[J].Hint := FDefHints[Ord(J)];
J := Low(Buttons);
for I := 0 to (FHints.Count - 1) do
begin
if FHints.Strings[I] <> '' then Buttons[J].Hint := FHints.Strings[I];
if J = High(Buttons) then Exit;
Inc(J);
end; *)
end;
procedure TCustomBindNavigator.HintsChanged(Sender: TObject);
begin
InitHints;
end;
procedure TCustomBindNavigator.SetHints(Value: TStrings);
begin
if Value.Text = FDefHints.Text then
FHints.Clear else
FHints.Assign(Value);
end;
function TCustomBindNavigator.GetHints: TStrings;
begin
if (csDesigning in ComponentState) and not (csWriting in ComponentState) and
not (csReading in ComponentState) and (FHints.Count = 0) then
Result := FDefHints else
Result := FHints;
end;
procedure TCustomBindNavigator.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (FController <> nil) and
(AComponent = BindScope) then BindScope := nil;
end;
procedure TCustomBindNavigator.SetVisible(Value: TBindNavButtonSet);
var
I: TBindNavigateBtn;
W, H: single;
begin
W := Width;
H := Height;
FVisibleButtons := Value;
for I := Low(Buttons) to High(Buttons) do
Buttons[I].Visible := I in FVisibleButtons;
SetSize(W, H);
if (W <> Width) or (H <> Height) then
SetBounds(Position.X, Position.Y, W, H);
end;
procedure TCustomBindNavigator.CalcMinSize(var W, H: single);
var
Count: Integer;
I: TBindNavigateBtn;
begin
if (csLoading in ComponentState) then Exit;
if Buttons[nbFirst] = nil then Exit;
Count := 0;
for I := Low(Buttons) to High(Buttons) do
if Buttons[I].Visible then
Inc(Count);
if Count = 0 then Inc(Count);
W := Max(W, Count * MinBtnSize.X);
H := Max(H, MinBtnSize.Y);
if Align = TAlignLayout.alNone then
W := Trunc(W / Count) * Count;
end;
procedure TCustomBindNavigator.SetSize(var W: single; var H: single);
var
Count: Integer;
I: TBindNavigateBtn;
Space, Temp, Remain: single;
X: single;
begin
if (csLoading in ComponentState) then Exit;
if Buttons[nbFirst] = nil then Exit;
CalcMinSize(W, H);
Count := 0;
for I := Low(Buttons) to High(Buttons) do
if Buttons[I].Visible then
Inc(Count);
if Count = 0 then Inc(Count);
ButtonWidth := trunc(W / Count);
Temp := Count * ButtonWidth;
if Align = TAlignLayout.alNone then W := Temp;
X := 0;
Remain := W - Temp;
Temp := Count div 2;
for I := Low(Buttons) to High(Buttons) do
begin
if Buttons[I].Visible then
begin
if X = 0 then
Buttons[I].Corners := [TCorner.crTopLeft] * FCorners + [TCorner.crBottomLeft] * FCorners
else
if X > Width - (ButtonWidth * 1.5) then
Buttons[I].Corners := [TCorner.crTopRight] * FCorners + [TCorner.crBottomRight] * FCorners
else
Buttons[I].Corners := [];
Buttons[I].xRadius := FxRadius;
Buttons[I].yRadius := FyRadius;
Buttons[I].CornerType := FCornerType;
Buttons[I].ApplyStyle;
Space := 0;
if Remain <> 0 then
begin
Temp := Temp - Remain;
if Temp < 0 then
begin
Temp := Temp + Count;
Space := 1;
end;
end;
Buttons[I].SetBounds(X, 0, ButtonWidth + Space, Height);
X := X + ButtonWidth + Space;
end
else
Buttons[I].SetBounds (Width + 1, 0, ButtonWidth, Height);
end;
end;
procedure TCustomBindNavigator.Realign;
var
W, H: single;
begin
inherited ;
W := Width;
H := Height;
SetSize(W, H);
end;
procedure TCustomBindNavigator.ClickHandler(Sender: TObject);
begin
BtnClick (TBindNavButton (Sender).Index);
end;
procedure TCustomBindNavigator.BtnMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: single);
var
OldFocus: TBindNavigateBtn;
begin
OldFocus := FocusedButton;
FocusedButton := TBindNavButton(Sender).Index;
if IsFocused then
begin
SetFocus;
end
else
if CanFocus and (IsFocused) and (OldFocus <> FocusedButton) then
begin
Buttons[OldFocus].Repaint;
Buttons[FocusedButton].Repaint;
end;
end;
procedure TCustomBindNavigator.BtnClick(Index: TBindNavigateBtn);
begin
if (BindScope <> nil) then // and (FDataLink.DataSource.State <> dsInactive) then
begin
if not (csDesigning in ComponentState) and Assigned(FBeforeAction) then
FBeforeAction(Self, Index);
with FController do
begin
case Index of
nbPrior: Prior;
nbNext: Next;
nbFirst: First;
nbLast: Last;
nbInsert: Insert;
nbEdit: Edit;
nbCancel: Cancel;
nbPost: Post;
nbRefresh: Refresh;
nbDelete:
if not FConfirmDelete or (MessageDlg(TranslateText('Delete record?'), TMsgDlgType.mtConfirmation, mbOKCancel, 0) <> mrCancel) then Delete;
end;
end;
end;
if not (csDesigning in ComponentState) and Assigned(FOnNavClick) then
FOnNavClick(Self, Index);
end;
procedure TCustomBindNavigator.KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState);
//var
// NewFocus: TBindNavigateBtn;
// OldFocus: TBindNavigateBtn;
begin
(* OldFocus := FocusedButton;
case Key of
VK_RIGHT:
begin
if OldFocus < High(Buttons) then
begin
NewFocus := OldFocus;
repeat
NewFocus := Succ(NewFocus);
until (NewFocus = High(Buttons)) or (Buttons[NewFocus].Visible);
if Buttons[NewFocus].Visible then
begin
FocusedButton := NewFocus;
Buttons[OldFocus].Invalidate;
Buttons[NewFocus].Invalidate;
end;
end;
end;
VK_LEFT:
begin
NewFocus := FocusedButton;
repeat
if NewFocus > Low(Buttons) then
NewFocus := Pred(NewFocus);
until (NewFocus = Low(Buttons)) or (Buttons[NewFocus].Visible);
if NewFocus <> FocusedButton then
begin
FocusedButton := NewFocus;
Buttons[OldFocus].Invalidate;
Buttons[FocusedButton].Invalidate;
end;
end;
VK_SPACE:
begin
if Buttons[FocusedButton].Enabled then
Buttons[FocusedButton].Click;
end;
end; *)
end;
procedure TCustomBindNavigator.DataChanged;
var
UpEnable, DnEnable: Boolean;
Selected: Boolean;
begin
Selected := FController.Active and FController.Selected;
UpEnable := Enabled and Selected and not FController.BOF;
DnEnable := Enabled and Selected and not FController.EOF;
Buttons[nbFirst].Enabled := UpEnable;
Buttons[nbPrior].Enabled := UpEnable;
Buttons[nbNext].Enabled := DnEnable;
Buttons[nbLast].Enabled := DnEnable;
Buttons[nbDelete].Enabled := Enabled and FController.Active and
FController.CanModify and
FController.Selected;
end;
procedure TCustomBindNavigator.EditingChanged;
var
CanModify: Boolean;
begin
CanModify := Enabled and FController.Active and FController.CanModify;
Buttons[nbInsert].Enabled := CanModify;
Buttons[nbEdit].Enabled := CanModify and not FController.Editing;
Buttons[nbPost].Enabled := CanModify and FController.Editing;
Buttons[nbCancel].Enabled := CanModify and FController.Editing;
Buttons[nbRefresh].Enabled := CanModify;
end;
procedure TCustomBindNavigator.ActiveChanged;
var
I: TBindNavigateBtn;
begin
if not (Enabled and FController.Active) then
for I := Low(Buttons) to High(Buttons) do
Buttons[I].Enabled := False
else
begin
DataChanged;
EditingChanged;
end;
end;
procedure TCustomBindNavigator.SetBindScope(Value: TBaseBindScopeComponent);
begin
FController.DataSource := Value;
if not (csLoading in ComponentState) then
ActiveChanged;
if Value <> nil then Value.FreeNotification(Self);
end;
function TCustomBindNavigator.GetBindScope: TBaseBindScopeComponent;
begin
Result := FController.DataSource;
end;
procedure TCustomBindNavigator.Loaded;
var
W, H: single;
begin
inherited Loaded;
W := Width;
H := Height;
SetSize(W, H);
if (W <> Width) or (H <> Height) then
SetBounds(Position.X, Position.Y, W, H);
InitHints;
ActiveChanged;
end;
procedure TCustomBindNavigator.SetCornerType(const Value: TCornerType);
begin
if FCornerType <> Value then
begin
FCornerType := Value;
Realign;
end;
end;
procedure TCustomBindNavigator.SetxRadius(const Value: single);
begin
if FxRadius <> Value then
begin
FxRadius := Value;
Realign;
end;
end;
procedure TCustomBindNavigator.SetyRadius(const Value: single);
begin
if FyRadius <> Value then
begin
FyRadius := Value;
Realign;
end;
end;
function TCustomBindNavigator.IsCornersStored: Boolean;
begin
Result := FCorners <> AllCorners;
end;
procedure TCustomBindNavigator.SetCorners(const Value: TCorners);
begin
if FCorners <> Value then
begin
FCorners := Value;
Realign;
end;
end;
{ TvgNavButton }
constructor TBindNavButton.Create(AOwner: TComponent);
begin
inherited;
CanFocus := false;
FStyleLookup := 'CornerButtonStyle';
Locked := true;
Stored := false;
end;
destructor TBindNavButton.Destroy;
begin
if FRepeatTimer <> nil then
FRepeatTimer.Free;
inherited Destroy;
end;
procedure TBindNavButton.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: single);
begin
inherited MouseDown (Button, Shift, X, Y);
if nsAllowTimer in FNavStyle then
begin
if FRepeatTimer = nil then
FRepeatTimer := TTimer.Create(Self);
FRepeatTimer.OnTimer := TimerExpired;
FRepeatTimer.Interval := InitRepeatPause;
FRepeatTimer.Enabled := True;
end;
end;
procedure TBindNavButton.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: single);
begin
inherited MouseUp (Button, Shift, X, Y);
if FRepeatTimer <> nil then
FRepeatTimer.Enabled := False;
end;
procedure TBindNavButton.TimerExpired(Sender: TObject);
begin
FRepeatTimer.Interval := RepeatPause;
if (IsPressed) then
begin
try
Click;
except
FRepeatTimer.Enabled := False;
raise;
end;
end;
end;
procedure TBindNavButton.ApplyStyle;
var
S: TObject;
begin
inherited;
{ from style }
S := FindStyleResource('text');
if (S <> nil) and (S is TShape) and (FPath <> nil) then
FPath.Fill.Assign(TShape(S).Fill);
end;
{ TBindNavigatorController }
procedure TBindNavigatorController.Cancel;
begin
if Assigned(FScopeEditor) then
FScopeEditor.Cancel
end;
constructor TBindNavigatorController.Create(AComponent: TComponent);
begin
inherited Create(AComponent);
end;
procedure TBindNavigatorController.Delete;
begin
if Assigned(FScopeEditor) then
FScopeEditor.Delete
end;
destructor TBindNavigatorController.Destroy;
begin
SetDataSource(nil); // Clear notifications
inherited;
end;
procedure TBindNavigatorController.DoOnActiveChanged(Sender: TObject);
begin
if Assigned(FOnActiveChanged) then
FOnActiveChanged(Sender);
end;
procedure TBindNavigatorController.DoOnDataChanged(Sender: TObject);
begin
if Assigned(FOnDataChanged) then
FOnDataChanged(Sender);
end;
procedure TBindNavigatorController.DoOnDataScrolled(Sender: TObject; Distance: Integer);
begin
if Assigned(FOnDataChanged) then
FOnDataChanged(Sender);
end;
procedure TBindNavigatorController.DoOnEditingChanged(Sender: TObject);
begin
if Assigned(FOnEditingChanged) then
FOnEditingChanged(Sender);
end;
procedure TBindNavigatorController.Edit;
begin
if Assigned(FScopeEditor) then
FScopeEditor.Edit
end;
procedure TBindNavigatorController.First;
begin
if Assigned(FScopeNavigator) then
FScopeNavigator.First
end;
function TBindNavigatorController.GetActive: Boolean;
begin
if Assigned(FScopeState) then
Result := FScopeState.Active
else
Result := False;
end;
function TBindNavigatorController.GetBOF: Boolean;
begin
if Assigned(FScopeNavigator) then
Result := FScopeNavigator.BOF
else
Result := True;
end;
function TBindNavigatorController.GetCanModify: Boolean;
begin
if Assigned(FScopeState) then
Result := FScopeState.CanModify
else
Result := False;
end;
function TBindNavigatorController.GetEditing: Boolean;
begin
if Assigned(FScopeState) then
Result := FScopeState.Editing
else
Result := False;
end;
function TBindNavigatorController.GetEOF: Boolean;
begin
if Assigned(FScopeNavigator) then
Result := FScopeNavigator.EOF
else
Result := True;
end;
function TBindNavigatorController.GetSelected: Boolean;
begin
if Assigned(FScopeNavigator) then
Result := FScopeNavigator.Selected
else
Result := True;
end;
procedure TBindNavigatorController.Insert;
begin
if Assigned(FScopeEditor) then
FScopeEditor.Insert
end;
procedure TBindNavigatorController.Last;
begin
if Assigned(FScopeNavigator) then
FScopeNavigator.Last;
end;
procedure TBindNavigatorController.Next;
begin
if Assigned(FScopeNavigator) then
FScopeNavigator.Next;
end;
procedure TBindNavigatorController.Post;
begin
if Assigned(FScopeEditor) then
FScopeEditor.Post
end;
procedure TBindNavigatorController.Prior;
begin
if Assigned(FScopeNavigator) then
FScopeNavigator.Prior;
end;
procedure TBindNavigatorController.Refresh;
begin
if Assigned(FScopeEditor) then
FScopeEditor.Refresh;
end;
procedure TBindNavigatorController.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if Operation = TOperation.opRemove then
begin
if AComponent = FDataSource then
DataSource := nil;
end;
end;
procedure TBindNavigatorController.SetDataSource(const Value: TBaseBindScopeComponent);
begin
if FDataSource <> nil then
begin
FScopeNavigator := nil;
if FScopeState <> nil then
begin
FScopeState.RemoveActiveChanged(DoOnActiveChanged);
FScopeState.RemoveDataSetChanged(DoOnDataChanged);
FScopeState.RemoveDataSetScrolled(DoOnDataScrolled);
FScopeState.RemoveEditingChanged(DoOnEditingChanged);
end;
FScopeState := nil;
FScopeEditor := nil;
FDataSource.RemoveFreeNotification(Self);
end;
FDataSource := Value;
if FDataSource <> nil then
begin
FDataSource.FreeNotification(Self);
Supports(FDataSource, IScopeNavigator, FScopeNavigator);
Supports(FDataSource, IScopeState, FScopeState);
Supports(FDataSource, IScopeEditor, FScopeEditor);
if Assigned(FScopeState) then
begin
FScopeState.AddActiveChanged(DoOnActiveChanged);
FScopeState.AddDataSetChanged(DoOnDataChanged);
FScopeState.AddDataSetScrolled(DoOnDataScrolled);
FScopeState.AddEditingChanged(DoOnEditingChanged);
end;
end;
end;
end.
|
unit UNumeroCampo;
interface
uses
Contnrs,
uRegistro;
type
TNumeroCampo = class(TRegistro)
private
fID : Integer;
fCodigo : String;
fDescricao : String;
procedure SetCodigo(const Value: String);
procedure SetDescricao(const Value: String);
procedure SetID(const Value: Integer);
public
property ID : Integer read fID write SetID;
property Descricao : String read fDescricao write SetDescricao;
property Codigo : String read fCodigo write SetCodigo;
function Todos : TObjectList;
function Procurar () : TRegistro;
constructor create();
end;
implementation
uses
UNumeroCampoBD;
{ TNumeroCampo }
constructor TNumeroCampo.create;
begin
end;
function TNumeroCampo.Procurar: TRegistro;
var
lNumeroCampoBD : TNumeroCampoBD;
begin
lNumeroCampoBD := TNumeroCampoBD.Create;
result := lNumeroCampoBD.Procurar(self);
fDescricao := TNumeroCampo(result).fDescricao;
fCodigo := TNumeroCampo(result).fCodigo;
end;
procedure TNumeroCampo.SetCodigo(const Value: String);
begin
fCodigo := Value;
end;
procedure TNumeroCampo.SetDescricao(const Value: String);
begin
fDescricao := Value;
end;
procedure TNumeroCampo.SetID(const Value: Integer);
begin
fID := Value;
end;
function TNumeroCampo.Todos: TObjectList;
var
lNumeroCampoBD : TNumeroCampoBD;
begin
lNumeroCampoBD := TNumeroCampoBD.Create;
result := lNumeroCampoBD.Todos();
end;
end.
|
// Ported CrystalDiskInfo (The MIT License, http://crystalmark.info)
unit SMARTSupport.Seagate.SSD;
interface
uses
BufferInterpreter, Device.SMART.List, SMARTSupport, Support;
type
TSeagateSSDSMARTSupport = class(TSMARTSupport)
private
function GetTotalWrite(const SMARTList: TSMARTValueList): TTotalWrite;
public
function IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean; override;
function GetTypeName: String; override;
function IsSSD: Boolean; override;
function IsInsufficientSMART: Boolean; override;
function GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted; override;
function IsWriteValueSupported(
const SMARTList: TSMARTValueList): Boolean; override;
end;
implementation
{ TSeagateSSDSMARTSupport }
function TSeagateSSDSMARTSupport.GetTypeName: String;
begin
result := 'SmartSsd';
end;
function TSeagateSSDSMARTSupport.IsInsufficientSMART: Boolean;
begin
result := false;
end;
function TSeagateSSDSMARTSupport.IsSSD: Boolean;
begin
result := true;
end;
function TSeagateSSDSMARTSupport.IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean;
begin
result :=
(Pos('STT', IdentifyDevice.Model) = 0) and
(Pos('ST', IdentifyDevice.Model) > 0) and
(CheckIsSSDInCommonWay(IdentifyDevice));
end;
function TSeagateSSDSMARTSupport.IsWriteValueSupported(
const SMARTList: TSMARTValueList): Boolean;
const
WriteID = $F1;
begin
try
SMARTList.GetIndexByID(WriteID);
result := true;
except
result := false;
end;
end;
function TSeagateSSDSMARTSupport.GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted;
const
ReadError = true;
EraseError = false;
UsedHourID = $09;
ThisErrorType = ReadError;
ErrorID = $01;
ReplacedSectorsID = $05;
begin
FillChar(result, SizeOf(result), 0);
result.UsedHour := SMARTList.ExceptionFreeGetRAWByID(UsedHourID);
result.ReadEraseError.TrueReadErrorFalseEraseError := ReadError;
result.ReadEraseError.Value :=
SMARTList.ExceptionFreeGetRAWByID(ErrorID);
result.ReplacedSectors :=
SMARTList.ExceptionFreeGetRAWByID(ReplacedSectorsID);
result.TotalWrite := GetTotalWrite(SMARTList);
end;
function TSeagateSSDSMARTSupport.GetTotalWrite(
const SMARTList: TSMARTValueList): TTotalWrite;
function LBAToMB(const SizeInLBA: Int64): UInt64;
begin
result := SizeInLBA shr 1;
end;
function GBToMB(const SizeInLBA: Int64): UInt64;
begin
result := SizeInLBA shl 10;
end;
const
HostWrite = true;
NANDWrite = false;
WriteID = $F1;
begin
result.InValue.TrueHostWriteFalseNANDWrite :=
HostWrite;
result.InValue.ValueInMiB :=
GBToMB(SMARTList.ExceptionFreeGetRAWByID(WriteID));
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit System.Internal.Unwinder;
{
Internal only interface onto the unwinder for supplementary diagnostic information.
Not portable to different platforms, because it requires a PC mapped unwinder
implementation currently.
}
interface
{$IFDEF LINUX}
const
unwind = 'libcgunwind.so.1';
{$EXTERNALSYM unwind}
{$ENDIF LINUX}
{$IFDEF MACOS}
const
unwind = 'libcgunwind.1.0.dylib';
{$EXTERNALSYM unwind}
{$ENDIF MACOS}
{$IFDEF MACOS}
const
_U = '_';
{$EXTERNALSYM _U}
{$ELSE !MACOS}
_U = '';
{$EXTERNALSYM _U}
{$ENDIF}
type
{ Opaque handle into a thread context that the unwinder API understands. }
TUnwindContext = Pointer;
{ Opaque pointer into compiler specific unwind information for a procedure. }
TUnwindProcedureInfo = Pointer;
{ Callback function used to obtain the initial context for unwind queries. }
TQueryFunc = procedure(Context: TUnwindContext; UserData: Pointer); cdecl;
{
Stack trace element. Currently contains only the name of the procedure in
a given frame. Count be updated to contain more, at the cost of additional
development work in the unwinder libraries.
}
TStackTraceElement = class
private
FProcedureName: string;
protected
constructor Create(Name: string);
public
{ The name of the procedure that is running at this frame. }
property ProcedureName: string read FProcedureName;
end;
TStackTraceElements = array of TStackTraceElement;
{
Stack trace object. Contains an array of frame elements. Very primitive.
}
TStackTrace = class
private
FElements: TStackTraceElements;
protected
procedure AddElement(Name: string);
public
{ The stack frame elements. }
property Elements: TStackTraceElements read FElements;
end;
{
Crawls the stack, returning a stack trace from the invocation point. The
depth of the trace is currently hardcoded to in the implementation. This
should be fixed. Returns the resulting stack trace.
}
function CrawlStack: TStackTrace;
implementation
{
This is a callback initiator that enables us to get our paws on a
local instance of a data structure known only to the unwinder library.
The callback can then pass that internal data structure back into the
unwinder to get information about the stack.
}
procedure BeginQuery(Func: TQueryFunc; UserData: Pointer); cdecl;
external unwind name _U + '_BorUnwind_BeginQuery';
{
Gets the compiler specific implementation handle for the unwind information
for the stack frame that the given unwind context represents. This handle
can be passed to other APIs to provide information.
}
function GetProcedureInfo(Context: TUnwindContext): TUnwindProcedureInfo; cdecl;
external unwind name _U + '_BorUnwind_GetProcedureInfo';
{
Moves up one frame in the given stack context. The stack context is modified.
There is no way to move back down. Returns 0 if there are no more frames, and
1 otherwise.
}
function UpFrame(Context: TUnwindContext): Integer; cdecl;
external unwind name _U + '_BorUnwind_UpFrame';
{
Gets the procedure name, if any is available, for the given procedure information.
In debug builds, this is available. In a final shipping build, this may return
nil.
}
function GetProcedureName(ProcInfo: TUnwindProcedureInfo): PAnsiChar; cdecl;
external unwind name _U + '_BorUnwind_GetProcedureName';
constructor TStackTraceElement.Create(Name: string);
begin
FProcedureName := Name;
end;
{
Adds an element to the stack trace. Very primitive - we're only tracking
names right now.
}
procedure TStackTrace.AddElement(Name: string);
var
Idx: Integer;
begin
Idx := Length(FElements);
SetLength(FElements, Idx + 1);
FElements[Idx] := TStackTraceElement.Create(Name);
end;
type
PTStackTrace = ^TStackTrace;
{
Helper function that is the callback function we pass to BeginQuery to get the
stack trace going.
}
procedure StackCrawlHelper(Context: TUnwindContext; UserData: Pointer); cdecl;
var
PI: TUnwindProcedureInfo;
name: String;
pname: PAnsiChar;
trace: TStackTrace;
I: Integer;
begin
trace := TStackTrace.Create;
for I := 1 to 3 do
begin
PI := GetProcedureInfo(Context);
pname := GetProcedureName(PI);
name := string(pname);
trace.AddElement(name);
UpFrame(Context);
end;
PTStackTrace(UserData)^ := trace;
end;
function CrawlStack: TStackTrace;
var
Trace: TStackTrace;
begin
BeginQuery(StackCrawlHelper, @Trace);
Result := Trace;
end;
end.
|
unit eSocial.Controllers.Interfaces;
interface
uses
eSocial.Models.DAO.Interfaces,
eSocial.Models.Entities.Competencia,
eSocial.Models.Entities.Operacao,
eSocial.Models.Entities.Configuracao;
type
IControllerCompetencia = interface
['{D0B306D9-C0AC-483D-9AE4-EF68784F8711}']
function DAO : iModelDAOEntity<TCompetencia>;
end;
IControllerOperacao = interface
['{1D8FFED2-A3F5-456D-A0CC-CFD09D8A5363}']
function DAO : iModelDAOEntity<TOperacao>;
end;
IControllerConfiguracao = interface
['{8B6B43C0-59B4-49AF-8C85-72095CFB6544}']
function DAO : iModelDAOEntity<TConfiguracao>;
function ValidarConfiguracao : Boolean;
function Erros : String;
end;
implementation
end.
|
unit ExpressionLanguage4Delphi.Types;
interface
uses System.Classes;
type
{$SCOPEDENUMS ON}
TCondicaoFiltro = (IGUAL, MAIOR, MAIOR_IGUAL, MENOR, MENOR_IGUAL, DIFERENTE, INTERVALO, COMECE, CONTENHA, TERMINE, NAO_NULO, NULO,
SEQUENCIA, INTERVALO_NAO, COMECE_NAO, CONTENHA_NAO, TERMINE_NAO, SEQUENCIA_NAO, MES_IGUAL, ANO_IGUAL);
{$SCOPEDENUMS OFF}
TCondicaoFiltroHelper = record helper for TCondicaoFiltro
/// <returns>
/// Retorna o valor referente á condição de filtro selecionada.
/// </returns>
function GetValue: Integer;
/// <summary>
/// Converte o enum para uma string de fácil entendimento para o usuário.
/// </summary>
function ToString: string;
/// <summary>
/// Converte o enum para o expression language;
/// </summary>
function ToExpressionLanguage: string;
end;
procedure CondicaoLoadComboBox(const Items: TStrings);
function ExpressionLanguageToCondicaoFiltro(const AExpression: string): TCondicaoFiltro;
implementation
uses System.StrUtils;
function ExpressionLanguageToCondicaoFiltro(const AExpression: string): TCondicaoFiltro;
begin
case AnsiIndexStr(AExpression, ['eq', 'gt', 'ge', 'lt', 'le', 'ne', 'gap', 'begin', 'c', 'eeq', 'nnull', 'null', 'seq', 'ngap',
'nbegin', 'nc', 'neeq', 'nseq', 'meq', 'yeq']) of
0:
Result := TCondicaoFiltro.IGUAL;
1:
Result := TCondicaoFiltro.MAIOR;
2:
Result := TCondicaoFiltro.MAIOR_IGUAL;
3:
Result := TCondicaoFiltro.MENOR;
4:
Result := TCondicaoFiltro.MENOR_IGUAL;
5:
Result := TCondicaoFiltro.DIFERENTE;
6:
Result := TCondicaoFiltro.INTERVALO;
7:
Result := TCondicaoFiltro.COMECE;
8:
Result := TCondicaoFiltro.CONTENHA;
9:
Result := TCondicaoFiltro.TERMINE;
10:
Result := TCondicaoFiltro.NAO_NULO;
11:
Result := TCondicaoFiltro.NULO;
12:
Result := TCondicaoFiltro.SEQUENCIA;
13:
Result := TCondicaoFiltro.INTERVALO_NAO;
14:
Result := TCondicaoFiltro.COMECE_NAO;
15:
Result := TCondicaoFiltro.CONTENHA_NAO;
16:
Result := TCondicaoFiltro.TERMINE_NAO;
17:
Result := TCondicaoFiltro.SEQUENCIA_NAO;
18:
Result := TCondicaoFiltro.MES_IGUAL;
else
Result := TCondicaoFiltro.ANO_IGUAL;
end;
end;
procedure CondicaoLoadComboBox(const Items: TStrings);
var
Indice: Integer;
begin
Items.Clear;
for Indice := Ord(Low(TCondicaoFiltro)) to Ord(High(TCondicaoFiltro)) do
Items.Add(TCondicaoFiltro(Indice).ToString);
end;
function TCondicaoFiltroHelper.GetValue: Integer;
begin
Result := Ord(Self);
end;
function TCondicaoFiltroHelper.ToExpressionLanguage: string;
begin
case Self of
TCondicaoFiltro.IGUAL:
Result := 'eq';
TCondicaoFiltro.MAIOR:
Result := 'gt';
TCondicaoFiltro.MAIOR_IGUAL:
Result := 'ge';
TCondicaoFiltro.MENOR:
Result := 'lt';
TCondicaoFiltro.MENOR_IGUAL:
Result := 'le';
TCondicaoFiltro.DIFERENTE:
Result := 'ne';
TCondicaoFiltro.INTERVALO:
Result := 'gap';
TCondicaoFiltro.COMECE:
Result := 'begin';
TCondicaoFiltro.CONTENHA:
Result := 'c';
TCondicaoFiltro.TERMINE:
Result := 'eeq';
TCondicaoFiltro.NAO_NULO:
Result := 'nnull';
TCondicaoFiltro.NULO:
Result := 'null';
TCondicaoFiltro.SEQUENCIA:
Result := 'seq';
TCondicaoFiltro.INTERVALO_NAO:
Result := 'ngap';
TCondicaoFiltro.COMECE_NAO:
Result := 'nbegin';
TCondicaoFiltro.CONTENHA_NAO:
Result := 'nc';
TCondicaoFiltro.TERMINE_NAO:
Result := 'neeq';
TCondicaoFiltro.SEQUENCIA_NAO:
Result := 'nseq';
TCondicaoFiltro.MES_IGUAL:
Result := 'meq';
else
Result := 'yeq';
end;
end;
function TCondicaoFiltroHelper.ToString: string;
begin
case Self of
TCondicaoFiltro.IGUAL:
Result := 'Igual';
TCondicaoFiltro.MAIOR:
Result := 'Maior';
TCondicaoFiltro.MAIOR_IGUAL:
Result := 'Maior/Igual';
TCondicaoFiltro.MENOR:
Result := 'Menor';
TCondicaoFiltro.MENOR_IGUAL:
Result := 'Menor/Igual';
TCondicaoFiltro.DIFERENTE:
Result := 'Diferente';
TCondicaoFiltro.INTERVALO:
Result := 'Intervalo';
TCondicaoFiltro.COMECE:
Result := 'Que Comece';
TCondicaoFiltro.CONTENHA:
Result := 'Que Contenha';
TCondicaoFiltro.TERMINE:
Result := 'Que Termine';
TCondicaoFiltro.NAO_NULO:
Result := 'Não Nulo';
TCondicaoFiltro.NULO:
Result := 'Nulo';
TCondicaoFiltro.SEQUENCIA:
Result := 'Sequência';
TCondicaoFiltro.INTERVALO_NAO:
Result := 'Intervalo (Não)';
TCondicaoFiltro.COMECE_NAO:
Result := 'Que Comece (Não)';
TCondicaoFiltro.CONTENHA_NAO:
Result := 'Que Contenha (Não)';
TCondicaoFiltro.TERMINE_NAO:
Result := 'Que Termine (Não)';
TCondicaoFiltro.SEQUENCIA_NAO:
Result := 'Sequência (Não)';
TCondicaoFiltro.MES_IGUAL:
Result := 'Mês Igual';
else
Result := 'Ano Igual';
end;
end;
end.
|
unit ATipoContrato;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
Componentes1, ExtCtrls, PainelGradiente, StdCtrls, Mask, DBCtrls, Tabela,
DBKeyViolation, BotaoCadastro, Buttons, Db, DBTables, CBancoDados,
Localizacao, Grids, DBGrids, DBClient;
type
TFTipoContrato = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
TipoContrato: TRBSQL;
TipoContratoCODTIPOCONTRATO: TFMTBCDField;
TipoContratoNOMTIPOCONTRATO: TWideStringField;
Label1: TLabel;
DataTipoContrato: TDataSource;
Label2: TLabel;
MoveBasico1: TMoveBasico;
BotaoCadastrar1: TBotaoCadastrar;
BotaoAlterar1: TBotaoAlterar;
BotaoExcluir1: TBotaoExcluir;
BotaoGravar1: TBotaoGravar;
BotaoCancelar1: TBotaoCancelar;
BFechar: TBitBtn;
ECodigo: TDBKeyViolation;
DBEditColor1: TDBEditColor;
Bevel1: TBevel;
Label3: TLabel;
ELocaliza: TLocalizaEdit;
GridIndice1: TGridIndice;
TipoContratoCODPLANOCONTAS: TWideStringField;
Label17: TLabel;
BPlano: TSpeedButton;
LPlano: TLabel;
ConsultaPadrao1: TConsultaPadrao;
DBEditColor2: TDBEditColor;
ValidaGravacao1: TValidaGravacao;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BFecharClick(Sender: TObject);
procedure TipoContratoAfterInsert(DataSet: TDataSet);
procedure TipoContratoAfterEdit(DataSet: TDataSet);
procedure TipoContratoBeforePost(DataSet: TDataSet);
procedure TipoContratoAfterPost(DataSet: TDataSet);
procedure BPlanoClick(Sender: TObject);
procedure DBEditColor2KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ECodigoChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FTipoContrato: TFTipoContrato;
implementation
uses APrincipal, APlanoConta;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFTipoContrato.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
ELocaliza.AtualizaConsulta;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFTipoContrato.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
procedure TFTipoContrato.BFecharClick(Sender: TObject);
begin
close;
end;
{******************************************************************************}
procedure TFTipoContrato.TipoContratoAfterInsert(DataSet: TDataSet);
begin
ECodigo.ProximoCodigo;
ECodigo.ReadOnly := false;
end;
{******************************************************************************}
procedure TFTipoContrato.TipoContratoAfterEdit(DataSet: TDataSet);
begin
ECodigo.ReadOnly := true;
end;
{******************************************************************************}
procedure TFTipoContrato.TipoContratoBeforePost(DataSet: TDataSet);
begin
if TipoContrato.State = dsinsert then
ECodigo.VerificaCodigoUtilizado;
end;
{******************************************************************************}
procedure TFTipoContrato.TipoContratoAfterPost(DataSet: TDataSet);
begin
ELocaliza.AtualizaConsulta;
end;
{******************************************************************************}
procedure TFTipoContrato.BPlanoClick(Sender: TObject);
var
VpfCodigo : String;
begin
if TipoContrato.State in [dsinsert,dsedit] then
begin
FPlanoConta := TFPlanoConta.criarSDI(Self, '', True);
VpfCodigo := TipoContratoCODPLANOCONTAS.Asstring;
if not FPlanoConta.VerificaCodigo(VpfCodigo,'C', LPlano, False, (Sender is TSpeedButton)) then
DBEditColor2.SetFocus;
TipoContratoCODPLANOCONTAS.AsString := VpfCodigo;
end;
end;
procedure TFTipoContrato.DBEditColor2KeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if (Key = 114) then
BPlano.Click;
end;
{******************************************************************************}
procedure TFTipoContrato.ECodigoChange(Sender: TObject);
begin
if TipoContrato.State in [dsedit,dsinsert] then
ValidaGravacao1.execute;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFTipoContrato]);
end.
|
unit FrameDialogs;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, ComCtrls, Graphics, Dialogs,
ExtCtrls, DataBases, AddFriendDlg, Transports;
type
{ TFrameWithDialogs }
TFrameWithDialogs = class(TFrame)
ImageList: TImageList;
ListView: TListView;
PageControl: TPageControl;
PanelLeft: TPanel;
PanelLeftBottom: TPanel;
ProgressBar: TProgressBar;
Splitter: TSplitter;
MainStatusBar: TStatusBar;
TabSheet1: TTabSheet;
ToolBar: TToolBar;
ToolButtonDel: TToolButton;
ToolButtonAdd: TToolButton;
procedure ListViewResize(Sender: TObject);
procedure MainStatusBarDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect);
procedure ToolButtonAddClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
constructor Create(AOwner: TComponent); override;
procedure LoadFriendsFromDB;
procedure ShowWaitForm;
procedure HideWaitForm;
procedure OnStartOperation(AName: string);
procedure OnEndOperation;
end;
implementation
{$R *.lfm}
uses WaitForm;
var
FormWait: TFormWait;
{ TFrameWithDialogs }
procedure TFrameWithDialogs.ListViewResize(Sender: TObject);
begin
ListView.Column[0].Width := ListView.Width - 14;
end;
procedure TFrameWithDialogs.MainStatusBarDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect);
// Должен рисовать прогресс бар в статус баре
begin
case Panel.Index of
0:
begin
ProgressBar.BoundsRect := Rect;
ProgressBar.PaintTo(StatusBar.Canvas.Handle, Rect.Left, Rect.Top);
end;
end;
end;
procedure TFrameWithDialogs.ToolButtonAddClick(Sender: TObject);
// Добавляем нового друга
begin
with FormAddFriend do
begin
Clear;
if ShowModal = mrOk then
if DataBase.AddFriend(DataBase.CurrentUserID, EditName.Text, EditMail.Text, OpenPictureDialog.FileName) then
Transport.AddFriend(EditName.Text, EditMail.Text, OpenPictureDialog.FileName);
end;
end;
constructor TFrameWithDialogs.Create(AOwner: TComponent);
// Если открывается этот фрэйм, значит получаем все сообщения
begin
inherited Create(AOwner);
// Ставим иконки
ToolButtonAdd.ImageIndex := 0;
ToolButtonDel.ImageIndex := 1;
// Установим новые события
Transport.OnStartOperation := @OnStartOperation;
Transport.OnEndOperation := @OnEndOperation;
// Впишем прогресс бар в статус бар
ProgressBar.Width := 100;
ProgressBar.Parent := self;
ProgressBar.Visible := False;
ProgressBar.Position := 100;
// Грузим список друзей
LoadFriendsFromDB;
// Читаем входящие сообщения
Transport.SynchronizeMails;
end;
procedure TFrameWithDialogs.LoadFriendsFromDB;
// Загружаем пользователей из БД
var
i: integer;
Stream: TMemoryStream;
BMP: TBitmap;
JPG: TJPEGImage;
Item: TListItem;
Rect, ListItemRect: TRect;
Buf: string;
begin
BMP := TBitmap.Create;
JPG := TJPEGImage.Create;
Stream := TMemoryStream.Create;
ListView.Clear;
for i := 1 to DataBase.GetFriendsCount(DataBase.CurrentUserID) do
begin
try
Stream.Clear;
DataBase.SaveFriendAvatarToStream(DataBase.CurrentUserID, i, Stream);
if Stream.Size > 0 then
begin
Stream.Seek(0, TSeekOrigin.soBeginning);
Buf := '';
Buf += char(AnsiChar(Stream.ReadByte));
Buf += char(AnsiChar(Stream.ReadByte));
Stream.Seek(0, TSeekOrigin.soBeginning);
if AnsiLowerCase(Buf) = 'bm' then
// Грузим BMP
BMP.LoadFromStream(Stream, Stream.Size)
else
begin
// Грузим JPG
JPG.LoadFromStream(Stream);
BMP.SetSize(22, 22);
Rect.Left := 0;
Rect.Top := 0;
Rect.Right := JPG.Width;
Rect.Bottom := JPG.Height;
ListItemRect := Rect;
ListItemRect.Right := 22;
ListItemRect.Bottom := 22;
BMP.Canvas.CopyRect(ListItemRect, JPG.Canvas, Rect);
end;
// PNG и ICO
ImageList.Add(BMP, nil);
end;
except
end;
item := ListView.Items.Add;
item.Caption := DataBase.GetFriendNickName(DataBase.CurrentUserID, i);
item.ImageIndex := 1;
end;
Stream.Free;
BMP.Free;
JPG.Free;
end;
procedure TFrameWithDialogs.ShowWaitForm;
// Показать диалог ожидания
begin
if Assigned(FormWait) then
exit;
FormWait := TFormWait.Create(Self);
FormWait.ShowModal;
end;
procedure TFrameWithDialogs.HideWaitForm;
// Скрыть диалог ожидания
begin
if not Assigned(FormWait) then
Exit;
FormWait.Close;
MessageDlg('Информация', Format('На почту %s отправлен запрос открытого ключа, после получения ответа, Вы можете начать переписку...',
[FormAddFriend.EditMail.Text]), mtInformation, [mbOK], '');
end;
procedure TFrameWithDialogs.OnStartOperation(AName: string);
// Устанавливаем статус операции и дёргаем ProgressBar
begin
MainStatusBar.Panels[1].Text := AName;
ProgressBar.Position := 100;
end;
procedure TFrameWithDialogs.OnEndOperation;
// Перестаем дёрьгать ProgressBar
begin
MainStatusBar.Panels[1].Text := 'Все задания выполнены...';
end;
end.
|
unit Main;
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.Mask,
JvExMask,
JvToolEdit,
Vcl.Samples.Spin,
Vcl.Buttons,
PngSpeedButton,
System.ImageList,
Vcl.ImgList,
Vcl.Imaging.pngimage,
Vcl.Imaging.jpeg,
Quick.Chrono,
Quick.ImageFX,
Quick.ImageFX.Types,
Quick.ImageFX.GDI,
Quick.ImageFX.GR32,
Quick.ImageFX.OpenCV,
Quick.ImageFX.Vampyre;
//Needs Quick.Chrono from QuickLibs https://github.com/exilon/QuickLibs
type
TMainForm = class(TForm)
btnResize: TButton;
Memo1: TMemo;
Button2: TButton;
btnConvertTo: TButton;
cbFormat: TComboBox;
edFilename: TJvFilenameEdit;
ScrollBox1: TScrollBox;
ScrollBox2: TScrollBox;
imgSource: TImage;
imgTarget: TImage;
btnRotate: TButton;
Label1: TLabel;
Label2: TLabel;
spedX: TSpinEdit;
spedY: TSpinEdit;
Label3: TLabel;
Button3: TButton;
PngSpeedButton1: TPngSpeedButton;
btnGrayScale: TButton;
btnReloadImage: TButton;
cxNoMagnify: TCheckBox;
ImageList1: TImageList;
spedImageIndex: TSpinEdit;
btnGetImageFromList: TButton;
Label4: TLabel;
lblResolution: TLabel;
btnRounded: TButton;
spedRounded: TSpinEdit;
btnScanlineH: TButton;
btnScanlineV: TButton;
btnDarken: TButton;
btnLighten: TButton;
btnAntiAliasing: TButton;
btnAlpha: TButton;
spedAlpha: TSpinEdit;
PaintBox: TPaintBox;
btnClear: TButton;
btnSaveAsString: TButton;
btnLoadFromString: TButton;
btnTintRed: TButton;
btnTintGreen: TButton;
btnTintBlue: TButton;
btnSolarize: TButton;
btnTintAdd: TButton;
btnRotateAngle: TButton;
spedRotateAngle: TSpinEdit;
btnClearTarget: TButton;
btnLoadFromHTTP: TButton;
lblNewAspectRatio: TLabel;
btnWatermark: TButton;
cxCenter: TCheckBox;
cxFillBorders: TCheckBox;
cbResizeMode: TComboBox;
btnLoadFromStream: TButton;
btnSaveAsStream: TButton;
btnCheckJPGCorruption: TButton;
btnGetExternalIcon: TButton;
btnRandomGenerator: TButton;
Button6: TButton;
cbImageLIb: TComboBox;
procedure btnResizeClick(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnConvertToClick(Sender: TObject);
procedure edFilenameChange(Sender: TObject);
procedure btnRotateClick(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure PngSpeedButton1Click(Sender: TObject);
procedure btnGrayScaleClick(Sender: TObject);
procedure PaintImageTarget;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure LoadImagen;
procedure btnReloadImageClick(Sender: TObject);
procedure btnGetImageFromListClick(Sender: TObject);
procedure btnRoundedClick(Sender: TObject);
procedure btnScanlineHClick(Sender: TObject);
procedure btnScanlineVClick(Sender: TObject);
procedure btnDarkenClick(Sender: TObject);
procedure btnLightenClick(Sender: TObject);
procedure btnAntiAliasingClick(Sender: TObject);
procedure btnAlphaClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure btnLoadFromStringClick(Sender: TObject);
function RandomImageGenerator(w,h : Integer): Boolean;
procedure btnSaveAsStringClick(Sender: TObject);
procedure btnTintRedClick(Sender: TObject);
procedure btnTintGreenClick(Sender: TObject);
procedure btnTintBlueClick(Sender: TObject);
procedure btnSolarizeClick(Sender: TObject);
procedure btnTintAddClick(Sender: TObject);
procedure btnRotateAngleClick(Sender: TObject);
procedure btnClearTargetClick(Sender: TObject);
procedure btnLoadFromHTTPClick(Sender: TObject);
procedure spedXChange(Sender: TObject);
procedure btnWatermarkClick(Sender: TObject);
procedure btnLoadFromStreamClick(Sender: TObject);
procedure btnSaveAsStreamClick(Sender: TObject);
procedure btnCheckJPGCorruptionClick(Sender: TObject);
procedure btnGetExternalIconClick(Sender: TObject);
procedure btnRandomGeneratorClick(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure cbImageLIbChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainForm: TMainForm;
crono : TChronometer;
imagefx : IImageFX;
PicStr : string;
implementation
{$R *.dfm}
procedure TMainForm.btnAlphaClick(Sender: TObject);
begin
crono.Start;
//imagefx.SetAlpha(spedAlpha.Value);
crono.Stop;
Memo1.Lines.Add('Alpha: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnAntiAliasingClick(Sender: TObject);
begin
crono.Start;
//imagefx.AntiAliasing;
crono.Stop;
Memo1.Lines.Add('AntiAliasing: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnClearClick(Sender: TObject);
begin
PaintBox.Canvas.Brush.Color := clSilver;
PaintBox.Canvas.FillRect(PaintBox.BoundsRect);
PaintBox.Repaint;
end;
procedure TMainForm.btnClearTargetClick(Sender: TObject);
begin
imagefx.Clear;
PaintImageTarget;
end;
procedure TMainForm.btnConvertToClick(Sender: TObject);
var
bmp : TBitmap;
jpg : TJPEGImage;
png : TPngImage;
begin
crono.Start;
imagefx.LoadFromFile(edFilename.FileName);
case cbFormat.ItemIndex of
0 : begin
bmp := imagefx.AsBitmap;
try
bmp.SaveToFile('.\newbmp.bmp');
imgTarget.Picture.Assign(bmp);
finally
bmp.Free;
end;
end;
1 : begin
jpg := imagefx.AsJPG;
try
jpg.SaveToFile('.\newjpg.jpg');
imgTarget.Picture.Assign(jpg);
finally
jpg.Free;
end;
end;
2 : begin
png := imagefx.AsPNG;
try
png.SaveToFile('.\newpng.png');
imgTarget.Picture.Assign(png);
finally
png.Free;
end;
end;
3 : imgTarget.Picture.Assign(imagefx.AsGIF);
end;
crono.Stop;
Memo1.Lines.Add('Convert: ' + crono.ElapsedTime);
end;
procedure TMainForm.btnDarkenClick(Sender: TObject);
begin
crono.Start;
imagefx.Darken;
crono.Stop;
Memo1.Lines.Add('Darken: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnGetImageFromListClick(Sender: TObject);
var
png : TPngImage;
begin
crono.Start;
imagefx.LoadFromImageList(ImageList1,spedImageIndex.Value);
crono.Stop;
Memo1.Lines.Add('GetFromImageList: ' + crono.ElapsedTime);
png := imagefx.Resize(64,64,rmFitToBounds,[rfNoMagnify]).AsPNG;
try
PngSpeedButton1.PngImage.Assign(png);
finally
png.Free;
end;
PngSpeedButton1.Refresh;
end;
procedure TMainForm.btnGrayScaleClick(Sender: TObject);
begin
crono.Start;
imagefx.GrayScale;
crono.Stop;
Memo1.Lines.Add('GrayScale: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnLightenClick(Sender: TObject);
begin
crono.Start;
imagefx.Lighten;
crono.Stop;
Memo1.Lines.Add('Lighten: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnLoadFromHTTPClick(Sender: TObject);
var
statuscode : Integer;
begin
crono.Start;
imagefx.LoadFromHTTP('https://cdn.pixabay.com/photo/2015/02/01/22/16/parrot-620345_960_720.jpg',statuscode,True);
crono.Stop;
Memo1.Lines.Add('LoadFromHTTP: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnLoadFromStreamClick(Sender: TObject);
var
fs : TFileStream;
begin
fs := TFileStream.Create('..\..\img\Portrait.jpg',fmOpenRead);
try
crono.Start;
imagefx.LoadFromStream(fs);
finally
fs.Free;
end;
crono.Stop;
Memo1.Lines.Add('LoadFromStream: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnLoadFromStringClick(Sender: TObject);
begin
crono.Start;
imagefx.LoadFromString(PicStr);
crono.Stop;
Memo1.Lines.Add('LoadFromString: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnReloadImageClick(Sender: TObject);
begin
LoadImagen;
end;
procedure TMainForm.LoadImagen;
begin
if FileExists(edFilename.FileName) then
begin
imgSource.Picture.LoadFromFile(edFilename.FileName);
//imagefx.AsBitmap.Assign(imgSource.Picture.Bitmap);
crono.Start;
imagefx.LoadFromFile(edFilename.FileName);
crono.Stop;
Memo1.Lines.Add('Load Image: ' + crono.ElapsedTime);
lblResolution.Caption := imagefx.GetResolution + ' ' + imagefx.AspectRatioStr;
end;
imgTarget.Picture.Bitmap.PixelFormat := pf32bit;
imgTarget.Picture.Bitmap.AlphaFormat := afDefined;
end;
procedure TMainForm.btnRotateAngleClick(Sender: TObject);
begin
crono.Start;
imagefx.RotateBy(spedRotateAngle.Value);
crono.Stop;
Memo1.Lines.Add('Rotate Angle: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnRotateClick(Sender: TObject);
begin
crono.Start;
imagefx.Rotate90;
crono.Stop;
Memo1.Lines.Add('Rotate: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnRoundedClick(Sender: TObject);
begin
crono.Start;
imagefx.Rounded(spedRounded.Value);
crono.Stop;
Memo1.Lines.Add('Rounded: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnSaveAsStreamClick(Sender: TObject);
var
ms : TMemoryStream;
begin
crono.Start;
imagefx.LoadFromFile('..\..\img\guacamayo.png');
ms := TMemoryStream.Create;
try
imagefx.SaveToStream(ms,ifPNG);
imagefx.LoadFromStream(ms);
finally
ms.Free;
end;
crono.Stop;
Memo1.Lines.Add('SaveAsStream: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnSaveAsStringClick(Sender: TObject);
begin
crono.Start;
PicStr := imagefx.AsString(ifPNG);
crono.Stop;
Memo1.Lines.Add('SaveAsString: ' + crono.ElapsedTime);
end;
procedure TMainForm.btnScanlineHClick(Sender: TObject);
begin
crono.Start;
imagefx.ScanlineH;
crono.Stop;
Memo1.Lines.Add('Scanline Horizontal: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnScanlineVClick(Sender: TObject);
begin
crono.Start;
imagefx.ScanlineV;
crono.Stop;
Memo1.Lines.Add('Scanline Vertical: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnSolarizeClick(Sender: TObject);
begin
crono.Start;
imagefx.Solarize;
crono.Stop;
Memo1.Lines.Add('Solarize: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnTintAddClick(Sender: TObject);
begin
crono.Start;
imagefx.TintAdd(-1,-1,255);
crono.Stop;
Memo1.Lines.Add('Tint Add: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnTintBlueClick(Sender: TObject);
begin
crono.Start;
imagefx.TintBlue;
crono.Stop;
Memo1.Lines.Add('Tint Blue: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnTintGreenClick(Sender: TObject);
begin
crono.Start;
imagefx.TintGreen;
crono.Stop;
Memo1.Lines.Add('Tint Green: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnTintRedClick(Sender: TObject);
begin
crono.Start;
imagefx.TintRed;
crono.Stop;
Memo1.Lines.Add('Tint Red: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnWatermarkClick(Sender: TObject);
var
png : TPngImage;
begin
png := TPngImage.Create;
try
png.LoadFromFile('..\..\img\watermark.png');
crono.Start;
imagefx.DrawCentered(png,0.5);
finally
png.Free;
end;
crono.Stop;
Memo1.Lines.Add('Watermark: ' + crono.ElapsedTime);
PaintImageTarget;
end;
function TMainForm.RandomImageGenerator(w,h : Integer): Boolean;
var
x, y : Integer;
Pixel : TPixelInfo;
begin
Result := False;
Randomize;
imagefx.NewBitmap(w,h);
for y := 0 to h - 1 do
begin
for x := 0 to w - 1 do
begin
//Pixel := imageFX.Pixel[x,y];
Pixel.R := Random(255); //R
Pixel.G := Random(255); //G
Pixel.B := Random(255); //B
Pixel.A := 255; //A
//repair imageFX.Pixel[x,y] := Pixel;
//imagefx.SetPixelImage(x,y,Pixel,imagefx.AsImage);
end;
end;
//imagefx.SaveToJPG('D:\random.jpg');
end;
procedure TMainForm.btnResizeClick(Sender: TObject);
var
rsop : string;
begin
rsop := cbResizeMode.Text;
if cxNoMagnify.Checked then rsop := rsop + ',NoMagnify';
if cxCenter.Checked then rsop := rsop + ',Center';
if cxFillBorders.Checked then rsop := rsop + ',FillBorders';
//if cxCenter.Checked then rsop := rsop + 'Center';
crono.Start;
imagefx.ResizeOptions.NoMagnify := cxNoMagnify.Checked;
imagefx.ResizeOptions.ResizeMode := TResizeMode(cbResizeMode.ItemIndex);
imagefx.ResizeOptions.Center := cxCenter.Checked;
imagefx.ResizeOptions.FillBorders := cxFillBorders.Checked;
if cxFillBorders.Checked then imagefx.ResizeOptions.BorderColor := clWhite;
imagefx.Resize(spedX.Value,spedY.Value);
crono.Stop;
Memo1.Lines.Add(Format('Resize [%s]: %s',[rsop,crono.ElapsedTime]));
PaintImageTarget;
end;
procedure TMainForm.btnCheckJPGCorruptionClick(Sender: TObject);
var
jpg : TJPEGImage;
begin
jpg := TJPEGImage.Create;
try
jpg.LoadFromFile('..\..\img\corruptedjpg.jpg');
if imagefx.JPEGCorruptionCheck(jpg) then ShowMessage('Corrupto')
else ShowMessage('OK');
finally
jpg.Free;
end;
end;
procedure TMainForm.Button2Click(Sender: TObject);
begin
crono.Start;
if not FileExists('c:\windows\explorer.exe') then
begin
ShowMessage('Icon file not found');
Exit;
end;
imagefx.LoadFromFileIcon('c:\windows\explorer.exe',0);
crono.Stop;
Memo1.Lines.Add('ExtractIcon: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.Button3Click(Sender: TObject);
begin
crono.Start;
with imagefx do
begin
case cbFormat.ItemIndex of
0 : SaveToBMP('.\output.bmp');
1 : SaveToJPG('.\output.jpg');
2 : SaveToPNG('.\output.png');
3 : SaveToGIF('.\output.gif');
end;
end;
crono.Stop;
Memo1.Lines.Add('SaveFile: ' + crono.ElapsedTime);
end;
procedure TMainForm.btnGetExternalIconClick(Sender: TObject);
begin
crono.Start;
imagefx.LoadFromFileExtension('c:\windows\explorer.exe',True);
crono.Stop;
Memo1.Lines.Add('GetExtIcon: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.btnRandomGeneratorClick(Sender: TObject);
begin
crono.Start;
RandomImageGenerator(1920,1080);
crono.Stop;
Memo1.Lines.Add('RandomGenerator: ' + crono.ElapsedTime);
PaintImageTarget;
end;
procedure TMainForm.Button6Click(Sender: TObject);
begin
PaintImageTarget;
end;
procedure TMainForm.cbImageLIbChange(Sender: TObject);
begin
case cbImageLIb.ItemIndex of
0 : imagefx := TImageFXGDI.Create;
1 : imagefx := TImageFXGR32.Create;
2 : imagefx := TImageFXOpenCV.Create;
3 : imagefx := TImageFXVampyre.Create;
end;
LoadImagen;
end;
procedure TMainForm.PaintImageTarget;
var
bmp : TBitmap;
begin
bmp := imagefx.AsBitmap;
try
imgTarget.Picture.Assign(bmp);
PaintBox.Canvas.Draw(0,0,bmp);
finally
bmp.Free;
end;
lblResolution.Caption := imagefx.GetResolution + ' ' + imagefx.AspectRatioStr;
end;
procedure TMainForm.edFilenameChange(Sender: TObject);
begin
LoadImagen;
end;
procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
crono.Free;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
crono := TChronometer.Create(False);
crono.ReportFormatPrecission := TPrecissionFormat.pfFloat;
imagefx := TImageFXOpenCV.Create;
LoadImagen;
end;
procedure TMainForm.PngSpeedButton1Click(Sender: TObject);
var
png : TPngImage;
begin
crono.Start;
imagefx.LoadFromFile(edFilename.FileName);
png := imagefx.Resize(64,64,rmFitToBounds,[rfNoMagnify]).AsPNG;
try
PngSpeedButton1.PngImage.Assign(png);
crono.Stop;
finally
png.Free;
end;
Memo1.Lines.Add('LoadPNGButton: ' + crono.ElapsedTime);
end;
procedure TMainForm.spedXChange(Sender: TObject);
begin
if (spedY.Value = 0) or (spedX.Value = 0) then Exit;
lblNewAspectRatio.Caption := TImageFX.GetAspectRatio(spedX.Value,spedY.Value);
end;
end.
|
unit ClassUpdates;
interface
uses Classes, ComCtrls, SKonstanty;
type TUpdateItem = class
private
procedure LoadFromFile( InfoFile : string );
procedure LoadListkyFromFile( ListkyFile : string );
procedure SaveToFile;
procedure SaveListkyToFile;
public
FileName : string;
ListkyFileName : string;
Title : string;
Datum : string;
ZastavkyFile : string;
RozvrhyFiles : TStringList;
Listky : TTickets;
procedure Save;
constructor Create( InfoFile : string );
destructor Destroy; override;
end;
TUpdates = class
private
FOnTreeChange : TNotifyEvent;
FActive : integer;
procedure LoadAllUpdates;
procedure SaveAllUpdates;
public
Items : TList;
constructor Create;
destructor Destroy; override;
procedure CreateItem( FileName : string; Day, Month, Year : integer );
procedure DeleteItem( Item : TUpdateItem );
property OnTreeChange : TNotifyEvent read FOnTreeChange write FOnTreeChange;
property Active : integer read FActive write FActive;
end;
var Updates : TUpdates;
implementation
uses IniFiles, SysUtils;
//==============================================================================
//==============================================================================
//
// U P D A T E I T E M S
//
//==============================================================================
//==============================================================================
//==============================================================================
// Constructor
//==============================================================================
constructor TUpdateItem.Create( InfoFile : string );
begin
inherited Create;
RozvrhyFiles := TStringList.Create;
LoadFromFile( InfoFile );
end;
//==============================================================================
// Destructor
//==============================================================================
destructor TUpdateItem.Destroy;
begin
RozvrhyFiles.Free;
inherited;
end;
//==============================================================================
// Files
//==============================================================================
procedure TUpdateItem.LoadListkyFromFile( ListkyFile : string );
var IniFile : TIniFile;
Sections : TStringList;
I : integer;
begin
ListkyFileName := ListkyFile;
SetLength( Listky , 0 );
if (ListkyFile = '') then exit;
IniFile := TIniFile.Create( ListkyFile );
try
Sections := TStringList.Create;
try
IniFile.ReadSections( Sections );
SetLength( Listky , Sections.Count );
for I := 0 to Sections.Count-1 do
begin
Listky[I].Min := StrToInt( Sections[I] );
Listky[I].Norm := StrToInt( IniFile.ReadString( Sections[I] , 'Norm' , '' ) );
Listky[I].Zlav := StrToInt( IniFile.ReadString( Sections[I] , 'Zlav' , '' ) );
end;
finally
Sections.Free;
end;
finally
IniFile.Free;
end;
end;
procedure TUpdateItem.LoadFromFile( InfoFile : string );
var IniFile : TIniFile;
I : integer;
S : string;
begin
FileName := InfoFile;
IniFile := TIniFile.Create( InfoFile );
try
Datum := IniFile.ReadString( 'Datum' , 'Datum' , '??.??.????' );
ZastavkyFile := IniFile.ReadString( 'Zastavky' , 'File' , '' );
LoadListkyFromFile( IniFile.ReadString( 'Listky' , 'File' , '' ) );
IniFile.ReadSectionValues( 'Rozvrhy' , RozvrhyFiles );
for I := 0 to RozvrhyFiles.Count-1 do
begin
S := RozvrhyFiles[I];
Delete( S , 1 , Pos( '=' , S ) );
RozvrhyFiles[I] := S;
end;
finally
IniFile.Free;
end;
end;
procedure TUpdateItem.SaveToFile;
var IniFile : TIniFile;
Sections : TStringList;
I : integer;
begin
IniFile := TIniFile.Create( FileName );
try
Sections := TStringList.Create;
try
IniFile.ReadSections( Sections );
for I := 0 to Sections.Count-1 do
IniFile.EraseSection( Sections[I] );
finally
Sections.Free;
end;
IniFile.WriteString( 'Datum' , 'Datum' , Datum );
IniFile.WriteString( 'Zastavky' , 'File' , ZastavkyFile );
IniFile.WriteString( 'Listky' , 'File' , ListkyFileName );
IniFile.WriteString( 'Rozvrhy' , 'File1' , '' );
for I := 0 to RozvrhyFiles.Count-1 do
IniFile.WriteString( 'Rozvrhy' , 'File'+IntToStr(I+1) , RozvrhyFiles[I] );
finally
IniFile.Free;
end;
end;
procedure TUpdateItem.SaveListkyToFile;
var IniFile : TIniFile;
Sections : TStringList;
I : integer;
begin
if (ListkyFileName = '') then ListkyFileName := ExtractFilePath( FileName )+'Listky.ini';
IniFile := TIniFile.Create( ListkyFileName );
try
Sections := TStringList.Create;
try
IniFile.ReadSections( Sections );
for I := 0 to Sections.Count-1 do
IniFile.EraseSection( Sections[I] );
finally
Sections.Free;
end;
for I := 0 to Length( Listky )-1 do
begin
IniFile.WriteString( IntToStr( Listky[I].Min ) , 'Norm' , IntToStr( Listky[I].Norm ) );
IniFile.WriteString( IntToStr( Listky[I].Min ) , 'Zlav' , IntToStr( Listky[I].Zlav ) );
end;
finally
IniFile.Free;
end;
end;
procedure TUpdateItem.Save;
begin
SaveListkyToFile;
SaveToFile;
end;
//==============================================================================
//==============================================================================
//
// U P D A T E S
//
//==============================================================================
//==============================================================================
//==============================================================================
// Constructor
//==============================================================================
constructor TUpdates.Create;
begin
inherited;
Items := TList.Create;
LoadAllUpdates;
if (Assigned( OnTreeChange )) then OnTreeChange( Self );
end;
//==============================================================================
// Destructor
//==============================================================================
destructor TUpdates.Destroy;
var I : integer;
begin
SaveAllUpdates;
for I := 0 to Items.Count-1 do
TUpdateItem( Items[I] ).Free;
Items.Free;
inherited;
end;
//==============================================================================
// Praca so subormi
//==============================================================================
procedure TUpdates.LoadAllUpdates;
var IniFile : TIniFile;
Sections : TStringList;
I : integer;
begin
IniFile := TIniFile.Create( UPDATES_FILE );
try
Sections := TStringList.Create;
try
IniFile.ReadSections( Sections );
for I := 0 to Sections.Count-1 do
begin
Items.Add( TUpdateItem.Create( IniFile.ReadString( Sections[I] , 'UpdateInfo' , '' ) ) );
TUpdateItem( Items[I] ).Title := Sections[I];
end;
finally
Sections.Free;
end;
finally
IniFile.Free;
end;
end;
procedure TUpdates.SaveAllUpdates;
var IniFile : TIniFile;
Sections : TStringList;
I : integer;
begin
IniFile := TIniFile.Create( UPDATES_FILE );
try
Sections := TStringList.Create;
try
IniFile.ReadSections( Sections );
for I := 0 to Sections.Count-1 do
IniFile.EraseSection( Sections[I] );
finally
Sections.Free;
end;
for I := 0 to Items.Count-1 do
IniFile.WriteString( TUpdateItem( Items[I] ).Title , 'UpdateInfo' , TUpdateItem( Items[I] ).FileName );
finally
IniFile.Free;
end;
end;
procedure TUpdates.CreateItem( FileName : string; Day, Month, Year : integer );
var IniFile : TIniFile;
FormatDate : string;
I : integer;
Sections : TStringList;
begin
FormatDate := '';
if (Day < 10) then FormatDate := '0';
FormatDate := FormatDate + IntToStr( Day );
if (Month < 10) then FormatDate := FormatDate + '0';
FormatDate := FormatDate + IntToStr( Month );
FormatDate := FormatDate + IntToStr( Year );
IniFile := TIniFile.Create( FileName );
try
Sections := TStringList.Create;
try
IniFile.ReadSections( Sections );
for I := 0 to Sections.Count-1 do
IniFile.EraseSection( Sections[I] );
finally
Sections.Free;
end;
IniFile.WriteString( 'Datum' , 'Datum' , FormatDate );
IniFile.WriteString( 'Zastavky' , 'File' , '' );
IniFile.WriteString( 'Listky' , 'File' , '' );
IniFile.WriteString( 'Rozvrhy' , 'File1' , '' );
finally
IniFile.Free;
end;
I := Items.Add( TUpdateItem.Create( FileName ) );
TUpdateItem( Items[I] ).Title := IntToStr( Day )+'.'+IntToStr( Month )+'.'+IntToStr( Year );
if (Assigned( OnTreeChange )) then OnTreeChange( Self );
end;
procedure TUpdates.DeleteItem( Item : TUpdateItem );
var I : integer;
begin
I := Items.IndexOf( Item );
TUpdateItem( Items[I] ).Free;
Items.Delete( I );
if (Assigned( OnTreeChange )) then OnTreeChange( Self );
end;
end.
|
unit CoordTransform;
interface
uses LatLon;
function ConvertOSGB36toWGS84(pOSGB36 : TLatLon) : TLatLon;
function ConvertWGS84toOSGB36(pWGS84 : TLatLon) : TLatLon;
implementation
uses Math;
type
TEllipse = record
a : double;
b : double;
f : double;
end;
TDatumTransform = record
tx : double;
ty : double;
tz : double;
rx : double;
ry : double;
rz : double;
s : double;
end;
TEllipses = record
WGS84 : TEllipse;
GRS80 : TEllipse;
Airy1830: TEllipse;
AiryModified : TEllipse;
Intl1924 : TEllipse;
end;
TDatumTransforms = record
toOSGB36 : TDatumTransform;
toED50 : TDatumTransform;
toIrl1975 : TDatumTransform;
end;
const
ELLIPSES : TEllipses = (
WGS84 : ( a : 6378137; b : 6356752.3142; f : 1/298.257223563);
GRS80 : ( a : 6378137; b : 6356752.314140; f : 1/298.257222101);
Airy1830 : ( a : 6377563.396; b : 6356256.910; f : 1/299.3249646);
AiryModified : ( a: 6377340.189; b: 6356034.448; f: 1/299.32496);
Intl1924 : ( a: 6378388.000; b: 6356911.946; f: 1/297.0);
);
DATUMS : TDatumTransforms = (
toOSGB36 : (tx : -446.448; ty : 125.157; tz : -542.060; rx : -0.1502; ry : -0.2470; rz : -0.8421; s : 20.4894);
toED50 : (tx : 89.5; ty : 93.8; tz : 123.1; rx : 0.0; ry : 0.0; rz : 0.156; s : -1.2);
toIrl1975 : (tx : -482.530; ty : 130.596; tz : -564.557; rx : -1.042; ry : -0.214; rz : -0.631; s :-8.150);
);
function ConvertEllipsoid(point : TLatLon; e1 : TEllipse; t : TDatumTransform; e2: TEllipse) : TLatLon; forward;
function ConvertOSGB36toWGS84(pOSGB36 : TLatLon) : TLatLon;
var
txToOSGB36 : TDatumTransform;
txFromOSGB36 : TDatumTransform;
begin
txToOSGB36 := DATUMS.toOSGB36;
with txFromOSGB36 do begin
tx := - txToOSGB36.tx;
ty := - txToOSGB36.ty;
tz := - txToOSGB36.tz;
rx := - txToOSGB36.rx;
ry := - txToOSGB36.ry;
rz := - txToOSGB36.rz;
s := - txToOSGB36.s;
end;
Result := ConvertEllipsoid(pOSGB36, ELLIPSES.Airy1830, txFromOSGB36, ELLIPSES.WGS84);
end;
function ConvertWGS84toOSGB36(pWGS84 : TLatLon) : TLatLon;
begin
Result := ConvertEllipsoid(pWGS84, ELLIPSES.WGS84, DATUMS.toOSGB36, ELLIPSES.Airy1830);
end;
function ConvertEllipsoid(point : TLatLon; e1 : TEllipse; t : TDatumTransform; e2: TEllipse) : TLatLon;
var
lat, lon : double;
a, b : double;
sinPhi, cosPhi, sinLambda, cosLambda, H : double;
eSq, nu, x1, y1, z1, tx, ty, tz, rx, ry, rz, s1, x2, y2, z2 : double;
precision, p, phi, phiP, lambda : double;
begin
lat := DegToRad(point.Lat);
lon := DegToRad(point.Lon);
a := e1.a;
b := e1.b;
sinPhi := Sin(lat);
cosPhi := Cos(lat);
sinLambda := Sin(lon);
cosLambda := Cos(lon);
H := 24.7; // for the moment
eSq := (a * a - b * b) / (a * a);
nu := a / Sqrt(1 - eSq * sinPhi * sinPhi);
x1 := (nu + H) * cosPhi * cosLambda;
y1 := (nu + H) * cosPhi * sinLambda;
z1 := ((1 - eSq) * nu + H) * sinPhi;
// -- 2: apply helmert transform using appropriate params
tx := t.tx;
ty := t.ty;
tz := t.tz;
rx := DegToRad(t.rx / 3600); // normalise seconds to radians
ry := DegToRad(t.ry / 3600);
rz := DegToRad(t.rz / 3600);
s1 := t.s / 1e6 + 1; // normalise ppm to (s+1)
// apply transform
x2 := tx + x1 * s1 - y1 * rz + z1 * ry;
y2 := ty + x1 * rz + y1 * s1 - z1 * rx;
z2 := tz - x1 * ry + y1 * rx + z1 * s1;
// -- 3: convert cartesian to polar coordinates (using ellipse 2)
a := e2.a;
b := e2.b;
precision := 4 / a; // results accurate to around 4 metres
eSq := (a * a - b * b) / (a * a);
p := Sqrt(x2*x2 + y2*y2);
phi := Math.ArcTan2(z2, p*(1-eSq));
phiP := 2 * Pi;
while (Abs(phi-phiP) > precision) do begin
nu := a / Sqrt(1 - eSq * Sin(phi) * Sin(phi));
phiP := phi;
phi := Math.ArcTan2(z2 + eSq * nu * Sin(phi), p);
end;
lambda := Math.ArcTan2(y2, x2);
H := p / Cos(phi) - nu;
Result := TLatLon.Create(RadToDeg(phi), RadToDeg(lambda), H);
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ExtCtrls, Vcl.StdCtrls,
//GLS
GLScene, GLObjects, GLVectorGeometry, GLTexture, GLCadencer,
GLMesh, GLWin32Viewer, GLState, GLColor, GLCrossPlatform,
GLCoordinates, GLBaseClasses;
type
TForm1 = class(TForm)
GLSceneViewer1: TGLSceneViewer;
GLScene1: TGLScene;
Mesh1: TGLMesh;
DummyCube1: TGLDummyCube;
GLCamera1: TGLCamera;
GLLightSource1: TGLLightSource;
Timer1: TTimer;
GLSceneViewer2: TGLSceneViewer;
Panel1: TPanel;
Label1: TLabel;
GLScene2: TGLScene;
DummyCube2: TGLDummyCube;
Mesh2: TGLMesh;
GLLightSource2: TGLLightSource;
GLCamera2: TGLCamera;
Label2: TLabel;
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
private
{ Private declarations }
mx, my : Integer;
invRes1, invRes2 : Single;
function MakeVect(const aX, aY : Single) : TAffineVector;
procedure AddTriangle(const p1, p2, p3 : TAffineVector;
const color : TColorVector);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
const
// half-grid resolution, grid width is actually cResolution*2 of "quads"
cResolution = 50;
function TForm1.MakeVect(const aX, aY : Single) : TAffineVector;
begin
SetVector(Result, aX*invRes1, sin((aX*aX+aY*aY)*invRes2), aY*invRes1);
end;
procedure TForm1.AddTriangle(const p1, p2, p3 : TAffineVector;
const color : TColorVector);
begin
with Mesh1.Vertices do begin
AddVertex(p1, NullVector, color);
AddVertex(p2, NullVector, color);
AddVertex(p3, NullVector, color);
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
x, y : Integer;
pTopLeft, pTopRight, pBottomRight, pBottomLeft : TAffineVector;
begin
// scaling precalcs for our math func
invRes1:=10/cResolution;
invRes2:=0.1*Sqr(invRes1);
//
// Triangles
//
// this one is basic : we calculate the corner points for each grid quad and
// add the two triangles that make it
with Mesh1 do begin
Mode:=mmTriangles;
Vertices.Clear;
for y:=-cResolution to cResolution do begin
for x:=-cResolution to cResolution do begin
pTopLeft:=MakeVect(x, y+1);
pTopRight:=MakeVect(x+1, y+1);
pBottomRight:=MakeVect(x+1, y);
pBottomLeft:=MakeVect(x, y);
// top left triangle
AddTriangle(pBottomLeft, pTopLeft, pTopRight, clrBlue);
// bottom right triangle
AddTriangle(pTopRight, pBottomRight, pBottomLeft, clrBlue);
end;
end;
CalcNormals(fwCounterClockWise);
// Vertices.Locked:=True;
end;
//
// TriangleStrip
//
// Same as triangle, however trianglestrips are continuous, and to cover
// the grid, "null" segments are used at both ends of a strip (to avoid a
// visible triangle that would stretch for the full width of the grid).
// Note : this can be avoided by reversing grid traversing direction (one line
// from left to right, one from right to left, etc.)
with Mesh2 do begin
Mode:=mmTriangleStrip;
Vertices.Clear;
for y:=-cResolution to cResolution do begin
pTopLeft:=MakeVect(-cResolution, y+1);
Vertices.AddVertex(pTopLeft, NullVector, clrBlue);
Vertices.AddVertex(pTopLeft, NullVector, clrBlue);
for x:=-cResolution to cResolution do begin
pTopRight:=MakeVect(x+1, y+1);
pBottomLeft:=MakeVect(x, y);
with Vertices do begin
AddVertex(pBottomLeft, NullVector, clrBlue);
AddVertex(pTopRight, NullVector, clrBlue);
end;
end;
pBottomRight:=MakeVect(cResolution+1, y);
Vertices.AddVertex(pBottomRight, NullVector, clrBlue);
Vertices.AddVertex(pBottomRight, NullVector, clrBlue);
end;
CalcNormals(fwClockWise);
// Vertices.Locked:=True;
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
// nb of triangles in scene
Caption:= 'Formula ' + Format('%d Triangles', [2*(cResolution*2)*(cResolution*2)]);
// calculate & display triangles framerate
with GLSceneViewer1 do begin
// we render twice to get a fair FPS rating
ResetPerformanceMonitor;
Buffer.Render;
Buffer.Render;
Label1.Caption:=Format('%.2f FPS (mmTriangles)', [FramesPerSecond]);
end;
// calculate & display trianglestrip framerate
with GLSceneViewer2 do begin
// we render twice to get a fair FPS rating
ResetPerformanceMonitor;
Buffer.Render;
Buffer.Render;
Label2.Caption:=Format('%.2f FPS (mmTriangleStrip)', [FramesPerSecond]);
end;
end;
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
mx:=X; my:=Y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if ssLeft in Shift then begin
TGLSceneViewer(Sender).Camera.MoveAroundTarget(my-Y, mx-X);
my:=Y; mx:=X;
end;
end;
end.
|
program myName;
var
myName: array[1..16] of char; {User's name}
begin
writeln('What is your name?');
readln(myName);
writeln('Hello,', myName, '!');
end.
|
{ :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: QuickReport 3.0 for Delphi 3.0/4.0/5.0 ::
:: ::
:: Simple report for print the contents of a stringlist ::
:: ::
:: Copyright (c) 1995-1999 QuSoft AS ::
:: All Rights Reserved ::
:: ::
:: web: http://www.qusoft.com fax: +47 22 41 74 91 ::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: }
unit history;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
QuickRpt, Qrctrls, ExtCtrls;
type
TfrmHistory = class(TForm)
QuickRep1: TQuickRep;
DetailBand1: TQRBand;
QRMemo1: TQRMemo;
PageHeaderBand1: TQRBand;
QRSysData1: TQRSysData;
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmHistory: TfrmHistory;
implementation
{$R *.dfm}
end.
|
unit Nodes;
//{$MODE Delphi}
interface
uses
Classes, SysUtils;
type
TNodeKind = Integer;
TNode =
class(TObject)
protected
FAnno: TStringList;
public
// construction/destruction
constructor Create; virtual;
constructor CreateList(const AList: array of TNode);
destructor Destroy; override;
class function GetKind: TNodeKind; virtual; abstract;
class function OpName: String; virtual; abstract;
// subtrees
class function GetNrofSons: Integer; virtual; abstract;
function GetSon(I: Integer): TNode; virtual; abstract;
procedure SetSon(I: Integer; ANode: TNode); virtual; abstract;
// data
class function HasData: Boolean; virtual;
function GetData: String; virtual;
procedure SetData(AString: String); virtual;
function Clone: TNode;
// queries
class function IsHole: Boolean; virtual;
class function IsMeta: Boolean; virtual;
function IsClosed: Boolean; virtual;
// annotation
procedure SetAnno(AName: String; AObject: TObject);
function HasAnno(AName: String): Boolean;
function GetAnno(AName: String): TObject;
procedure ClearAllAnno;
end;
TNodeClass = class of TNode;
TNodeFactory =
class(TObject)
public
function MakeHole: TNode; virtual; abstract;
function MakeNode(AName: String; AData: String): TNode; virtual; abstract;
function MakeNodeWithHoles(AName: String; AData: string): TNode; virtual;
procedure ReturnTree(ATree: TNode); virtual; abstract;
// more
end;
TSimpleNodeFactory =
class(TNodeFactory)
protected
FList: TStringList;
function GetNodeClass(AName: String): TNodeClass;
public
constructor Create;
destructor Destroy; override;
procedure AddNodeClass(AClass: TNodeClass);
function MakeHole: TNode; override;
function MakeNode(AName: String; AData: String): TNode; override;
procedure ReturnTree(ATree: TNode); override;
end;
ENodeError =
class(Exception)
end;
ESetSonIndex =
class(ENodeError)
end;
EGetSonIndex =
class(ENodeError)
end;
EGetAnno =
class(ENodeError)
end;
ENodeKind =
class(ENodeError)
end;
implementation {==========================================}
constructor TNode.Create;
begin
inherited Create;
FAnno := TStringList.Create;
end;
constructor TNode.CreateList(const AList: array of TNode);
var
I: Integer;
begin
Create;
for I := 0 to High(AList) do SetSon(I, AList[I]);
end;
destructor TNode.Destroy;
begin
FAnno.Free;
inherited Destroy;
end;
class function TNode.HasData: Boolean;
begin
Result := false;
end;
function TNode.GetData: String;
begin
Result := '';
end;
procedure TNode.SetData(AString: String);
begin
end;
function TNode.Clone: TNode;
var
I: Integer;
begin
Result := ClassType.Create as TNode;
Result.SetData(GetData);
for I := 0 to GetNrOfSons - 1 do
Result.SetSon(I, GetSon(I).Clone);
end;
class function TNode.IsHole: Boolean;
begin
Result := false;
end;
class function TNode.IsMeta: Boolean;
begin
Result := false;
end;
procedure TNode.SetAnno(AName: String; AObject: TObject);
var
I: Integer;
begin
I := FAnno.IndexOf(AName);
if I = -1
then FAnno.AddObject(AName, Aobject)
else FAnno.Objects[I] := AObject;
end;
function TNode.HasAnno(AName: String): Boolean;
begin
Result := FAnno.Indexof(AName) <> -1;
end;
function TNode.GetAnno(AName: String): TObject;
var
I: Integer;
begin
I := FAnno.IndexOf(AName);
if I = -1
then raise EGetAnno.Create('Error in GetAnno with argument: '+ AName)
else Result := FAnno.Objects[I];
end;
procedure TNode.ClearAllAnno;
begin
FAnno.Clear;
end;
{ TNodeFactory }
function TNodeFactory.MakeNodeWithHoles(AName: String; AData: string): TNode;
var
I: Integer;
begin
Result := MakeNode(AName, AData);
with Result do
for I := 0 to GetNrOfSons - 1 do
SetSon(I, MakeHole);
end;
{Auxiliary class used by TSimpleNodeFactory}
type
TNC =
class
FNodeClass: TNodeClass;
end;
{ TSimpleNodeFactory }
procedure TSimpleNodeFactory.AddNodeClass(AClass: TNodeClass);
var
VNC: TNC;
begin
if FList.IndexOf(AClass.OpName) <> -1
then raise Exception.Create('TSimpleNodefactory.AddNodeClass: Name added twice');
VNC := TNC.Create;
VNC.FNodeClass := AClass;
FList.AddObject(AClass.OpName, VNC);
end;
constructor TSimpleNodeFactory.Create;
begin
inherited Create;
FList := TStringList.Create;
end;
destructor TSimpleNodeFactory.Destroy;
begin
FList.Free;
inherited;
end;
function TSimpleNodeFactory.GetNodeClass(AName: String): TNodeClass;
var
I: Integer;
begin
I := FList.IndexOf(AName);
if I = -1
then raise Exception.Create('TSimpleNodeFactory.GetNodeClass: Name not found');
Result := (FList.Objects[I] as TNC).FNodeClass;
end;
function TSimpleNodeFactory.MakeHole: TNode;
begin
Result := MakeNode('??', '');
end;
function TSimpleNodeFactory.MakeNode(AName: String; AData: String): TNode;
begin
Result := GetNodeClass(AName).Create; //N.B. virtual constructor call
Result.SetData(AData);
end;
procedure TSimpleNodeFactory.ReturnTree(ATree: TNode);
begin
ATree.Free;
end;
function TNode.IsClosed: Boolean;
var
I: Integer;
begin
Result := true;
if IsHole
then Result := false
else
for I := 0 to GetnrOfSons - 1 do
if not GetSon(I).IsClosed
then Result := false;
end;
end.
|
unit LoanMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseDocked, Vcl.StdCtrls, RzLabel,
Vcl.ExtCtrls, RzPanel, Vcl.Mask, RzEdit, RzDBEdit, RzBtnEdt, Vcl.DBCtrls, RzDBCmbo, SaveIntf, RzButton, RzRadChk,
LoanIntf, Loan, RzLstBox, RzDBList, Data.DB, Vcl.Grids, Vcl.DBGrids, RzDBGrid,
Vcl.Imaging.pngimage, RzDBLbl, RzTabs, Vcl.ComCtrls, Vcl.ToolWin, RzGrids, AlertIntf;
type
TfrmLoanMain = class(TfrmBaseDocked, ISave, ILoan, IAlert)
pnlMain: TRzPanel;
lblHeader: TRzLabel;
pnlApplication: TRzPanel;
edDesiredTerm: TRzDBNumericEdit;
edAppAmount: TRzDBNumericEdit;
dteDateApplied: TRzDBDateTimeEdit;
edInterest: TRzDBNumericEdit;
dbluLoanClass: TRzDBLookupComboBox;
bteClient: TRzButtonEdit;
RzDBNumericEdit1: TRzDBNumericEdit;
RzDBNumericEdit2: TRzDBNumericEdit;
lblComakersDesc: TRzDBLabel;
lbxComakers: TRzListBox;
pnlAssessment: TRzPanel;
pnlApproval: TRzPanel;
pnlRelease: TRzPanel;
pnlCancellation: TRzPanel;
pnlRejection: TRzPanel;
mmAddress: TRzMemo;
mmEmployer: TRzMemo;
RzGroupBox1: TRzGroupBox;
RzGroupBox2: TRzGroupBox;
RzGroupBox3: TRzGroupBox;
pnlToolbar: TRzPanel;
pnlAdd: TRzPanel;
btnAddComaker: TRzShapeButton;
pnlRemoveComaker: TRzPanel;
btnRemoveComaker: TRzShapeButton;
RzDBLabel1: TRzDBLabel;
RzDBLabel2: TRzDBLabel;
RzDBLabel3: TRzDBLabel;
pnlEditAssessment: TRzPanel;
btnEditAssessment: TRzShapeButton;
pcStatus: TRzPageControl;
tsAssessment: TRzTabSheet;
tsApproval: TRzTabSheet;
RzDBLabel4: TRzDBLabel;
RzDBLabel5: TRzDBLabel;
RzDBLabel6: TRzDBLabel;
RzDBLabel7: TRzDBLabel;
RzDBLabel8: TRzDBLabel;
pnlEditApproval: TRzPanel;
btnEditApproval: TRzShapeButton;
tsReleased: TRzTabSheet;
tsRejected: TRzTabSheet;
tsCancelled: TRzTabSheet;
RzDBLabel9: TRzDBLabel;
RzDBLabel10: TRzDBLabel;
RzDBLabel11: TRzDBLabel;
RzDBLabel12: TRzDBLabel;
RzDBLabel13: TRzDBLabel;
RzDBLabel14: TRzDBLabel;
pnlEditCancel: TRzPanel;
btnEditCancel: TRzShapeButton;
pnlEditRejection: TRzPanel;
btnEditRejection: TRzShapeButton;
RzGroupBox6: TRzGroupBox;
RzGroupBox7: TRzGroupBox;
RzPanel2: TRzPanel;
RzShapeButton1: TRzShapeButton;
tsSummary: TRzTabSheet;
pnlSummary: TRzPanel;
pnlClientRecord: TRzPanel;
imgClientRecord: TImage;
pnlAlerts: TRzPanel;
imgAlerts: TImage;
RzDBLabel15: TRzDBLabel;
dbluPurpose: TRzDBLookupComboBox;
pnlStatus: TRzPanel;
edNetPay: TRzNumericEdit;
pcAssessment: TRzPageControl;
tsFinInfo: TRzTabSheet;
tsMonExp: TRzTabSheet;
grFinInfo: TRzDBGrid;
grMonExp: TRzDBGrid;
RzDBLabel16: TRzDBLabel;
RzDBLabel17: TRzDBLabel;
RzDBLabel18: TRzDBLabel;
RzDBLabel19: TRzDBLabel;
RzDBLabel20: TRzDBLabel;
RzDBLabel21: TRzDBLabel;
tsClosed: TRzTabSheet;
RzDBLabel22: TRzDBLabel;
RzDBLabel23: TRzDBLabel;
RzDBLabel24: TRzDBLabel;
RzDBLabel25: TRzDBLabel;
urlAssessment: TRzURLLabel;
urlApproval: TRzURLLabel;
urlRelease: TRzURLLabel;
urlReject: TRzURLLabel;
urlCancel: TRzURLLabel;
urlClose: TRzURLLabel;
urlReloan: TRzURLLabel;
urlLedger: TRzURLLabel;
RzPanel3: TRzPanel;
grRecipients: TRzDBGrid;
RzPanel4: TRzPanel;
grCharges: TRzDBGrid;
RzDBLabel26: TRzDBLabel;
RzDBLabel27: TRzDBLabel;
RzDBLabel28: TRzDBLabel;
RzDBLabel29: TRzDBLabel;
RzDBLabel30: TRzDBLabel;
urlSummary: TRzURLLabel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
Label15: TLabel;
Label16: TLabel;
Label17: TLabel;
Label18: TLabel;
Label19: TLabel;
Label20: TLabel;
Label21: TLabel;
Label22: TLabel;
Label23: TLabel;
Label24: TLabel;
Label25: TLabel;
Label26: TLabel;
Label27: TLabel;
lblTotalCharges: TLabel;
lblAdvancePayment: TLabel;
lblReleaseAmount: TLabel;
lblNetProceeds: TLabel;
Label28: TLabel;
Label29: TLabel;
Label30: TLabel;
Label31: TLabel;
Label32: TLabel;
Label33: TLabel;
Label34: TLabel;
Label35: TLabel;
Label36: TLabel;
Label37: TLabel;
Label38: TLabel;
Label39: TLabel;
Label40: TLabel;
Label41: TLabel;
Label42: TLabel;
Label43: TLabel;
Label44: TLabel;
Label45: TLabel;
Label46: TLabel;
Label47: TLabel;
Label48: TLabel;
Label49: TLabel;
Label50: TLabel;
lblDaysFromLastTransaction: TLabel;
lblInterestDueAsOfDate: TLabel;
lblTotalInterestDue: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure bteClientButtonClick(Sender: TObject);
procedure lbxComakersDblClick(Sender: TObject);
procedure btnAddComakerClick(Sender: TObject);
procedure imgAssessmentMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure imgAssessmentMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure pnlEditAssessmentClick(Sender: TObject);
procedure btnEditApprovalClick(Sender: TObject);
procedure btnRemoveComakerClick(Sender: TObject);
procedure pnlEditRejectionClick(Sender: TObject);
procedure btnEditCancelClick(Sender: TObject);
procedure btnEditAssessmentClick(Sender: TObject);
procedure imgClientRecordClick(Sender: TObject);
procedure imgAlertsClick(Sender: TObject);
procedure urlAssessmentClick(Sender: TObject);
procedure urlApprovalClick(Sender: TObject);
procedure urlReleaseClick(Sender: TObject);
procedure urlRejectClick(Sender: TObject);
procedure urlCancelClick(Sender: TObject);
procedure urlCloseClick(Sender: TObject);
procedure urlLedgerClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure urlSummaryClick(Sender: TObject);
private
{ Private declarations }
procedure ChangeControlState;
procedure ShowAlerts;
procedure PopulateComakers;
procedure RetrieveLoan;
procedure SetActiveTab(const index: integer); overload;
procedure SetActiveTab; overload;
procedure ApproveLoan;
procedure AssessLoan;
procedure RejectLoan;
procedure CancelLoan;
procedure ReleaseLoan;
procedure CloseLoan;
procedure ShowLedger;
function LoanApplicationIsValid: boolean;
public
{ Public declarations }
procedure SetLoanHeaderCaption;
procedure SetUnboundControls;
procedure RefreshDropDownSources;
procedure Cancel;
procedure InitForm;
procedure SelectClient;
function Save: boolean;
end;
const
// tab index
ASSESSED = 0;
APPROVAL = 1;
RELEASED = 2;
REJECTION = 3;
CANCELLATION = 4;
SUMMARY = 5;
CLOSED = 6;
// finalised error message
FINALISED_MSG = 'Changes have been restricted. Loan application has been finalised.';
implementation
{$R *.dfm}
uses
LoanData, FormsUtil, LoanClient, ClientSearch, StatusIntf, DockIntf, IFinanceGlobal,
Comaker, ComakerSearch, DecisionBox, ComakerDetail, FinInfoDetail, MonthlyExpenseDetail,
LoansAuxData, LoanApprovalDetail, LoanAssessmentDetail, LoanCancellationDetail,
LoanRejectionDetail, Alert, Alerts, LoanReleaseDetail, Client, AppConstants, Assessment,
IFinanceDialogs, LoanLedger, LoanClosureDetail, Backlog, Posting, DateUtils, DBUtil;
procedure TfrmLoanMain.SetActiveTab;
var
index: integer;
begin
index := 0;
// this routine sets the active tab based on current loan status
if (ln.IsPending) or (ln.New) then index := SUMMARY
else if ln.IsAssessed then index := ASSESSED
else if ln.IsApproved then index := APPROVAL
else if (ln.IsActive) or (ln.IsClosed) then index := RELEASED
else if ln.IsRejected then index := REJECTION
else if ln.IsCancelled then index := CANCELLATION;
SetActiveTab(index);
end;
procedure TfrmLoanMain.SetActiveTab(const index: Integer);
var
advancePayment: currency;
begin
advancePayment := 0;
if index = RELEASED then
begin
advancePayment := ln.TotalAdvancePayment;
lblReleaseAmount.Caption := FormatCurr('###,###,##0.00',ln.TotalReleased + ln.TotalCharges + advancePayment);
lblNetProceeds.Caption := FormatCurr('###,###,##0.00',ln.TotalReleased);
lblTotalCharges.Caption := FormatCurr('###,###,##0.00',ln.TotalCharges);
lblAdvancePayment.Caption := FormatCurr('###,###,##0.00',advancePayment);
if ln.LoanClass.HasAdvancePayment then
begin
if ln.LoanClass.AdvancePayment.IncludePrincipal then
lblAdvancePayment.Caption := lblAdvancePayment.Caption + ' (' +
IntToStr(ln.AdvancePaymentCount) + ' months)'
else
lblAdvancePayment.Caption := lblAdvancePayment.Caption + ' (' +
IntToStr(ln.AdvancePaymentCount) + ' months - Interest only)'
end
else lblAdvancePayment.Caption := 'No advance payment required';
end;
with pcStatus do
begin
ActivePageIndex := index;
case ActivePageIndex of
ASSESSED: pnlAssessment.Visible := ln.HasLoanState(lsAssessed);
APPROVAL: pnlApproval.Visible := ln.HasLoanState(lsApproved);
RELEASED: pnlRelease.Visible := ln.HasLoanState(lsActive);
REJECTION: pnlRejection.Visible := ln.HasLoanState(lsRejected);
CANCELLATION: pnlCancellation.Visible := ln.HasLoanState(lsCancelled);
end;
end;
end;
procedure TfrmLoanMain.ApproveLoan;
begin
if not LoanApplicationIsValid then Exit
else if ln.IsFinalised then
begin
ShowErrorBox(FINALISED_MSG);
Exit;
end
else if ln.IsPending then
begin
ShowErrorBox('Approval restricted. Assessment details not found.');
Exit;
end
else if Assigned(ln.Assessment) and (ln.Assessment.Recommendation = rcReject)
and (not ln.LoanStateExists(lsApproved)) then
begin
if ShowDecisionBox('Application has been recommended for REJECTION.' +
' Do you wish to continue with the approval?') <> mrYes then Exit;
end;
with TfrmLoanAppvDetail.Create(self) do
begin
try
ln.Action := laApproving;
ln.Retrieve;
ln.SetDefaultValues;
ShowModal;
if ModalResult = mrOk then
begin
SetLoanHeaderCaption;
ChangeControlState;
SetActiveTab(APPROVAL);
end;
Free;
except
on e: Exception do
ShowErrorBox(e.Message);
end;
end;
end;
procedure TfrmLoanMain.AssessLoan;
begin
if not LoanApplicationIsValid then Exit
else if ln.IsFinalised then
begin
ShowErrorBox(FINALISED_MSG);
Exit;
end
else if ln.IsApproved then
begin
ShowErrorBox('Assessment changes have been restricted. Loan has been approved.');
Exit;
end;
with TfrmLoanAssessmentDetail.Create(self) do
begin
try
ln.Action := laAssessing;
ln.Retrieve;
ln.SetDefaultValues;
ShowModal;
if ModalResult = mrOk then
begin
SetLoanHeaderCaption;
ChangeControlState;
SetActiveTab(ASSESSED);
end;
Free;
except
on e: Exception do
ShowErrorBox(e.Message);
end;
end;
end;
procedure TfrmLoanMain.RejectLoan;
begin
if not LoanApplicationIsValid then Exit
else if ln.IsFinalised then
begin
ShowErrorBox(FINALISED_MSG);
Exit;
end
else if Assigned(ln.Assessment) and (ln.Assessment.Recommendation = rcApprove)
and (not ln.LoanStateExists(lsRejected)) then
begin
if ShowDecisionBox('Application has been recommended for APPROVAL.' +
' Do you wish to continue with the rejection?') <> mrYes then Exit;
end;
with TfrmLoanRejectionDetail.Create(self) do
begin
try
ln.Action := laRejecting;
ln.Retrieve;
ln.SetDefaultValues;
ShowModal;
if ModalResult = mrOk then
begin
SetLoanHeaderCaption;
ChangeControlState;
SetActiveTab(REJECTION);
end;
Free;
except
on e: Exception do
ShowErrorBox(e.Message);
end;
end;
end;
procedure TfrmLoanMain.CancelLoan;
begin
if not LoanApplicationIsValid then Exit
else if ln.IsActive then
begin
if ShowWarningBox('Loan is already ACTIVE. ' +
'Do you wish to continue with the cancellation?') <> mrYes then
begin
SetActiveTab(CANCELLATION);
Exit;
end;
end
else if ln.IsFinalised then
begin
ShowErrorBox(FINALISED_MSG);
Exit;
end;
with TfrmLoanCancellationDetail.Create(self) do
begin
try
ln.Action := laCancelling;
ln.Retrieve;
ln.SetDefaultValues;
ShowModal;
if ModalResult = mrOk then
begin
SetLoanHeaderCaption;
ChangeControlState;
SetActiveTab(CANCELLATION);
end;
Free;
except
on e: Exception do
ShowErrorBox(e.Message);
end;
end;
end;
procedure TfrmLoanMain.ReleaseLoan;
begin
if not LoanApplicationIsValid then Exit
else if ln.IsFinalised then
begin
ShowErrorBox(FINALISED_MSG);
Exit;
end
else if not ln.HasLoanState(lsApproved) then
begin
ShowErrorBox('Releasing restricted. Approval details not found.');
Exit;
end;
with TfrmLoanReleaseDetail.Create(self) do
begin
try
ln.Action := laReleasing;
ln.Retrieve;
ShowModal;
if ModalResult = mrOk then
begin
SetLoanHeaderCaption;
ChangeControlState;
SetActiveTab(RELEASED);
end;
Free;
except
on e: Exception do
ShowErrorBox(e.Message);
end;
end;
end;
procedure TfrmLoanMain.ChangeControlState;
var
i: integer;
tags: set of 0..1;
begin
// control whose tag is in the tags array will be enabled
if (ln.Action = laCreating) or (ln.IsPending) then
begin
if Assigned(ln.Client) then tags := [0,1]
else tags := [0];
end
else tags := [];
// enable controls
for i := 0 to pnlApplication.ControlCount - 1 do
if pnlApplication.Controls[i].Tag <> -1 then
pnlApplication.Controls[i].Enabled := pnlApplication.Controls[i].Tag in tags;
pnlToolbar.Enabled := not ln.New;
pnlClientRecord.Visible := Assigned(ln.Client);
pnlAlerts.Visible := (Assigned(ln.Client)) and (not ln.IsFinalised);
end;
procedure TfrmLoanMain.CloseLoan;
begin
if not ln.IsActive then
begin
ShowErrorBox('Cannot close an INACTIVE loan.');
Exit;
end
else if ln.IsClosed then
begin
ShowErrorBox(FINALISED_MSG);
Exit;
end;
with TfrmLoanClosureDetail.Create(self) do
begin
try
ln.Action := laClosing;
ln.Retrieve;
ln.SetDefaultValues;
ShowModal;
if ModalResult = mrOk then
begin
SetLoanHeaderCaption;
ChangeControlState;
SetActiveTab(CLOSED);
end;
Free;
except
on e: Exception do
ShowErrorBox(e.Message);
end;
end;
end;
procedure TfrmLoanMain.RefreshDropDownSources;
begin
OpenDropdownDataSources(pnlMain);
end;
procedure TfrmLoanMain.SelectClient;
begin
if (ln.Action = laCreating) or (ln.IsPending) then
with TfrmClientSearch.Create(self) do
begin
try
try
ShowModal;
if ModalResult = mrOK then
begin
bteClient.Text := lnc.Name;
mmAddress.Text := lnc.Address;
mmEmployer.Text := lnc.Employer.Name;
edNetPay.Value := lnc.NetPay;
ln.Client := lnc;
ln.Client.GetLoans;
OpenDropdownDataSources(self.pnlApplication);
ChangeControlState;
ShowAlerts;
end;
except
on e: Exception do
ShowErrorBox(e.Message);
end;
finally
Free;
end;
end;
end;
procedure TfrmLoanMain.bteClientButtonClick(Sender: TObject);
begin
SelectClient;
end;
procedure TfrmLoanMain.btnAddComakerClick(Sender: TObject);
begin
if dbluLoanClass.Text = '' then
ShowErrorBox('Please select a loan class.')
else if ln.LoanClass.ComakersNotRequired then
ShowErrorBox('No comakers required.')
else if ln.ComakerCount >= ln.LoanClass.ComakersMax then
ShowErrorBox('The maximum number of comakers has already been added. ' +
'If a comaker has been mistakenly declared, remove the comaker and add again.')
else
with TfrmComakerSearch.Create(self) do
begin
try
cm := TComaker.Create;
ShowModal;
if ModalResult = mrOK then
begin
if Trim(ln.Client.Id) = Trim(cm.Id) then
ShowErrorBox('Client cannot be declared as a comaker.')
else if ln.ComakerExists(cm) then
ShowErrorBox('Comaker already exists.')
else if cm.ComakeredLoans >= ifn.MaxComakeredLoans then
ShowErrorBox('Comaker has reached the maximum allowable comakered loans.')
else
begin
lbxComakers.Items.AddObject(cm.Name,cm);
ln.AddComaker(cm,true);
end;
end;
Free;
// cm.Free;
except
on e: Exception do
ShowErrorBox(e.Message);
end;
end;
end;
procedure TfrmLoanMain.btnEditApprovalClick(Sender: TObject);
begin
inherited;
ApproveLoan;
end;
procedure TfrmLoanMain.btnEditAssessmentClick(Sender: TObject);
begin
inherited;
AssessLoan;
end;
procedure TfrmLoanMain.btnEditCancelClick(Sender: TObject);
begin
inherited;
CancelLoan;
end;
procedure TfrmLoanMain.btnRemoveComakerClick(Sender: TObject);
const
CONF = 'Are you sure you want to remove the selected comaker?';
var
obj: TObject;
id: string;
begin
if (lbxComakers.Items.Count > 0) and (lbxComakers.IndexOf(lbxComakers.SelectedItem) > -1) then
begin
obj := lbxComakers.Items.Objects[lbxComakers.IndexOf(lbxComakers.SelectedItem)];
if Assigned(obj) then
begin
with TfrmDecisionBox.Create(nil,CONF) do
begin
try
if lbxComakers.Items.Count > 0 then
begin
id := (obj as TComaker).Id;
ShowModal;
if ModalResult = mrYes then
begin
ln.RemoveComaker(TComaker(obj));
lbxComakers.Items.Delete(lbxComakers.IndexOf(lbxComakers.SelectedItem));
end;
Free;
end;
except
on e: Exception do
ShowMessage(e.Message);
end;
end;
end;
end;
end;
procedure TfrmLoanMain.Cancel;
begin
if ln.Action = laCreating then
begin
bteClient.Clear;
mmAddress.Clear;
mmEmployer.Clear;
lbxComakers.Clear;
ln.Client := nil;
ln.ClearComakers;
ln.LoanClass := nil;
ln.Cancel;
ln.Action := laCreating;
end
else
begin
ln.Cancel;
RetrieveLoan;
end;
ChangeControlState;
end;
procedure TfrmLoanMain.InitForm;
begin
// ExtendLastColumn(grFinInfo);
// ExtendLastColumn(grMonExp);
// ExtendLastColumn(grRecipients);
// ExtendLastColumn(grCharges);
ChangeControlState;
SetActiveTab;
end;
procedure TfrmLoanMain.FormClose(Sender: TObject; var Action: TCloseAction);
var
intf: IDock;
begin
if ln.Action <> laCreating then
if Supports(Application.MainForm,IDock,intf) then
intf.AddRecentLoan(ln);
dmLoan.Destroy;
dmLoansAux.Destroy;
ln.Destroy;
inherited;
end;
procedure TfrmLoanMain.FormCreate(Sender: TObject);
begin
inherited;
dmLoan := TdmLoan.Create(self);
dmLoansAux := TdmLoansAux.Create(self);
if not Assigned(ln) then
begin
ln := TLoan.Create;
ln.Add;
end
else
RetrieveLoan;
InitForm;
end;
procedure TfrmLoanMain.FormShow(Sender: TObject);
begin
inherited;
if (ifn.BacklogEntryEnabled) and (ln.Action = laCreating) then
if ShowDecisionBox('Is this a backlog entry?') = mrYes then
begin
ln.IsBacklog := true;
pnlTitle.GradientColorStart := $00CCCCFF;
pnlTitle.GradientColorStop := $00CCCCFF;
lblTitle.Caption := 'Loan record - This is a backlog entry.';
lblHeader.Caption := '-';
end;
end;
procedure TfrmLoanMain.imgAlertsClick(Sender: TObject);
begin
inherited;
ShowAlerts;
end;
procedure TfrmLoanMain.imgAssessmentMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited;
ButtonDown(Sender);
end;
procedure TfrmLoanMain.imgAssessmentMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited;
ButtonUp(Sender);
end;
procedure TfrmLoanMain.imgClientRecordClick(Sender: TObject);
var
id, displayId: string;
intf: IDock;
begin
if Assigned(ln.Client) then
begin
id := ln.Client.Id;
displayId := ln.Client.Id;
cln := TClient.Create;
cln.Id := id;
cln.DisplayId := displayId;
if Supports(Application.MainForm,IDock,intf) then
intf.DockForm(fmClientMain);
end;
end;
procedure TfrmLoanMain.RetrieveLoan;
begin
ln.Retrieve;
OpenDropdownDataSources(pnlApplication);
SetUnboundControls;
SetLoanHeaderCaption;
// ChangeControlState;
end;
procedure TfrmLoanMain.lbxComakersDblClick(Sender: TObject);
var
obj: TObject;
index: integer;
begin
index := lbxComakers.IndexOf(lbxComakers.SelectedItem);
if index > -1 then
begin
obj := lbxComakers.Items.Objects[index];
if Assigned(obj) then
if obj is TComaker then
with TfrmComakerDetail.Create(self) do
begin
cm := obj as TComaker;
cm.Retrieve;
ShowModal;
Free;
end;
end;
end;
procedure TfrmLoanMain.pnlEditAssessmentClick(Sender: TObject);
begin
inherited;
AssessLoan;
end;
procedure TfrmLoanMain.pnlEditRejectionClick(Sender: TObject);
begin
inherited;
RejectLoan;
end;
procedure TfrmLoanMain.SetLoanHeaderCaption;
begin
lblHeader.Caption := 'LOAN ID: ' + ln.Id + ' ' + ln.StatusName + #10#10 +
'Balance : ' + FormatCurr('###,###0.00',ln.Balance);
end;
procedure TfrmLoanMain.SetUnboundControls;
begin
bteClient.Text := ln.Client.Name;
mmAddress.Text := ln.Client.Address;
mmEmployer.Text := ln.Client.Employer.Name;
lblDaysFromLastTransaction.Caption := IntToStr(ln.DaysFromLastTransaction);
lblInterestDueAsOfDate.Caption := FormatCurr('###,###0.00;;-',ln.InterestDueAsOfDate);
lblTotalInterestDue.Caption := FormatCurr('###,###0.00;;-',ln.TotalInterestDue);
PopulateComakers;
end;
function TfrmLoanMain.LoanApplicationIsValid: boolean;
var
error: string;
begin
try
error := '';
if (ln.Action in [laCreating, laAssessing]) or (ln.IsPending) then
begin
if not Assigned(ln.Client) then
error := 'No client selected.'
else if dbluLoanClass.Text = '' then
error := 'Please select a loan class.'
else if dteDateApplied.Text = '' then
error := 'Please enter date applied.'
else if edAppAmount.Value <= 0 then
error := 'Invalid value for amount applied.'
else if edDesiredTerm.Value <= 0 then
error := 'Invalid value for desired term.'
else if edAppAmount.Value > ln.LoanClass.MaxLoan then
error := 'Amount applied exceeds the maximum loanable amount for the selected loan class.'
else if edDesiredTerm.Value > ln.LoanClass.Term then
error := 'Term applied exceeds the maximum allowed term for the selected loan class.'
else if (ln.LoanClass.HasMaxAge) and ((edDesiredTerm.Value / 12) + ln.Client.Age > ln.LoanClass.MaxAge) then
error := 'Term exceeds the maximum age limit for the selected loan class.'
else if ln.ComakerCount < ln.LoanClass.ComakersMin then
error := 'Number of required comakers has not been entered.'
else if ln.ComakerCount > ln.LoanClass.ComakersMax then
error := 'Declared comakers exceeds the required maximum.'
else if ln.Client.ValidIdentityDocs < ln.LoanClass.Group.Attributes.IdentityDocs then
error := 'Client has not submitted the required number of identity documents.'
else if ln.LoanClass.Group.Attributes.HasConcurrent then // note: this else block should ALWAYS be at the bottom..
begin
if ln.Client.GetLoanClassCount(ln.LoanClass.ClassificationId) >= ln.LoanClass.Group.Attributes.MaxConcurrent then
error := 'The selected loan class has already reached the maximum concurrent loans allowed.'
// else if edAppAmount.Value + ln.Client.GetLoanClassBalance(ln.LoanClass.ClassificationId) > ln.LoanClass.LoanType.MaxTotalAmount then
// error := 'Amount applied exceeds the maximum total amount allowed for concurrent loans.'
else if edAppAmount.Value + ln.Client.GetLoanClassBalance(ln.LoanClass.ClassificationId) > ln.LoanClass.Group.Attributes.MaxTotalAmount then
error := 'Amount applied exceeds the maximum total amount allowed for concurrent loans.'
end
end;
Result := error = '';
if not Result then ShowErrorBox(error);
finally
end;
end;
function TfrmLoanMain.Save: Boolean;
var
LPosting: TPosting;
LDate, LNewDate: TDateTime;
begin
Result := false;
if (ln.New) or (ln.IsPending) then
begin
Result := LoanApplicationIsValid;
if Result then
begin
if ln.IsBacklog then
begin
with TfrmBacklog.Create(self) do
begin
ShowModal;
if ModalResult = mrOk then
begin
ln.Save;
SetLoanHeaderCaption;
ChangeControlState;
ln.Action := laNone;
// interest and principal posting
LPosting := TPosting.Create;
try
LDate := IncDay(ln.LastTransactionDate);
LNewDate := ifn.AppDate;
while LDate <= LNewDate do
begin
LPosting.PostPrincipal(LDate);
LPosting.PostInterest2(LDate);
UpdateLoanDeficit(LDate);
LDate := IncDay(LDate);
end;
finally
LPosting.Free;
end;
end
else Result := false;
end;
end
else
begin
ln.Save;
SetLoanHeaderCaption;
ChangeControlState;
ln.Action := laNone;
end;
end;
end;
end;
procedure TfrmLoanMain.ShowAlerts;
begin
if Assigned(ln.Client) then
begin
ln.GetAlerts;
if alrt.Count > 0 then
with TfrmAlerts.Create(self) do
begin
ShowModal;
Free;
end
else
ShowInfoBox('No alerts found.');
end;
end;
procedure TfrmLoanMain.ShowLedger;
begin
if (ln.IsActive) or (ln.IsClosed) then
begin
with TfrmLoanLedger.Create(self) do
begin
Parent := self;
Show;
//Free;
end
end;
end;
procedure TfrmLoanMain.urlApprovalClick(Sender: TObject);
begin
inherited;
if (ln.HasLoanState(lsApproved)) or (ln.IsFinalised) then SetActiveTab(APPROVAL)
else ApproveLoan;
end;
procedure TfrmLoanMain.urlAssessmentClick(Sender: TObject);
begin
inherited;
if (ln.HasLoanState(lsAssessed)) or (ln.IsFinalised) then SetActiveTab(ASSESSED)
else AssessLoan;
end;
procedure TfrmLoanMain.urlCancelClick(Sender: TObject);
begin
inherited;
if (ln.HasLoanState(lsCancelled)) or (ln.IsClosed) then SetActiveTab(CANCELLATION)
else CancelLoan;
end;
procedure TfrmLoanMain.urlCloseClick(Sender: TObject);
begin
inherited;
if ln.IsClosed then SetActiveTab(CLOSED)
else CloseLoan;
end;
procedure TfrmLoanMain.urlLedgerClick(Sender: TObject);
begin
inherited;
ShowLedger;
end;
procedure TfrmLoanMain.urlRejectClick(Sender: TObject);
begin
inherited;
if (ln.HasLoanState(lsRejected)) or (ln.IsFinalised) then SetActiveTab(REJECTION)
else RejectLoan;
end;
procedure TfrmLoanMain.urlReleaseClick(Sender: TObject);
begin
inherited;
if (ln.HasLoanState(lsActive)) or (ln.IsFinalised) then SetActiveTab(RELEASED)
else ReleaseLoan;
end;
procedure TfrmLoanMain.urlSummaryClick(Sender: TObject);
begin
inherited;
SetActiveTab(SUMMARY);
end;
procedure TfrmLoanMain.PopulateComakers;
var
i, len: integer;
begin
lbxComakers.Clear;
len := ln.ComakerCount - 1;
for i := 0 to len do
lbxComakers.AddObject(ln.Comaker[i].Name,ln.Comaker[i]);
end;
end.
|
PROGRAM RevString(INPUT, OUTPUT);
PROCEDURE Reverse(VAR FileInp: TEXT);
VAR
Ch: CHAR;
BEGIN{Reverse}
IF NOT EOLN(FileInp)
THEN
BEGIN
READ(FileInp, Ch);
Reverse(FileInp);
WRITE(Ch)
END;
END;{Reverse}
BEGIN{RevString}
Reverse(INPUT);
END.{RevString}
|
unit Device.SMART.List;
interface
uses
SysUtils, Generics.Collections;
type
EEntryNotFound = class(EArgumentException);
TSMARTValueEntry = record
ID: Byte;
Current: Byte;
Worst: Byte;
Threshold: Byte;
RAW: UInt64;
end;
TSMARTValueList = class(TList<TSMARTValueEntry>)
public
function GetIndexByID(ID: Byte): Integer;
function GetRAWByID(ID: Byte): UInt64;
function ExceptionFreeGetRAWByID(ID: Byte): UInt64;
procedure MergeThreshold(const ThresholdList: TSMARTValueList);
end;
implementation
{ TSMARTValueList }
function TSMARTValueList.GetIndexByID(ID: Byte): Integer;
var
CurrentEntryNumber: Integer;
begin
for CurrentEntryNumber := 0 to (Self.Count - 1) do
if Self[CurrentEntryNumber].ID = ID then
exit(CurrentEntryNumber);
raise EEntryNotFound.Create('Entry not found with ID: ' + IntToStr(ID));
end;
function TSMARTValueList.GetRAWByID(ID: Byte): UInt64;
var
CurrentEntryNumber: Integer;
begin
for CurrentEntryNumber := 0 to (Self.Count - 1) do
if Self[CurrentEntryNumber].ID = ID then
exit(Self[CurrentEntryNumber].RAW);
raise EEntryNotFound.Create('Entry not found with ID: ' + IntToStr(ID));
end;
function TSMARTValueList.ExceptionFreeGetRAWByID(ID: Byte): UInt64;
var
CurrentEntryNumber: Integer;
begin
for CurrentEntryNumber := 0 to (Self.Count - 1) do
if Self[CurrentEntryNumber].ID = ID then
exit(Self[CurrentEntryNumber].RAW);
result := 0;
end;
procedure TSMARTValueList.MergeThreshold(const ThresholdList: TSMARTValueList);
var
CurrentItem: TSMARTValueEntry;
IndexInSelf: Integer;
EntryToChange: TSMARTValueEntry;
begin
for CurrentItem in ThresholdList do
begin
IndexInSelf := self.GetIndexByID(CurrentItem.ID);
EntryToChange := self[IndexInSelf];
EntryToChange.Threshold := CurrentItem.Threshold;
self[IndexInSelf] := EntryToChange;
end;
end;
end.
|
{ ---------------------------------------------------------------------------- }
{ HeightMapGenerator MB3D }
{ Copyright (C) 2017 Andreas Maschke }
{ ---------------------------------------------------------------------------- }
unit PNMWriter;
interface
uses
SysUtils, Classes, Windows;
type
TPGM16Writer = class
public
procedure SaveToFile( const Buffer: PWord; const Width, Height: Integer; const Filename: String);
end;
implementation
procedure TPGM16Writer.SaveToFile( const Buffer: PWord; const Width, Height: Integer; const Filename: String);
var
FileStream: TFileStream;
StrBuffer: AnsiString;
I, J: Integer;
Lst: TStringList;
CurrPGMBuffer: PWord;
ValStr: String;
Histogram: TStringList;
begin
FileStream := TFileStream.Create(Filename, fmCreate);
try
Lst := TStringList.Create;
try
Lst.Delimiter := ' ';
StrBuffer := 'P2'#10+'# MB3D'#10 +IntTostr(Width)+' '+IntToStr(Height)+#10+'65535' +#10;
FileStream.WriteData( PAnsiChar( StrBuffer ), Length( StrBuffer ) );
CurrPGMBuffer := Buffer;
Histogram := TStringList.Create;
try
Histogram.Sorted := True;
Histogram.Duplicates := dupIgnore;
for I := 0 to Height - 1 do begin
Lst.Clear;
for J := 0 to Width - 1 do begin
ValStr := IntToStr( CurrPGMBuffer^ );
Lst.Add( ValStr );
Histogram.Add( ValStr );
CurrPGMBuffer := PWord( Longint( CurrPGMBuffer ) + SizeOf( Word ) );
end;
StrBuffer := Lst.DelimitedText+#10;
FileStream.WriteData( PAnsiChar( StrBuffer ), Length( StrBuffer ) );
end;
OutputDebugString(PChar('PGM: ' + IntToStr( Histogram.Count ) + ' distinct colors'));
finally
Histogram.Free;
end;
finally
Lst.Free;
end;
finally
FileStream.Free;
end;
end;
end.
|
UNIT myStringUtil;
INTERFACE
USES math, strutils, sysutils, myGenerics, zstream, Classes, huffman, LazUTF8;
TYPE T_charSet=set of char;
T_byteSet=set of byte;
T_escapeStyle=(es_javaStyle,es_mnhPascalStyle,es_pickShortest,es_dontCare);
T_stringEncoding=(se_testPending,se_ascii,se_utf8,se_mixed);
CONST
C_backspaceChar = #8;
C_tabChar = #9;
C_lineBreakChar = #10;
C_invisibleTabChar = #11;
C_formFeedChar = #12;
C_carriageReturnChar= #13;
C_shiftOutChar = #14;
C_shiftInChar = #15;
C_compression_gzip :byte=1;
C_compression_huffman_default :byte=2;
C_compression_huffman_lucky :byte=3;
C_compression_huffman_numbers :byte=4;
C_compression_huffman_wikipedia:byte=5;
C_compression_huffman_mnh :byte=6;
BLANK_TEXT = '';
IDENTIFIER_CHARS:T_charSet=['a'..'z','A'..'Z','0'..'9','.','_'];
FUNCTION canonicalFileName(CONST s:string):string;
FUNCTION formatTabs(CONST s: T_arrayOfString): T_arrayOfString;
FUNCTION isBlank(CONST s: ansistring): boolean;
FUNCTION replaceRecursively(CONST original, lookFor, replaceBy: ansistring; OUT isValid: boolean): ansistring; inline;
FUNCTION replaceOne(CONST original, lookFor, replaceBy: ansistring): ansistring; inline;
FUNCTION escapeString(CONST s: ansistring; CONST style:T_escapeStyle; enc:T_stringEncoding; OUT nonescapableFound:boolean): ansistring;
FUNCTION unescapeString(CONST input: ansistring; CONST offset:longint; OUT parsedLength: longint): ansistring;
FUNCTION isIdentifier(CONST s: ansistring; CONST allowDot: boolean): boolean;
FUNCTION isFilename(CONST s: ansistring; CONST acceptedExtensions:array of string):boolean;
PROCEDURE collectIdentifiers(CONST s:ansistring; VAR list:T_setOfString; CONST skipWordAtPosition:longint);
FUNCTION startsWith(CONST input, head: ansistring): boolean;
FUNCTION endsWith(CONST input, tail: ansistring): boolean;
FUNCTION unbrace(CONST s:ansistring):ansistring;
FUNCTION split(CONST s:ansistring):T_arrayOfString;
FUNCTION reSplit(CONST s:T_arrayOfString):T_arrayOfString;
FUNCTION split(CONST s:ansistring; CONST splitters:T_arrayOfString; CONST retainSplitters:boolean=false):T_arrayOfString;
FUNCTION splitCommandLine(CONST s:ansistring):T_arrayOfString;
FUNCTION join(CONST lines:T_arrayOfString; CONST joiner:ansistring):ansistring;
FUNCTION cleanString(CONST s:ansistring; CONST whiteList:T_charSet; CONST instead:char):ansistring;
FUNCTION myTimeToStr(dt:double; CONST useSecondsIfLessThanOneMinute:boolean=true):string;
FUNCTION isAsciiEncoded(CONST s: ansistring): boolean;
FUNCTION isUtf8Encoded(CONST s: ansistring): boolean;
FUNCTION encoding(CONST s: ansistring):T_stringEncoding;
FUNCTION StripHTML(CONST S: string): string;
FUNCTION ensureSysEncoding(CONST s:ansistring):ansistring;
FUNCTION ensureUtf8Encoding(CONST s:ansistring):ansistring;
FUNCTION compressString(CONST src: ansistring; CONST algorithmsToConsider:T_byteSet):ansistring;
FUNCTION decompressString(CONST src:ansistring):ansistring;
FUNCTION tokenSplit(CONST stringToSplit:ansistring; CONST language:string='MNH'):T_arrayOfString;
FUNCTION ansistringInfo(VAR s:ansistring):string;
FUNCTION getListOfSimilarWords(CONST typedSoFar:string; CONST completionList:T_arrayOfString; CONST targetResultSize:longint; CONST ignorePosition:boolean):T_arrayOfString;
FUNCTION percentEncode(CONST s:string):string;
FUNCTION percentDecode(CONST s:string):string;
FUNCTION base92Encode(CONST src:ansistring):ansistring;
FUNCTION base92Decode(CONST src:ansistring):ansistring;
FUNCTION shortcutToString(CONST ShortCut:word):string;
IMPLEMENTATION
USES LCLType;
FUNCTION canonicalFileName(CONST s:string):string;
VAR isValidDummy:boolean;
begin
result:=ansiReplaceStr(replaceRecursively(ansiReplaceStr(expandFileName(s),'\','/'),'//','/',isValidDummy),'/',DirectorySeparator);
if result[length(result)]=DirectorySeparator then result:=copy(result,1,length(result)-1);
end;
FUNCTION TrimRightRetainingSpecials(CONST S: string): string;
CONST MY_WHITESPACE:T_charSet=[#0..#7,#16..' '];
VAR l:integer;
begin
l := length(s);
while (l>0) and (s[l] in MY_WHITESPACE) do
dec(l);
result := copy(s,1,l);
end ;
FUNCTION formatTabs(CONST s: T_arrayOfString): T_arrayOfString;
TYPE TcellInfo=record
cellType:(ctLeftAlignedString,ctRightAlignedString,ctNumeric);
posOfDot,txtLength:longint;
txt:ansistring;
end;
FUNCTION infoFromString(CONST s:ansistring):TcellInfo;
FUNCTION isNumeric(CONST untrimmedString: ansistring): boolean;
VAR i: longint;
hasDot, hasExpo: boolean;
s:ansistring;
begin
s:=trim(untrimmedString);
result:=length(s)>0;
hasDot:=false;
hasExpo:=false;
for i:=1 to length(s)-1 do if s [i] in ['.',','] then begin
result:=result and not(hasDot);
hasDot:=true;
end else if (s [i] in ['e', 'E']) and (i>1) then begin
result:=result and not(hasExpo);
hasExpo:=true;
end else result:=result and ((s [i] in ['0'..'9']) or ((i = 1) or (s [i-1] in ['e', 'E'])) and (s [i] in ['-', '+']));
end;
FUNCTION findDot(s: ansistring): longint;
begin
result:=pos('.', s); if result>0 then exit(result);
result:=pos(',', s); if result>0 then exit(result);
result:=UTF8Length(s)+1;
end;
begin
with result do begin
txt:=s;
txtLength:=UTF8Length(txt);
if isNumeric(txt) then begin
cellType:=ctNumeric;
posOfDot:=findDot(s);
end else begin
posOfDot:=txtLength+1;
if (length(txt)>=1) and (txt[1]=C_shiftInChar) then begin
dec(txtLength);
txt:=copy(txt,2,length(txt)-1);
cellType:=ctRightAlignedString;
end else cellType:=ctLeftAlignedString;
end;
end;
end;
PROCEDURE padLeft(VAR c:TcellInfo; CONST dotPos:longint); inline;
VAR count:longint;
begin
count:=dotPos-c.posOfDot;
if count<=0 then exit;
c.txt:=StringOfChar(' ',count)+c.txt;
inc(c.posOfDot,count);
inc(c.txtLength,count);
end;
PROCEDURE padRight(VAR c:TcellInfo; CONST targetLength:longint); inline;
VAR count:longint;
begin
count:=targetLength-c.txtLength;
if count<=0 then exit;
c.txt:=c.txt+StringOfChar(' ',count);
inc(c.txtLength,count);
end;
VAR matrix: array of array of TcellInfo=();
i, j, maxJ, maxLength, dotPos: longint;
anyTab:boolean=false;
anyInvisibleTab:boolean=false;
tmp:T_arrayOfString;
begin
for i:=0 to length(s)-1 do begin
anyTab :=anyTab or (pos(C_tabChar ,s[i])>0);
anyInvisibleTab:=anyInvisibleTab or (pos(C_invisibleTabChar,s[i])>0);
end;
if not(anyTab or anyInvisibleTab) then exit(s);
result:=s;
setLength(matrix,length(result));
if anyInvisibleTab then begin
if anyTab then
for i:=0 to length(result)-1 do result[i]:=ansiReplaceStr(result[i],C_tabChar ,' '+C_tabChar);
for i:=0 to length(result)-1 do result[i]:=ansiReplaceStr(result[i],C_invisibleTabChar, C_tabChar);
end;
j:=-1;
maxJ:=-1;
for i:=0 to length(result)-1 do begin
tmp:=split(result[i],C_tabChar);
setLength(matrix[i],length(tmp));
for j:=0 to length(tmp)-1 do matrix[i][j]:=infoFromString(tmp[j]);
j:=length(matrix[i])-1;
if j>maxJ then maxJ:=j;
end;
//expand columns to equal size:
for j:=0 to maxJ do begin
//Align numeric cells at decimal point
dotPos:=0;
for i:=0 to length(matrix)-1 do if (length(matrix[i])>j) and (matrix[i][j].cellType=ctNumeric) and (matrix[i][j].posOfDot>dotPos) then dotPos:=matrix[i][j].posOfDot;
if dotPos>0 then
for i:=0 to length(matrix)-1 do if (length(matrix[i])>j) and (matrix[i][j].cellType=ctNumeric) then padLeft(matrix[i][j],dotPos);
//Expand cells to equal width
if j<maxJ then begin //skip last column 'cause it will be trimmed right anyway
maxLength:=0;
for i:=0 to length(matrix)-1 do if (length(matrix[i])>j) and (matrix[i][j].txtLength>maxLength) then maxLength:=matrix[i][j].txtLength;
if not(anyInvisibleTab) then inc(maxLength);
for i:=0 to length(matrix)-1 do if (length(matrix[i])>j) then begin
if matrix[i][j].cellType=ctRightAlignedString
then padLeft (matrix[i][j],maxLength+1);
padRight(matrix[i][j],maxLength);
end;
end;
end;
//join matrix to result;
for i:=0 to length(matrix)-1 do begin
result[i]:='';
for j:=0 to length(matrix[i])-1 do result[i]:=result[i]+matrix[i][j].txt;
setLength(matrix[i],0);
result[i]:=TrimRightRetainingSpecials(result[i]);
end;
setLength(matrix,0);
end;
FUNCTION isBlank(CONST s: ansistring): boolean;
VAR
i: longint;
begin
result:=true;
for i:=1 to length(s) do
if not (s [i] in [C_lineBreakChar, C_carriageReturnChar, C_tabChar, ' ']) then
exit(false);
end;
FUNCTION replaceOne(CONST original, lookFor, replaceBy: ansistring): ansistring; inline;
VAR
p: longint;
begin
p:=pos(lookFor, original);
if p>0 then
result:=copy(original, 1, p-1)+replaceBy+
copy(original, p+length(lookFor), length(original))
else
result:=original;
end;
FUNCTION replaceRecursively(CONST original, lookFor, replaceBy: ansistring; OUT isValid: boolean): ansistring; inline;
VAR prev:ansistring;
begin
if pos(lookFor, replaceBy)>0 then begin
isValid:=false;
exit(ansiReplaceStr(original, lookFor, replaceBy));
end else begin
isValid:=true;
result:=original;
repeat
prev:=result;
result:=ansiReplaceStr(prev,lookFor,replaceBy);
until prev=result;
end;
end;
FUNCTION escapeString(CONST s: ansistring; CONST style:T_escapeStyle; enc:T_stringEncoding; OUT nonescapableFound:boolean): ansistring;
CONST javaEscapes:array[0..9,0..1] of char=(('\','\'),(C_backspaceChar ,'b'),
(C_tabChar ,'t'),
(C_lineBreakChar,'n'),
(C_invisibleTabChar,'v'),
(C_formFeedChar,'f'),
(C_carriageReturnChar,'r'),
(C_shiftInChar,'i'),
(C_shiftOutChar,'o'),
('"','"'));
javaEscapable:T_charSet=[C_backspaceChar,C_tabChar,C_lineBreakChar,C_invisibleTabChar,C_formFeedChar,C_carriageReturnChar,C_shiftInChar,C_shiftOutChar];
FUNCTION isJavaEscapable:boolean;
VAR c:char;
begin
if enc=se_testPending then enc:=encoding(s);
for c in s do if (c<#32) and not(c in javaEscapable) or ((enc<>se_utf8) and (c>#127)) then exit(false);
result:=true;
end;
FUNCTION pascalStyle:ansistring;
CONST DELIM='''';
begin
result:=DELIM+ansiReplaceStr(s,DELIM,DELIM+DELIM)+DELIM;
end;
FUNCTION strictPascalStyle:ansistring;
CONST DELIM='''';
VAR nonAsciiChars:set of char=[];
c:char;
nonAsciiMode:boolean=true;
begin
for c in s do if (c<#32) or (c>#126) then include(nonAsciiChars,c);
if nonAsciiChars=[] then exit(pascalStyle);
result:='';
for c in s do if (c in nonAsciiChars) then begin
if not(nonAsciiMode) then result:=result+DELIM;
nonAsciiMode:=true;
result:=result+'#'+intToStr(ord(c))
end else if c=DELIM then begin
if nonAsciiMode then result:=result+'#39'
else result:=result+DELIM+DELIM;
end else begin
if nonAsciiMode then result:=result+DELIM;
nonAsciiMode:=false;
result:=result+c;
end;
if not(nonAsciiMode) then result:=result+DELIM;
end;
FUNCTION javaStyle:ansistring;
VAR i:longint;
begin
result:=s;
for i:=0 to length(javaEscapes)-1 do result:=ansiReplaceStr(result,javaEscapes[i,0],'\'+javaEscapes[i,1]);
result:='"'+result+'"';
end;
VAR tmp:ansistring;
begin
result:='';
nonescapableFound:=false;
case style of
es_javaStyle: begin
nonescapableFound:=not(isJavaEscapable);
exit(javaStyle);
end;
es_mnhPascalStyle: exit(strictPascalStyle);
es_pickShortest : begin
if isJavaEscapable then begin
tmp:=javaStyle;
result:=strictPascalStyle;
if (length(tmp)<length(result)) then result:=tmp;
end else result:=strictPascalStyle;
end;
es_dontCare: if isJavaEscapable then exit(javaStyle)
else exit(strictPascalStyle);
end;
end;
FUNCTION unescapeString(CONST input: ansistring; CONST offset:longint; OUT parsedLength: longint): ansistring;
{$MACRO ON}
{$define exitFailing:=begin parsedLength:=0; exit(''); end}
CONST SQ='''';
DQ='"';
VAR i,i0,i1: longint;
continue:boolean;
begin
if length(input)>=offset+1 then begin //need at least a leading and a trailing delimiter
i0:=offset+1; i:=i0; i1:=offset; continue:=true; result:='';
if input[offset]=SQ then begin
while (i<=length(input)) and continue do if input[i]=SQ then begin
if (i<length(input)) and (input[i+1]=SQ) then begin
result:=result+copy(input,i0,i1-i0+1)+SQ;
inc(i,2);
i0:=i;
i1:=i0-1;
end else continue:=false;
end else begin
i1:=i;
inc(i);
end;
if continue then exitFailing;
result:=result+copy(input,i0,i1-i0+1);
parsedLength:=i+1-offset;
result:=result+unescapeString(input,offset+parsedLength,i1);
inc(parsedLength,i1);
exit(result);
end else if input[offset]=DQ then begin
while (i<=length(input)) and (input[i]<>DQ) do if input[i]='\' then begin
if (i<length(input)) then begin
case input[i+1] of
'b': result:=result+copy(input,i0,i1-i0+1)+#8 ;
't': result:=result+copy(input,i0,i1-i0+1)+#9 ;
'n': result:=result+copy(input,i0,i1-i0+1)+#10 ;
'v': result:=result+copy(input,i0,i1-i0+1)+#11 ;
'f': result:=result+copy(input,i0,i1-i0+1)+#12 ;
'r': result:=result+copy(input,i0,i1-i0+1)+#13 ;
else result:=result+copy(input,i0,i1-i0+1)+input[i+1];
end;
inc(i,2);
i0:=i;
i1:=i0-1;
end else exitFailing;
end else begin
i1:=i;
inc(i);
end;
result:=result+copy(input,i0,i1-i0+1);
parsedLength:=i+1-offset;
result:=result+unescapeString(input,offset+parsedLength,i1);
inc(parsedLength,i1);
exit(result);
end else if input[offset]='#' then begin
i:=offset+1;
while (i<length(input)) and (input[i+1] in ['0'..'9']) do inc(i);
result:=copy(input,offset+1,i-offset);
i0:=strToIntDef(result,256);
if (i0<0) or (i0>255)
then exitFailing
else begin
result:=chr(i0);
parsedLength:=i-offset+1;
result:=result+unescapeString(input,offset+parsedLength,i1);
inc(parsedLength,i1);
exit(result);
end;
end;
end;
exitFailing;
end;
FUNCTION isIdentifier(CONST s: ansistring; CONST allowDot: boolean): boolean;
VAR i: longint;
dotAllowed: boolean;
begin
dotAllowed:=allowDot;
result:=(length(s)>=1) and (s[1] in ['a'..'z', 'A'..'Z']);
i:=2;
while result and (i<=length(s)) do
if (s [i] in IDENTIFIER_CHARS) then inc(i)
else if (s [i] = '.') and dotAllowed then begin
inc(i);
dotAllowed:=false;
end else
result:=false;
end;
FUNCTION isFilename(CONST s: ansistring; CONST acceptedExtensions:array of string):boolean;
VAR i:longint;
ext:string;
begin
if length(s)=0 then exit(false);
ext:=uppercase(extractFileExt(s));
if length(acceptedExtensions)=0 then exit(true);
for i:=0 to length(acceptedExtensions)-1 do
if uppercase(acceptedExtensions[i])=ext then exit(true);
result:=false;
end;
PROCEDURE collectIdentifiers(CONST s:ansistring; VAR list:T_setOfString; CONST skipWordAtPosition:longint);
VAR i,i0:longint;
begin
i:=1;
while i<=length(s) do begin
if s[i] in ['a'..'z','A'..'Z'] then begin
i0:=i;
while (i<=length(s)) and (s[i] in IDENTIFIER_CHARS) do inc(i);
if not((i0<=skipWordAtPosition) and (i>=skipWordAtPosition)) then list.put(copy(s,i0,i-i0));
end else if (s[i]='/') and (i+1<=length(s)) and (s[i+1]='/') then exit
else inc(i);
end;
end;
FUNCTION startsWith(CONST input, head: ansistring): boolean;
begin
result:=copy(input, 1, length(head)) = head;
end;
FUNCTION endsWith(CONST input, tail: ansistring): boolean;
begin
result:=(length(input)>=length(tail)) and (copy(input,length(input)-length(tail)+1,length(tail))=tail);
end;
FUNCTION unbrace(CONST s:ansistring):ansistring;
begin
if (length(s)>=2) and (
(s[1]='(') and (s[length(s)]=')') or
(s[1]='[') and (s[length(s)]=']') or
(s[1]='{') and (s[length(s)]='}'))
then result:=copy(s,2,length(s)-2)
else result:=s;
end;
FUNCTION split(CONST s:ansistring):T_arrayOfString;
VAR lineSplitters:T_arrayOfString;
begin
lineSplitters:=(C_carriageReturnChar+C_lineBreakChar);
append(lineSplitters, C_lineBreakChar+C_carriageReturnChar);
append(lineSplitters, C_lineBreakChar);
result:=split(s,lineSplitters);
end;
FUNCTION reSplit(CONST s:T_arrayOfString):T_arrayOfString;
VAR i:longint;
begin
initialize(result);
setLength(result,0);
for i:=0 to length(s)-1 do append(result,split(s[i]));
end;
FUNCTION split(CONST s:ansistring; CONST splitters:T_arrayOfString; CONST retainSplitters:boolean=false):T_arrayOfString;
PROCEDURE nextSplitterPos(CONST startSearchAt:longint; OUT splitterStart,splitterEnd:longint); inline;
VAR splitter:string;
i:longint;
begin
splitterStart:=length(s)+1;
splitterEnd:=splitterStart;
for splitter in splitters do if length(splitter)>0 then begin
i:=PosEx(splitter,s,startSearchAt);
if (i>0) and (i<splitterStart) then begin
splitterStart:=i;
splitterEnd:=i+length(splitter);
end;
end;
end;
VAR resultLen:longint=0;
PROCEDURE appendToResult(CONST part:string); inline;
begin
if length(result)<resultLen+1 then setLength(result,round(length(result)*1.2)+2);
result[resultLen]:=part;
inc(resultLen);
end;
VAR partStart:longint=1;
splitterStart,splitterEnd:longint;
endsOnSplitter:boolean=false;
begin
setLength(result,0);
nextSplitterPos(partStart,splitterStart,splitterEnd);
endsOnSplitter:=splitterEnd>splitterStart;
while(partStart<=length(s)) do begin
appendToResult(copy(s,partStart,splitterStart-partStart));
partStart:=splitterEnd;
endsOnSplitter:=splitterEnd>splitterStart;
if endsOnSplitter and retainSplitters then appendToResult(copy(s,splitterStart,splitterEnd-splitterStart));
nextSplitterPos(partStart,splitterStart,splitterEnd);
end;
if endsOnSplitter and not retainSplitters then appendToResult('');
setLength(result,resultLen);
end;
FUNCTION splitCommandLine(CONST s:ansistring):T_arrayOfString;
VAR parseIndex:longint=1;
k:longint;
begin
initialize(result);
setLength(result,0);
while parseIndex<=length(s) do case s[parseIndex] of
' ': inc(parseIndex);
'"': begin
append(result,unescapeString(s,parseIndex,k));
if k<=0 then inc(parseIndex) else inc(parseIndex,k);
end;
else begin
k:=parseIndex;
while (k<=length(s)) and (s[k]<>' ') do inc(k);
append(result,copy(s,parseIndex,k-parseIndex));
parseIndex:=k+1;
end;
end;
end;
FUNCTION join(CONST lines:T_arrayOfString; CONST joiner:ansistring):ansistring;
VAR i:longint;
k:longint=0;
hasJoiner:boolean;
begin
if length(lines)=0 then exit('');
hasJoiner:=length(joiner)>0;
for i:=0 to length(lines)-1 do inc(k,length(lines[i]));
inc(k,length(joiner)*(length(lines)-1));
setLength(result,k);
k:=1;
if length(lines[0])>0 then begin
move(lines[0][1],result[k],length(lines[0]));
inc(k,length(lines[0]));
end;
if hasJoiner then for i:=1 to length(lines)-1 do begin
move(joiner [1],result[k],length(joiner )); inc(k,length(joiner ));
if length(lines[i])>0 then begin
move(lines[i][1],result[k],length(lines[i])); inc(k,length(lines[i]));
end;
end else for i:=1 to length(lines)-1 do begin
if length(lines[i])>0 then begin
move(lines[i][1],result[k],length(lines[i])); inc(k,length(lines[i]));
end;
end
end;
FUNCTION cleanString(CONST s:ansistring; CONST whiteList:T_charSet; CONST instead:char):ansistring;
VAR k:longint;
tmp:shortstring;
begin
if length(s)<=255 then begin
tmp:=s;
for k:=1 to length(s) do if not(tmp[k] in whiteList) then tmp[k]:=instead;
exit(tmp);
end;
result:='';
for k:=1 to length(s) do if s[k] in whiteList then result:=result+s[k] else result:=result+instead;
end;
FUNCTION myTimeToStr(dt:double; CONST useSecondsIfLessThanOneMinute:boolean=true):string;
CONST oneMinute=1/(24*60);
oneSecond=oneMinute/60;
begin
if (dt<oneMinute) and useSecondsIfLessThanOneMinute
then begin
result:=formatFloat('#0.00',dt/oneSecond)+'sec';
if length(result)<8 then result:=' '+result;
end
else if dt>1
then begin
dt:=dt*24; result:= formatFloat('00',floor(dt))+':';
dt:=(dt-floor(dt))*60; result:=result+formatFloat('00',floor(dt))+':';
dt:=(dt-floor(dt))*60; result:=result+formatFloat('00',floor(dt));
end
else result:=timeToStr(dt);
end;
FUNCTION isAsciiEncoded(CONST s: ansistring): boolean;
VAR i:longint;
begin
for i:=1 to length(s) do if ord(s[i])>127 then exit(false);
result:=true;
end;
FUNCTION isUtf8Encoded(CONST s: ansistring): boolean;
VAR i:longint;
begin
if length(s)=0 then exit(true);
i:=1;
while i<=length(s) do begin
// ASCII
if (s[i] in [#$09,#$0A,#$0D,#$20..#$7E]) then begin
inc(i);
continue;
end;
// non-overlong 2-byte
if (i+1<=length(s)) and
(s[i ] in [#$C2..#$DF]) and
(s[i+1] in [#$80..#$BF]) then begin
inc(i,2);
continue;
end;
// excluding overlongs
if (i+2<=length(s)) and
(((s[i]=#$E0) and
(s[i+1] in [#$A0..#$BF]) and
(s[i+2] in [#$80..#$BF])) or
((s[i] in [#$E1..#$EC,#$EE,#$EF]) and
(s[i+1] in [#$80..#$BF]) and
(s[i+2] in [#$80..#$BF])) or
((s[i]=#$ED) and
(s[i+1] in [#$80..#$9F]) and
(s[i+2] in [#$80..#$BF]))) then
begin
inc(i,3);
continue;
end;
// planes 1-3
if (i+3<=length(s)) and
(((s[i ]=#$F0) and
(s[i+1] in [#$90..#$BF]) and
(s[i+2] in [#$80..#$BF]) and
(s[i+3] in [#$80..#$BF])) or
((s[i ] in [#$F1..#$F3]) and
(s[i+1] in [#$80..#$BF]) and
(s[i+2] in [#$80..#$BF]) and
(s[i+3] in [#$80..#$BF])) or
((s[i]=#$F4) and
(s[i+1] in [#$80..#$8F]) and
(s[i+2] in [#$80..#$BF]) and
(s[i+3] in [#$80..#$BF]))) then
begin
inc(i,4);
continue;
end;
exit(false);
end;
exit(true);
end;
FUNCTION encoding(CONST s: ansistring):T_stringEncoding;
VAR i:longint;
asciiOnly:boolean=true;
begin
if length(s)=0 then exit(se_ascii);
i:=1;
while i<=length(s) do begin
// ASCII
if (s[i] in [#$09,#$0A,#$0D,#$20..#$7E]) then begin
inc(i);
continue;
end;
asciiOnly:=false;
// non-overlong 2-byte
if (i+1<=length(s)) and
(s[i ] in [#$C2..#$DF]) and
(s[i+1] in [#$80..#$BF]) then begin
inc(i,2);
continue;
end;
// excluding overlongs
if (i+2<=length(s)) and
(((s[i]=#$E0) and
(s[i+1] in [#$A0..#$BF]) and
(s[i+2] in [#$80..#$BF])) or
((s[i] in [#$E1..#$EC,#$EE,#$EF]) and
(s[i+1] in [#$80..#$BF]) and
(s[i+2] in [#$80..#$BF])) or
((s[i]=#$ED) and
(s[i+1] in [#$80..#$9F]) and
(s[i+2] in [#$80..#$BF]))) then
begin
inc(i,3);
continue;
end;
// planes 1-3
if (i+3<=length(s)) and
(((s[i ]=#$F0) and
(s[i+1] in [#$90..#$BF]) and
(s[i+2] in [#$80..#$BF]) and
(s[i+3] in [#$80..#$BF])) or
((s[i ] in [#$F1..#$F3]) and
(s[i+1] in [#$80..#$BF]) and
(s[i+2] in [#$80..#$BF]) and
(s[i+3] in [#$80..#$BF])) or
((s[i]=#$F4) and
(s[i+1] in [#$80..#$8F]) and
(s[i+2] in [#$80..#$BF]) and
(s[i+3] in [#$80..#$BF]))) then
begin
inc(i,4);
continue;
end;
exit(se_mixed);
end;
if asciiOnly then result:=se_ascii
else result:=se_utf8;
end;
FUNCTION ensureSysEncoding(CONST s:ansistring):ansistring;
begin
if isUtf8Encoded(s) or isAsciiEncoded(s) then result:=UTF8ToWinCP(s) else result:=s;
end;
FUNCTION ensureUtf8Encoding(CONST s:ansistring):ansistring;
begin
if isUtf8Encoded(s) or isAsciiEncoded(s) then result:=s else result:=WinCPToUTF8(s);
end;
FUNCTION StripHTML(CONST S: string): string;
VAR TagBegin, TagEnd, TagLength: integer;
begin
result:=s;
TagBegin := pos( '<', result); // search position of first <
while (TagBegin > 0) do begin // while there is a < in S
TagEnd := pos('>', result); // find the matching >
TagEnd := PosEx('>',result,TagBegin);
TagLength := TagEnd - TagBegin + 1;
delete(result, TagBegin, TagLength); // delete the tag
TagBegin:= pos( '<', result); // search for next <
end;
end;
FUNCTION gzip_compressString(CONST ASrc: ansistring):ansistring;
VAR vDest: TStringStream;
vSource: TStream;
vCompressor: TCompressionStream;
begin
result:='';
vDest := TStringStream.create('');
try
vCompressor := TCompressionStream.create(clMax, vDest,false);
try
vSource := TStringStream.create(ASrc);
try vCompressor.copyFrom(vSource, 0);
finally vSource.free; end;
finally
vCompressor.free;
end;
vDest.position := 0;
result := vDest.DataString;
finally
vDest.free;
end;
end;
FUNCTION gzip_decompressString(CONST ASrc:ansistring):ansistring;
VAR vDest: TStringStream;
vSource: TStream;
vDecompressor: TDecompressionStream;
begin
result:='';
vSource := TMemoryStream.create;
try
vSource.write(ASrc[1], length(ASrc));
vSource.position := 0;
vDecompressor := TDecompressionStream.create(vSource,false);
try
vDest := TStringStream.create('');
vDest.copyFrom(vDecompressor,0);
vDest.position := 0;
result := vDest.DataString;
vDest.free;
finally
vDecompressor.free;
end;
finally
vSource.free;
end;
end;
FUNCTION compressString(CONST src: ansistring; CONST algorithmsToConsider:T_byteSet):ansistring;
PROCEDURE checkAlternative(CONST alternativeSuffix:ansistring; CONST c0:char);
VAR alternative:ansistring;
begin
alternative:=c0+alternativeSuffix;
if length(alternative)<length(result) then result:=alternative;
end;
begin
if length(src)=0 then exit(src);
if src[1] in [#1..#4,#35..#38] then result:=#35+src
else result:= src;
if 1 in algorithmsToConsider then checkAlternative(gzip_compressString(src),#36);
if 2 in algorithmsToConsider then checkAlternative(huffyEncode(src,hm_DEFAULT ),#37);
if 3 in algorithmsToConsider then checkAlternative(huffyEncode(src,hm_LUCKY ),#38);
if 4 in algorithmsToConsider then checkAlternative(huffyEncode(src,hm_NUMBERS ),#1);
if 5 in algorithmsToConsider then checkAlternative(huffyEncode(src,hm_WIKIPEDIA),#2);
if 6 in algorithmsToConsider then checkAlternative(huffyEncode(src,hm_MNH ),#3);
end;
FUNCTION decompressString(CONST src:ansistring):ansistring;
begin
if length(src)=0 then exit(src);
case src[1] of
#35: exit( copy(src,2,length(src)-1));
#36: exit(gzip_decompressString(copy(src,2,length(src)-1)));
#37: exit(huffyDecode( copy(src,2,length(src)-1),hm_DEFAULT ));
#38: exit(huffyDecode( copy(src,2,length(src)-1),hm_LUCKY ));
#1: exit(huffyDecode( copy(src,2,length(src)-1),hm_NUMBERS ));
#2: exit(huffyDecode( copy(src,2,length(src)-1),hm_WIKIPEDIA));
#3: exit(huffyDecode( copy(src,2,length(src)-1),hm_MNH ));
end;
result:=src;
end;
FUNCTION tokenSplit(CONST stringToSplit: ansistring; CONST language: string): T_arrayOfString;
VAR i0,i1:longint;
resultCount:longint=0;
PROCEDURE stepToken;
begin
if length(result)<=resultCount then setLength(result,resultCount+128);
result[resultCount]:=copy(stringToSplit,i0,i1-i0);
inc(resultCount);
i0:=i1;
end;
VAR doubleQuoteString:boolean=false;
singleQuoteString:boolean=false;
escapeStringDelimiter:boolean=false;
cStyleComments:boolean=false;
dollarVariables:boolean=false;
commentDelimiters:array of array[0..1] of string;
PROCEDURE parseNumber(CONST input: ansistring; CONST offset:longint; OUT parsedLength: longint);
VAR i: longint;
begin
parsedLength:=0;
if (length(input)>=offset) and (input [offset] in ['0'..'9', '-', '+']) then begin
i:=offset;
while (i<length(input)) and (input [i+1] in ['0'..'9']) do inc(i);
parsedLength:=i+1-offset;
//Only digits on indexes [1..i]; accept decimal point and following digts
if (i<length(input)) and (input [i+1] = '.') then begin
inc(i);
if (i<length(input)) and (input [i+1] = '.') then dec(i);
end;
while (i<length(input)) and (input [i+1] in ['0'..'9']) do inc(i);
//Accept exponent marker and following exponent
if (i<length(input)) and (input [i+1] in ['e', 'E']) then begin
inc(i);
if (i<length(input)) and (input [i+1] in ['+', '-']) then inc(i);
end;
while (i<length(input)) and (input [i+1] in ['0'..'9']) do inc(i);
if i+1-offset>parsedLength then begin
parsedLength:=i+1-offset;
end;
end;
end;
PROCEDURE setLanguage(name:string);
PROCEDURE addCommentDelimiter(CONST opening,closing:string);
begin
setLength(commentDelimiters,length(commentDelimiters)+1);
commentDelimiters[length(commentDelimiters)-1,0]:=opening;
commentDelimiters[length(commentDelimiters)-1,1]:=closing;
end;
begin
setLength(commentDelimiters,0);
if trim(uppercase(name))='MNH' then begin
doubleQuoteString:=true;
singleQuoteString:=true;
escapeStringDelimiter:=true;
cStyleComments:=true;
dollarVariables:=true;
end else if trim(uppercase(name))='JAVA' then begin
addCommentDelimiter('/**','*/');
addCommentDelimiter('/*','*/');
doubleQuoteString:=true;
singleQuoteString:=true;
escapeStringDelimiter:=true;
cStyleComments:=true;
end else if trim(uppercase(name))='PASCAL' then begin
addCommentDelimiter('{','}');
addCommentDelimiter('(*','*)');
doubleQuoteString:=false;
singleQuoteString:=true;
escapeStringDelimiter:=false;
cStyleComments:=true;
end;
end;
FUNCTION readComment:boolean;
VAR i,nextOpen,nextClose:longint;
depth:longint=1;
begin
for i:=0 to length(commentDelimiters)-1 do
if copy(stringToSplit,i0,length(commentDelimiters[i,0]))=commentDelimiters[i,0]
then begin
i1:=i0+length(commentDelimiters[i,0]);
while (depth>0) and (i1<length(stringToSplit)) do begin
nextOpen :=PosEx(commentDelimiters[i,0],stringToSplit,i1); if nextOpen <=0 then nextOpen :=maxLongint;
nextClose:=PosEx(commentDelimiters[i,1],stringToSplit,i1); if nextClose<=0 then nextClose:=maxLongint;
if (nextOpen=nextClose) then begin
exit(true);
end else if (nextOpen<nextClose) then begin
inc(depth);
i1:=nextOpen+length(commentDelimiters[i,0]);
end else begin
dec(depth);
i1:=nextClose+length(commentDelimiters[i,1]);
end;
end;
if i1>length(stringToSplit)+1 then i1:=length(stringToSplit)+1;
exit(true);
end;
result:=false;
end;
begin
setLanguage(language);
setLength(result,0);
i0:=1;
while i0<=length(stringToSplit) do begin
if stringToSplit[i0] in [' ',C_lineBreakChar,C_carriageReturnChar,C_tabChar] then begin //whitespace
i1:=i0;
while (i1<=length(stringToSplit)) and (stringToSplit[i1] in [' ',C_lineBreakChar,C_carriageReturnChar,C_tabChar]) do inc(i1);
end else if readComment then begin
end else if (stringToSplit[i0]='''') and singleQuoteString or
(stringToSplit[i0]='"') and doubleQuoteString then begin
if escapeStringDelimiter then begin
unescapeString(copy(stringToSplit,i0,length(stringToSplit)-i0+1),1,i1);
if i1<=0 then i1:=i0+1
else i1:=i0+i1;
end else begin
i1:=i0+1;
while (i1<=length(stringToSplit)) and (stringToSplit[i1]<>stringToSplit[i0]) do inc(i1);
inc(i1);
end;
end else if (stringToSplit[i0] in ['(',')','[',']','{','}']) then begin
i1:=i0+1;
end else if (copy(stringToSplit,i0,2)='//') and cStyleComments then begin
i1:=i0+1;
while (i1<=length(stringToSplit)) and not(stringToSplit[i1] in [C_lineBreakChar,C_carriageReturnChar]) do inc(i1);
end else if (stringToSplit[i0] in ['a'..'z','A'..'Z']) or (stringToSplit[i0]='$') and dollarVariables then begin
i1:=i0+1;
while (i1<=length(stringToSplit)) and (stringToSplit[i1] in ['a'..'z','A'..'Z','_','0'..'9']) do inc(i1);
end else if stringToSplit[i0] in ['0'..'9'] then begin //numbers
parseNumber(stringToSplit,i0,i1);
if i1<=0 then i1:=i0
else i1:=i0+i1;
end else begin
i1:=i0;
while (i1<=length(stringToSplit)) and (stringToSplit[i1] in ['+','-','*','/','?',':','=','<','>','!','%','&','|']) do inc(i1);
if i1=i0 then i1:=i0+1;
end;
stepToken;
end;
setLength(result,resultCount);
end;
FUNCTION ansistringInfo(VAR s:ansistring):string;
begin
try
result:=IntToHex(ptrint (pointer(s)-24) ,16)
+' '+IntToHex(PByte (pointer(s)-24)^,2)
+' '+IntToHex(PByte (pointer(s)-23)^,2)
+' '+IntToHex(PByte (pointer(s)-22)^,2)
+' '+IntToHex(PByte (pointer(s)-21)^,2)
+' '+intToStr(plongint(pointer(s)-20)^)
+' '+intToStr(PInt64 (pointer(s)-16)^)
+' '+intToStr(PInt64 (pointer(s)- 8)^)
+' '+s;
except
result:=IntToHex(ptrint (pointer(s)-24) ,16)+' <?!?> '+s;
end;
end;
FUNCTION getListOfSimilarWords(CONST typedSoFar:string; CONST completionList:T_arrayOfString; CONST targetResultSize:longint; CONST ignorePosition:boolean):T_arrayOfString;
CONST BUCKET_COUNT=32;
VAR i:longint;
j:longint=0;
s:string;
typedUpper:string;
buckets:array of T_arrayOfString=();
PROCEDURE putToBucket(CONST match:string; CONST dist,uppercaseDist:longint);
VAR bin:longint=BUCKET_COUNT;
begin
if dist>0 then begin
if uppercaseDist>0
then bin:=min(dist,uppercaseDist)-1
else bin:=dist-1;
end else if uppercaseDist>0 then bin:=uppercaseDist-1;
if bin>=BUCKET_COUNT then exit;
append(buckets[bin],match);
end;
begin
if typedSoFar='' then exit(completionList);
setLength(result,targetResultSize);
if ignorePosition then begin
for s in completionList do if (pos(uppercase(typedSoFar),uppercase(s))>0) then begin
result[j]:=s;
inc(j);
if j>=targetResultSize then exit(result);
end;
end else begin
typedUpper:=uppercase(typedSoFar);
setLength(buckets,BUCKET_COUNT);
for i:=0 to length(buckets)-1 do buckets[i]:=C_EMPTY_STRING_ARRAY;
for s in completionList do
putToBucket(s,pos(typedSoFar,s)
,2*pos(typedUpper,uppercase(s)));
j:=0;
for i:=0 to BUCKET_COUNT-1 do for s in buckets[i] do begin;
result[j]:=s;
inc(j);
if j>=targetResultSize then exit(result);
end;
end;
setLength(result,j);
end;
FUNCTION percentCode(CONST c:byte):string;
CONST hexDigit:array[0..15] of char=('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
begin
result:='%'+hexDigit[c shr 4]+hexDigit[c and 15];
end;
FUNCTION percentEncode(CONST s:string):string;
VAR c:char;
begin
result:='';
for c in s do if c in ['A'..'Z','a'..'z','0'..'9','-','_'] then result:=result+c else result:=result+percentCode(ord(c));
end;
FUNCTION percentDecode(CONST s:string):string;
VAR c:byte;
begin
result:=s;
for c:=0 to 255 do result:=ansiReplaceStr(result,percentCode(c),chr(c));
end;
FUNCTION base92Encode(CONST src:ansistring):ansistring;
VAR k:longint;
FUNCTION encodeQuartet(CONST startIdx:longint):string;
CONST CODE92:array[0..91] of char=('!','"','#','$','%','&','(',')','*','+',',','-','.','/','0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[','\',']','^','_','`','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','{','|','}');
VAR i:longint;
j:byte;
value:int64=0;
begin
for i:=3 downto 0 do if startIdx+i<=length(src)
then value:=value*257+ord(src[startIdx+i])
else value:=value*257+256;
setLength(result,5);
for i:=0 to 4 do begin
j:=value mod 92; value:=value div 92;
result[i+1]:=CODE92[j];
end;
end;
begin
result:='';
k:=1;
while k<=length(src) do begin
result:=result+encodeQuartet(k);
inc(k,4);
end;
end;
FUNCTION base92Decode(CONST src:ansistring):ansistring;
VAR oneNum:int64;
i,j,k:longint;
CONST coded:T_charSet=['!'..'&','('..'}'];
FUNCTION nextNum:longint;
CONST DECODE92:array['!'..'}'] of byte=(0,1,2,3,4,5,0,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,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,91);
begin
inc(i);
while (i<=length(src)) and not(src[i] in coded) do inc(i);
if i>length(src) then exit(91)
else result:=DECODE92[src[i]];
end;
begin
result:='';
i:=0;
while i<length(src) do begin
oneNum:=nextNum;
oneNum:=oneNum+int64(92 )*nextNum;
oneNum:=oneNum+int64(8464 )*nextNum;
oneNum:=oneNum+int64(778688 )*nextNum;
oneNum:=oneNum+int64(71639296)*nextNum;
for j:=0 to 3 do begin
k:=oneNum mod 257; oneNum:=oneNum div 257;
if (k<256) and (k>=0) then result:=result+chr(k);
end;
while (i<length(src)) and not(src[i+1] in coded) do inc(i);
end;
end;
FUNCTION shortcutToString(CONST ShortCut:word):string;
begin
if ShortCut and scMeta >0 then result:='Meta+' else result:='';
if ShortCut and scShift>0 then result+='Shift+';
if ShortCut and scCtrl >0 then result+='Ctrl+';
if ShortCut and scAlt >0 then result+='Alt+';
if chr(ShortCut and 255) in ['0'..'9','A'..'Z'] then exit(result+chr(ShortCut and 255));
if (ShortCut and 255)=0 then exit('');
if (ShortCut and 255)=VK_OEM_PLUS then exit(result+'(+)');
if (ShortCut and 255)=VK_OEM_MINUS then exit(result+'(-)');
if (ShortCut and 255)=VK_F1 then exit(result+'F1');
if (ShortCut and 255)=VK_F2 then exit(result+'F2');
if (ShortCut and 255)=VK_F3 then exit(result+'F3');
if (ShortCut and 255)=VK_F4 then exit(result+'F4');
if (ShortCut and 255)=VK_F5 then exit(result+'F5');
if (ShortCut and 255)=VK_F6 then exit(result+'F6');
if (ShortCut and 255)=VK_F7 then exit(result+'F7');
if (ShortCut and 255)=VK_F8 then exit(result+'F8');
if (ShortCut and 255)=VK_F9 then exit(result+'F9');
if (ShortCut and 255)=VK_F10 then exit(result+'F10');
if (ShortCut and 255)=VK_F11 then exit(result+'F11');
if (ShortCut and 255)=VK_F12 then exit(result+'F12');
result:=result+'[unresolved key '+intToStr(ShortCut and 255)+']';
end;
end.
|
unit CameraConfigUtils;
interface
uses
System.SysUtils,
Androidapi.JNIBridge,
Androidapi.JNI.Hardware,
Androidapi.JNI.JavaTypes,
Androidapi.Helpers,
Androidapi.Log;
type
TCameraConfigUtils = class sealed
private
class var Tms: TMarshaller;
class function findSettableValue(name: string; const supportedValues: JList;
desiredValues: TArray<JString>): JString;
public
class procedure setVideoStabilization(parameters
: JCamera_Parameters); static;
class procedure setBarcodeSceneMode(parameters: JCamera_Parameters); static;
class procedure setFocus(parameters: JCamera_Parameters; autoFocus, disableContinuous,
safeMode: Boolean);
end;
implementation
class function TCameraConfigUtils.findSettableValue(name: string;
const supportedValues: JList; desiredValues: TArray<JString>): JString;
var
desiredValue: JString;
s: string;
I: Integer;
begin
if supportedValues <> nil then
begin
for desiredValue in desiredValues do
begin
if supportedValues.contains(desiredValue) then
Exit(desiredValue);
end;
end;
Result := nil;
end;
class procedure TCameraConfigUtils.setVideoStabilization
(parameters: JCamera_Parameters);
begin
if (parameters.isVideoStabilizationSupported()) then
begin
if (parameters.getVideoStabilization()) then
begin
// Log.i(TAG, "Video stabilization already enabled");
end
else
begin
// Log.i(TAG, "Enabling video stabilization...");
parameters.setVideoStabilization(true);
end;
end
else
begin
// Log.i(TAG, "This device does not support video stabilization");
end;
end;
class procedure TCameraConfigUtils.setBarcodeSceneMode
(parameters: JCamera_Parameters);
var
sceneMode: JString;
begin
if SameText(JStringToString(parameters.getSceneMode),
JStringToString(TJCamera_Parameters.JavaClass.SCENE_MODE_BARCODE)) then
begin
// Log.i(TAG, "Barcode scene mode already set");
Exit;
end;
sceneMode := findSettableValue('scene mode',
parameters.getSupportedSceneModes(),
[TJCamera_Parameters.JavaClass.SCENE_MODE_BARCODE]);
if (sceneMode <> nil) then
parameters.setSceneMode(sceneMode);
end;
class procedure TCameraConfigUtils.setFocus
(parameters: JCamera_Parameters; autoFocus, disableContinuous,
safeMode: Boolean);
var
supportedFocusModes: JList;
focusMode: JString;
begin
supportedFocusModes := parameters.getSupportedFocusModes();
focusMode := nil;
if (autoFocus) then
begin
if (safeMode or disableContinuous) then
begin
focusMode := findSettableValue('focus mode', supportedFocusModes,
[TJCamera_Parameters.JavaClass.FOCUS_MODE_AUTO]);
end
else
begin
focusMode := findSettableValue('focus mode', supportedFocusModes,
[// TJCamera_Parameters.JavaClass.FOCUS_MODE_MACRO,
TJCamera_Parameters.JavaClass.FOCUS_MODE_CONTINUOUS_PICTURE,
TJCamera_Parameters.JavaClass.FOCUS_MODE_CONTINUOUS_VIDEO,
TJCamera_Parameters.JavaClass.FOCUS_MODE_AUTO]);
end;
end;
// Maybe selected auto-focus but not available, so fall through here:
if (not safeMode) and (focusMode = nil) then
begin
focusMode := findSettableValue('focus mode', supportedFocusModes,
[TJCamera_Parameters.JavaClass.FOCUS_MODE_MACRO,
TJCamera_Parameters.JavaClass.FOCUS_MODE_EDOF]);
end;
if (focusMode <> nil) then
begin
if (focusMode.equals(parameters.getFocusMode())) then
begin
Logi(Tms.asAnsi('Focus mode already set to ' + JStringToString(focusMode))
.ToPointer);
end
else
begin
parameters.setFocusMode(focusMode);
end;
end;
end;
end.
|
unit WebSocketServer;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, ssockets, fgl, wsutils, wsstream;
type
TRequestData = record
Host: string;
Path: string;
Key: string;
Headers: THttpHeader;
end;
{ TWebsocketHandler }
TWebsocketHandler = class
public
function Accept(const ARequest: TRequestData;
const ResponseHeaders: TStrings): boolean; virtual;
procedure HandleCommunication(ACommunicator: TWebsocketCommunincator); virtual;
end;
TThreadedWebsocketHandler = class(TWebsocketHandler)
public
procedure HandleCommunication(ACommunicator: TWebsocketCommunincator); override;
procedure DoHandleCommunication(ACommunication: TWebsocketCommunincator); virtual;
end;
{ THostHandler }
THostHandler = class(specialize TStringObjectMap<TWebsocketHandler>)
private
FHost: string;
public
constructor Create(const AHost: string; FreeObjects: boolean);
property Host: string read FHost;
end;
{ THostMap }
THostMap = class(specialize TStringObjectMap<THostHandler>)
public
constructor Create;
procedure AddHost(const AHost: THostHandler);
end;
{ TLockedHostMap }
TLockedHostMap = class(specialize TThreadedObject<THostMap>)
public
constructor Create;
end;
TServerAcceptingMethod = (samDefault, samThreaded, samThreadPool);
{ TWebSocketServer }
TWebSocketServer = class
private
FSocket: TInetServer;
FHostMap: TLockedHostMap;
FFreeHandlers: boolean;
FAcceptingMethod: TServerAcceptingMethod;
procedure DoCreate;
procedure HandleConnect(Sender: TObject; Data: TSocketStream);
public
procedure Start;
procedure Stop(DoAbort: boolean = False);
procedure RegisterHandler(const AHost: string; const APath: string;
AHandler: TWebsocketHandler; DefaultHost: boolean = False;
DefaultPath: boolean = False);
destructor Destroy; override;
constructor Create(const AHost: string; const APort: word;
AHandler: TSocketHandler);
constructor Create(const APort: word);
property Socket: TInetServer read FSocket;
property FreeHandlers: boolean read FFreeHandlers write FFreeHandlers;
property AcceptingMethod: TServerAcceptingMethod
read FAcceptingMethod write FAcceptingMethod;
end;
const
MalformedRequestMessage =
'HTTP/1.1 400 Bad Request'#13#10#13#10'Not a Websocket Request';
ForbiddenRequestMessage =
'HTTP/1.1 403 Forbidden'#13#10#13#10'Request not accepted by Handler';
HandlerNotFoundMessage = 'HTTP/1.1 404 Not Found'#13#10#13#10'No Handler registered for this request';
implementation
type
{Thread Types}
{ TWebsocketHandlerThread }
TWebsocketHandlerThread = class(TPoolableThread)
private
FCommunicator: TWebsocketCommunincator;
FHandler: TThreadedWebsocketHandler;
protected
procedure DoExecute; override;
property Handler: TThreadedWebsocketHandler read FHandler write FHandler;
property Communicator: TWebsocketCommunincator
read FCommunicator write FCommunicator;
end;
THandlerThreadFactory = specialize TPoolableThreadFactory<TWebsocketHandlerThread>;
THandlerThreadPool = specialize TObjectPool<TWebsocketHandlerThread,
THandlerThreadFactory, THandlerThreadFactory>;
TLockedHandlerThreadPool = specialize TThreadedObject<THandlerThreadPool>;
{ TWebsocketRecieverThread }
TWebsocketRecieverThread = class(TPoolableThread)
private
FCommunicator: TWebsocketCommunincator;
FStopped: boolean;
protected
procedure DoExecute; override;
procedure Kill;
property Communicator: TWebsocketCommunincator
read FCommunicator write FCommunicator;
end;
TRecieverThreadFactory = specialize TPoolableThreadFactory<TWebsocketRecieverThread>;
TRecieverThreadPool = specialize TObjectPool<TWebsocketRecieverThread,
TRecieverThreadFactory, TRecieverThreadFactory>;
TLockedRecieverThreadPool = specialize TThreadedObject<TRecieverThreadPool>;
{ TWebsocketHandshakeHandler }
TWebsocketHandshakeHandler = class
private
FStream: TSocketStream;
FHostMap: TLockedHostMap;
function ReadRequest(var RequestData: TRequestData): boolean;
public
procedure PerformHandshake;
constructor Create(AStream: TSocketStream; AHostMap: TLockedHostMap);
end;
{ TAcceptingThread }
TAcceptingThread = class(TPoolableThread)
private
FHandshakeHandler: TWebsocketHandshakeHandler;
protected
procedure DoExecute; override;
property HandshakeHandler: TWebsocketHandshakeHandler
read FHandshakeHandler write FHandshakeHandler;
end;
TAcceptingThreadFactory = specialize TPoolableThreadFactory<TAcceptingThread>;
TAcceptingThreadPool = specialize TObjectPool<TAcceptingThread,
TAcceptingThreadFactory, TAcceptingThreadFactory>;
TLockedAcceptingThreadPool = specialize TThreadedObject<TAcceptingThreadPool>;
var
RecieverThreadPool: TLockedRecieverThreadPool;
HandlerThreadPool: TLockedHandlerThreadPool;
AcceptingThreadPool: TLockedAcceptingThreadPool;
function CreateAcceptingThread(
const AHandshakeHandler: TWebsocketHandshakeHandler): TAcceptingThread; inline;
var
pool: TAcceptingThreadPool;
begin
pool := AcceptingThreadPool.Lock;
try
Result := pool.GetObject;
Result.HandshakeHandler := AHandshakeHandler;
Result.Restart;
finally
AcceptingThreadPool.Unlock;
end;
end;
function CreateHandlerThread(const ACommunicator: TWebsocketCommunincator;
const AHandler: TThreadedWebsocketHandler): TWebsocketHandlerThread; inline;
var
pool: THandlerThreadPool;
begin
pool := HandlerThreadPool.Lock;
try
Result := pool.GetObject;
Result.Communicator := ACommunicator;
Result.Handler := AHandler;
Result.Restart;
finally
HandlerThreadPool.Unlock;
end;
end;
function CreateRecieverThread(const ACommunicator: TWebsocketCommunincator):
TWebsocketRecieverThread; inline;
var
pool: TRecieverThreadPool;
begin
pool := RecieverThreadPool.Lock;
try
Result := pool.GetObject;
Result.Communicator := ACommunicator;
Result.Restart;
finally
RecieverThreadPool.Unlock;
end;
end;
{ TWebsocketHandlerThread }
procedure TWebsocketHandlerThread.DoExecute;
var
Recv: TWebsocketRecieverThread;
begin
Recv := CreateRecieverThread(FCommunicator);
try
try
FHandler.DoHandleCommunication(FCommunicator);
finally
FCommunicator.Close;
FCommunicator.Free;
end;
finally
Recv.Kill;
end;
end;
procedure TAcceptingThread.DoExecute;
begin
FHandshakeHandler.PerformHandshake;
end;
{ TWebsocketRecieverThread }
procedure TWebsocketRecieverThread.DoExecute;
begin
FStopped := False;
while not Terminated and not FStopped and FCommunicator.Open do
begin
FCommunicator.RecieveMessage;
Sleep(10);
end;
end;
procedure TWebsocketRecieverThread.Kill;
begin
FStopped := True;
end;
{ THostHandler }
constructor THostHandler.Create(const AHost: string; FreeObjects: boolean);
begin
FHost := AHost;
inherited Create(FreeObjects);
end;
{ TWebsocketHandler }
function TWebsocketHandler.Accept(const ARequest: TRequestData;
const ResponseHeaders: TStrings): boolean;
begin
Result := True;
end;
procedure TWebsocketHandler.HandleCommunication(
ACommunicator: TWebsocketCommunincator);
begin
// No implementation; To be overriden
end;
procedure TThreadedWebsocketHandler.HandleCommunication(
ACommunicator: TWebsocketCommunincator);
begin
CreateHandlerThread(ACommunicator, Self);
end;
procedure TThreadedWebsocketHandler.DoHandleCommunication(
ACommunication: TWebsocketCommunincator);
begin
// No implementation; To be overriden
end;
{ THostMap }
constructor THostMap.Create;
begin
inherited Create(True);
end;
procedure THostMap.AddHost(const AHost: THostHandler);
begin
Objects[AHost.FHost] := AHost;
end;
{ TLockedHostMap }
constructor TLockedHostMap.Create;
begin
inherited Create(THostMap.Create);
end;
{ TWebsocketHandshakeHandler }
function TWebsocketHandshakeHandler.ReadRequest(var RequestData: TRequestData): boolean;
var
method: string;
proto: string;
headerstr: string;
upg: string;
conn: string;
version: string;
begin
Result := False;
// Check if this is HTTP by checking the first line
// Method GET is required
SetLength(method, 4);
FStream.ReadBuffer(method[1], 4);
if method <> 'GET ' then
begin
// Not GET
Exit;
end;
// Read path and HTTP version
FStream.ReadTo(' ', RequestData.Path);
FStream.ReadTo(#13#10, proto, 10);
RequestData.Path := RequestData.Path.TrimRight;
proto := proto.TrimRight.ToLower;
if not proto.StartsWith('http/') then
begin
// Only accept http/1.1
Exit;
end;
if not proto.EndsWith('1.1') then
begin
// non 1.1 version: return forbidden
Exit;
end;
// Headers are separated by 2 newlines (CR+LF)
FStream.ReadTo(#13#10#13#10, headerstr, 2048);
RequestData.Headers.Parse(headerstr.TrimRight);
if not (RequestData.Headers.TryGetData('Upgrade', upg) and
RequestData.Headers.TryGetData('Connection', conn) and
RequestData.Headers.TryGetData('Sec-WebSocket-Key', RequestData.Key) and
(upg = 'websocket') and (conn.Contains('Upgrade'))) then
begin
// Seems to be a normal HTTP request, we only handle websockets
Exit;
end;
// How to handle this?
if not RequestData.Headers.TryGetData('Sec-WebSocket-Version', version) then
version := '';
if not RequestData.Headers.TryGetData('Host', RequestData.Host) then
RequestData.Host := '';
Result := True;
end;
procedure TWebsocketHandshakeHandler.PerformHandshake;
var
RequestData: TRequestData;
hm: THostMap;
hh: THostHandler;
sh: TWebsocketHandler;
ResponseHeaders: TStringList;
i: integer;
HandsakeResponse: TStringList;
Comm: TWebsocketCommunincator;
begin
try
RequestData.Headers := THttpHeader.Create;
try
// Reqding request
try
if not ReadRequest(RequestData) then
begin
FStream.WriteRaw(MalformedRequestMessage);
FStream.Free;
Exit;
end;
except
on E: EReadError do
begin
FStream.WriteRaw(MalformedRequestMessage);
FStream.Free;
Exit;
end;
end;
// Getting responsible handler
hm := FHostMap.Lock;
try
hh := hm.Objects[RequestData.Host];
if not Assigned(hh) then
begin
FStream.WriteRaw(HandlerNotFoundMessage);
FStream.Free;
Exit;
end;
sh := hh.Objects[RequestData.Path];
if not Assigned(sh) then
begin
FStream.WriteRaw(HandlerNotFoundMessage);
FStream.Free;
Exit;
end;
finally
FHostMap.Unlock;
end;
// Checking if handler wants to accept
ResponseHeaders := TStringList.Create;
try
ResponseHeaders.NameValueSeparator := ':';
if not sh.Accept(RequestData, ResponseHeaders) then
begin
FStream.WriteRaw(ForbiddenRequestMessage);
FStream.Free;
Exit;
end;
// Neseccary headers
ResponseHeaders.Values['Connection'] := 'Upgrade';
ResponseHeaders.Values['Upgrade'] := 'websocket';
ResponseHeaders.Values['Sec-WebSocket-Accept'] :=
GenerateAcceptingKey(RequestData.Key);
// Generating response
HandsakeResponse := TStringList.Create;
try
HandsakeResponse.TextLineBreakStyle := tlbsCRLF;
HandsakeResponse.Add('HTTP/1.1 101 Switching Protocols');
for i := 0 to ResponseHeaders.Count - 1 do
HandsakeResponse.Add('%s: %s'.Format([ResponseHeaders.Names[i],
ResponseHeaders.ValueFromIndex[i]]));
HandsakeResponse.Add('');
FStream.WriteRaw(HandsakeResponse.Text);
finally
HandsakeResponse.Free;
end;
finally
ResponseHeaders.Free;
end;
finally
RequestData.Headers.Free;
end;
Comm := TWebsocketCommunincator.Create(TLockedSocketStream.Create(FStream),
False, True);
finally
// Not needed anymore, we can now die in piece.
// All information requier for the rest is now on the stack
Self.Free;
end;
sh.HandleCommunication(Comm);
end;
constructor TWebsocketHandshakeHandler.Create(AStream: TSocketStream;
AHostMap: TLockedHostMap);
begin
FHostMap := AHostMap;
FStream := AStream;
end;
{ TWebSocketServer }
procedure TWebSocketServer.DoCreate;
begin
FSocket.OnConnect := @HandleConnect;
FHostMap := TLockedHostMap.Create;
FFreeHandlers := True;
FAcceptingMethod := samDefault;
end;
procedure TWebSocketServer.HandleConnect(Sender: TObject; Data: TSocketStream);
var
HandshakeHandler: TWebsocketHandshakeHandler;
t: TAcceptingThread;
begin
HandshakeHandler := TWebsocketHandshakeHandler.Create(Data, FHostMap);
case AcceptingMethod of
samDefault:
HandshakeHandler.PerformHandshake;
samThreaded:
begin
t := TAcceptingThread.Create(True);
t.DoTerminate := True;
t.FreeOnTerminate := True;
t.HandshakeHandler := HandshakeHandler;
t.Restart;
end;
samThreadPool:
CreateAcceptingThread(HandshakeHandler);
end;
end;
procedure TWebSocketServer.Start;
begin
FSocket.StartAccepting;
end;
procedure TWebSocketServer.Stop(DoAbort: boolean);
begin
FSocket.StopAccepting(DoAbort);
end;
procedure TWebSocketServer.RegisterHandler(const AHost: string;
const APath: string; AHandler: TWebsocketHandler; DefaultHost: boolean;
DefaultPath: boolean);
var
map: THostMap;
hh: THostHandler;
begin
map := FHostMap.Lock;
try
if not map.TryGetObject(AHost, hh) then
begin
hh := THostHandler.Create(AHost, FFreeHandlers);
map.AddHost(hh);
end;
if DefaultHost then
map.DefaultObject := hh;
hh[APath] := AHandler;
if DefaultPath then
hh.DefaultObject := AHandler;
finally
FHostMap.Unlock;
end;
end;
destructor TWebSocketServer.Destroy;
begin
Stop(True);
FSocket.Free;
FHostMap.Free;
inherited Destroy;
end;
constructor TWebSocketServer.Create(const AHost: string; const APort: word;
AHandler: TSocketHandler);
begin
FSocket := TInetServer.Create(AHost, APort, AHandler);
DoCreate;
end;
constructor TWebSocketServer.Create(const APort: word);
begin
FSocket := TInetServer.Create(APort);
DoCreate;
end;
initialization
AcceptingThreadPool := TLockedAcceptingThreadPool.Create(TAcceptingThreadPool.Create);
HandlerThreadPool := TLockedHandlerThreadPool.Create(THandlerThreadPool.Create);
RecieverThreadPool := TLockedRecieverThreadPool.Create(TRecieverThreadPool.Create);
finalization
AcceptingThreadPool.Free;
RecieverThreadPool.Free;
HandlerThreadPool.Free;
end.
|
program Sample;
var
H : String;
procedure CopyPrint1(G: String);
var F : String;
begin
F := G;
F[1] := 'M';
WriteLn('F: ', F);
WriteLn('G: ', G);
end;
procedure CopyPrint2(var G: String);
var F : String;
begin
F := G;
G[1] := 'M';
WriteLn('F: ', F);
WriteLn('G: ', G);
end;
begin
H := 'Hello World';
CopyPrint1(H);
WriteLn('1 H: ', H);
CopyPrint2(H);
WriteLn('2 H: ', H);
end.
|
unit uObjPool;
interface
uses
Windows,
Classes,
SysUtils,
SyncObjs;
type
TCreateNewPoolObj = function: TObject of object;
TPoolItem = class
private
InUse : Boolean;
Obj : TObject;
public
constructor Create(AObj: TObject);
destructor Destroy; override;
end;
TObjectPool = class
private
FItems: TList;
FThreads: TList;
FCS: TCriticalSection;
FMaxObjs : Integer;
FWaitTime : Cardinal;
FCreateNewPoolObj: TCreateNewPoolObj;
function GetObj(T: Pointer): TObject;
protected
function CreateObj: TObject; virtual;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure ReleaseObj(AObj: TObject);
function GetObjFromPool: TObject;
property WaitTime: Cardinal
read FWaitTime write FWaitTime;
property MaxObjs: Integer
read FMaxObjs write FMaxObjs;
property CreateNewPoolObj: TCreateNewPoolObj
read FCreateNewPoolObj write FCreateNewPoolObj;
end;
implementation
{ TObjectPool }
procedure TObjectPool.Clear;
begin
FCS.Enter;
try
while FItems.Count > 0 do begin
TPoolItem(FItems[0]).Free;
FItems.Delete(0);
end;
finally
FCS.Leave;
end;
end;
constructor TObjectPool.Create;
begin
inherited;
FCS := TCriticalSection.Create;
FItems := TList.Create;
FThreads := TList.Create;
FMaxObjs := -1;
FWaitTime := 5;
FCreateNewPoolObj := nil;
end;
function TObjectPool.CreateObj: TObject;
begin
if not Assigned(FCreateNewPoolObj) then
Raise Exception.Create('CreateNewPoolObj method not assigned');
Result := FCreateNewPoolObj;
end;
destructor TObjectPool.Destroy;
begin
Clear;
FItems.Free;
FThreads.Free;
FCS.Free;
inherited;
end;
function TObjectPool.GetObj(T: Pointer): TObject;
var
I, P: Integer;
PI : TPoolItem;
begin
FCS.Enter;
try
if (FMaxObjs>0) and (FThreads[0]<>T) then begin
Result := nil;
Exit;
end;
for I := 0 to FItems.Count-1 do
with TPoolItem(FItems[I]) do
if not InUse then begin
InUse := True;
Result := Obj;
Exit;
end;
if (FMaxObjs=-1) or (FItems.Count<FMaxObjs) then begin
Result := CreateObj;
PI := TPoolItem.Create(Result);
FItems.Add(PI);
end else
Result := nil;
finally
FCS.Leave;
end;
end;
function TObjectPool.GetObjFromPool: TObject;
var T: Pointer;
begin
if FMaxObjs>0 then begin
T := Pointer(GetCurrentThreadID);
FCS.Enter;
try
FThreads.Add(T);
finally
FCS.Leave;
end;
end;
try
repeat
Result := GetObj(T);
if Result = nil then
Sleep(FWaitTime);
until (Result<>nil);
finally
if FMaxObjs>0 then begin
FCS.Enter;
try
FThreads.Remove(T);
finally
FCS.Leave;
end;
end;
end;
end;
procedure TObjectPool.ReleaseObj(AObj: TObject);
var I : Integer;
begin
FCS.Enter;
try
for I := 0 to FItems.Count-1 do
with TPoolItem(FItems[I]) do
if Obj = AObj then begin
InUse := False;
Exit;
end;
AObj.Free;
finally
FCS.Leave;
end;
end;
{ TPoolItem }
constructor TPoolItem.Create(AObj: TObject);
begin
inherited Create;
Obj := AObj;
InUse := True;
end;
destructor TPoolItem.Destroy;
begin
Obj.Free;
inherited;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Datasnap.DSCustomConnectorProxyWriter;
interface
uses
Data.DBXPlatform,
Datasnap.DSCommonProxy,
Datasnap.DSProxyWriter,
System.SysUtils;
type
TDSCustomConnectorProxyWriter = class abstract(TDSCustomProxyWriter)
public
constructor Create; virtual;
protected
Get: UnicodeString;
Post: UnicodeString;
Put: UnicodeString;
Delete: UnicodeString;
FPostPrefix: UnicodeString;
FPutPrefix: UnicodeString;
FDeletePrefix: UnicodeString;
FGenerateURLFunctions: Boolean;
FSupportedTypes: TDBXInt32s;
FNonURLTypes: TDBXInt32s;
function GetMethodRequestType(const ProxyClass: TDSProxyClass;
const Method: TDSProxyMethod): UnicodeString; virtual;
function Contains(const Arr: TDBXInt32s; const Value: Integer): Boolean;
function ExtendedIncludeClass(const ProxyClass: TDSProxyClass): Boolean;
function ExtendedIncludeMethod(const ProxyMethod: TDSProxyMethod): Boolean;
procedure ForEachInputParameter(const ProxyMethod: TDSProxyMethod;
Callback: TProc<TDSProxyParameter>);
procedure ForEachOutputParameter(const ProxyMethod: TDSProxyMethod;
Callback: TProc<TDSProxyParameter>);
procedure ForEachParameter(const ProxyMethod: TDSProxyMethod;
Callback: TProc<TDSProxyParameter>);
function GetFirstClass: TDSProxyClass;
function IsOutputParameter(const Param: TDSProxyParameter): Boolean;
function IsInputParameter(const Param: TDSProxyParameter): Boolean;
function GetNonURLTypes: TDBXInt32s; virtual;
function GetSupportedTypes: TDBXInt32s; virtual;
function IsPrimitiveJSONType(ClassName: String): Boolean; virtual; final;
function GetAssignmentString: UnicodeString; override;
function GetSetter(Param: TDSProxyParameter): String; virtual;
function GetGetter(Param: TDSProxyParameter): String; virtual;
function IsDBXValueTypeParameter(const Param: TDSProxyParameter): Boolean;
function GetParameterDirection(Direction: Integer): string; virtual;
function GetParameterDirectionPrefix:String;virtual;
function GetOutputParametersCount(const ProxyMethod: TDSProxyMethod)
: Integer; virtual;
function HasOnlyURLParams(const Method: TDSProxyMethod): Boolean;
function IsProcedure(const ProxyMethod: TDSProxyMethod): Boolean;
function GetReturnParam(const ProxyMethod: TDSProxyMethod)
: TDSProxyParameter;
function GetMethodRequestName(const ProxyClass: TDSProxyClass;
const Method: TDSProxyMethod): UnicodeString; virtual;
function GetParameterType(ParameterType: Integer): String;virtual;
function GetParameterTypePrefix:string;virtual;
property SupportedTypes: TDBXInt32s read GetSupportedTypes;
property NonURLTypes: TDBXInt32s read GetNonURLTypes;
property FirstClass: TDSProxyClass read GetFirstClass;
end;
implementation
uses
Data.DbxCommon, Datasnap.DSProxyUtils, System.StrUtils;
{ TDSCustomConnectorProxyWriter }
constructor TDSCustomConnectorProxyWriter.Create;
begin
Get := 'GET';
Post := 'POST';
Put := 'PUT';
Delete := 'DELETE';
FPostPrefix := 'update';
FPutPrefix := 'accept';
FDeletePrefix := 'cancel';
inherited Create;
FIndentIncrement := 2;
FIndentString := '';
end;
function TDSCustomConnectorProxyWriter.GetAssignmentString: UnicodeString;
begin
Result := '=';
end;
function TDSCustomConnectorProxyWriter.GetGetter
(Param: TDSProxyParameter): String;
begin
if IsDBXValueTypeParameter(Param) then
Exit('GetAsDBXValue');
case Param.DataType of
TDBXDataTypes.UnknownType:
raise EDSProxyException.Create('Cannot get getter for DataType UNKNOWN');
TDBXDataTypes.AnsiStringType:
begin
Exit('GetAsAnsiString');
end;
TDBXDataTypes.DateType:
begin
Exit('GetAsTDBXDate');
end;
TDBXDataTypes.BlobType:
Exit('GetAsBlob');
TDBXDataTypes.BooleanType:
begin
Exit('GetAsBoolean');
end;
TDBXDataTypes.Int16Type:
begin
Exit('GetAsInt16');
end;
TDBXDataTypes.Int32Type:
begin
Exit('GetAsInt32');
end;
TDBXDataTypes.DoubleType:
begin
Exit('GetAsDouble');
end;
TDBXDataTypes.BcdType:
Exit('GetAsBcd');
TDBXDataTypes.BytesType:
Exit('GetAsBytes');
TDBXDataTypes.TimeType:
Exit('GetAsTDBXTime');
TDBXDataTypes.DatetimeType:
Exit('GetAsDateTime');
TDBXDataTypes.UInt16Type:
begin
Exit('GetAsUInt16');
end;
TDBXDataTypes.UInt32Type:
begin
Exit('GetAsUInt32');
end;
TDBXDataTypes.VarBytesType:
Exit('<NOT SUPPORTED VARBYTES>');
TDBXDataTypes.CursorType:
Exit('<NOT SUPPORTED CURSOR>');
TDBXDataTypes.Int64Type:
begin
Exit('GetAsInt64');
end;
TDBXDataTypes.UInt64Type:
begin
Exit('GetAsUInt64');
end;
TDBXDataTypes.AdtType:
Exit('<NOT SUPPORTED ADT>');
TDBXDataTypes.ArrayType:
Exit('<NOT SUPPORTED ARRAY>');
TDBXDataTypes.RefType:
Exit('<NOT SUPPORTED REF>');
TDBXDataTypes.TableType:
Exit('GetAsTable');
TDBXDataTypes.TimeStampType:
Exit('GetAsTimeStamp');
TDBXDataTypes.CurrencyType:
Exit('GetAsCurrency');
TDBXDataTypes.WideStringType:
begin
Exit('GetAsString');
end;
TDBXDataTypes.SingleType:
begin
Exit('GetAsSingle');
end;
TDBXDataTypes.Int8Type:
begin
Exit('GetAsInt8');
end;
TDBXDataTypes.UInt8Type:
begin
Exit('GetAsUInt8');
end;
TDBXDataTypes.ObjectType:
Exit('GetAsObject');
TDBXDataTypes.CharArrayType:
Exit('<NOT SUPPORTED CHARARRAY>');
TDBXDataTypes.IntervalType:
Exit('<NOT SUPPORTED INTERVAL>');
TDBXDataTypes.BinaryBlobType:
Exit('GetAsStream');
TDBXDataTypes.DBXConnectionType:
Exit('<NOT SUPPORTED DBXConnection>');
TDBXDataTypes.VariantType:
Exit('GetAsVariant');
TDBXDataTypes.TimeStampOffsetType:
Exit('<NOT SUPPORTED TimeStampOffset>');
TDBXDataTypes.JsonValueType:
Exit('GetAsJSONValue');
TDBXDataTypes.CallbackType:
Exit('<NOT SUPPORTED Callback>');
TDBXDataTypes.MaxBaseTypes:
Exit('<NOT SUPPORTED MaxBase>');
end;
Exit('<NOT SUPPORTED ???>');
end;
function TDSCustomConnectorProxyWriter.GetMethodRequestType(const ProxyClass
: TDSProxyClass; const Method: TDSProxyMethod): UnicodeString;
var
MName: UnicodeString;
Param: TDSProxyParameter;
Aux: TDSProxyParameter;
LastType: Integer;
HadIn: Boolean;
begin
MName := Method.ProxyMethodName;
if StringStartsWith(MName, FPutPrefix) and (Length(MName) > Length(FPutPrefix))
then
Exit(Put);
if StringStartsWith(MName, FPostPrefix) and
(Length(MName) > Length(FPostPrefix)) then
Exit(Post);
if StringStartsWith(MName, FDeletePrefix) and
(Length(MName) > Length(FDeletePrefix)) then
Exit(Delete);
if (CompareText(sDSAdminClassName, ProxyClass.ProxyClassName) = 0) and
(Method.ParameterCount > 0) then
begin
HadIn := False;
Param := Method.Parameters;
Aux := Param;
while Aux <> nil do
begin
if (Aux <> nil) and
((Aux.ParameterDirection = TDBXParameterDirections.InParameter) or
(Aux.ParameterDirection = TDBXParameterDirections.InOutParameter)) then
begin
HadIn := True;
Param := Aux;
end;
Aux := Aux.Next;
end;
LastType := Param.DataType;
if HadIn and Contains(NonURLTypes, LastType) then
Exit(Post);
end;
Result := Get;
end;
function TDSCustomConnectorProxyWriter.GetNonURLTypes: TDBXInt32s;
var
I: Integer;
begin
if FNonURLTypes = nil then
begin
SetLength(FNonURLTypes, 9);
I := 0;
FNonURLTypes[IncrAfter(I)] := TDBXDataTypes.JsonValueType;
FNonURLTypes[IncrAfter(I)] := TDBXDataTypes.ObjectType;
FNonURLTypes[IncrAfter(I)] := TDBXDataTypes.TableType;
FNonURLTypes[IncrAfter(I)] := TDBXDataTypes.BytesType;
FNonURLTypes[IncrAfter(I)] := TDBXDataTypes.VarBytesType;
FNonURLTypes[IncrAfter(I)] := TDBXDataTypes.ArrayType;
FNonURLTypes[IncrAfter(I)] := TDBXDataTypes.CharArrayType;
FNonURLTypes[IncrAfter(I)] := TDBXDataTypes.BlobType;
FNonURLTypes[IncrAfter(I)] := TDBXDataTypes.BinaryBlobType;
end;
Result := FNonURLTypes;
end;
function TDSCustomConnectorProxyWriter.GetSetter
(Param: TDSProxyParameter): String;
begin
if IsDBXValueTypeParameter(Param) then
Exit('SetAsDBXValue');
case Param.DataType of
TDBXDataTypes.UnknownType:
raise EDSProxyException.Create('Cannot get setter for DataType UNKNOWN');
TDBXDataTypes.AnsiStringType:
begin
Exit('SetAsAnsiString');
end;
TDBXDataTypes.DateType:
begin
Exit('SetAsTDBXDate');
end;
TDBXDataTypes.BlobType:
Exit('SetAsBlob');
TDBXDataTypes.BooleanType:
begin
Exit('SetAsBoolean');
end;
TDBXDataTypes.Int16Type:
begin
Exit('SetAsInt16');
end;
TDBXDataTypes.Int32Type:
begin
Exit('SetAsInt32');
end;
TDBXDataTypes.DoubleType:
begin
Exit('SetAsDouble');
end;
TDBXDataTypes.BcdType:
Exit('SetAsBcd');
TDBXDataTypes.BytesType:
Exit('SetAsBytes');
TDBXDataTypes.TimeType:
Exit('SetAsTDBXTime');
TDBXDataTypes.DatetimeType:
Exit('SetAsDateTime');
TDBXDataTypes.UInt16Type:
begin
Exit('SetAsUInt16');
end;
TDBXDataTypes.UInt32Type:
begin
Exit('SetAsUInt32');
end;
TDBXDataTypes.Int64Type:
begin
Exit('SetAsInt64');
end;
TDBXDataTypes.UInt64Type:
begin
Exit('SetAsUInt64');
end;
TDBXDataTypes.TableType:
Exit('SetAsTable');
TDBXDataTypes.TimeStampType:
Exit('SetAsTimeStamp');
TDBXDataTypes.CurrencyType:
Exit('SetAsCurrency');
TDBXDataTypes.WideStringType:
// Exit('SetAsString');
begin
Exit('SetAsString');
end;
TDBXDataTypes.SingleType:
begin
Exit('SetAsSingle');
end;
TDBXDataTypes.Int8Type:
begin
Exit('SetAsInt8');
end;
TDBXDataTypes.UInt8Type:
begin
Exit('SetAsUInt8');
end;
TDBXDataTypes.ObjectType:
Exit('SetAsObject');
TDBXDataTypes.BinaryBlobType:
Exit('SetAsStream');
TDBXDataTypes.JsonValueType:
Exit('SetAsJSONValue');
TDBXDataTypes.MaxBaseTypes:
Exit('<NOT SUPPORTED MaxBase>');
TDBXDataTypes.VariantType, TDBXDataTypes.DBXConnectionType,
TDBXDataTypes.TimeStampOffsetType, TDBXDataTypes.CallbackType,
TDBXDataTypes.IntervalType, TDBXDataTypes.CharArrayType,
TDBXDataTypes.AdtType, TDBXDataTypes.ArrayType, TDBXDataTypes.RefType,
TDBXDataTypes.VarBytesType, TDBXDataTypes.CursorType:
Exit('<WARNING! Type ' + Param.TypeName + ' is not supported>');
end;
end;
function TDSCustomConnectorProxyWriter.GetSupportedTypes: TDBXInt32s;
var
I: Integer;
begin
if FSupportedTypes = nil then
begin
SetLength(FSupportedTypes, 24);
I := 0;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.AnsiStringType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.WideStringType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.BooleanType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.Int8Type;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.Int16Type;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.Int32Type;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.Int64Type;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.UInt8Type;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.UInt16Type;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.UInt32Type;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.UInt64Type;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.DoubleType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.SingleType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.CurrencyType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.BcdType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.DateType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.DatetimeType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.TimeType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.TimeStampType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.JsonValueType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.ArrayType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.ObjectType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.TableType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.BinaryBlobType;
end;
Result := FSupportedTypes;
end;
function TDSCustomConnectorProxyWriter.HasOnlyURLParams
(const Method: TDSProxyMethod): Boolean;
var
Param: TDSProxyParameter;
PtType: Integer;
begin
Param := nil;
if Method <> nil then
Param := Method.Parameters;
while Param <> nil do
begin
if (Param.ParameterDirection = TDBXParameterDirections.InOutParameter) or
(Param.ParameterDirection = TDBXParameterDirections.InParameter) then
begin
PtType := Param.DataType;
if not Contains(SupportedTypes, PtType) or Contains(NonURLTypes, PtType)
then
Exit(False);
end;
Param := Param.Next;
end;
Result := True;
end;
function TDSCustomConnectorProxyWriter.IsProcedure(const ProxyMethod
: TDSProxyMethod): Boolean;
var
Param: TDSProxyParameter;
begin
Param := GetReturnParam(ProxyMethod);
Result := (not Assigned(Param));
end;
function TDSCustomConnectorProxyWriter.IsDBXValueTypeParameter
(const Param: TDSProxyParameter): Boolean;
begin
Result := AnsiStartsStr('TDBX', Param.TypeName) and
AnsiEndsStr('Value', Param.TypeName);
end;
function TDSCustomConnectorProxyWriter.IsInputParameter
(const Param: TDSProxyParameter): Boolean;
begin
Result := Param.ParameterDirection in [TDBXParameterDirections.InParameter,
TDBXParameterDirections.InOutParameter];
end;
function TDSCustomConnectorProxyWriter.IsOutputParameter
(const Param: TDSProxyParameter): Boolean;
begin
Result := Param.ParameterDirection in [TDBXParameterDirections.OutParameter,
TDBXParameterDirections.InOutParameter,
TDBXParameterDirections.ReturnParameter];
end;
function TDSCustomConnectorProxyWriter.IsPrimitiveJSONType
(ClassName: String): Boolean;
begin
Result := (ClassName = 'TJSONTrue') or (ClassName = 'TJSONFalse') or
(ClassName = 'TJSONNull') or (ClassName = 'TJSONString') or
(ClassName = 'TJSONNumber');
end;
function TDSCustomConnectorProxyWriter.GetParameterDirection
(Direction: Integer): string;
begin
case Direction of
TDBXParameterDirections.InParameter:
Exit(GetParameterDirectionPrefix+'Input');
TDBXParameterDirections.OutParameter:
Exit(GetParameterDirectionPrefix+'Output');
TDBXParameterDirections.InOutParameter:
Exit(GetParameterDirectionPrefix+'InputOutput');
TDBXParameterDirections.ReturnParameter:
Exit(GetParameterDirectionPrefix+'ReturnValue');
else
raise Exception.Create('Param direction not allowed');
end;
end;
function TDSCustomConnectorProxyWriter.GetParameterDirectionPrefix: String;
begin
result := 'DSRESTParamDirection.';
end;
function TDSCustomConnectorProxyWriter.GetParameterType(
ParameterType: Integer): String;
begin
case ParameterType of
TDBXDataTypes.UnknownType:
Exit(GetParameterTypePrefix+'UnknownType');
TDBXDataTypes.AnsiStringType:
Exit(GetParameterTypePrefix+'AnsiStringType');
TDBXDataTypes.DateType:
Exit(GetParameterTypePrefix+'DateType');
TDBXDataTypes.BlobType:
Exit(GetParameterTypePrefix+'BlobType');
TDBXDataTypes.BooleanType:
Exit(GetParameterTypePrefix+'BooleanType');
TDBXDataTypes.Int16Type:
Exit(GetParameterTypePrefix+'Int16Type');
TDBXDataTypes.Int32Type:
Exit(GetParameterTypePrefix+'Int32Type');
TDBXDataTypes.DoubleType:
Exit(GetParameterTypePrefix+'DoubleType');
TDBXDataTypes.BcdType:
Exit(GetParameterTypePrefix+'BcdType');
TDBXDataTypes.BytesType:
Exit(GetParameterTypePrefix+'BytesType');
TDBXDataTypes.TimeType:
Exit(GetParameterTypePrefix+'TimeType');
TDBXDataTypes.DatetimeType:
Exit(GetParameterTypePrefix+'DateTimeType');
TDBXDataTypes.UInt16Type:
Exit(GetParameterTypePrefix+'UInt16Type');
TDBXDataTypes.UInt32Type:
Exit(GetParameterTypePrefix+'UInt32Type');
TDBXDataTypes.VarBytesType:
Exit(GetParameterTypePrefix+'VarBytesType');
TDBXDataTypes.CursorType:
Exit(GetParameterTypePrefix+'CursorType');
TDBXDataTypes.Int64Type:
Exit(GetParameterTypePrefix+'Int64Type');
TDBXDataTypes.UInt64Type:
Exit(GetParameterTypePrefix+'UInt64Type');
TDBXDataTypes.AdtType:
Exit(GetParameterTypePrefix+'AdtType');
TDBXDataTypes.ArrayType:
Exit(GetParameterTypePrefix+'ArrayType');
TDBXDataTypes.RefType:
Exit(GetParameterTypePrefix+'RefType');
TDBXDataTypes.TableType:
Exit(GetParameterTypePrefix+'TableType');
TDBXDataTypes.TimeStampType:
Exit(GetParameterTypePrefix+'TimeStampType');
TDBXDataTypes.CurrencyType:
Exit(GetParameterTypePrefix+'CurrencyType');
TDBXDataTypes.WideStringType:
Exit(GetParameterTypePrefix+'WideStringType');
TDBXDataTypes.SingleType:
Exit(GetParameterTypePrefix+'SingleType');
TDBXDataTypes.Int8Type:
Exit(GetParameterTypePrefix+'Int8Type');
TDBXDataTypes.UInt8Type:
Exit(GetParameterTypePrefix+'UInt8Type');
TDBXDataTypes.ObjectType:
Exit(GetParameterTypePrefix+'ObjectType');
TDBXDataTypes.CharArrayType:
Exit(GetParameterTypePrefix+'CharArrayType');
TDBXDataTypes.IntervalType:
Exit(GetParameterTypePrefix+'IntervalType');
TDBXDataTypes.BinaryBlobType:
Exit(GetParameterTypePrefix+'BinaryBlobType');
TDBXDataTypes.DBXConnectionType:
Exit('NOT ALLOWED');
TDBXDataTypes.VariantType:
Exit(GetParameterTypePrefix+'VariantType');
TDBXDataTypes.TimeStampOffsetType:
Exit(GetParameterTypePrefix+'TimeStampOffsetType');
TDBXDataTypes.JsonValueType:
Exit(GetParameterTypePrefix+'JsonValueType');
TDBXDataTypes.CallbackType:
Exit('NOT ALLOWED');
TDBXDataTypes.MaxBaseTypes:
Exit('NOT ALLOWED');
end;
end;
function TDSCustomConnectorProxyWriter.GetParameterTypePrefix: string;
begin
result:= 'DBXDataTypes.';
end;
function TDSCustomConnectorProxyWriter.GetReturnParam(const ProxyMethod
: TDSProxyMethod): TDSProxyParameter;
var
R: TDSProxyParameter;
begin
ForEachOutputParameter(ProxyMethod,
procedure(Param: TDSProxyParameter)
begin
if Param.ParameterDirection = TDBXParameterDirections.ReturnParameter then
R := Param;
end);
Result := R;
end;
function TDSCustomConnectorProxyWriter.GetOutputParametersCount
(const ProxyMethod: TDSProxyMethod): Integer;
var
Param: TDSProxyParameter;
begin
Result := 0;
Param := ProxyMethod.Parameters;
while Param <> nil do
begin
if IsOutputParameter(Param) then
inc(Result);
Param := Param.Next;
end;
end;
function TDSCustomConnectorProxyWriter.ExtendedIncludeClass(const ProxyClass
: TDSProxyClass): Boolean;
var
ProxyMethod: TDSProxyMethod;
begin
if IncludeClass(ProxyClass) then
begin
if (CompareText(sDSMetadataClassName, ProxyClass.ProxyClassName) = 0) or
(CompareText(sDSAdminClassName, ProxyClass.ProxyClassName) = 0) then
Exit(False);
ProxyMethod := ProxyClass.FirstMethod;
while ProxyMethod <> nil do
begin
if ExtendedIncludeMethod(ProxyMethod) then
Exit(True);
ProxyMethod := ProxyMethod.Next;
end;
end;
Result := False;
end;
function TDSCustomConnectorProxyWriter.Contains(const Arr: TDBXInt32s;
const Value: Integer): Boolean;
var
I: Integer;
begin
for I := 0 to Length(Arr) - 1 do
begin
if Arr[I] = Value then
Exit(True);
end;
Result := False;
end;
function TDSCustomConnectorProxyWriter.ExtendedIncludeMethod(const ProxyMethod
: TDSProxyMethod): Boolean;
var
Param: TDSProxyParameter;
PtType: Integer;
PtName: UnicodeString;
begin
if IncludeMethod(ProxyMethod) then
begin
Param := ProxyMethod.Parameters;
if Param <> nil then
while Param <> nil do
begin
PtType := Param.DataType;
if not Contains(SupportedTypes, PtType) then
Exit(False)
else if (Param.ParameterDirection = TDBXParameterDirections.
ReturnParameter) and (PtType = TDBXDataTypes.WideStringType) then
begin
PtName := Param.TypeName;
if not(WideLowerCase(PtName) = 'string') then
Exit(False);
end;
Param := Param.Next;
end;
Exit(True);
end;
Result := False;
end;
procedure TDSCustomConnectorProxyWriter.ForEachParameter(const ProxyMethod
: TDSProxyMethod; Callback: TProc<TDSProxyParameter>);
var
Param: TDSProxyParameter;
begin
Param := ProxyMethod.Parameters;
while Param <> nil do
begin
Callback(Param);
Param := Param.Next;
end;
end;
procedure TDSCustomConnectorProxyWriter.ForEachOutputParameter(const ProxyMethod
: TDSProxyMethod; Callback: TProc<TDSProxyParameter>);
var
Param: TDSProxyParameter;
begin
Param := ProxyMethod.Parameters;
while Param <> nil do
begin
if IsOutputParameter(Param) then
Callback(Param);
Param := Param.Next;
end;
end;
procedure TDSCustomConnectorProxyWriter.ForEachInputParameter(const ProxyMethod
: TDSProxyMethod; Callback: TProc<TDSProxyParameter>);
var
Param: TDSProxyParameter;
begin
Param := ProxyMethod.Parameters;
while Param <> nil do
begin
if IsInputParameter(Param) then
Callback(Param);
Param := Param.Next;
end;
end;
function TDSCustomConnectorProxyWriter.GetFirstClass: TDSProxyClass;
begin
Result := Metadata.Classes;
end;
function TDSCustomConnectorProxyWriter.GetMethodRequestName(const ProxyClass
: TDSProxyClass; const Method: TDSProxyMethod): UnicodeString;
var
MType: UnicodeString;
MName: UnicodeString;
PrefixLength: Integer;
begin
MType := GetMethodRequestType(ProxyClass, Method);
MName := Method.ProxyMethodName;
PrefixLength := 0;
if not(CompareText(sDSAdminClassName, ProxyClass.ProxyClassName) = 0) then
begin
if (Put = MType) then
PrefixLength := Length(FPutPrefix)
else if (Post = MType) then
PrefixLength := Length(FPostPrefix)
else if (Delete = MType) then
PrefixLength := Length(FDeletePrefix);
if (PrefixLength > 0) and (PrefixLength < Length(MName)) then
MName := Copy(MName, PrefixLength + 1, Length(MName) - (PrefixLength));
end;
Result := MName;
end;
end.
|
unit uCustomEdit;
interface
uses
Windows, SysUtils, Classes, Controls, Forms, StdCtrls, Vcl.Mask, Vcl.ComCtrls;
type
TEditMultiLine = class(TEdit)
private
FMultiline: Boolean;
FEnabled: Boolean;
procedure FSetEnabled(Value: Boolean);
protected
procedure CreateParams(var Params:TCreateParams);override;
public
published
property Multiline: Boolean read FMultiline write FMultiline;
property Enabled: Boolean read FEnabled write FSetEnabled;
end;
implementation
procedure TEditMultiLine.CreateParams(var Params: TCreateParams);
begin
inherited createParams(Params);
//Params.Style:=Params.Style + WS_BORDER;
//Params.ExStyle:=Params.ExStyle or WS_EX_CLIENTEDGE ;
if FMultiline then
Params.Style:=Params.Style
or ES_MULTILINE {or WS_VSCROLL};
end;
procedure TEditMultiLine.FSetEnabled(Value: Boolean);
begin
//inherited;
if Value then
SetWindowLongPtr(Handle, GWL_STYLE, GetWindowLongPtr(Handle, GWL_STYLE) and not WS_DISABLED)
else
SetWindowLongPtr(Handle, GWL_STYLE, GetWindowLongPtr(Handle, GWL_STYLE) or WS_DISABLED);
FEnabled:=Value;
end;
end.
|
unit dosheader;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
const
IMAGE_SIZEOF_SHORT_NAME = 8;
IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
IMAGE_FILE_RELOCS_STRIPPED = $0001;
IMAGE_FILE_EXECUTABLE_IMAGE = $0002;
IMAGE_FILE_LINE_NUMS_STRIPPED = $0004;
IMAGE_FILE_LOCAL_SYMS_STRIPPED = $0008;
IMAGE_FILE_AGGRESIVE_WS_TRIM = $0010;
IMAGE_FILE_LARGE_ADDRESS_AWARE = $0020;
IMAGE_FILE_BYTES_REVERSED_LO = $0080;
IMAGE_FILE_32BIT_MACHINE = $0100;
IMAGE_FILE_DEBUG_STRIPPED = $0200;
IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP = $0400;
IMAGE_FILE_NET_RUN_FROM_SWAP = $0800;
IMAGE_FILE_SYSTEM = $1000;
IMAGE_FILE_DLL = $2000;
IMAGE_FILE_UP_SYSTEM_ONLY = $4000;
IMAGE_FILE_BYTES_REVERSED_HI = $8000;
IMAGE_ORDINAL_FLAG32 = DWORD($80000000);
IMAGE_ORDINAL_FLAG64 = QWORD($8000000000000000);
IMAGE_SIZEOF_BASE_RELOCATION = 8;
IMAGE_REL_BASED_HIGHLOW = 3;
IMAGE_SCN_MEM_DISCARDABLE = $02000000;
IMAGE_SCN_MEM_NOT_CACHED = $04000000;
IMAGE_SCN_CNT_INITIALIZED_DATA = $00000040;
IMAGE_SCN_CNT_UNINITIALIZED_DATA = $00000080;
IMAGE_SCN_MEM_EXECUTE = $20000000;
IMAGE_SCN_MEM_READ = $40000000;
IMAGE_SCN_MEM_WRITE = DWORD($80000000);
cDOSRelocOffset = $18; // offset of "pointer" to DOS relocation table
cWinHeaderOffset = $3C; // offset of "pointer" to windows header in file
cNEAppTypeOffset = $0D; // offset in NE windows header of app type field
cDOSMagic = $5A4D; // magic number for a DOS executable
cNEMagic = $454E; // magic number for a NE executable (Win 16)
cPEMagic = $4550; // magic nunber for a PE executable (Win 32)
cLEMagic = $454C; // magic number for a Virtual Device Driver
cNEDLLFlag = $80; // flag in NE app type field indicating a DLL
type
LIST_ENTRY = record
Flink : ^_LIST_ENTRY;
Blink : ^_LIST_ENTRY;
end;
_LIST_ENTRY = LIST_ENTRY;
TLISTENTRY = LIST_ENTRY;
PLISTENTRY = ^LIST_ENTRY;
IMAGE_BASE_RELOCATION = packed record
VirtualAddress: DWORD;
SizeOfBlock: DWORD;
end;
PIMAGE_BASE_RELOCATION = ^IMAGE_BASE_RELOCATION;
IMAGE_EXPORT_DIRECTORY = packed record
Characteristics: DWORD;
TimeDateStamp: DWORD;
MajorVersion: WORD;
MinorVersion: WORD;
Name: DWORD;
Base: DWORD;
NumberOfFunctions: DWORD;
NumberOfNames: DWORD;
AddressOfFunctions: DWORD;
AddressOfNames: DWORD;
AddressOfNameOrdinals: DWORD;
end;
PIMAGE_EXPORT_DIRECTORY = ^IMAGE_EXPORT_DIRECTORY;
IMAGE_EXPORT_DIRECTORY_ARRAY = array[0..0] of IMAGE_EXPORT_DIRECTORY;
PIMAGE_EXPORT_DIRECTORY_ARRAY = ^IMAGE_EXPORT_DIRECTORY_ARRAY;
IMAGE_IMPORT_DESCRIPTOR = packed record
OriginalFirstThunk: DWORD;
TimeDateStamp: DWORD;
ForwarderChain: DWORD;
Name: DWORD;
FirstThunk: DWORD;
end;
PIMAGE_IMPORT_DESCRIPTOR = ^IMAGE_IMPORT_DESCRIPTOR;
TImageImportDescriptor = IMAGE_IMPORT_DESCRIPTOR;
IMAGE_IMPORT_DESCRIPTOR_ARRAY = packed array[0..0] of IMAGE_IMPORT_DESCRIPTOR;
PIMAGE_IMPORT_DESCRIPTOR_ARRAY = ^IMAGE_IMPORT_DESCRIPTOR_ARRAY;
PImageImportByName = ^TImageImportByName;
IMAGE_IMPORT_BY_NAME = packed record
Hint: Word;
Name: array [0 .. 255] of Byte; // original: "Name: array [0..0] of Byte;"
end;
TImageImportByName = IMAGE_IMPORT_BY_NAME;
PIMAGE_IMPORT_BY_NAME = ^IMAGE_IMPORT_BY_NAME;
IMAGE_DATA_DIRECTORY = packed record
VirtualAddress : DWORD;
Size : DWORD;
end;
PIMAGE_DATA_DIRECTORY = ^IMAGE_DATA_DIRECTORY;
IMAGE_SECTION_HEADER = packed record
Name : packed array [0..IMAGE_SIZEOF_SHORT_NAME-1] of Char;
PhysicalAddress : DWORD; // or VirtualSize (union);
VirtualAddress : DWORD;
SizeOfRawData : DWORD;
PointerToRawData : DWORD;
PointerToRelocations : DWORD;
PointerToLinenumbers : DWORD;
NumberOfRelocations : WORD;
NumberOfLinenumbers : WORD;
Characteristics : DWORD;
end;
PIMAGE_SECTION_HEADER = ^IMAGE_SECTION_HEADER;
IMAGE_OPTIONAL_HEADER = packed record
{ Standard fields. }
Magic : WORD;
MajorLinkerVersion : Byte;
MinorLinkerVersion : Byte;
SizeOfCode : DWORD;
SizeOfInitializedData : DWORD;
SizeOfUninitializedData : DWORD;
AddressOfEntryPoint : DWORD;
BaseOfCode : DWORD;
BaseOfData : DWORD;
{ NT additional fields. }
ImageBase : DWORD;
SectionAlignment : DWORD;
FileAlignment : DWORD;
MajorOperatingSystemVersion : WORD;
MinorOperatingSystemVersion : WORD;
MajorImageVersion : WORD;
MinorImageVersion : WORD;
MajorSubsystemVersion : WORD;
MinorSubsystemVersion : WORD;
Reserved1 : DWORD;
SizeOfImage : DWORD;
SizeOfHeaders : DWORD;
CheckSum : DWORD;
Subsystem : WORD;
DllCharacteristics : WORD;
SizeOfStackReserve : DWORD;
SizeOfStackCommit : DWORD;
SizeOfHeapReserve : DWORD;
SizeOfHeapCommit : DWORD;
LoaderFlags : DWORD;
NumberOfRvaAndSizes : DWORD;
DataDirectory: packed array[0..IMAGE_NUMBEROF_DIRECTORY_ENTRIES-1] of IMAGE_DATA_DIRECTORY;
end;
PIMAGE_OPTIONAL_HEADER = ^IMAGE_OPTIONAL_HEADER;
IMAGE_OPTIONAL_HEADER64 = packed record
{ Standard fields. }
Magic : WORD;
MajorLinkerVersion : Byte;
MinorLinkerVersion : Byte;
SizeOfCode : DWORD;
SizeOfInitializedData : DWORD;
SizeOfUninitializedData : DWORD;
AddressOfEntryPoint : DWORD;
BaseOfCode : DWORD;
// BaseOfData : DWORD;
{ NT additional fields. }
ImageBase : UInt64;
SectionAlignment : DWORD;
FileAlignment : DWORD;
MajorOperatingSystemVersion : WORD;
MinorOperatingSystemVersion : WORD;
MajorImageVersion : WORD;
MinorImageVersion : WORD;
MajorSubsystemVersion : WORD;
MinorSubsystemVersion : WORD;
Win32VersionValue : DWORD;
SizeOfImage : DWORD;
SizeOfHeaders : DWORD;
CheckSum : DWORD;
Subsystem : WORD;
DllCharacteristics : WORD;
SizeOfStackReserve : UInt64;
SizeOfStackCommit : UInt64;
SizeOfHeapReserve : UInt64;
SizeOfHeapCommit : UInt64;
LoaderFlags : DWORD;
NumberOfRvaAndSizes : DWORD;
DataDirectory: packed array[0..IMAGE_NUMBEROF_DIRECTORY_ENTRIES-1] of IMAGE_DATA_DIRECTORY;
end;
PIMAGE_OPTIONAL_HEADER64 = ^IMAGE_OPTIONAL_HEADER64;
IMAGE_FILE_HEADER = packed record
Machine : WORD;
NumberOfSections : WORD;
TimeDateStamp : DWORD;
PointerToSymbolTable : DWORD;
NumberOfSymbols : DWORD;
SizeOfOptionalHeader : WORD;
Characteristics : WORD;
end;
PIMAGE_FILE_HEADER = ^IMAGE_FILE_HEADER;
IMAGE_NT_HEADERS = packed record
Signature : DWORD;
FileHeader : IMAGE_FILE_HEADER;
OptionalHeader : IMAGE_OPTIONAL_HEADER;
end;
PIMAGE_NT_HEADERS = ^IMAGE_NT_HEADERS;
IMAGE_NT_HEADERS64 = packed record
Signature : DWORD;
FileHeader : IMAGE_FILE_HEADER;
OptionalHeader : IMAGE_OPTIONAL_HEADER64;
end;
PIMAGE_NT_HEADERS64 = ^IMAGE_NT_HEADERS64;
LOADED_IMAGE = record
ModuleName:pchar;//name of module
hFile:thandle;//handle of file
MappedAddress:pchar;// the base address of mapped file
FileHeader:PIMAGE_NT_HEADERS;//The Header of the file.
LastRvaSection:PIMAGE_SECTION_HEADER;
NumberOfSections:integer;
Sections:PIMAGE_SECTION_HEADER ;
Characteristics:integer;
fSystemImage:boolean;
fDOSImage:boolean;
Links:LIST_ENTRY;
SizeOfImage:integer;
end;
PLOADED_IMAGE= ^LOADED_IMAGE;
IMAGE_DOS_HEADER = packed record
e_magic : Word; // Magic number ("MZ")
e_cblp : Word; // Bytes on last page of file
e_cp : Word; // Pages in file
e_crlc : Word; // Relocations
e_cparhdr : Word; // Size of header in paragraphs
e_minalloc: Word; // Minimum extra paragraphs needed
e_maxalloc: Word; // Maximum extra paragraphs needed
e_ss : Word; // Initial (relative) SS value
e_sp : Word; // Initial SP value
e_csum : Word; // Checksum
e_ip : Word; // Initial IP value
e_cs : Word; // Initial (relative) CS value
e_lfarlc : Word; // Address of relocation table
e_ovno : Word; // Overlay number
e_res : packed array [0..3] of Word; // Reserved words
e_oemid : Word; // OEM identifier (for e_oeminfo)
e_oeminfo : Word; // OEM info; e_oemid specific
e_res2 : packed array [0..9] of Word; // Reserved words
e_lfanew : Longint; // File address of new exe header
end;
PIMAGE_DOS_HEADER = ^IMAGE_DOS_HEADER;
implementation
end.
|
Unit ExFile;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: Bill BEAM
Description: The TExFile component is used to launch one or more processes.
A single instance of the component can keep track of multiple
processes and provides a variety of useful properties and methods.
You can launch one or more processes in the background or cause
the main application to wait for a process to terminate or time-
out. You can use the event handlers to make something happen when
a process terminates or fails to launch.
Creation: December 29, 1998
Version: 1.05
EMail: billb@catoctinsoftware.com
wilbeam@erols.com http://www.catoctinsoftware.com
Support: Use comments/suggestions at website or email. I am interested
in any comments or questions you may have.
Legal issues: Copyright (C) 1998, 1999 by Bill Beam
6714 Fish Hatchery Road
Frederick, MD 21702 (USA)
This software is provided 'as-is', without any express or
implied warranty. In no event will the author 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.
Updates:
Jul 07, 1999 V1.04
1. Added ProcCurrentDir Property. Suggested by Lani.
2. Expanded Priority Property. Suggested by Lani.
Jul 10, 1999 V1.05
1. Removed hThread from GetProcInfo method. IMO better off
being closed before starting new thread.
2. Added WaitForInputIdle for ThreadedWait should someone
want to find a slow starting window just after launch.
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
interface
uses
Windows, SysUtils, Classes, Messages;
type
TProcCompleted = Procedure (sender : Tobject;
evFileName : String;
evIdentifier : String;
evRetValue : Integer;
evTimedOut : Boolean) of Object;
TLaunchFailed = Procedure (sender : Tobject;
evFileName : String;
evIdentifier : String;
evErrorCode : Integer;
evErrorMessage : String) of Object;
TWindowType = (wtNorm, wtMinimize, wtMaximize, wtHide,
wtMinNoActivate, wtShowNoActivate);
TWindowTypes = Array[TWindowType] of Word;
TErrMsg = (emZero, emDuplicateProc, emOnlyOneMeth, emTimedOut,
emInValidDir, emUnknown);
TErrMsgs = Array[TErrMsg] of String [55];
TUseEvent = (ueAll, ueOnLaunchFailed, ueOnProcCompleted, ueNone);
TPriorityClass = (prNormal, prIdle, prHigh, prRealTime);
TPriorityClasses = Array[TPriorityClass] of Word;
TStartType = (NonThreadedWait, ThreadedWait, Independent);
TVersion = string;
TProcInfo =(PrhProcess, PrDwProcessId, PrHWND);
PProcList = ^AThreadRecord;
AThreadRecord = record
PrName : String;
PrProcIdentifier : String;
PrhProcess : THandle;
PrDwProcessId : Dword;
PrhThread : THandle;
PrHWND : HWND;
PrStartType : TStartType;
end;
TExFile = class(TComponent)
private
FOnLaunchFailed: TLaunchFailed;
FOnProcCompleted : TProcCompleted;
FProcFileName: String;
FProcFileNamelc : String;
FFParams: String;
FProcIdentifier : String;
FProcCurrentDir : String;
FWindowType: TWindowType;
FWaitUntilDone : Boolean;
FPriorityClass: TPriorityClass;
StartUpInfo: TStartUpInfo;
ProcessInfo: TProcessInformation;
hEventHandle: THandle;
hMutex : THandle;
FErrorCode : Integer;
FExitCode : Integer;
FUseEvent : TUseEvent;
FTimeOutSec : Integer;
FTimedOut : Boolean;
FMilliSeconds : DWORD;
protected
HandLst : TList;
AProcList : PProcList;
FVersion : TVersion;
PCurDir : PChar;
procedure SetVersion(Value: TVersion);
Procedure SetWindowType(Value: TWindowType);
procedure SetPriorityClass(Value: TPriorityClass);
procedure SetTimeOutSec(Value : Integer);
procedure SetProcFileName(Value: String);
procedure ListMaint;
procedure AddToList(StartType : TStartType);
function GethProcess(StatProcName, StatProcIdentifier : String; Var Hidx : Integer): Boolean;
function GetExitCode(hProcess : THandle) : Boolean;
function DuplicateProc : Boolean;
function StartProcess(StartType : TStartType) : Boolean;
Procedure ErrorEvent(efError : integer; efMessage : String);
function AlreadyRunning(GRT : TStartType) : Boolean;
function AssignCurrentDir : Boolean;
Public
function Execute: Boolean;
function CloseProcess : Boolean;
function GetProcStatus : Boolean;
function CloseThreads : Boolean;
function GetErrorCode : Integer;
function GetReturnCode : Integer;
function ExErrorMessage(ExErrorCode : Integer) : String;
procedure ResetProps;
function GetProcInfo(GPIType : TProcInfo; Var GPIReturn : Integer) : Boolean;
constructor Create(Aowner: TComponent); Override;
destructor Destroy; override;
published
property Version: TVersion read FVersion write SetVersion stored False;
property ProcFileName: String read FProcFileName write SetProcFileName;
property ProcParameters: String read FFParams write FFParams;
property ProcIdentifier: String read FProcIdentifier write FProcIdentifier;
property ProcCurrentDir: String read FProcCurrentDir write FProcCurrentDir;
property OnProcCompleted : TProcCompleted read FOnProcCompleted write FonProcCompleted;
property OnLaunchFailed : TLaunchFailed read FOnLaunchFailed write FOnLaunchFailed;
property WindowType: TWindowType read FWindowType write SetWindowType;
property WaitUntilDone: Boolean read FWaitUntilDone write FWaitUntilDone;
property UseEvent : TUseEvent read FUseEvent write FUseEvent;
property Priority: TPriorityClass read FPriorityClass write SetPriorityClass;
property TimeOutSec : Integer read FTimeOutSec write SetTimeOutSec;
end;
type
TProcThread = class(TThread)
Private
thArray : array[0..1] of THandle;
thFileName : String;
thIdentifier : String;
thRetVal : DWord;
FOnThreadDone: TProcCompleted;
thMutex : THandle;
thUseEvent : TUseEvent;
thMilliseconds : DWORD;
thRetType : Boolean;
protected
procedure Execute; override;
procedure CallOnTerminate;
Constructor Create(vProcHandle: THandle;
vProcEventHandle : THandle;
vFileName : String;
vProcIdentifier : String;
vDoneMethod: TProcCompleted;
vMutex : THandle;
vUseEvent : TUseEvent;
vMilliseconds : DWORD);
end;
procedure Register;
implementation
const
cWindowType : TWindowTypes = (SW_SHOWNORMAL, SW_SHOWMINIMIZED,
SW_SHOWMAXIMIZED, SW_HIDE, SW_SHOWMINNOACTIVE, SW_SHOWNA);
cPriorityClass : TPriorityClasses = (NORMAL_PRIORITY_CLASS,
IDLE_PRIORITY_CLASS, HIGH_PRIORITY_CLASS, REALTIME_PRIORITY_CLASS);
cErrMsg : TErrMsgs = ('Zero',
'Another Process with the same Name and ID is executing.',
'Cannot mix ''WaitUntilDone'' types.',
'Process timed out',
'Current Directory Invalid',
'Unknown Error Code');
{Thread array locations}
ChPROCESS = 0;
ChEvent = 1;
{Timeout Constants}
MAX_ALLOWED : DWORD = 3600000;
MAX_IDLE : DWORD = 3000;
{$IFDEF VER90}
CompVer = 'D2';
{$ENDIF}
{$IFDEF VER100}
CompVer = 'D3';
{$ENDIF}
{$IFDEF VER120}
CompVer = 'D4';
{$ENDIF}
{ ugly hack for BCB}
CompVer = 'BCB4';
cVersion : TVersion = ('1.05 (' + CompVer + ')'); { Current version number }
constructor TExFile.Create(Aowner: TComponent);
begin
inherited Create(AOwner);
HandLst := TList.create;
Fversion := Cversion;
hEventHandle := CreateEvent(nil, True, False, nil);
hMutex := CreateMutex(nil, false, nil);
end;
destructor TExFile.Destroy;
var i : Integer;
begin
{signal and wait for waiting threads to release. hProcess handles
are closed as well}
PulseEvent(hEventHandle);
for i := 0 to (HandLst.Count - 1) do begin
AProcList := HandLst.Items[i];
if AProcList^.PrStartType = NonThreadedWait then begin
try
CloseHandle(AProcList^.PrhProcess);
except
end;
try
CloseHandle(AProcList^.PrhThread);
except
end;
end;
Dispose(AProcList);
end; {for}
HandLst.Free;
CloseHandle(hEventHandle);
CloseHandle(hMutex);
inherited Destroy;
end;
constructor TProcThread.Create(vProcHandle: THandle;
vProcEventHandle : THandle;
vFileName : String;
vProcIdentifier : String;
vDoneMethod: TProcCompleted;
vMutex : THandle;
vUseEvent : TUseEvent;
vMilliSeconds : DWORD);
begin
Inherited Create(True);
thArray[ChPROCESS] := vProcHandle;
thArray[ChEvent] := vProcEventHandle;
thFileName := vFileName;
thIdentifier := vProcIdentifier;
FreeOnTerminate := True;
FonThreadDone := vDoneMethod;
thMutex := vMutex;
thUseEvent := vUseEvent;
thMilliseconds := vMilliSeconds;
Resume;
end;
procedure TProcThread.Execute;
var Signaled : Integer;
begin
Signaled := WaitForMultipleObjects(2, @thArray, False, thMilliseconds);
if Signaled <> WAIT_OBJECT_0 + ChEvent then //Event not signaled
begin
if Signaled = WAIT_OBJECT_0 + ChPROCESS then //hProcess signaled
GetExitCodeProcess(thArray[ChPROCESS], thRetVal)
else
thRetVal := thMilliseconds div 1000; //WAIT_TIMEOUT or WAIT_ABANDONED
thRetType := (Signaled <> WAIT_OBJECT_0 + ChPROCESS);
if assigned(FOnThreadDone) and
((thUseEvent = ueAll) or (thUseEvent = ueOnProcCompleted)) then
begin
WaitForSingleObject(thMutex, INFINITE);
Synchronize(CallOnTerminate);
ReleaseMutex(thMutex);
end;
end;
CloseHandle(thArray[ChPROCESS]); //Close hProcess. hThread is already closed.
Terminate;
end;
procedure TProcThread.CallOnTerminate;
begin
FOnThreadDone(Self, thFileName, thIdentifier, thRetVal, thRetType);
end;
procedure TExFile.SetWindowType(Value : TWindowType);
begin
FWindowType := Value;
end;
procedure TexFile.ResetProps;
begin
ProcFileName := '';
ProcParameters := '';
ProcIdentifier := '';
WindowType := wtNorm;
Priority := prNormal;
UseEvent := ueAll;
WaitUntilDone := false;
TimeOutSec := 0;
ProcCurrentDir := '';
end;
procedure TExFile.SetPriorityClass(Value : TPriorityClass);
begin
FPriorityClass := Value;
end;
procedure TExFile.SetVersion(Value: TVersion);
begin
{Do Nothing. Set by create}
end;
procedure TExFile.SetProcFileName(Value : String);
begin
FProcFileNamelc := LowerCase(Value);
FProcFileName := Value;
end;
Procedure TExFile.SetTimeOutSec(Value : Integer);
begin
FTimeOutSec := Value;
if Value = 0 then
FMilliSeconds := INFINITE
else
if Value > 3600 then
FMilliSeconds := MAX_ALLOWED
else
FMilliSeconds := Value * 1000;
end;
function TExFile.Execute: Boolean;
var
WaitStatus : Integer;
begin
Result := False;
FErrorCode := 0;
if FWaitUntilDone then
begin
Result := StartProcess(NonThreadedWait);
if Result then
begin
WaitStatus := WaitforSingleObject(ProcessInfo.hProcess, FMilliSeconds);
if WaitStatus = WAIT_OBJECT_0 + ChProcess then
GetExitCodeProcess(ProcessInfo.hProcess, DWord(FExitCode))
else
begin
FExitCode := FTimeOutSec;
FErrorCode := ord(emTimedOut) * -1;
end;
FTimedOut := (WaitStatus <> WAIT_OBJECT_0 + ChProcess);
CloseHandle(ProcessInfo.hProcess);
CloseHandle(ProcessInfo.hThread);
if assigned(FonProcCompleted) and
((FUseEvent = ueAll) or (FUseEvent = ueOnProcCompleted)) then
FonProcCompleted(Self, FProcFileName, FProcIdentifier,
FExitCode, FTimedOut);
end;
end
else
begin
result := StartProcess(ThreadedWait);
if result then
begin
CloseHandle(ProcessInfo.hThread);
TProcThread.create(ProcessInfo.hProcess,
hEventHandle,
FProcFileName,
FProcIdentifier,
FonProcCompleted,
hMutex,
FUseEvent,
FMilliseconds);
end;
end;
end;
Procedure TExFile.AddToList(StartType : TStartType);
begin
new(AProcList);
with AProcList^ do begin
PrName := FProcFileNamelc;
PrProcIdentifier := FProcIdentifier;
PrhProcess := ProcessInfo.hProcess;
PrDwProcessId := ProcessInfo.dwProcessId;
PrhThread := ProcessInfo.hThread;
PrStartType := StartType;
HandLst.add(AProcList);
end;
end;
Function TExFile.StartProcess(StartType : TStartType) : boolean;
var
vProcFileName: array[0..512] of char;
vIdle : DWORD;
begin
result := false;
ListMaint;
{sets pointer to lpCurrentDirectory}
if not AssignCurrentDir then
exit;
{see if trying to start a NonThreadedWait while another process is running}
if StartType = NonThreadedWait then
if AlreadyRunning(ThreadedWait) then
exit;
{see if trying to start a duplicate process}
if DuplicateProc then
exit;
{Start the process}
StrPCopy(vProcFileName, FProcFileNamelc + ' ' + FFParams);
FillChar(Startupinfo, SizeOf(TstartupInfo), #0);
with StartupInfo do
begin
cb := SizeOf(TStartupInfo);
dwFlags := STARTF_USESHOWWINDOW;
wShowWindow := cWindowType[FWindowType];
end;
result := CreateProcess(nil,
VProcFileName,
nil,
nil,
False,
CREATE_NEW_CONSOLE or cPriorityClass[FPriorityClass],
nil,
pCurDir,
StartupInfo,
ProcessInfo);
{Wait no longer than MAX_IDLE for initialization. For ThreadedWait types only}
if (result) and (StartType = ThreadedWait) then
begin
vIdle := WaitForInputIdle(ProcessInfo.hProcess, MAX_IDLE);
result := ((vIdle = 0) or (vIdle = WAIT_TIMEOUT));
end;
if result then
AddToList(StartType)
else
ErrorEvent(GetLastError, SysErrorMessage(GetLastError));
end;
Procedure TExFile.ErrorEvent(efError : integer; efMessage : String);
begin
FErrorCode := efError;
if Assigned(FOnLaunchFailed) and
((FUseEvent = ueAll) or (FUseEvent = ueOnLaunchFailed)) then
FOnLaunchFailed(Self, FProcFileName, FProcIdentifier, efError, efMessage);
end;
Function TExFile.DuplicateProc : Boolean; //returns true if duplicate found
var x : integer;
begin
result := GethProcess(FProcFileNamelc, FProcIdentifier, x);
if result then
ErrorEvent(ord(emDuplicateProc) * -1, cErrMsg[emDuplicateProc]);
end;
Function TExFile.AssignCurrentDir : Boolean;
var Code : Integer;
begin
Result := true;
PCurDir := nil;
if FProcCurrentDir <> '' then
begin {avoid bringing in the FileCtrl unit for the DirectoryExists function}
Code := GetFileAttributes(PChar(FProcCurrentDir));
Result := (Code <> -1) and (FILE_ATTRIBUTE_DIRECTORY and Code <> 0);
if result then
PCurDir := PChar(FprocCurrentDir)
else
ErrorEvent(ord(emInvalidDir) * -1, cErrMsg[emInValidDir]);
end;
end;
Function TExFile.GetErrorCode : integer;
begin
result := FErrorCode;
end;
Procedure TExFile.ListMaint;
var
I : Integer;
begin
For I := HandLst.count - 1 downto 0 do
if not GetExitCode(PProcList(HandLst.Items[I]).PrhProcess) then
begin
AProcList := HandLst.Items[I];
Dispose(AProcList);
HandLst.delete(I);
end;
end;
Function TExFile.GetProcStatus : Boolean;
var i : integer;
Begin
result := GethProcess(FProcFileNamelc, FProcIdentifier, i);
if result then
result := GetExitCode(PProcList(HandLst.Items[I]).PrhProcess);
end;
Function TExFile.GethProcess(StatProcName, StatProcIdentifier : String;
var Hidx : Integer): Boolean;
var i : integer;
Begin
result := false;
Hidx := -1;
For i := 0 to HandLst.count - 1 do
if (PProcList(HandLst.Items[I]).PrName = StatProcName) and
(PProcList(HandLst.Items[I]).PrProcIdentifier = StatProcIdentifier) then
begin
result := true;
Hidx := i;
break;
end;
end;
Function TExFile.AlreadyRunning(GRT : TStartType) : Boolean;
var I : integer;
Begin
result := false;
For I := 0 to HandLst.count - 1 do
if (PProcList(HandLst.Items[I]).PrStartType = GRT) then begin
result := true;
break;
end;
if result then
ErrorEvent(ord(emOnlyOneMeth) * -1, cErrMsg[emOnlyOneMeth]);
end;
Function TExFile.GetExitCode(hProcess : THandle) : Boolean;
var vExitCode : Dword;
begin
result := false;
if GetExitCodeProcess(hProcess, vExitCode) then
result := (vExitCode = STILL_ACTIVE);
end;
Function TExFile.GetReturnCode : Integer;
begin
result := FExitCode;
end;
function EnumCallBack(hWindow : HWND; pHArray : Integer): Bool stdcall;
var
ProcessIdx : DWORD;
begin
result := Bool(1);
GetWindowThreadProcessId(hWindow, @ProcessIdx);
if PProcList(pHArray).PrDwProcessId = processidx then begin
PProcList(pHArray).PrHWND := hWindow;
result := False; //stop enumeration
end;
end;
function TExFile.GetProcInfo(GPIType : TProcInfo; Var GPIReturn : Integer) : Boolean;
var i : Integer;
Begin
result := GethProcess(FProcFileNamelc, FProcIdentifier, i);
if result then
case GPIType of
PrhProcess : GPIReturn := PProcList(HandLst.Items[i]).PrhProcess;
PrdwProcessId : GPIReturn := PProcList(HandLst.Items[i]).PrdwProcessid;
PrHWND :
begin
result := (EnumWindows(@EnumCallBack, Integer(HandLst.Items[i])) = false);
if result then
GPIReturn := PProcList(HandLst.Items[i]).PrHWND;
end;
end;
end;
function TExFile.CloseProcess : Boolean;
var i : Integer;
Begin
Result := false;
if GethProcess(FProcFileNamelc, FProcIdentifier, i) then
result := (EnumWindows(@EnumCallBack, Integer(HandLst.Items[i])) = false);
if result then
SendMessage(PProcList(HandLst.Items[i]).PrHWND, WM_CLOSE, 0, 0);
end;
function TExFile.ExErrorMessage(ExErrorCode : Integer) : String;
begin
if ExErrorCode < 0 then
if abs(ExErrorCode) < abs(ord(emUnknown)) then
result := cErrMsg[TErrMsg(abs(ExErrorCode))]
else
result := cErrMsg[emUnknown]
else
result := SysErrorMessage(ExErrorCode);
end;
Function TExFile.CloseThreads : Boolean;
Begin
result := PulseEvent(hEventHandle);
end;
procedure Register;
begin
RegisterComponents('Samples', [TExFile]);
end;
end.
|
unit frm_xplTimer;
{$mode objfpc}{$H+}
{$r *.lfm}
interface
uses
Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,
ComCtrls, Buttons, StdCtrls, ExtCtrls, RTTICtrls, RTTIGrids,
u_xpl_timer;
type
{ TfrmxPLTimer }
TfrmxPLTimer = class(TForm)
Label1: TLabel;
lblMode: TLabel;
Label2: TLabel;
Label3: TLabel;
Label5: TLabel;
Label6: TLabel;
sbOk: TSpeedButton;
tiStart: TTILabel;
tiStatus: TTIComboBox;
tiMode: TTIComboBox;
tiName: TTIEdit;
tiDuration: TTISpinEdit;
tiFrequence: TTISpinEdit;
ToolBar2: TToolBar;
procedure FormShow(Sender: TObject);
procedure sbOkClick(Sender: TObject);
procedure tiModeChange(Sender: TObject);
private
Timer : TxPLTimer;
end;
function ShowFrmxPLTimer(const aTimer : TxPLTImer) : boolean;
implementation { TxPLTimer ====================================================}
function ShowFrmxPLTimer(const aTimer: TxPLTImer) : boolean;
var form : TFrmxPLTimer;
begin
form := TFrmxPLTimer.Create(nil);
form.Timer := aTimer;
result := form.ShowModal = mrOk;
form.Destroy;
end;
{ TfrmxPLTimer ================================================================}
procedure TfrmxPLTimer.FormShow(Sender: TObject);
begin
tiName.Link.TIObject := Timer;
tiDuration.Link.TIObject := Timer;
tiFrequence.Link.TIObject := Timer;
tiMode.Link.TIObject := Timer;
tiStatus.Link.TIObject := Timer;
tiName.Link.TIPropertyName:='displayname';
tiduration.link.tipropertyname := 'remaining';
tifrequence.link.tipropertyname := 'frequence';
tiStatus.link.tipropertyname := 'status';
timode.link.tipropertyname := 'mode';
tiStart.link.tiObject := Timer;
tiStart.Link.tipropertyname := 'start_time';
tiModeChange(self);
end;
procedure TfrmxPLTimer.sbOkClick(Sender: TObject);
begin
Close;
ModalResult := mrOk;
end;
procedure TfrmxPLTimer.tiModeChange(Sender: TObject);
begin
tiFrequence.Enabled := (tiMode.Text = 'recurrent');
tiDuration.Enabled := (tiMode.Text = 'descending');
end;
end.
|
unit adot.Hash;
{
TDigest = record
Simple API for block / chain hashing
Supported hashes:
MD5, SHA1, SHA2, BobJenkins32 (System.Hash)
CRC32, Adler32 (System.ZLib)
TDigests = record
Simple API for single data block hashing
Hashing helpers (mix function etc)
}
interface
uses
System.ZLib,
System.Hash,
System.SysUtils,
System.Classes,
System.Math,
System.Generics.Collections,
System.Generics.Defaults;
type
TCustomDigest = class abstract(TInterfacedObject, IInterface)
protected
type
{ Stream block reader (ReadNext to get next block of data from stream as array of byte) }
TBlockReader = class
private
const
StreamingBufSize = 64*1024;
var
Stream: TStream;
OwnsStream: boolean;
BytesToRead: int64;
public
Bytes: TArray<Byte>;
Count: integer;
constructor Create(Src: TStream; AOwnsStream: Boolean; BufSize: integer; FromBeginning: boolean = True);
destructor Destroy; override;
function ReadNext: Boolean;
end;
{ block/chain functions }
procedure DoUpdate(const Data; SizeOFData: integer); virtual; abstract;
function DoDone: TBytes; virtual; abstract;
class procedure CreateDigest(out ADigest: TCustomDigest; out ADigestInt: IInterface);
{ Low level functions. They calculate digest from data only }
procedure Update(const AData; ADataSize: integer); overload;
procedure Update(const AData: TStream); overload;
procedure Update(const AData: TBytes; AStartIndex,ACount: integer); overload;
procedure Update(const AData: TBytes); overload;
procedure Update(const AData: string); overload;
procedure Update(const AData: string; AStartIndex,ACount: integer); overload;
procedure Update(const AData: TArray<string>); overload;
procedure Update(const AData: TEnumerable<string>); overload;
procedure Update(const AData: TObject); overload;
procedure Update<T: record>(const AData: T); overload;
procedure UpdateFromFile(const AFileName: string); overload;
public
constructor Create; virtual; abstract;
{ High level functions. They calculate digest from size and data, not from data only }
class function GetHash(const AData; ADataSize: integer): TBytes; overload;
class function GetHash(const AData: TStream): TBytes; overload;
class function GetHash(const AData: TBytes; AStartIndex,ACount: integer): TBytes; overload;
class function GetHash(const AData: TBytes): TBytes; overload;
class function GetHash(const AData: string): TBytes; overload;
class function GetHash(const AData: string; AStartIndex,ACount: integer): TBytes; overload;
class function GetHash(const AData: TObject): TBytes; overload;
class function GetHash<T: record>(const AData: T): TBytes; overload;
class function GetHashOfFile(const AFileName: string): TBytes; overload;
{ For containers we calculate digest from size and data, not from data only.
It guarantees that
GetHash(["A", "BC"]) <>
GetHash(["AB", "C"]) }
class function GetHash(const AData: TArray<string>): TBytes; overload;
class function GetHash(const AData: TEnumerable<string>): TBytes; overload;
end;
TDigestClass = class of TCustomDigest;
{
function GetHash(L: TList<TRec>): string;
var
D: TDigest;
I: Integer;
begin
D.InitStrong;
for I := 0 to List.Count-1 do
D.Update(L[I]);
result := D.ToString;
end;
}
TDigest = record
private
type
TMD5 = class(TCustomDigest)
protected
FData: THashMD5;
procedure DoUpdate(const Data; SizeOFData: integer); override;
function DoDone: TBytes; override;
public
constructor Create; override;
end;
TSHA1 = class(TCustomDigest)
protected
FData: THashSHA1;
procedure DoUpdate(const Data; SizeOFData: integer); override;
function DoDone: TBytes; override;
public
constructor Create; override;
end;
TSHA2 = class(TCustomDigest)
protected
FData: THashSHA2;
procedure DoUpdate(const Data; SizeOFData: integer); override;
function DoDone: TBytes; override;
public
constructor Create; overload; override;
constructor Create(const Ver: THashSHA2.TSHA2Version); reintroduce; overload;
end;
TCRC32 = class(TCustomDigest)
protected
FData: cardinal;
procedure DoUpdate(const Data; SizeOFData: integer); override;
function DoDone: TBytes; override;
public
constructor Create; override;
end;
TAdler32 = class(TCustomDigest)
protected
FData: cardinal;
procedure DoUpdate(const Data; SizeOFData: integer); override;
function DoDone: TBytes; override;
public
constructor Create; override;
end;
TBobJenkins32 = class(TCustomDigest)
protected
FData: THashBobJenkins;
procedure DoUpdate(const Data; SizeOFData: integer); override;
function DoDone: TBytes; override;
public
constructor Create; override;
end;
var
FDigest: TCustomDigest;
FDigestInt: IInterface;
procedure SetDigest(const Value: TCustomDigest);
property Digest: TCustomDigest read FDigest write SetDigest;
public
{ Block / chain functions }
procedure InitMD5;
procedure InitSHA1;
procedure InitSHA2; overload;
procedure InitSHA2(const Ver: THashSHA2.TSHA2Version); overload;
procedure InitCRC32;
procedure InitAdler32;
procedure InitBobJenkins32;
procedure InitStrong;
procedure InitFast;
procedure InitFastest;
procedure Update(const AData; ADataSize: integer); overload;
procedure Update(const AData: TStream); overload;
procedure Update(const AData: TBytes; AStartIndex,ACount: integer); overload;
procedure Update(const AData: TBytes); overload;
procedure Update(const AData: string); overload;
procedure Update(const AData: string; AStartIndex,ACount: integer); overload;
procedure Update(const AData: TArray<string>); overload;
procedure Update(const AData: TEnumerable<string>); overload;
procedure Update(const AData: TObject); overload;
procedure Update<T: record>(const AData: T); overload;
procedure UpdateFromFile(const AFileName: string); overload;
function Done: TBytes;
function ToString: string;
function ToBytes: TBytes;
end;
{
var
A,B,R: TBytes;
V: TArray<string>;
begin
V := ['1', '2', '3'];
A := TDigests.MD5.GetHashOfFile('c:\1.xml');
B := TDigests.SHA2.GetHash(V);
R := TDigests.Mix(A,B);
end;
}
TDigests = record
private
class function GetAdler32Class : TDigestClass; static;
class function GetBobJenkins32Class : TDigestClass; static;
class function GetCRC32Class : TDigestClass; static;
class function GetMD5Class : TDigestClass; static;
class function GetSHA1Class : TDigestClass; static;
class function GetSHA2Class : TDigestClass; static;
public
class property MD5 : TDigestClass read GetMD5Class;
class property SHA1 : TDigestClass read GetSHA1Class;
class property SHA2 : TDigestClass read GetSHA2Class;
class property CRC32 : TDigestClass read GetCRC32Class;
class property Adler32 : TDigestClass read GetAdler32Class;
class property BobJenkins32 : TDigestClass read GetBobJenkins32Class;
class function Mix(const HashA,HashB: integer): integer; overload; static; {$IFDEF UseInline}inline;{$ENDIF}
class function Mix(const HashA,HashB,HashC: integer): integer; overload; static;
class function Mix(const HashA,HashB: TBytes): TBytes; overload; static;
class function Mix(const Hashes: array of integer): integer; overload; static;
class function Mix(const Hashes: array of TBytes): TBytes; overload; static;
class function ToString(const AHash: TBytes): string; static;
class function GetHash32(const Hash: TBytes): integer; static;
class function GetHash24(const Hash: TBytes): integer; static;
class function GetHash16(const Hash: TBytes): integer; static;
end;
implementation
uses
adot.Tools;
{ TDigest.TMD5 }
constructor TDigest.TMD5.Create;
begin
FData := THashMD5.Create;
end;
procedure TDigest.TMD5.DoUpdate(const Data; SizeOFData: integer);
begin
inherited;
FData.Update(Data, SizeOFData);
end;
function TDigest.TMD5.DoDone: TBytes;
begin
result := FData.HashAsBytes;
end;
{ TDigest }
function TDigest.Done: TBytes;
begin
result := Digest.DoDone;
end;
procedure TDigest.InitAdler32;
begin
Digest := TAdler32.Create;
end;
procedure TDigest.InitBobJenkins32;
begin
Digest := TBobJenkins32.Create;
end;
procedure TDigest.InitCRC32;
begin
Digest := TCRC32.Create;
end;
procedure TDigest.InitMD5;
begin
Digest := TMD5.Create;
end;
procedure TDigest.InitSHA1;
begin
Digest := TSHA1.Create;
end;
procedure TDigest.InitSHA2;
begin
Digest := TSHA2.Create(THashSHA2.TSHA2Version.SHA256);
end;
procedure TDigest.InitSHA2(const Ver: THashSHA2.TSHA2Version);
begin
Digest := TSHA2.Create(Ver);
end;
procedure TDigest.InitStrong;
begin
InitMD5;
end;
procedure TDigest.InitFast;
begin
InitBobJenkins32;
end;
procedure TDigest.InitFastest;
begin
InitAdler32;
end;
procedure TDigest.SetDigest(const Value: TCustomDigest);
begin
if FDigest = Value then
Exit;
FDigest := nil;
FDigestInt := nil;
FDigestInt := Value;
FDigest := Value;
end;
function TDigest.ToBytes: TBytes;
begin
result := Digest.DoDone;
end;
function TDigest.ToString: string;
begin
result := TDigests.ToString(Digest.DoDone);
end;
procedure TDigest.Update(const AData: TBytes);
begin
Digest.Update(AData);
end;
procedure TDigest.Update(const AData: TBytes; AStartIndex, ACount: integer);
begin
Digest.Update(AData, AStartIndex, ACount);
end;
procedure TDigest.Update(const AData: TStream);
begin
Digest.Update(AData);
end;
procedure TDigest.Update(const AData; ADataSize: integer);
begin
Digest.Update(AData, ADataSize);
end;
procedure TDigest.Update(const AData: string);
begin
Digest.Update(AData);
end;
procedure TDigest.Update(const AData: string; AStartIndex,ACount: integer);
begin
Digest.Update(AData,AStartIndex,ACount);
end;
procedure TDigest.Update(const AData: TObject);
begin
Digest.Update(AData);
end;
procedure TDigest.Update(const AData: TEnumerable<string>);
begin
Digest.Update(AData);
end;
procedure TDigest.Update(const AData: TArray<string>);
begin
Digest.Update(AData);
end;
procedure TDigest.Update<T>(const AData: T);
begin
Digest.Update(AData);
end;
procedure TDigest.UpdateFromFile(const AFileName: string);
begin
Digest.UpdateFromFile(AFileName);
end;
{ TDigest.TSHA1 }
constructor TDigest.TSHA1.Create;
begin
FData := THashSHA1.Create;
end;
procedure TDigest.TSHA1.DoUpdate(const Data; SizeOFData: integer);
begin
inherited;
FData.Update(Data, SizeOFData);
end;
function TDigest.TSHA1.DoDone: TBytes;
begin
result := FData.HashAsBytes;
end;
{ TDigest.TSHA2 }
constructor TDigest.TSHA2.Create(const Ver: THashSHA2.TSHA2Version);
begin
FData := THashSHA2.Create(Ver);
end;
constructor TDigest.TSHA2.Create;
begin
FData := THashSHA2.Create(THashSHA2.TSHA2Version.SHA256);
end;
procedure TDigest.TSHA2.DoUpdate(const Data; SizeOFData: integer);
begin
inherited;
FData.Update(Data, SizeOFData);
end;
function TDigest.TSHA2.DoDone: TBytes;
begin
result := FData.HashAsBytes;
end;
{ TDigest.TCRC32 }
constructor TDigest.TCRC32.Create;
begin
FData := System.ZLib.crc32(0, nil, 0);
end;
procedure TDigest.TCRC32.DoUpdate(const Data; SizeOFData: integer);
begin
inherited;
FData := System.ZLib.crc32(FData, @Data, SizeOFData);
end;
function TDigest.TCRC32.DoDone: TBytes;
begin
SetLength(Result, 4);
PCardinal(@Result[0])^ := System.Hash.THash.ToBigEndian(FData);
end;
{ TDigest.TAdler32 }
constructor TDigest.TAdler32.Create;
begin
FData := System.ZLib.adler32(0, nil, 0);
end;
procedure TDigest.TAdler32.DoUpdate(const Data; SizeOFData: integer);
begin
inherited;
FData := System.ZLib.adler32(FData, @Data, SizeOFData);
end;
function TDigest.TAdler32.DoDone: TBytes;
begin
SetLength(Result, 4);
PCardinal(@Result[0])^ := System.Hash.THash.ToBigEndian(FData);
end;
{ TDigest.TBobJenkins32 }
constructor TDigest.TBobJenkins32.Create;
begin
FData := THashBobJenkins.Create;
end;
procedure TDigest.TBobJenkins32.DoUpdate(const Data; SizeOFData: integer);
begin
inherited;
FData.Update(Data, SizeOFData);
end;
function TDigest.TBobJenkins32.DoDone: TBytes;
begin
result := FData.HashAsBytes;
end;
{ TCustomDigest }
class procedure TCustomDigest.CreateDigest(out ADigest: TCustomDigest; out ADigestInt: IInterface);
begin
ADigest := Self.Create;
ADigestInt := ADigest;
end;
class function TCustomDigest.GetHash(const AData: TBytes): TBytes;
begin
result := GetHash(AData, 0, Length(AData));
end;
class function TCustomDigest.GetHash(const AData: TBytes; AStartIndex,ACount: integer): TBytes;
var
Digest: TCustomDigest;
DigestInt: IInterface;
begin
CreateDigest(Digest, DigestInt);
Digest.Update(AData, AStartIndex, ACount);
Result := Digest.DoDone;
end;
class function TCustomDigest.GetHash(const AData: TStream): TBytes;
var
Digest: TCustomDigest;
DigestInt: IInterface;
begin
CreateDigest(Digest, DigestInt);
Digest.Update(AData);
Result := Digest.DoDone;
end;
class function TCustomDigest.GetHash(const AData; ADataSize: integer): TBytes;
var
Digest: TCustomDigest;
DigestInt: IInterface;
begin
CreateDigest(Digest, DigestInt);
Digest.Update(AData, ADataSize);
Result := Digest.DoDone;
end;
class function TCustomDigest.GetHash(const AData: string): TBytes;
var
Digest: TCustomDigest;
DigestInt: IInterface;
begin
CreateDigest(Digest, DigestInt);
Digest.Update(AData);
Result := Digest.DoDone;
end;
class function TCustomDigest.GetHash(const AData: string; AStartIndex,ACount: integer): TBytes;
var
Digest: TCustomDigest;
DigestInt: IInterface;
begin
CreateDigest(Digest, DigestInt);
Digest.Update(AData,AStartIndex,ACount);
Result := Digest.DoDone;
end;
class function TCustomDigest.GetHash(const AData: TEnumerable<string>): TBytes;
var
Digest: TCustomDigest;
DigestInt: IInterface;
S: string;
begin
CreateDigest(Digest, DigestInt);
for S in AData do
begin
Digest.Update(Length(S));
Digest.Update(S);
end;
Result := Digest.DoDone;
end;
class function TCustomDigest.GetHash(const AData: TArray<string>): TBytes;
var
Digest: TCustomDigest;
DigestInt: IInterface;
S: string;
begin
CreateDigest(Digest, DigestInt);
for S in AData do
begin
Digest.Update(Length(S));
Digest.Update(S);
end;
Result := Digest.DoDone;
end;
class function TCustomDigest.GetHashOfFile(const AFileName: string): TBytes;
var
Hasher: TCustomDigest;
HasherInt: IInterface;
begin
CreateDigest(Hasher, HasherInt);
Hasher.UpdateFromFile(AFileName);
Result := Hasher.DoDone;
end;
procedure TCustomDigest.Update(const AData: string);
begin
Update(TEncoding.UTF8.GetBytes(AData));
end;
procedure TCustomDigest.Update(const AData: string; AStartIndex,ACount: integer);
begin
Update(TEncoding.UTF8.GetBytes(AData.Substring(AStartIndex, ACount)));
end;
procedure TCustomDigest.Update(const AData: TBytes);
begin
if Length(AData) > 0
then DoUpdate(AData[0], Length(AData))
else DoUpdate(nil^, 0);
end;
procedure TCustomDigest.Update(const AData: TBytes; AStartIndex, ACount: integer);
begin
if ACount > 0
then DoUpdate(AData[AStartIndex], ACount)
else DoUpdate(nil^, 0);
end;
procedure TCustomDigest.Update(const AData: TStream);
var
Reader: TBlockReader;
begin
Reader := TBlockReader.Create(AData, False, TBlockReader.StreamingBufSize, True);
try
while Reader.ReadNext do
DoUpdate(Reader.Bytes[0], Reader.Count);
finally
Reader.Free;
end;
end;
procedure TCustomDigest.Update(const AData: TObject);
var
Code: Integer;
begin
Code := AData.GetHashCode;
DoUpdate(Code, SizeOf(Code));
end;
procedure TCustomDigest.Update(const AData; ADataSize: integer);
begin
if ADataSize > 0
then DoUpdate(AData, ADataSize)
else DoUpdate(nil^, 0);
end;
procedure TCustomDigest.Update(const AData: TEnumerable<string>);
var
S: string;
begin
for S in AData do
Update(S);
end;
procedure TCustomDigest.Update(const AData: TArray<string>);
var
S: string;
begin
for S in AData do
Update(S);
end;
procedure TCustomDigest.Update<T>(const AData: T);
begin
DoUpdate(AData, SizeOf(AData));
end;
procedure TCustomDigest.UpdateFromFile(const AFileName: string);
var
FileStream: TFileStream;
begin
FileStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyNone);
try
Update(FileStream);
finally
FileStream.Free;
end;
end;
class function TCustomDigest.GetHash(const AData: TObject): TBytes;
var
Digest: TCustomDigest;
DigestInt: IInterface;
begin
CreateDigest(Digest, DigestInt);
Digest.Update(AData);
Result := Digest.DoDone;
end;
class function TCustomDigest.GetHash<T>(const AData: T): TBytes;
var
Hasher: TCustomDigest;
HasherInt: IInterface;
begin
CreateDigest(Hasher, HasherInt);
Hasher.Update(AData);
Result := Hasher.DoDone;
end;
{ TDigests }
class function TDigests.GetAdler32Class: TDigestClass;
begin
result := TDigest.TAdler32;
end;
class function TDigests.GetBobJenkins32Class: TDigestClass;
begin
result := TDigest.TBobJenkins32;
end;
class function TDigests.GetCRC32Class: TDigestClass;
begin
result := TDigest.TCRC32;
end;
class function TDigests.GetMD5Class: TDigestClass;
begin
result := TDigest.TMD5;
end;
class function TDigests.GetSHA1Class: TDigestClass;
begin
result := TDigest.TSHA1;
end;
class function TDigests.GetSHA2Class: TDigestClass;
begin
result := TDigest.TSHA2;
end;
class function TDigests.GetHash16(const Hash: TBytes): integer;
begin
if Length(Hash) = 0 then
result := 0
else
if Length(Hash) = 4 then
result :=
((integer(Hash[0]) xor integer(Hash[1])) shl 8) or
(integer(Hash[2]) xor integer(Hash[3]))
else
result := GetHash16(CRC32.GetHash(Hash,0,Length(Hash)));
end;
class function TDigests.GetHash24(const Hash: TBytes): integer;
begin
if Length(Hash) = 0 then
result := 0
else
if Length(Hash) = 4 then
result :=
(integer(Hash[0]) shl 16) or
(integer(Hash[1]) shl 8) or
(integer(Hash[2]) xor integer(Hash[3]))
else
result := GetHash24(CRC32.GetHash(Hash,0,Length(Hash)));
end;
class function TDigests.GetHash32(const Hash: TBytes): integer;
begin
if Length(Hash) = 0 then
result := 0
else
if Length(Hash) = 4 then
result :=
(integer(Hash[0]) shl 24) or
(integer(Hash[1]) shl 16) or
(integer(Hash[2]) shl 8) or
(integer(Hash[3]))
else
result := GetHash32(CRC32.GetHash(Hash,0,Length(Hash)));
end;
class function TDigests.ToString(const AHash: TBytes): string;
begin
Result := THex.Encode(AHash).ToLower;
end;
class function TDigests.Mix(const HashA, HashB: integer): integer;
begin
result := (HashA*1103515245 + 12345) xor HashB;
end;
class function TDigests.Mix(const HashA, HashB, HashC: integer): integer;
begin
result := Mix(Mix(HashA, HashB), HashC);
end;
class function TDigests.Mix(const HashA, HashB: TBytes): TBytes;
var
V,L1,L2,LR: Integer;
Src1,Src2,Dst: pointer;
begin
L1 := Length(HashA);
L2 := Length(HashB);
LR := Max(L1, L2);
SetLength(result, LR);
if LR = 0 then
Exit;
Dst := @result[0];
if L1>0 then Src1 := @HashA[0] else Src1 := nil;
if L2>0 then Src2 := @HashB[0] else Src2 := nil;
V := 0;
while LR >= SizeOf(integer) do
begin
{ read from HashA }
if L1 >= SizeOf(integer) then
begin
V := (V*1103515245 + 12345) xor integer(Src1^);
inc(PByte(Src1), SizeOf(integer));
dec(L1, SizeOf(integer));
end
else
while L1 > 0 do
begin
V := (V*1103515245 + 12345) xor PByte(Src1)^;
inc(PByte(Src1));
dec(L1);
end;
{ read from HashB }
if L2 >= SizeOf(integer) then
begin
V := (V*1103515245 + 12345) xor integer(Src2^);
inc(PByte(Src2), SizeOf(integer));
dec(L2, SizeOf(integer));
end
else
while L2 > 0 do
begin
V := (V*1103515245 + 12345) xor PByte(Src2)^;
inc(PByte(Src2));
dec(L2);
end;
integer(Dst^) := V;
dec(LR, SizeOf(integer));
end;
while LR > 0 do
begin
if L1 > 0 then
begin
V := (V*1103515245 + 12345) xor byte(Src1^);
inc(PByte(Src1));
dec(L1);
end;
if L2 > 0 then
begin
V := (V*1103515245 + 12345) xor byte(Src2^);
inc(PByte(Src2));
dec(L2);
end;
Byte(Dst^) := V;
dec(LR);
end;
end;
class function TDigests.Mix(const Hashes: array of integer): integer;
var
I: Integer;
begin
result := 0;
for I := Low(Hashes) to High(Hashes) do
result := Mix(result, Hashes[I]);
end;
class function TDigests.Mix(const Hashes: array of TBytes): TBytes;
var
I: Integer;
begin
SetLength(result, 0);
for I := Low(Hashes) to High(Hashes) do
result := Mix(result, Hashes[I]);
end;
{ TCustomDigest.TBlockReader }
constructor TCustomDigest.TBlockReader.Create(Src: TStream; AOwnsStream: Boolean; BufSize: integer; FromBeginning: boolean);
begin
Stream := Src;
OwnsStream := AOwnsStream;
SetLength(Bytes, BufSize);
if not FromBeginning then
BytesToRead := Stream.Size - Stream.Position
else
begin
Stream.Position := 0;
BytesToRead := Stream.Size;
end;
end;
destructor TCustomDigest.TBlockReader.Destroy;
begin
if OwnsStream then
Stream.Free;
Stream := nil;
inherited;
inherited;
end;
function TCustomDigest.TBlockReader.ReadNext: Boolean;
begin
Result := BytesToRead > 0;
if Result then
begin
Count := Min(BytesToRead, Length(Bytes));
Stream.ReadBuffer(Bytes, Count);
Dec(BytesToRead, Count);
end
else
begin
SetLength(Bytes, 0);
Count := 0;
end;
end;
end.
|
PROGRAM SortingAlgorithms;
TYPE IntArray = ARRAY [1..100] OF INTEGER;
VAR
numComp, numAssign: LONGINT;
(* Less Than *)
FUNCTION LT(a, b: INTEGER): BOOLEAN;
BEGIN (* LT *)
Inc(numComp);
LT := a < b;
END; (* LT *)
PROCEDURE Swap(VAR a, b: INTEGER);
VAR t: INTEGER;
BEGIN (* Swap *)
t := a;
a := b;
b := t;
Inc(numAssign,3);
END; (* Swap *)
PROCEDURE SelectionSort(VAR arr: IntArray; left, right: INTEGER);
VAR i, j, minIdx: INTEGER;
BEGIN (* SelectionSort *)
FOR i := left TO right - 1 DO BEGIN
minIdx := i;
FOR j := i + 1 to right DO BEGIN
IF LT(arr[j], arr[minIdx]) THEN minIdx := j;
END; (* FOR *)
IF (i <> minIdx) THEN Swap(arr[i], arr[minIdx]);
END; (* FOR *)
END; (* SelectionSort *)
VAR
arr: IntArray;
i, j : INTEGER;
BEGIN
numAssign := 0;
numComp := 0;
for i := 1 to 100 do begin
arr[i] := Random(100);
end;
SelectionSort(arr, 1, 100);
for i := 1 to 100 do begin
Write(arr[i], ', ');
end;
WriteLn();
WriteLn(numComp);
WriteLn(numAssign);
END. |
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
Buttons;
type
{ TfrmSellingPrice }
TfrmSellingPrice = class(TForm)
bmbReset: TBitBtn;
btnCalculateSellingPrice: TButton;
edtCost: TEdit;
edtProfit: TEdit;
edtVat: TEdit;
lblCost: TLabel;
lblProfit: TLabel;
lblVat: TLabel;
lblSelling: TLabel;
lblSellingOutput: TLabel;
procedure bmbResetClick(Sender: TObject);
procedure btnCalculateSellingPriceClick(Sender: TObject);
private
{ private declarations }
function IncrementedRateIncluded(fCost, fRate: double) : double;
public
{ public declarations }
end;
const
ProfitRate = 50;
TaxRate = 14;
var
frmSellingPrice: TfrmSellingPrice;
implementation
{$R *.lfm}
{ TfrmSellingPrice }
function TfrmSellingPrice.IncrementedRateIncluded(fCost, fRate: double) : double;
begin
IncrementedRateIncluded:=fCost * (fRate / 100);
end;
procedure TfrmSellingPrice.btnCalculateSellingPriceClick(Sender: TObject);
var
fCostPrice: double;
fProfit: double;
fTax: double;
fSellingPrice: double;
begin
edtCost.ReadOnly:=TRUE;
fCostPrice:=StrToFloat(edtCost.Text);
fProfit:=fCostPrice * (ProfitRate / 100);
fTax:=(fCostPrice + fProfit) * (TaxRate / 100);
fSellingPrice:=fCostPrice + fProfit + fTax;
edtProfit.ReadOnly:=TRUE;
edtProfit.Text:=FloatToStrF(fProfit, ffNumber, 15, 2);
edtVat.ReadOnly:=TRUE;
edtVat.Text:=FloatToStrF(fTax, ffNumber, 15, 2);
lblSellingOutput.Caption:='R ' + FloatToStrF(fSellingPrice, ffNumber, 15, 2);
end;
procedure TfrmSellingPrice.bmbResetClick(Sender: TObject);
begin
edtCost.ReadOnly:=FALSE;
edtCost.Text:='0.00';
edtProfit.Text:='0.00';
edtVat.Text:='0.00';
lblSellingOutput.Caption:='0.00';
end;
end.
|
unit fPatientEd;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
fPCEBase, StdCtrls, ORCtrls, CheckLst, ExtCtrls, Buttons, uPCE, rPCE, ORFn,
fPCELex, fPCEOther, ComCtrls, fPCEBaseMain, VA508AccessibilityManager;
type
TfrmPatientEd = class(TfrmPCEBaseMain)
lblUnderstanding: TLabel;
cboPatUnderstanding: TORComboBox;
procedure cboPatUnderstandingChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
protected
procedure UpdateNewItemStr(var x: string); override;
procedure UpdateControls; override;
public
end;
var
frmPatientEd: TfrmPatientEd;
implementation
{$R *.DFM}
uses
fEncounterFrame, VA508AccessibilityRouter;
{///////////////////////////////////////////////////////////////////////////////
//Name:procedure tfrmPatientEd.cboPatUnderstandingChange(Sender: TObject);
//Created: Jan 1999
//By: Robert Bott
//Location: ISL
//Description:Change the level of understanding assigned to the education item.
///////////////////////////////////////////////////////////////////////////////}
procedure tfrmPatientEd.cboPatUnderstandingChange(Sender: TObject);
var
i: integer;
begin
if(NotUpdating) and (cboPatUnderstanding.Text <> '') then
begin
for i := 0 to lstCaptionList.Items.Count-1 do
if(lstCaptionList.Items[i].Selected) then
TPCEPat(lstCaptionList.Objects[i]).Level := cboPatUnderstanding.ItemID;
GridChanged;
end;
end;
procedure TfrmPatientEd.FormCreate(Sender: TObject);
begin
inherited;
FTabName := CT_PedNm;
FPCEListCodesProc := ListPatientCodes;
FPCEItemClass := TPCEPat;
FPCECode := 'PED';
PCELoadORCombo(cboPatUnderstanding);
end;
procedure TfrmPatientEd.UpdateNewItemStr(var x: string);
begin
SetPiece(x, U, pnumPEDLevel, NoPCEValue);
end;
procedure TfrmPatientEd.UpdateControls;
var
ok, First: boolean;
SameLOU: boolean;
i: integer;
LOU: string;
Obj: TPCEPat;
begin
inherited;
if(NotUpdating) then
begin
BeginUpdate;
try
ok := (lstCaptionList.SelCount > 0);
lblUnderstanding.Enabled := ok;
cboPatUnderstanding.Enabled := ok;
if(ok) then
begin
First := TRUE;
SameLOU := TRUE;
LOU := NoPCEValue;
for i := 0 to lstCaptionList.Items.Count-1 do
begin
if lstCaptionList.Items[i].Selected then
begin
Obj := TPCEPat(lstCaptionList.Objects[i]);
if(First) then
begin
First := FALSE;
LOU := Obj.Level;
end
else
begin
if(SameLOU) then
SameLOU := (LOU = Obj.Level);
end;
end;
end;
if(SameLOU) then
cboPatUnderstanding.SelectByID(LOU)
else
cboPatUnderstanding.Text := '';
end
else
begin
cboPatUnderstanding.Text := '';
end;
finally
EndUpdate;
end;
end;
end;
initialization
SpecifyFormIsNotADialog(TfrmPatientEd);
end.
|
unit JATypes;
{$mode objfpc}{$H+}
{$PACKRECORDS 2} {required for compatibility with various amiga APIs}
{$i JA.inc}
interface
uses
{Amiga} Exec;
type
{32-bit float}
Float32 = Single;
PFloat32 = ^Float32;
{64-bit float}
Float64 = Double;
PFloat64 = ^Float64;
{unsigned 8-bit integer}
UInt8 = Byte;
PUInt8 = ^UInt8;
{signed 8-bit integer}
SInt8 = ShortInt;
PSInt8 = ^SInt8;
{unsigned 16-bit integer}
UInt16 = Word;
PUInt16 = ^UInt16;
{signed 16-bit integer}
SInt16 = SmallInt;
PSInt16 = ^SInt16;
{unsigned 32-bit integer}
UInt32 = LongWord;
PUInt32 = ^UInt32;
{signed 32-bit integer}
SInt32 = LongInt;
PSInt32 = ^SInt32;
{16-bit DualByte helper}
TDualByte = record
case UInt8 of
0 : (DB : array[0..1] of UInt8);
1 : (DC : array[0..1] of Char);
2 : (High, Low : UInt8);
3 : (U16 : UInt16);
4 : (S16 : SInt16);
end;
PDualByte = ^TDualByte;
{32-bit QuadByte helper}
TQuadByte = record
case UInt8 of
0 : (QB : array[0..3] of UInt8);
1 : (QC : array[0..3] of Char);
2 : (High, Low : UInt16);
3 : (U32 : UInt32);
4 : (S32 : SInt32);
end;
PQuadByte = ^TQuadByte;
{32-bit float 2D Vector/Vertex}
TVec2 = record
case UInt8 of
1:(X,Y : Float32);
2:(V : array[0..1] of Float32);
end;
PVec2 = ^TVec2;
{signed 16-bit Integer 2D Vector/Vertex}
TVec2SInt16 = record
case UInt8 of
1:(X,Y : SInt16);
2:(V : array[0..1] of SInt16);
end;
PVec2SInt16 = ^TVec2SInt16;
{signed 32-bit Integer 2D Vector/Vertex}
TVec2SInt32 = record
case UInt8 of
1:(X,Y : SInt32);
2:(V : array[0..1] of SInt32);
end;
PVec2SInt32 = ^TVec2SInt32;
{32-bit Float Rect Type}
TJRect = record
case UInt8 of
1:(Left,Top,Right,Bottom : Float32);
2:(LT,RB : TVec2);
3:(R : array[0..3] of Float32);
end;
PJRect = ^TJRect;
{Signed 16-bit Integer Rect Type}
TJRectSInt16 = record
case UInt8 of
1:(Left,Top,Right,Bottom : SInt16);
2:(LT,RB : TVec2SInt16);
3:(R : array[0..3] of SInt16);
end;
PJRectSInt16 = ^TJRectSInt16;
{Signed 32-bit Integer Rect Type}
TJRectSInt32 = record
case UInt8 of
1:(Left,Top,Right,Bottom : SInt32);
2:(LT,RB : TVec2SInt32);
3:(R : array[0..3] of SInt32);
end;
PJRectSInt32 = ^TJRectSInt32;
{32-bit Float Bounding Box Type}
TJBBox = record
case UInt8 of
1:(MinX,MinY,MaxX,MaxY : Float32);
2:(Min, Max : TVec2);
3:(B : array[0..3] of Float32);
end;
PJBBox = ^TJBBox;
{Signed 16-bit Integer Bounding Box Type}
TJBBoxSInt16 = record
case UInt8 of
1:(MinX,MinY,MaxX,MaxY : SInt16);
2:(Min, Max : TVec2SInt16);
3:(B : array[0..3] of SInt16);
end;
PJBBoxSInt16 = ^TJBBoxSInt16;
{Signed 32-bit Integer Bounding Box Type}
TJBBoxSInt32 = record
case UInt8 of
1:(MinX,MinY,MaxX,MaxY : SInt32);
2:(Min, Max : TVec2SInt32);
3:(B : array[0..3] of SInt32);
end;
PJBBoxSInt32 = ^TJBBoxSInt32;
{32-bit Float Circle Definition}
TJCircle = record
Origin : TVec2;
Radius : Float32;
end;
PJCircle = ^TJCircle;
{Signed 16-bit Integer Circle Definition}
TJCircleSInt16 = record
Origin : TVec2SInt16;
Radius : SInt16;
end;
PJCircleSInt16 = ^TJCircleSInt16;
{Signed 32-bit Integer Circle Definition}
TJCircleSInt32 = record
Origin : TVec2SInt32;
Radius : SInt32;
end;
PJCircleSInt32 = ^TJCircleSInt32;
{32-bit float 2x2 Matrix}
TMat2 = record
case UInt8 of
1:(_00, _01,
_10, _11 : Float32);
2 : (M : array[0..3] of Float32);
3 : (RC : array[0..1, 0..1] of Float32);
end;
PMat2 = ^TMat2;
{32-bit float 3x3 Matrix}
TMat3 = record
case UInt8 of
1:(_00, _01, _02,
_10, _11, _12,
_20, _21, _22 : Float32);
2 : (M : array[0..8] of Float32);
3 : (RC : array[0..2, 0..2] of Float32);
end;
PMat3 = ^TMat3;
{Ray Type}
TJRay = record
case UInt8 of
1:(Origin : TVec2; Vector : TVec2);
2:(OV : array[0..1] of TVec2);
end;
PJRay = ^TJRay;
{3 unsigned 8-bit Integer colour}
TJColour3UInt8 = record
case UInt8 of
1:(R,G,B: UInt8);
2:(RGB : array [0..2] of UInt8);
end;
PJColour3UInt8 = ^TJColour3UInt8;
{4 unsigned 8-bit Integer colour}
TJColourUInt8 = record
case UInt8 of
1:(RGB: TJColour3UInt8);
2:(R,G,B,A: UInt8);
3:(RGBA: array [0..3] of UInt8);
4:(RGBA32 : UInt32);
end;
PJColourUInt8 = ^TJColourUInt8;
{3 32-bit Float colour}
TJColour3 = record
case UInt8 of
1:(R,G,B: Float32);
2:(RGB: array [0..2] of Float32);
end;
PJColour3 = ^TJColour3;
{4 32-bit Float Colour}
TJColour = record
case UInt8 of
1:(RGB: TJColour3);
2:(R,G,B,A: Float32);
3:(RGBA: array [0..3] of Float32);
end;
PJColour = ^TJColour;
TJRectSide = (JRect_Left=0, JRect_Top=1, JRect_Right=2, JRect_Bottom=3);
TJAGraphicsAPI = (
JAGraphicsAPI_Intuition=0,
JAGraphicsAPI_Picasso=1,
JAGraphicsAPI_CyberGraphics=2,
JAGraphicsAPI_Auto=3);
const
{Math Constants}
JEpsilon : Float32 = 1e-40;
JPI : Float32 = 3.141592653589793238462643383279502;
JPI2 : Float32 = 6.283185307179586476925286766558;
JPIDiv2 : Float32 = 1.5707963267948966192313216916395;
JPIDiv180 : Float32 = 0.017453292519943295769236907684883;
J180DivPI : Float32 = 57.295779513082320876798154814114;
JDegToRad : Float32 = 0.017453292519943295769236907684883;
JRadToDeg : Float32 = 57.295779513082320876798154814114;
{Vec2 Constants}
Vec2Zero : TVec2 = (X:0; Y:0);
Vec2Up : TVec2 = (X:0; Y:1);
Vec2Down : Tvec2 = (X:0; Y:-1);
Vec2Left : TVec2 = (X:-1; Y:0);
Vec2Right : TVec2 = (X:1; Y:0);
{Rect Constants}
JRectZero : TJRect = (Left : 0; Top : 0; Right : 0; Bottom : 0);
JRectSInt16Zero : TJRectSInt16 = (Left : 0; Top : 0; Right : 0; Bottom : 0);
JRectSInt32Zero : TJRectSInt32 = (Left : 0; Top : 0; Right : 0; Bottom : 0);
{BBox Constants}
JBBoxZero : TJBBox = (MinX : 0; MinY : 0; MaxX : 0; MaxY : 0);
JBBoxSInt16Zero : TJBBoxSInt16 = (MinX : 0; MinY : 0; MaxX : 0; MaxY : 0);
JBBoxSInt32Zero : TJBBoxSInt32 = (MinX : 0; MinY : 0; MaxX : 0; MaxY : 0);
{Matrix Constants}
Mat2Identity: TMat2 = (
_00:1; _01:0;
_10:0; _11:1);
Mat2Zero: TMat2 = (
_00:1; _01:0;
_10:0; _11:1);
Mat3Identity: TMat3 = (
_00:1; _01:0; _02:0;
_10:0; _11:1; _12:0;
_20:0; _21:0; _22:1);
Mat3One: TMat3 = (
_00:1; _01:1; _02:1;
_10:1; _11:1; _12:1;
_20:1; _21:1; _22:1);
Mat3Zero: TMat3 = (
_00:0; _01:0; _02:0;
_10:0; _11:0; _12:0;
_20:0; _21:0; _22:0);
{default blocksize for list/array/memory growth etc}
JAPool_BlockSize = 32;
{Amiga Library Names}
JALibNameExec : PChar = 'exec.library';
JALibNameIntuition : PChar = 'intuition.library';
JALibNameGraphics : PChar = 'graphics.library';
JALibNameLayers : PChar = 'layers.library';
JALibNamePicasso96API : PChar = 'Picasso96API.library';
JALibNameCybergraphics : PChar = 'cybergraphics.library';
{Amiga Device Names}
JADeviceNameTimer : PChar = 'timer.device';
JADeviceNameNarrator : PChar = 'narrator.device';
JADeviceNameSerial : PChar = 'serial.device';
JADeviceNameParallel : PChar = 'parallel.device';
{MouseWheel Defines}
NM_WHEEL_UP = $7A;
NM_WHEEL_DOWN = $7B;
NM_WHEEL_LEFT = $7C;
NM_WHEEL_RIGHT = $7D;
NM_BUTTON_FOURTH = $7E;
var
JAMemAllocated : UInt32 = 0;
JAMemReleased : UInt32 = 0;
{Memory Allocation}
function JAMemGet(ASize : UInt32) : Pointer;
procedure JAMemFree(AMemory : Pointer; ASize : UInt32);
function JAMemRealloc(AMemory : Pointer; ASize : UInt32) : Pointer;
{Type Constuctors}
function Vec2(X,Y : Float32) : TVec2; overload;
function Vec2(V : TVec2SInt16) : TVec2; overload;
function Vec2SInt16(V : TVec2) : TVec2SInt16; overload;
function Vec2SInt16(X,Y : SInt16) : TVec2SInt16; overload;
function Vec2SInt32(X,Y : SInt32) : TVec2SInt32;
function JRect(Left, Top, Right, Bottom : Float32) : TJRect; overload;
function JRect(ARect : TJRectSInt16) : TJRect; overload;
function JRectSInt16(Left, Top, Right, Bottom : SInt16) : TJRectSInt16;
function JRectSInt32(Left, Top, Right, Bottom : SInt32) : TJRectSInt32;
function JColour3UInt8(Red,Green,Blue : UInt8) : TJColour3UInt8;
function JColourUInt8(Red,Green,Blue,Alpha : UInt8) : TJColourUInt8;
{TVec2 Operators}
operator + (const A, B : TVec2) : TVec2; {$I JAInline.inc}
operator + (const A : TVec2; B : TVec2SInt16) : TVec2; {$I JAInline.inc}
operator + (const A : TVec2SInt16; B : TVec2) : TVec2; {$I JAInline.inc}
operator + (const A : TVec2; B : TVec2SInt32) : TVec2; {$I JAInline.inc}
operator + (const A : TVec2SInt32; B : TVec2) : TVec2; {$I JAInline.inc}
operator + (const A : TVec2SInt32; B : TVec2SInt32) : TVec2SInt32; {$I JAInline.inc}
operator - (const A, B : TVec2) : TVec2; {$I JAInline.inc}
operator - (const A, B : TVec2SInt32) : TVec2SInt32; {$I JAInline.inc}
operator * (const A, B : TVec2) : TVec2; {$I JAInline.inc}
operator * (const A : TVec2; const F : Float32) : TVec2; {$I JAInline.inc}
operator / (const A : TVec2; const F : Float32) : TVec2; {$I JAInline.inc}
operator + (const V : TVec2; const F : Float32) : TVec2; {$I JAInline.inc}
operator - (const V : TVec2; const F : Float32) : TVec2; {$I JAInline.inc}
operator := (const V : TVec2SInt16) : TVec2; {$I JAInline.inc}
operator := (const V : TVec2SInt32) : TVec2; {$I JAInline.inc}
operator = (const A, B : TVec2) : boolean; {$I JAInline.inc} {comparator}
operator - (const A : TVec2) : TVec2; {$I JAInline.inc} {Unary minus}
{TMat2 Operators}
operator * (const A, B : TMat2) : TMat2; {$I JAInline.inc}
{TMat3 Operators}
operator * (const A, B : TMat3) : TMat3; {$I JAInline.inc}
{TJColour3UInt8 Operators}
operator + (const A, B : TJColour3UInt8) : TJColour3UInt8; {$I JAInline.inc}
operator - (const A, B : TJColour3UInt8) : TJColour3UInt8; {$I JAInline.inc}
operator * (const A, B : TJColour3UInt8) : TJColour3UInt8; {$I JAInline.inc}
{TJColourUInt8 Operators}
operator + (const A, B : TJColourUInt8) : TJColourUInt8; {$I JAInline.inc}
operator - (const A, B : TJColourUInt8) : TJColourUInt8; {$I JAInline.inc}
{
{TJRect Operators}
operator + (const A : TJRect; B : TVec2) : TJRect; {$I JAInline.inc}
operator - (const A : TJRect; B : TVec2) : TJRect; {$I JAInline.inc}
{TJRectI Operators}
operator = (const A, B : TJRectI) : boolean; {$I JAInline.inc}
operator + (const A : TJRectI; B : TVec2I) : TJRectI; {$I JAInline.inc}
operator - (const A : TJRectI; B : TVec2I) : TJRectI; {$I JAInline.inc}
{TJBBox Operators}
operator * (const B : TJBBox; const F : Float32) : TJBBox; {$I JAInline.inc}
operator / (const B : TJBBox; const F : Float32) : TJBBox; {$I JAInline.inc}
operator + (const B : TJBBox; const V : TVec3) : TJBBox; {$I JAInline.inc}
operator - (const B : TJBBox; const V : TVec3) : TJBBox; {$I JAInline.inc}
operator := (const B : TJBBoxSInt16) : TJBBox; {$I JAInline.inc}
operator := (const B : TJBBoxI) : TJBBox; {$I JAInline.inc}
{TJColour Operators}
operator + (const A, B : TJColour) : TJColour; {$I JAInline.inc}
operator - (const A, B : TJColour) : TJColour; {$I JAInline.inc}
operator * (const A : TJColour; const B : Float32) : TJColour; {$I JAInline.inc}
operator * (const A,B : TJColour) : TJColour; {$I JAInline.inc}
operator / (const A : TJColour; const B : Float32) : TJColour; {$I JAInline.inc}
{TJColour3 Operators}
operator + (const A, B : TJColour3) : TJColour3; {$I JAInline.inc}
operator - (const A, B : TJColour3) : TJColour3; {$I JAInline.inc}
operator * (const A : TJColour3; const B : Float32) : TJColour3; {$I JAInline.inc}
operator * (const A,B : TJColour3) : TJColour3; {$I JAInline.inc}
operator / (const A : TJColour3; const B : Float32) : TJColour3; {$I JAInline.inc}
{TJColour3UInt8 Operators}
operator + (const A, B : TJColour3UInt8) : TJColour3UInt8; {$I JAInline.inc}
operator - (const A, B : TJColour3UInt8) : TJColour3UInt8; {$I JAInline.inc}
{TJColourUInt8 Operators}
operator + (const A, B : TJColourUInt8) : TJColourUInt8; {$I JAInline.inc}
operator - (const A, B : TJColourUInt8) : TJColourUInt8; {$I JAInline.inc}
}
implementation
function JAMemGet(ASize: UInt32): Pointer;
begin
JAMemAllocated += ASize;
//Result := AllocVec(ASize, MEMF_CHIP or MEMF_CLEAR);
Result := AllocMem(ASize);
end;
procedure JAMemFree(AMemory : Pointer; ASize : UInt32);
begin
JAMemReleased += ASize;
Freemem(AMemory);
end;
function JAMemRealloc(AMemory: Pointer; ASize: UInt32): Pointer;
begin
Result := reallocmem(AMemory, ASize);
end;
{--------------------------------------------------------------Type constuctors}
function Vec2(X, Y : Float32) : TVec2;
begin
Result.X := X;
Result.Y := Y;
end;
function Vec2(V: TVec2SInt16): TVec2;
begin
Result.X := V.X;
Result.Y := V.Y;
end;
function Vec2SInt16(V: TVec2): TVec2SInt16;
begin
Result.X := Round(V.X);
Result.Y := Round(V.Y);
end;
function Vec2SInt16(X, Y: SInt16) : TVec2SInt16;
begin
Result.X := X;
Result.Y := Y;
end;
function Vec2SInt32(X, Y : SInt32) : TVec2SInt32;
begin
Result.X := X;
Result.Y := Y;
end;
function JRect(Left, Top, Right, Bottom : Float32) : TJRect;
begin
Result.Left := Left;
Result.Top := Top;
Result.Right := Right;
Result.Bottom := Bottom;
end;
function JRect(ARect: TJRectSInt16): TJRect;
begin
Result.Left := ARect.Left;
Result.Top := ARect.Top;
Result.Right := ARect.Right;
Result.Bottom := ARect.Bottom;
end;
function JRectSInt16(Left, Top, Right, Bottom : SInt16) : TJRectSInt16;
begin
Result.Left := Left;
Result.Top := Top;
Result.Right := Right;
Result.Bottom := Bottom;
end;
function JRectSInt32(Left, Top, Right, Bottom : SInt32) : TJRectSInt32;
begin
Result.Left := Left;
Result.Top := Top;
Result.Right := Right;
Result.Bottom := Bottom;
end;
function JColour3UInt8(Red, Green, Blue: UInt8): TJColour3UInt8;
begin
Result.R := Red;
Result.G := Green;
Result.B := Blue;
end;
function JColourUInt8(Red,Green,Blue,Alpha : UInt8) : TJColourUInt8;
begin
Result.R := Red;
Result.G := Green;
Result.B := Blue;
Result.A := Alpha;
end;
{--------------------------------------------------------------- Vec2 Operators}
operator = (const A, B: TVec2): boolean;
begin
Result :=
(abs(A.X-B.X) < JEpsilon) and
(abs(A.Y-B.Y) < JEpsilon);
end;
operator + (const A, B : TVec2) : TVec2; {$I JAInline.inc}
begin
Result.X := A.X + B.X;
Result.Y := A.Y + B.Y;
end;
operator + (const A : TVec2; B : TVec2SInt16) : TVec2; {$I JAInline.inc}
begin
Result.X := A.X + B.X;
Result.Y := A.Y + B.Y;
end;
operator + (const A : TVec2SInt16; B : TVec2) : TVec2; {$I JAInline.inc}
begin
Result.X := A.X + B.X;
Result.Y := A.Y + B.Y;
end;
operator + (const A : TVec2; B : TVec2SInt32) : TVec2; {$I JAInline.inc}
begin
Result.X := A.X + B.X;
Result.Y := A.Y + B.Y;
end;
operator + (const A : TVec2SInt32; B : TVec2) : TVec2; {$I JAInline.inc}
begin
Result.X := A.X + B.X;
Result.Y := A.Y + B.Y;
end;
operator + (const A : TVec2SInt32; B : TVec2SInt32) : TVec2SInt32; {$I JAInline.inc}
begin
Result.X := A.X + B.X;
Result.Y := A.Y + B.Y;
end;
operator - (const A, B : TVec2) : TVec2; {$I JAInline.inc}
begin
Result.X := A.X - B.X;
Result.Y := A.Y - B.Y;
end;
operator - (const A, B : TVec2SInt32) : TVec2SInt32; {$I JAInline.inc}
begin
Result.X := A.X - B.X;
Result.Y := A.Y - B.Y;
end;
operator * (const A, B : TVec2) : TVec2; {$I JAInline.inc}
begin
Result.X := A.X * B.X;
Result.Y := A.Y * B.Y;
end;
operator * (const A : TVec2; const F : Float32) : TVec2; {$I JAInline.inc}
begin
Result.X := A.X * F;
Result.Y := A.Y * F;
end;
operator / (const A : TVec2; const F : Float32) : TVec2; {$I JAInline.inc}
begin
Result.X := A.X / F;
Result.Y := A.Y / F;
end;
operator - (const A : TVec2) : TVec2; {$I JAInline.inc}
begin
Result.X := -A.X;
Result.Y := -A.Y;
end;
operator + (const V : TVec2; const F : Float32):TVec2; {$I JAInline.inc}
begin
Result.X := V.X + F;
Result.Y := V.Y + F;
end;
operator - (const V : TVec2; const F : Float32):TVec2; {$I JAInline.inc}
begin
Result.X := V.X - F;
Result.Y := V.Y - F;
end;
operator := (const V: TVec2SInt16): TVec2;
begin
Result.X := V.X;
Result.Y := V.Y;
end;
operator := (const V: TVec2SInt32): TVec2;
begin
Result.X := V.X;
Result.Y := V.Y;
end;
{---------------------------------------------------------- TMat2 Operators}
operator * (const A, B : TMat2) : TMat2;
begin
end;
{---------------------------------------------------------- TMat3 Operators}
operator * (const A, B : TMat3) : TMat3; {$I JAInline.inc}
{var
M : array[0..23] of Float32; // not off by one, just wanted to match the index from the paper
begin
m[1] := (A._00+A._01+A._02-A._10-A._11-A._21-A._22)*B._11;
m[2] := (A._00-A._10)*(-B._01+B._11);
m[3] := A._11*(-B._00+B._01+B._10-B._11-B._12-B._20+B._22);
m[4] := (-A._00+A._10+A._11)*(B._00-B._01+B._11);
m[5] := (A._10+A._11)*(-B._00+B._01);
m[6] := A._00*B._00;
m[7] := (-A._00+A._20+A._21)*(B._00-B._02+B._12);
m[8] := (-A._00+A._20)*(B._02-B._12);
m[9] := (A._20+A._21)*(-B._00+B._02);
m[10]:= (A._00+A._01+A._02-A._11-A._12-A._20-A._21)*B._12;
m[11]:= A._21*(-B._00+B._02+B._10-B._11-B._12-B._20+B._21);
m[12]:= (-A._02+A._21+A._22)*(B._11+B._20-B._21);
m[13]:= (A._02-A._22)*(B._11-B._21);
m[14]:= A._02*B._20;
m[15]:= (A._21+A._22)*(-B._20+B._21);
m[16]:= (-A._02+A._11+A._12)*(B._12+B._20-B._22);
m[17]:= (A._02-A._12)*(B._12-B._22);
m[18]:= (A._11+A._12)*(-B._20+B._22);
m[19]:= A._01*B._10;
m[20]:= A._12*B._21;
m[21]:= A._10*B._02;
m[22]:= A._20*B._01;
m[23]:= A._22*B._22;
Result._00 := m[6]+m[14]+m[19];
Result._01 := m[1]+m[4]+m[5]+m[6]+m[12]+m[14]+m[15];
Result._02 := m[6]+m[7]+m[9]+m[10]+m[14]+m[16]+m[18];
Result._10 := m[2]+m[3]+m[4]+m[6]+m[14]+m[16]+m[17];
Result._11 := m[2]+m[4]+m[5]+m[6]+m[20];
Result._12 := m[14]+m[16]+m[17]+m[18]+m[21];
Result._20 := m[6]+m[7]+m[8]+m[11]+m[12]+m[13]+m[14];
Result._21 := m[12]+m[13]+m[14]+m[15]+m[22];
Result._22 := m[6]+m[7]+m[8]+m[9]+m[23];
}
begin
Result._00 := A._00*B._00+A._01*B._10+A._02*B._20;
Result._01 := A._00*B._01+A._01*B._11+A._02*B._21;
Result._02 := A._00*B._02+A._01*B._12+A._02*B._22;
Result._10 := A._10*B._00+A._11*B._10+A._12*B._20;
Result._11 := A._10*B._01+A._11*B._11+A._12*B._21;
Result._12 := A._10*B._02+A._11*B._12+A._12*B._22;
Result._20 := A._20*B._00+A._21*B._10+A._22*B._20;
Result._21 := A._20*B._01+A._21*B._11+A._22*B._21;
Result._22 := A._20*B._02+A._21*B._12+A._22*B._22;
end;
{----------------------------------------------------- TJColour3UInt8 Operators}
operator + (const A, B : TJColour3UInt8) : TJColour3UInt8; {$I JAInline.inc}
begin
Result.R := A.R+B.R;
Result.G := A.G+B.G;
Result.B := A.B+B.B;
end;
operator - (const A, B : TJColour3UInt8) : TJColour3UInt8; {$I JAInline.inc}
begin
Result.R := A.R-B.R;
Result.G := A.G-B.G;
Result.B := A.B-B.B;
end;
operator * (const A, B: TJColour3UInt8): TJColour3UInt8;
begin
Result.R := (A.R * B.R) div 255;
Result.G := (A.G * B.G) div 255;
Result.B := (A.B * B.B) div 255;
end;
{------------------------------------------------------ TJColourUInt8 Operators}
operator + (const A, B : TJColourUInt8) : TJColourUInt8; {$I JAInline.inc}
begin
Result.R := A.R+B.R;
Result.G := A.G+B.G;
Result.B := A.B+B.B;
Result.A := A.A+B.A;
end;
operator - (const A, B : TJColourUInt8) : TJColourUInt8; {$I JAInline.inc}
begin
Result.R := A.R-B.R;
Result.G := A.G-B.G;
Result.B := A.B-B.B;
Result.A := A.A-B.A;
end;
(*
{-------------------------------------------------------------- JRect Operators}
operator + (const A: TJRect; B: TVec2): TJRect; {$I JAInline.inc}
begin
Result.LT := A.LT+B;
Result.RB := A.RB+B;
end;
operator - (const A: TJRect; B: TVec2): TJRect; {$I JAInline.inc}
begin
Result.LT := A.LT-B;
Result.RB := A.RB-B;
end;
{------------------------------------------------------------- JRectI Operators}
operator = (const A, B : TJRectI): boolean;
begin
Result := (A.LT = B.LT) and (A.RB = B.RB);
end;
operator + (const A: TJRectI; B: TVec2I): TJRectI; {$I JAInline.inc}
begin
Result.LT := A.LT+B;
Result.RB := A.RB+B;
end;
operator - (const A: TJRectI; B: TVec2I): TJRectI; {$I JAInline.inc}
begin
Result.LT := A.LT-B;
Result.RB := A.RB-B;
end;
{------------------------------------------------------------- TJBBox Operators}
operator * (const B : TJBBox; const F : Float32) : TJBBox; {$I JAInline.inc}
begin
Result.Min := B.Min * F;
Result.Max := B.Max * F;
end;
operator / (const B : TJBBox; const F : Float32) : TJBBox; {$I JAInline.inc}
begin
Result.Min := B.Min / F;
Result.Max := B.Max / F;
end;
operator + (const B : TJBBox; const V : TVec3) : TJBBox; {$I JAInline.inc}
begin
Result.Min := B.Min + V;
Result.Max := B.Max + V;
end;
operator - (const B : TJBBox; const V : TVec3) : TJBBox; {$I JAInline.inc}
begin
Result.Min := B.Min - V;
Result.Max := B.Max - V;
end;
operator := (const B: TJBBoxSInt16) : TJBBox;
begin
Result.Min := B.Min;
Result.Max := B.Max;
end;
operator:=(const B: TJBBoxI): TJBBox;
begin
Result.Min := B.Min;
Result.Max := B.Max;
end;
{----------------------------------------------------------- TJColour Operators}
operator + (const A, B : TJColour) : TJColour; {$I JAInline.inc}
begin
Result.R := A.R+B.R;
Result.G := A.G+B.G;
Result.B := A.B+B.B;
Result.A := A.A+B.A;
end;
operator - (const A, B : TJColour) : TJColour; {$I JAInline.inc}
begin
Result.R := A.R-B.R;
Result.G := A.G-B.G;
Result.B := A.B-B.B;
Result.A := A.A-B.A;
end;
operator * (const A : TJColour; const B : Float32) : TJColour; {$I JAInline.inc}
begin
Result.R := A.R*B;
Result.G := A.G*B;
Result.B := A.B*B;
Result.A := A.A*B;
end;
operator * (const A, B: TJColour): TJColour;
begin
Result.R := A.R*B.R;
Result.G := A.G*B.G;
Result.B := A.B*B.B;
Result.A := A.A*B.A;
end;
operator / (const A : TJColour; const B : Float32) : TJColour; {$I JAInline.inc}
begin
Result.R := A.R/B;
Result.G := A.G/B;
Result.B := A.B/B;
Result.A := A.A/B;
end;
{----------------------------------------------------------- TJColour3 Operators}
operator + (const A, B : TJColour3) : TJColour3; {$I JAInline.inc}
begin
Result.R := A.R+B.R;
Result.G := A.G+B.G;
Result.B := A.B+B.B;
end;
operator - (const A, B : TJColour3) : TJColour3; {$I JAInline.inc}
begin
Result.R := A.R-B.R;
Result.G := A.G-B.G;
Result.B := A.B-B.B;
end;
operator * (const A : TJColour3; const B : Float32) : TJColour3; {$I JAInline.inc}
begin
Result.R := A.R*B;
Result.G := A.G*B;
Result.B := A.B*B;
end;
operator * (const A, B: TJColour3): TJColour3;
begin
Result.R := A.R*B.R;
Result.G := A.G*B.G;
Result.B := A.B*B.B;
end;
operator / (const A : TJColour3; const B : Float32) : TJColour3; {$I JAInline.inc}
begin
Result.R := A.R/B;
Result.G := A.G/B;
Result.B := A.B/B;
end;
*)
end.
|
unit ufrmLogin;
interface
{$I ThsERP.inc}
uses
System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.Samples.Spin,
Vcl.StdCtrls, FireDAC.Comp.Client, Vcl.Dialogs, Winapi.Windows, Vcl.Graphics,
Vcl.AppEvnts, Vcl.ExtCtrls, Vcl.ComCtrls,
xmldom, XMLDoc, XMLIntf,
Ths.Erp.Helper.Edit,
Ths.Erp.Helper.ComboBox,
ufrmBase, ufrmBaseInput, Vcl.Menus
;
type
TfrmLogin = class(TfrmBase)
btnShowConfigure: TButton;
lbllanguage: TLabel;
lblUserName: TLabel;
lblPassword: TLabel;
lblServer: TLabel;
lblServerExample: TLabel;
lblDatabase: TLabel;
lblPortNo: TLabel;
lblSaveSettings: TLabel;
cbbLanguage: TComboBox;
edtUserName: TEdit;
edtPassword: TEdit;
edtServer: TEdit;
edtDatabase: TEdit;
edtPortNo: TEdit;
chkSaveSettings: TCheckBox;
procedure FormCreate(Sender: TObject); override;
procedure FormShow(Sender: TObject); override;
procedure btnAcceptClick(Sender: TObject); override;
procedure RefreshLangValue();
procedure cbbLanguageChange(Sender: TObject);
procedure btnShowConfigureClick(Sender: TObject);
private
protected
public
class function Execute(): Boolean;
end;
implementation
uses
Ths.Erp.Functions
, Ths.Erp.Constants
, Ths.Erp.Database
, Ths.Erp.Database.Singleton
, Ths.Erp.Database.Connection.Settings
, Ths.Erp.Database.Table.SysLang
, Ths.Erp.Database.Table.SysLangGuiContent
;
{$R *.dfm}
class function TfrmLogin.Execute(): boolean;
begin
with TfrmLogin.Create(nil) do
try
if (ShowModal = mrYes) then
Result := True
else
Result := False;
finally
Free;
end;
end;
procedure TfrmLogin.btnAcceptClick(Sender: TObject);
begin
if ValidateInput then
begin
ModalResult := mrCancel;
TSingletonDB.GetInstance.DataBase.ConnSetting.Language := cbbLanguage.Text;
TSingletonDB.GetInstance.DataBase.ConnSetting.SQLServer := edtServer.Text;
TSingletonDB.GetInstance.DataBase.ConnSetting.DatabaseName := edtDatabase.Text;
TSingletonDB.GetInstance.DataBase.ConnSetting.DBUserName := edtUserName.Text;
TSingletonDB.GetInstance.DataBase.ConnSetting.DBUserPassword := edtPassword.Text;
TSingletonDB.GetInstance.DataBase.ConnSetting.DBPortNo := StrToIntDef(edtPortNo.Text, 0);
if TSingletonDB.GetInstance.DataBase.Connection.Connected then
begin
TSingletonDB.GetInstance.User.SelectToList(' AND ' + TSingletonDB.GetInstance.User.UserName.FieldName + '=' + QuotedStr(edtUserName.Text), False, False);
TSingletonDB.GetInstance.HaneMiktari.SelectToList('', False, False);
TSingletonDB.GetInstance.ApplicationSettings.SelectToList('', False, False);
//şimdilik kapatıldı form düzenlenince ileride açılacak
// TSingletonDB.GetInstance.ApplicationSettingsOther.SelectToList('', False, False);
TSingletonDB.GetInstance.SysLang.SelectToList(' AND ' + TSingletonDB.GetInstance.SysLang.Language.FieldName + '=' + QuotedStr(cbbLanguage.Text), False, False);
if TSingletonDB.GetInstance.User.List.Count = 0 then
raise Exception.Create(TranslateText('Username/Password not defined or correct!', FrameworkLang.ErrorLogin, LngMsgError, LngSystem));
ModalResult := mrYes;
if chkSaveSettings.Checked then
TSingletonDB.GetInstance.DataBase.ConnSetting.SaveToFile;
end;
end;
end;
procedure TfrmLogin.btnShowConfigureClick(Sender: TObject);
begin
if edtServer.Visible then
begin
lblServer.Visible := False;
edtServer.Visible := False;
lblServerExample.Visible := False;
lblDatabase.Visible := False;
edtDatabase.Visible := False;
lblPortNo.Visible := False;
edtPortNo.Visible := False;
chkSaveSettings.Visible := False;
ClientHeight := 120;
end
else
begin
lblServer.Visible := True;
edtServer.Visible := True;
lblServerExample.Visible := True;
lblDatabase.Visible := True;
edtDatabase.Visible := True;
lblPortNo.Visible := True;
edtPortNo.Visible := True;
chkSaveSettings.Visible := True;
ClientHeight := 230;
end;
end;
procedure TfrmLogin.cbbLanguageChange(Sender: TObject);
begin
inherited;
TSingletonDB.GetInstance.DataBase.ConnSetting.Language := cbbLanguage.Text;
RefreshLangValue;
Repaint;
end;
procedure TfrmLogin.FormCreate(Sender: TObject);
begin
inherited;
edtUserName.thsRequiredData := True;
edtPassword.thsRequiredData := True;
edtServer.thsRequiredData := True;
edtDatabase.thsRequiredData := True;
edtPortNo.thsRequiredData := True;
btnAccept.Visible := True;
btnClose.Visible := True;
btnDelete.Visible := False;
btnSpin.Visible := False;
cbbLanguage.Clear;
cbbLanguage.Items.Add(TSingletonDB.GetInstance.DataBase.ConnSetting.Language);
edtUserName.Text := TSingletonDB.GetInstance.Database.ConnSetting.DBUserName;
edtPassword.Text := TSingletonDB.GetInstance.Database.ConnSetting.DBUserPassword;
edtServer.Text := TSingletonDB.GetInstance.Database.ConnSetting.SQLServer;
edtDatabase.Text := TSingletonDB.GetInstance.Database.ConnSetting.DatabaseName;
edtPortNo.Text := TSingletonDB.GetInstance.Database.ConnSetting.DBPortNo.ToString;
cbbLanguage.ItemIndex := cbbLanguage.Items.IndexOf(TSingletonDB.GetInstance.Database.ConnSetting.Language);
cbbLanguageChange(cbbLanguage);
end;
procedure TfrmLogin.FormShow(Sender: TObject);
var
vLang: TSysLang;
n1: Integer;
begin
inherited;
TSingletonDB.GetInstance.DataBase.ConfigureConnection;
try
TSingletonDB.GetInstance.DataBase.Connection.Open();
vLang := TSysLang.Create(TSingletonDB.GetInstance.DataBase);
try
vLang.SelectToList('', False, False);
cbbLanguage.Clear;
for n1 := 0 to vLang.List.Count-1 do
cbbLanguage.Items.Add( TSysLang(vLang.List[n1]).Language.Value );
cbbLanguage.ItemIndex := cbbLanguage.Items.IndexOf( TSingletonDB.GetInstance.DataBase.ConnSetting.Language );
finally
vLang.Free;
end;
RefreshLangValue;
btnAccept.Images := TSingletonDB.GetInstance.ImageList32;
btnAccept.ImageIndex := 0;
btnShowConfigureClick(btnShowConfigure);
except
on E: Exception do
begin
raise Exception.Create(TranslateText('Failed to connect to database!', FrameworkLang.ErrorDatabaseConnection, LngMsgError, LngSystem) + sLineBreak + sLineBreak + E.Message);
end;
end;
end;
procedure TfrmLogin.RefreshLangValue;
begin
// if TSingletonDB.GetInstance.DataBase.Connection.Connected then
begin
Self.Caption := getFormCaptionByLang(Self.Name, Self.Caption);
btnAccept.Caption := TranslateText( btnAccept.Caption, FrameworkLang.ButtonAccept, LngButton, LngSystem);
btnClose.Caption := TranslateText( btnClose.Caption, FrameworkLang.ButtonClose, LngButton, LngSystem);
btnAccept.Width := Canvas.TextWidth(btnAccept.Caption) + 56;
btnClose.Width := Canvas.TextWidth(btnClose.Caption) + 56;
lblLanguage.Caption := TranslateText(lblLanguage.Caption, lblLanguage.Name, LngLabelCaption);
lblUserName.Caption := TranslateText( lblUserName.Caption, 'User Name', LngLogin, LngSystem );
lblPassword.Caption := TranslateText( lblPassword.Caption, 'Password', LngLogin, LngSystem );
lblServer.Caption := TranslateText( lblServer.Caption, 'Server', LngLogin, LngSystem );
lblServerExample.Caption := TranslateText( lblServerExample.Caption, 'Server Example', LngLogin, LngSystem );
lblDatabase.Caption := TranslateText( lblDatabase.Caption, 'Database', LngLogin, LngSystem );
lblPortNo.Caption := TranslateText( lblPortNo.Caption, 'Port No', LngLogin, LngSystem );
chkSaveSettings.Caption := TranslateText( chkSaveSettings.Caption, 'Save Settings', LngLogin, LngSystem );
end;
end;
end.
|
{
Translation of "ImGui SDL2 binding with OpenGL" example, using SDL2 headers provided by https://github.com/ev1313/Pascal-SDL-2-Headers
In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
You can copy and use unmodified imgui_impl_* files in your project.
If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), Imgui_ImplSdlGL2_RenderDrawLists() and ImGui_ImplXXXX_Shutdown().
If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
https://github.com/ocornut/imgui
}
unit fpimgui_impl_sdlgl2;
{$mode objfpc}{$H+}
interface
uses
sdl2, glad_gl,
fpimgui;
procedure ImGui_ImplSdlGL2_Init();
procedure ImGui_ImplSdlGL2_Shutdown();
procedure ImGui_ImplSdlGL2_NewFrame(window: PSDL_Window);
procedure Imgui_ImplSdlGL2_RenderDrawLists(draw_data: PImDrawData); cdecl;
function ImGui_ImplSdlGL2_ProcessEvent(event: PSDL_Event): boolean;
implementation
// Data
var
g_Time: double = 0.0;
g_MousePressed: array[0..2] of bool = ( false, false, false );
g_MouseWheel: single = 0.0;
g_FontTexture: GLuint = 0;
function ImGui_ImplSdlGL2_ProcessEvent(event: PSDL_Event): boolean;
var
key: TSDL_KeyCode;
io: PImGuiIO;
begin
result := false;
io := igGetIO();
case event^.type_ of
SDL_MOUSEWHEEL: begin
if (event^.wheel.y > 0) then
g_MouseWheel := 1;
if (event^.wheel.y < 0) then
g_MouseWheel := -1;
result := true;
end;
SDL_MOUSEBUTTONDOWN: begin
if (event^.button.button = SDL_BUTTON_LEFT) then g_MousePressed[0] := true;
if (event^.button.button = SDL_BUTTON_RIGHT) then g_MousePressed[1] := true;
if (event^.button.button = SDL_BUTTON_MIDDLE) then g_MousePressed[2] := true;
result := true;
end;
SDL_TEXTINPUT: begin
ImGuiIO_AddInputCharactersUTF8(event^.text.text);
result := true;
end;
SDL_KEYDOWN, SDL_KEYUP: begin
key := event^.key.keysym.sym and (not SDLK_SCANCODE_MASK);
io^.KeysDown[key] := event^.type_ = SDL_KEYDOWN;
io^.KeyShift := (SDL_GetModState() and KMOD_SHIFT) <> 0;
io^.KeyCtrl := (SDL_GetModState() and KMOD_CTRL) <> 0;
io^.KeyAlt := (SDL_GetModState() and KMOD_ALT) <> 0;
io^.KeySuper := (SDL_GetModState() and KMOD_GUI) <> 0;
result := true;
end;
end;
end;
procedure ImGui_ImplSdlGL2_CreateDeviceObjects();
var
io: PImGuiIO;
pixels: pbyte;
width, height: integer;
font_atlas: PImFontAtlas;
last_texture: GLint;
begin
// Build texture atlas
io := igGetIO();
font_atlas := io^.Fonts;
//ImFontAtlas_AddFontDefault(font_atlas);
ImFontAtlas_GetTexDataAsAlpha8(font_atlas, @pixels, @width, @height);
// Upload texture to graphics system
glGetIntegerv(GL_TEXTURE_BINDING_2D, @last_texture);
glGenTextures(1, @g_FontTexture);
glBindTexture(GL_TEXTURE_2D, g_FontTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, pixels);
// Store our identifier
ImFontAtlas_SetTexID(font_atlas, ImTextureID(g_FontTexture));
// Restore state
glBindTexture(GL_TEXTURE_2D, last_texture);
end;
procedure ImGui_ImplSdlGL2_InvalidateDeviceObjects();
begin
if (g_FontTexture <> 0) then begin
glDeleteTextures(1, @g_FontTexture);
ImFontAtlas_SetTexID(igGetIO()^.Fonts, nil);
g_FontTexture := 0;
end;
end;
function ImGui_MemAlloc(sz:size_t): pointer; cdecl;
begin
result := Getmem(sz);
end;
procedure ImGui_MemFree(ptr:pointer); cdecl;
begin
Freemem(ptr);
end;
procedure ImGui_ImplSdlGL2_Init();
var
io: PImGuiIO;
begin
io := igGetIO();
// Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
io^.KeyMap[ImGuiKey_Tab] := SDLK_TAB;
io^.KeyMap[ImGuiKey_LeftArrow] := SDL_SCANCODE_LEFT;
io^.KeyMap[ImGuiKey_RightArrow] := SDL_SCANCODE_RIGHT;
io^.KeyMap[ImGuiKey_UpArrow] := SDL_SCANCODE_UP;
io^.KeyMap[ImGuiKey_DownArrow] := SDL_SCANCODE_DOWN;
io^.KeyMap[ImGuiKey_PageUp] := SDL_SCANCODE_PAGEUP;
io^.KeyMap[ImGuiKey_PageDown] := SDL_SCANCODE_PAGEDOWN;
io^.KeyMap[ImGuiKey_Home] := SDL_SCANCODE_HOME;
io^.KeyMap[ImGuiKey_End] := SDL_SCANCODE_END;
io^.KeyMap[ImGuiKey_Delete] := SDLK_DELETE;
io^.KeyMap[ImGuiKey_Backspace] := SDLK_BACKSPACE;
io^.KeyMap[ImGuiKey_Enter] := SDLK_RETURN;
io^.KeyMap[ImGuiKey_Escape] := SDLK_ESCAPE;
io^.KeyMap[ImGuiKey_A] := SDLK_a;
io^.KeyMap[ImGuiKey_C] := SDLK_c;
io^.KeyMap[ImGuiKey_V] := SDLK_v;
io^.KeyMap[ImGuiKey_X] := SDLK_x;
io^.KeyMap[ImGuiKey_Y] := SDLK_y;
io^.KeyMap[ImGuiKey_Z] := SDLK_z;
io^.RenderDrawListsFn := @Imgui_ImplSdlGL2_RenderDrawLists;
io^.SetClipboardTextFn := nil;
io^.GetClipboardTextFn := nil;
io^.ClipboardUserData := nil;
// Allocate memory through pascal's memory allocator.
// This is optional, for example for seeing the number of memory allocations through HeapTrc
io^.MemAllocFn := @ImGui_MemAlloc;
io^.MemFreeFn := @ImGui_MemFree;
end;
procedure ImGui_ImplSdlGL2_Shutdown();
begin
ImGui_ImplSdlGL2_InvalidateDeviceObjects();
igShutdown();
end;
procedure ImGui_ImplSdlGL2_NewFrame(window: PSDL_Window);
var
w, h: integer;
display_w, display_h: integer;
io: PImGuiIO;
time, mouseMask: UInt32;
current_time: double;
mx, my: Integer;
begin
if g_FontTexture = 0 then
ImGui_ImplSdlGL2_CreateDeviceObjects();
io := igGetIO();
// Setup display size (every frame to accommodate for window resizing)
SDL_GetWindowSize(window, @w, @h);
io^.DisplaySize := ImVec2Init(w, h);
io^.DisplayFramebufferScale := ImVec2Init(1, 1);
// SDL_GL_GetDrawableSize might be missing in pascal sdl2 headers - remove the next 3 lines in that case
SDL_GL_GetDrawableSize(window, @display_w, @display_h);
if (w <> 0) and (h <> 0) and ((w <> display_w) or (h <> display_h)) then
io^.DisplayFramebufferScale := ImVec2Init(display_w/w, display_h/h);
// Setup time step
time := SDL_GetTicks();
current_time := time / 1000.0;
if (g_Time > 0.0) then
io^.DeltaTime := current_time - g_Time
else
io^.DeltaTime := 1.0/60.0;
g_Time := current_time;
// Setup inputs
// (we already got mouse wheel, keyboard keys & characters from SDL_PollEvent())
mouseMask := SDL_GetMouseState(@mx, @my);
if ((SDL_GetWindowFlags(window) and SDL_WINDOW_INPUT_FOCUS) <> 0) then
io^.MousePos := ImVec2Init(mx, my) // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
else
io^.MousePos := ImVec2Init(-FLT_MAX, -FLT_MAX);
// If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame.
io^.MouseDown[0] := g_MousePressed[0] or (mouseMask and SDL_BUTTON(SDL_BUTTON_LEFT) <> 0);
io^.MouseDown[1] := g_MousePressed[1] or (mouseMask and SDL_BUTTON(SDL_BUTTON_RIGHT) <> 0);
io^.MouseDown[2] := g_MousePressed[2] or (mouseMask and SDL_BUTTON(SDL_BUTTON_MIDDLE) <> 0);
g_MousePressed[0] := false;
g_MousePressed[1] := false;
g_MousePressed[2] := false;
io^.MouseWheel := g_MouseWheel;
g_MouseWheel := 0.0;
// Hide OS mouse cursor if ImGui is drawing it
if io^.MouseDrawCursor then SDL_ShowCursor(SDL_DISABLE) else SDL_ShowCursor(SDL_ENABLE);
// Start the frame
igNewFrame();
end;
procedure Imgui_ImplSdlGL2_RenderDrawLists(draw_data: PImDrawData); cdecl;
var
last_texture: GLint;
last_viewport: array[0..3] of GLint;
last_scissor_box: array[0..3] of GLint;
io: PImGuiIO;
fb_width, fb_height, n, cmd_i: integer;
cmd_list: PImDrawList;
vtx_buffer: PImDrawVert;
idx_buffer: PImDrawIdx;
pcmd: PImDrawCmd;
begin
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
io := igGetIO();
fb_width := trunc(io^.DisplaySize.x * io^.DisplayFramebufferScale.x);
fb_height := trunc(io^.DisplaySize.y * io^.DisplayFramebufferScale.y);
if (fb_width = 0) or (fb_height = 0) then
exit;
//draw_data->ScaleClipRects(io.DisplayFramebufferScale);
glGetIntegerv(GL_TEXTURE_BINDING_2D, @last_texture);
glGetIntegerv(GL_VIEWPORT, @last_viewport);
glGetIntegerv(GL_SCISSOR_BOX, @last_scissor_box);
glPushAttrib(GL_ENABLE_BIT or GL_COLOR_BUFFER_BIT or GL_TRANSFORM_BIT);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnable(GL_TEXTURE_2D);
//glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context
// Setup viewport, orthographic projection matrix
glViewport(0, 0, fb_width, fb_height);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0.0, io^.DisplaySize.x, io^.DisplaySize.y, 0.0, -1.0, +1.0);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
// Render command lists
Assert(SizeOf(ImDrawIdx) = 2);
for n := 0 to draw_data^.CmdListsCount - 1 do begin
cmd_list := draw_data^.CmdLists[n];
vtx_buffer := cmd_list^.VtxBuffer.Data;
idx_buffer := cmd_list^.IdxBuffer.Data;
//pos/uv/color offsets: 0, 8, 16
glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), Pbyte(vtx_buffer) + 0);
glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), Pbyte(vtx_buffer) + 8);
glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), Pbyte(vtx_buffer) + 16);
for cmd_i := 0 to cmd_list^.CmdBuffer.Size - 1 do begin
pcmd := @(cmd_list^.CmdBuffer.Data[cmd_i]);
if pcmd^.UserCallback <> nil then begin
pcmd^.UserCallback(cmd_list, pcmd);
end else begin
glBindTexture(GL_TEXTURE_2D, GLuint(pcmd^.TextureId));
glScissor(trunc(pcmd^.ClipRect.x), trunc(fb_height - pcmd^.ClipRect.w),
trunc(pcmd^.ClipRect.z - pcmd^.ClipRect.x), trunc(pcmd^.ClipRect.w - pcmd^.ClipRect.y));
glDrawElements(GL_TRIANGLES, pcmd^.ElemCount, GL_UNSIGNED_SHORT, idx_buffer);
end;
idx_buffer += pcmd^.ElemCount
end;
end;
// Restore modified state
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glBindTexture(GL_TEXTURE_2D, last_texture);
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glPopAttrib();
glViewport(last_viewport[0], last_viewport[1], GLsizei(last_viewport[2]), GLsizei(last_viewport[3]));
glScissor(last_scissor_box[0], last_scissor_box[1], GLsizei(last_scissor_box[2]), GLsizei(last_scissor_box[3]));
end;
end.
|
{*******************************************************************************
用于程序中的错误调试
创建人:TJH
创建日前:2009-11-26
描述:...
*******************************************************************************}
unit CaptureDebug;
interface
uses
Windows, Classes, SysUtils, Forms;
Type
TDebug = class(TObject)
public
class procedure DebugMsg(const className, methodName, msg: WideString);
end;
implementation
const
DEBUG_TURN_ON: Boolean = True; //如果为FALSE,则所有设置了TDebug.DebugMsg的地方将不起作用
{ TDebug }
class procedure TDebug.DebugMsg(const className, methodName, msg: WideString);
begin
if DEBUG_TURN_ON then
Application.MessageBox(PChar(String(DateTimeToStr(now) + ':' + className + '.' + methodName + ' [调试信息:' + msg + ']')), 'DEBUG', MB_OK + MB_ICONINFORMATION);
end;
end.
|
{-----------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/MPL-1.1.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is: JvgRuler.PAS, released on 2003-01-15.
The Initial Developer of the Original Code is Andrey V. Chudin, [chudin att yandex dott ru]
Portions created by Andrey V. Chudin are Copyright (C) 2003 Andrey V. Chudin.
All Rights Reserved.
Contributor(s):
Michael Beck [mbeck att bigfoot dott com].
You may retrieve the latest version of this file at the Project JEDI's JVCL home page,
located at http://jvcl.delphi-jedi.org
Known Issues:
-----------------------------------------------------------------------------}
// $Id$
unit JvRuler;
{$mode objfpc}{$H+}
interface
uses
LCLIntf, LCLType, LCLVersion, Types,
Classes, SysUtils, Graphics, Controls,
JvComponent;
const
DEFAULT_JVR_MAJOR_TICKLENGTH = 8;
DEFAULT_JVR_MINOR_TICKLENGTH = 3;
DEFAULT_JVR_MARKER_SIZE = 6;
type
TJvRulerUnit = (ruCentimeters, ruInches, ruPixels);
TJvRulerOrientation = (roHorizontal, roVertical);
TJvRuler = class(TJvGraphicControl)
private
FUseUnit: TJvRulerUnit;
FOrientation: TJvRulerOrientation;
FPosition: Double;
FTickColor: TColor;
FMarkerColor: TColor;
FMarkerFilled: Boolean;
FMarkerSize: Integer;
FMajorTickLength: Integer;
FMinorTickCount: Integer;
FMinorTickLength: Integer;
FShowBaseline: Boolean;
FShowPositionMarker: Boolean;
procedure SetMarkerColor(const Value: TColor);
procedure SetMarkerFilled(const Value: Boolean);
procedure SetMarkerSize(const Value: Integer);
procedure SetMajorTickLength(const Value: Integer);
procedure SetMinorTickCount(const Value: Integer);
procedure SetMinorTickLength(const Value: Integer);
procedure SetOrientation(const Value: TJvRulerOrientation);
procedure SetPosition(const Value: Double);
procedure SetShowBaseline(const Value: Boolean);
procedure SetShowPositionMarker(const Value: Boolean);
procedure SetTickColor(const Value: TColor);
procedure SetUseUnit(const Value: TJvRulerUnit);
protected
procedure DoAutoAdjustLayout(const AMode: TLayoutAdjustmentPolicy;
const AXProportion, AYProportion: Double); override;
class function GetControlClassDefaultSize: TSize; override;
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
published
property Align;
property BorderSpacing;
property Font;
property MarkerColor: TColor read FMarkerColor write SetMarkerColor default clBlack;
property MarkerFilled: Boolean read FMarkerFilled write SetMarkerFilled default true;
property MarkerSize: Integer read FMarkerSize write SetMarkerSize default DEFAULT_JVR_MARKER_SIZE;
property MajorTickLength: Integer read FMajorTickLength write SetMajorTickLength default DEFAULT_JVR_MAJOR_TICKLENGTH;
property MinorTickCount: Integer read FMinorTickCount write SetMinorTickCount default 1;
property MinorTickLength: Integer read FMinorTickLength write SetMinorTicklength default DEFAULT_JVR_MINOR_TICKLENGTH;
property Orientation: TJvRulerOrientation read FOrientation write SetOrientation default roHorizontal;
property Position: Double read FPosition write SetPosition;
property ShowBaseline: Boolean read FShowBaseline write SetShowBaseLine default false;
property ShowPositionMarker: Boolean read FShowPositionMarker write SetShowPositionMarker default false;
property TickColor: TColor read FTickColor write SetTickColor default clBlack;
property UseUnit: TJvRulerUnit read FUseUnit write SetUseUnit default ruCentimeters;
end;
implementation
uses
Math;
const
LogPixels: array [Boolean] of Integer = (LOGPIXELSY, LOGPIXELSX);
function InchesToPixels(DC: HDC; Value: Double; IsHorizontal: Boolean): Integer;
begin
Result := Round(Value * GetDeviceCaps(DC, LogPixels[IsHorizontal]));
end;
function CentimetersToPixels(DC: HDC; Value: Double; IsHorizontal: Boolean): Integer;
begin
Result := Round(Value * GetDeviceCaps(DC, LogPixels[IsHorizontal]) / 2.54);
end;
function IsMultipleOf(a, b: Double): Boolean;
var
c: Double;
begin
c := a / b;
Result := SameValue(c, round(c));
end;
//=== { TJvRuler } ===========================================================
constructor TJvRuler.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FOrientation := roHorizontal;
FTickColor := clBlack;
FUseUnit := ruCentimeters;
FMarkerFilled := true;
FMarkerSize := DEFAULT_JVR_MARKER_SIZE;
FMajorTickLength := DEFAULT_JVR_MAJOR_TICKLENGTH;
FMinorTickLength := DEFAULT_JVR_MINOR_TICKLENGTH;
FMinorTickCount := 1;
with GetControlClassDefaultSize do
SetInitialBounds(0, 0, CX, CY);
end;
procedure TJvRuler.DoAutoAdjustLayout(const AMode: TLayoutAdjustmentPolicy;
const AXProportion, AYProportion: Double);
var
proportion: Double;
begin
inherited;
if AMode in [lapAutoAdjustWithoutHorizontalScrolling, lapAutoAdjustForDPI] then
begin
case FOrientation of
roHorizontal: proportion := AYProportion;
roVertical: proportion := AXProportion;
end;
FMarkerSize := round(FMarkerSize * proportion);
FMajorTickLength := round(FMajorTickLength * proportion);
FMinorTicklength := round(FMinorTickLength * proportion);
end;
end;
class function TJvRuler.GetControlClassDefaultSize: TSize;
begin
Result.CX := 380;
Result.CY := 25;
end;
procedure TJvRuler.Paint;
const
MAJOR_DIST: array[TJvRulerUnit] of Double = (1.0, 1.0, 100.0);
var
X, Y: Double;
PX, PY, Pos: Integer;
S: string;
R: TRect;
ts: TTextStyle;
h, w: Integer;
delta: Double;
isLabeledTick: Boolean;
isLongTick: Boolean;
tickLength: Integer;
baselineOffset: Integer;
markerSizeL, markerSizeS: Integer;
Pts: array[0..2] of TPoint;
begin
w := inherited Width;
h := inherited Height;
ts := Canvas.TextStyle;
ts.SingleLine := true;
Canvas.Font := Font;
Canvas.Pen.Style := psSolid;
Canvas.Pen.Color := FTickColor;
X := 0;
Y := 0;
delta := MAJOR_DIST[FUseUnit] / (FMinorTickCount + 1);
case FUseUnit of
ruInches: Pos := InchesToPixels(Canvas.Handle, Position, Orientation = roHorizontal);
ruCentimeters: Pos := CentimetersToPixels(Canvas.Handle, Position, Orientation = roHorizontal);
ruPixels: Pos := Round(Position);
end;
// Draw baseline
baseLineOffset := 0;
if FShowBaseLine then
begin
case FOrientation of
roHorizontal: Canvas.Line(0, h-1, w, h-1);
roVertical: Canvas.Line(w-1, 0, w-1, h);
end;
baseLineOffset := 1;
end;
// Draw labels and ticks
while true do begin
case FUseUnit of
ruInches:
begin
PX := InchesToPixels(Canvas.Handle, X, True);
PY := InchesToPixels(Canvas.Handle, Y, False);
end;
ruCentimeters:
begin
PX := CentimetersToPixels(Canvas.Handle, X, True);
PY := CentimetersToPixels(Canvas.Handle, Y, False);
end;
ruPixels:
begin
PX := Round(X);
PY := Round(Y);
Pos := Round(Position);
end;
else
raise Exception.Create('Units not supported.');
end;
case Orientation of
roHorizontal: if PX > w then break;
roVertical: if PY > h then break;
end;
//SetBkMode(Canvas.Handle, TRANSPARENT);
with Canvas do begin
if Orientation = roHorizontal then
begin
isLabeledTick := IsMultipleOf(X, MAJOR_DIST[FUseUnit]) and (X <> 0);
if isLabeledTick then
begin
//R := Rect(PX - 10, 0, PX + 10, h);
if UseUnit = ruPixels then
S := IntToStr(PX)
else
S := IntToStr(Round(X));
R := Rect(PX - TextWidth(S), 0, PX + TextWidth(S), h);
ts.Alignment := taCenter;
TextRect(R, R.Left, R.Top, S, ts);
//Windows.DrawText(Handle, PChar(S), Length(S), R, DT_SINGLELINE or DT_CENTER);
end;
isLongTick := isLabeledTick or (IsMultipleOf(2*X, MAJOR_DIST[FUseUnit]) and (FMinorTickCount > 1));
tickLength := IfThen(isLongTick, FMajorTickLength, FMinorTickLength);
MoveTo(PX, h - baselineOffset - tickLength);
LineTo(PX, h - baselineOffset);
end else
begin
isLabeledTick := IsMultipleOf(Y, MAJOR_DIST[FUseUnit]) and (Y <> 0);
if isLabeledTick then
begin
if UseUnit = ruPixels then
S := IntToStr(PY)
else
S := IntToStr(Round(Y));
R := Rect(0, PY - TextHeight(S), w, PY + TextHeight(S));
ts.Layout := tlCenter;
TextRect(R, R.Left, R.Top, S, ts);
//Windows.DrawText(Handle, PChar(S), Length(S), R, DT_SINGLELINE or DT_VCENTER);
end;
isLongTick := isLabeledTick or (IsMultipleOf(2*Y, MAJOR_DIST[FUseUnit]) and (FMinorTickCount > 1));
tickLength := IfThen(isLongTick, FMajorTickLength, FMinorTickLength);
MoveTo(w - baselineOffset - tickLength, PY);
LineTo(w - baselineOffset, PY);
end;
X := X + delta;
Y := Y + delta;
end;
end;
// Draw Position marker
if FShowPositionMarker and (Position > 0.0) then
begin
markerSizeL := FMarkerSize;
markerSizeS := FMarkerSize div 2;
case Orientation of
roHorizontal:
begin
Pts[0] := Point(Pos - markerSizeS, h - markerSizeL - baseLineOffset);
Pts[1] := Point(Pos + markerSizeS, h - markerSizeL - baseLineOffset);
Pts[2] := Point(Pos, h - baselineOffset);
end;
roVertical:
begin
Pts[0] := Point(w - markerSizeL - baselineOffset, Pos - markerSizeS);
Pts[1] := Point(w - markerSizeL - baselineOffset, Pos + markerSizeS);
Pts[2] := Point(w - baselineOffset, Pos);
end;
end;
with Canvas do
begin
Pen.Color := FMarkerColor;
Brush.Color := FMarkerColor;
if FMarkerFilled then
Brush.Style := bsSolid
else
Brush.Style := bsClear;
Polygon(Pts);
end;
{
if Orientation = roHorizontal then
begin
MoveTo(Pos - markerSizeS, h - markerSizeL - baselineOffset);
LineTo(Pos + markerSizeS, h - markerSizeL - baselineOffset);
LineTo(Pos, h - baselineOffset);
LineTo(Pos - markerSizeS, h - markerSizeL - baselineOffset);
end else
begin
MoveTo(w - markerSizeL - baselineOffset, Pos - markerSizeS);
LineTo(w - markerSizeL - baselineOffset, Pos + markerSizeS);
LineTo(w - baselineOffset, Pos);
LineTo(w - markerSizeL - baselineOffset, Pos - markersizeS);
end;
}
end;
end;
procedure TJvRuler.SetMarkerColor(const Value: TColor);
begin
if FMarkerColor <> Value then
begin
FMarkerColor := Value;
Invalidate;
end;
end;
procedure TJvRuler.SetMarkerFilled(const Value: Boolean);
begin
if FMarkerFilled <> Value then
begin
FMarkerFilled := Value;
Invalidate;
end;
end;
procedure TJvRuler.SetMarkerSize(const Value: Integer);
begin
if FMarkerSize <> Value then
begin
FMarkerSize := abs(Value);
Invalidate;
end;
end;
procedure TJvRuler.SetMajorTickLength(const Value: Integer);
begin
if FMajorTickLength <> Value then
begin
FMajorTickLength := abs(Value);
Invalidate;
end;
end;
procedure TJvRuler.SetMinorTickCount(const Value: Integer);
begin
if FMinorTickCount <> Value then
begin
FMinorTickCount := abs(Value);
Invalidate;
end;
end;
procedure TJvRuler.SetMinorTickLength(const Value: Integer);
begin
if FMinorTickLength <> Value then
begin
FMinorTickLength := abs(Value);
Invalidate;
end;
end;
procedure TJvRuler.SetOrientation(const Value: TJvRulerOrientation);
begin
if FOrientation <> Value then
begin
FOrientation := Value;
if ([csDesigning, csLoading] * ComponentState = [csDesigning]) then
SetBounds(Left, Top, Height, Width);
Invalidate;
end;
end;
procedure TJvRuler.SetPosition(const Value: Double);
begin
if FPosition <> Value then
begin
FPosition := Value;
Invalidate;
end;
end;
procedure TJvRuler.SetShowBaseline(const Value: Boolean);
begin
if FShowBaseLine <> Value then
begin
FShowBaseLine := Value;
Invalidate;
end;
end;
procedure TJvRuler.SetShowPositionMarker(const Value: Boolean);
begin
if FShowPositionMarker <> Value then
begin
FShowPositionMarker := Value;
Invalidate;
end;
end;
procedure TJvRuler.SetTickColor(const Value: TColor);
begin
if FTickColor <> Value then
begin
FTickColor := Value;
Invalidate;
end;
end;
procedure TJvRuler.SetUseUnit(const Value: TJvRulerUnit);
begin
if FUseUnit <> Value then
begin
FUseUnit := Value;
Invalidate;
end;
end;
end.
|
(**********************************************************************************)
(* Code generated with NexusDB Enterprise Manager Data Dictionary Code Generator *)
(* *)
(* Version: 3,0401 *)
(* *)
(**********************************************************************************)
unit ncProdD;
interface
uses
nxdb,
nxsdTypes,
nxsdDataDictionary;
procedure BuildDatabase(aDatabase : TnxDatabase;
const aPassword : String = '');
function TableCount: Integer;
function GetTableDictionary(aDatabase : TnxDatabase; const aTableName : String): TnxDataDictionary;
implementation
uses
{$IFDEF NXWINAPI}nxWinAPI{$ELSE}Windows{$ENDIF},
Classes,
Math,
SysUtils,
StrUtils,
Variants,
DBCommon,
nxllTypes,
nxllBde,
nxllException,
nxllWideString,
nxsdConst,
nxsdDataDictionaryStrings,
nxsdDataDictionaryRefInt,
nxsdDataDictionaryFulltext,
nxsdFilterEngineSimpleExpression,
nxsdFilterEngineSql,
nxsdServerEngine,
nxsdTableMapperDescriptor;
type
TnxcgCreateDictCallback = function(aDatabase : TnxDatabase): TnxDataDictionary;
// prodd
function __prodd(aDatabase : TnxDatabase): TnxDataDictionary;
begin
Result := TnxDataDictionary.Create;
try
with Result do begin
AddRecordDescriptor(TnxBaseRecordDescriptor);
with FieldsDescriptor do begin
AddField('codbar', '', nxtShortString, 14, 0, True);
AddField('fk_user', '', nxtInt32, 10, 0, False);
AddField('descricao', '', nxtShortString, 55, 0, False);
AddField('unid', '', nxtShortString, 5, 0, False);
AddField('imagem', '', nxtBLOBGraphic, 0, 0, False);
AddField('md5', '', nxtShortString, 32, 0, False);
AddField('categoria', '', nxtShortString, 35, 0, False);
with AddField('id_upd', '', nxtWord32, 10, 0, True) do
with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do
AsVariant := 1;
end;
with EnsureIndicesDescriptor do begin
with AddIndex('pk', 0, idNone), KeyDescriptor as TnxCompKeyDescriptor do
Add(GetFieldFromName('codbar'));
with AddIndex('fk_user', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do
Add(GetFieldFromName('fk_user'));
with AddIndex('uq_codbar', 0, idNone), KeyDescriptor as TnxCompKeyDescriptor do begin
Add(GetFieldFromName('codbar'));
Add(GetFieldFromName('fk_user'));
end;
with AddIndex('ix_descricao', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do
Add(GetFieldFromName('descricao'));
with AddIndex('ix_unid', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do
Add(GetFieldFromName('unid'));
with AddIndex('ix_categoria', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do
Add(GetFieldFromName('categoria'));
with AddIndex('ix_md5', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do
Add(GetFieldFromName('md5'));
with AddIndex('ix_upd', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do
with Add(GetFieldFromName('id_upd')) do begin
Ascend := False;
NullBehaviour := nbBottom;
end;
if GetIndexFromName('Sequential Access Index') >= 0 then
RemoveIndex(GetIndexFromName('Sequential Access Index'));
end;
CheckValid(False);
end;
except
FreeAndNil(Result);
raise;
end;
end;
type
TnxcgTableInfo = record
TableName : String;
Callback : TnxcgCreateDictCallback;
end;
const
TableInfos : array[0..0] of TnxcgTableInfo =
((TableName : 'prodd'; Callback : __prodd));
function TableCount: Integer;
begin
Result := Length(TableInfos);
end;
function GetTableDictionary(aDatabase : TnxDatabase; const aTableName : String): TnxDataDictionary;
var
I : Integer;
begin
Result := nil;
for I := Low(TableInfos) to High(TableInfos) do
if SameText(aTableName, TableInfos[I].TableName) then begin
Result := TableInfos[I].Callback(aDatabase);
break;
end;
end;
procedure BuildTable(aDatabase : TnxDatabase;
const aTableName, aPassword : String;
aCreateDictCallback : TnxcgCreateDictCallback);
var
Dict : TnxDataDictionary;
begin
Dict := aCreateDictCallback(aDatabase);
if Assigned(Dict) then
try
if not aDatabase.TableExists(aTableName, aPassword) then
aDatabase.CreateTable(False, aTableName, aPassword, Dict);
finally
Dict.Free;
end;
end;
procedure BuildDatabase(aDatabase : TnxDatabase;
const aPassword : String);
var
I : Integer;
begin
for I := Low(TableInfos) to High(TableInfos) do
BuildTable(aDatabase,
TableInfos[I].TableName, aPassword,
TableInfos[I].Callback);
end;
end.
|
unit untIniIO;
interface
uses
Classes, SysUtils, IniFiles, Forms, Windows;
const
csIniDataConfigSection = 'DataConfig';
{Section: DataConfig}
csIniDataConfigserverAddr = 'serverAddr';
csIniDataConfigserverName = 'serverName';
csIniDataConfigserverPort = 'serverPort';
csIniDataConfiguserName = 'userName';
csIniDataConfigpassword = 'password';
type
TIniOptions = class(TObject)
private
{Section: DataConfig}
FDataConfigserverAddr: string;
FDataConfigserverName: string;
FDataConfigserverPort: string;
FDataConfiguserName: string;
FDataConfigpassword: string;
public
procedure LoadSettings(Ini: TIniFile);
procedure SaveSettings(Ini: TIniFile);
procedure LoadFromFile(const FileName: string);
procedure SaveToFile(const FileName: string);
{Section: DataConfig}
property DataConfigserverAddr: string read FDataConfigserverAddr write FDataConfigserverAddr;
property DataConfigserverName: string read FDataConfigserverName write FDataConfigserverName;
property DataConfigserverPort: string read FDataConfigserverPort write FDataConfigserverPort;
property DataConfiguserName: string read FDataConfiguserName write FDataConfiguserName;
property DataConfigpassword: string read FDataConfigpassword write FDataConfigpassword;
end;
var
IniOptions: TIniOptions = nil;
implementation
procedure TIniOptions.LoadSettings(Ini: TIniFile);
begin
if Ini <> nil then
begin
{Section: DataConfig}
FDataConfigserverAddr := Ini.ReadString(csIniDataConfigSection, csIniDataConfigserverAddr, '10.21.1.230');
FDataConfigserverName := Ini.ReadString(csIniDataConfigSection, csIniDataConfigserverName, 'vegaga');
FDataConfigserverPort := Ini.ReadString(csIniDataConfigSection, csIniDataConfigserverPort, '3306');
FDataConfiguserName := Ini.ReadString(csIniDataConfigSection, csIniDataConfiguserName, 'root');
FDataConfigpassword := Ini.ReadString(csIniDataConfigSection, csIniDataConfigpassword, 'root');
end;
end;
procedure TIniOptions.SaveSettings(Ini: TIniFile);
begin
if Ini <> nil then
begin
{Section: DataConfig}
Ini.WriteString(csIniDataConfigSection, csIniDataConfigserverAddr, FDataConfigserverAddr);
Ini.WriteString(csIniDataConfigSection, csIniDataConfigserverName, FDataConfigserverName);
Ini.WriteString(csIniDataConfigSection, csIniDataConfigserverPort, FDataConfigserverPort);
Ini.WriteString(csIniDataConfigSection, csIniDataConfiguserName, FDataConfiguserName);
Ini.WriteString(csIniDataConfigSection, csIniDataConfigpassword, FDataConfigpassword);
end;
end;
procedure TIniOptions.LoadFromFile(const FileName: string);
var
Ini: TIniFile;
begin
if FileExists(FileName) then
begin
Ini := TIniFile.Create(FileName);
try
LoadSettings(Ini);
finally
Ini.Free;
end;
end;
end;
procedure TIniOptions.SaveToFile(const FileName: string);
var
Ini: TIniFile;
begin
Ini := TIniFile.Create(FileName);
try
SaveSettings(Ini);
finally
Ini.Free;
end;
end;
initialization
IniOptions := TIniOptions.Create;
finalization
IniOptions.Free;
end.
|
unit MsgLog;
interface
uses
Classes,
Graphics;
type
TLog = class(TObject)
private
FMsg: string;
FLog: TStringList;
public
constructor Create;
destructor Destroy; override;
procedure Turn;
procedure Add(const Msg: string);
function Get: string;
procedure Render(Canvas: TCanvas);
end;
var
Log: TLog;
implementation
uses
SysUtils,
WorldMap;
{ TLog }
procedure TLog.Add(const Msg: string);
begin
FMsg := FMsg + Trim(Msg) + ' ';
end;
constructor TLog.Create;
begin
FLog := TStringList.Create;
FMsg := '';
end;
destructor TLog.Destroy;
begin
FreeAndNil(FLog);
inherited;
end;
function TLog.Get: string;
begin
Result := Trim(FMsg);
end;
procedure TLog.Render(Canvas: TCanvas);
begin
Canvas.TextOut(0, Map.GetCurrentMap.TileSize * (Map.GetCurrentMap.Height + 4) + 16, Get);
end;
procedure TLog.Turn;
begin
if FMsg <> '' then
begin
FLog.Append(Get);
FMsg := '';
end;
end;
initialization
Log := TLog.Create;
finalization
FreeAndNil(Log);
end.
|
{**********************************************}
{ TTriSurfaceSeries Editor Dialog }
{ Copyright (c) 1996-2004 by David Berneda }
{**********************************************}
unit TeeTriSurfEdit;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls,
{$ENDIF}
{$IFDEF CLR}
Variants,
{$ENDIF}
Chart, TeeSurfa, TeeTriSurface, TeCanvas, TeePenDlg, TeeProcs;
type
TTriSurfaceSeriesEditor = class(TForm)
Button2: TButtonPen;
Button3: TButton;
Button1: TButtonPen;
CBFastBrush: TCheckBox;
CBHide: TCheckBox;
ETransp: TEdit;
UDTransp: TUpDown;
LHeight: TLabel;
procedure FormShow(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure CBFastBrushClick(Sender: TObject);
procedure CBHideClick(Sender: TObject);
procedure ETranspChange(Sender: TObject);
private
{ Private declarations }
Surface : TTriSurfaceSeries;
Grid3DForm : TCustomForm;
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses TeeBrushDlg, TeeGriEd;
procedure TTriSurfaceSeriesEditor.FormShow(Sender: TObject);
begin
Surface:=TTriSurfaceSeries(Tag);
if Assigned(Surface) then
begin
Button2.LinkPen(Surface.Pen);
Button1.LinkPen(Surface.Border);
CBFastBrush.Checked:=Surface.FastBrush;
CBHide.Checked:=Surface.HideTriangles;
UDTransp.Position:=Surface.Transparency;
if not Assigned(Grid3DForm) then
Grid3DForm:=TeeInsertGrid3DForm(Parent,Surface);
end;
end;
procedure TTriSurfaceSeriesEditor.Button3Click(Sender: TObject);
begin
EditChartBrush(Self,Surface.Brush);
end;
procedure TTriSurfaceSeriesEditor.FormCreate(Sender: TObject);
begin
BorderStyle:=TeeBorderStyle;
end;
procedure TTriSurfaceSeriesEditor.CBFastBrushClick(Sender: TObject);
begin
Surface.FastBrush:=CBFastBrush.Checked;
end;
procedure TTriSurfaceSeriesEditor.CBHideClick(Sender: TObject);
begin
Surface.HideTriangles:=CBHide.Checked;
end;
procedure TTriSurfaceSeriesEditor.ETranspChange(Sender: TObject);
begin
if Showing then
Surface.Transparency:=UDTransp.Position;
end;
initialization
RegisterClass(TTriSurfaceSeriesEditor);
end.
|
PROGRAM test;
VAR
x : integer;
BEGIN
writeln('Hello world');
x := 5;
writeln('x = ', x);
writeln('third');
END.
|
unit Pizzaria;
interface
uses
System.SysUtils, InterfacePizzaria;
type
TPizzaria = class(TInterfacedObject, IPizzaria)
private
Pizza: string;
public
constructor Create(Pizza: string);
procedure EntregarPizzas;
procedure ReceberDinheiro;
end;
implementation
{ TPizzaria }
constructor TPizzaria.Create(Pizza: string);
begin
Self.Pizza := Pizza;
end;
procedure TPizzaria.EntregarPizzas;
begin
Writeln('Pizza de ' + Pizza + 'Saiu para entrega');
end;
procedure TPizzaria.ReceberDinheiro;
begin
Writeln('Pizza de ' + Pizza + ' foi entregue e o dinheiro foi recebido com sucesso...');
end;
end.
|
program client;
{$APPTYPE CONSOLE}
uses
SysUtils,
ScktComp,
StdCtrls;
type
_Client = class
socket: TClientSocket; // объект класса TClientSocket для соединения с сервером
text: string; // сообщение
procedure connect(); // метод соединения с сервером
procedure send(); // метод отправки сообщения
procedure disconnect(); // метод отсоединения от сервера
end;
procedure _Client.connect();
begin
socket := TClientSocket.Create(nil); // Инициализируем объект socket объектом класса TClientSocket
socket.Address := '127.0.0.1'; // Устанавливаем адрес
socket.Port := 13000; // Устанавливаем порт
socket.ClientType := ctBlocking; // Установка сокета в режим блокировки
socket.Open; // Устанавливаем соединение с сервером
if socket.Active then writeln('Подключение выполнено')
else
begin
writeln('Не удалось подключиться');
sleep(3000);
Halt; // Завершение программы
end;
end;
procedure _Client.send();
begin
readln(text); // Получаем сообщение в переменную text
socket.Socket.SendText(text + sLineBreak); // Отправляем сообщение с разделителем строки
end;
procedure _Client.disconnect();
begin
socket.Free; // Отсоединение от сервера
writeln('Отключено');
end;
var
client: _Client;
ch: string;
begin
client := _Client.Create(); // Инициализируем объект client объектом класса _Client
client.connect(); // Подключаемся к серверу
repeat
client.send(); // Отправляем сообщения в цикле
write('Хотите ещё отправить сообщение (y/n): ');
readln(ch);
until ch = 'n';
client.disconnect(); // Отключаемся от сервера
sleep(1000);
end. |
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//------------------------------------------------------------------------------}
unit untPlugParamsOP;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, untEasyEdit, untEasyButtons, untEasyPlateManager,
untEasyClassPluginDirectory;
type
TfrmPlugParamsOP = class(TForm)
edtCName: TEasyLabelEdit;
edtParam: TEasyLabelEdit;
btnOK: TEasyBitButton;
btnCancel: TEasyBitButton;
procedure btnCancelClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
private
{ Private declarations }
FAData: TEasysysPluginParam;
public
{ Public declarations }
end;
var
frmPlugParamsOP: TfrmPlugParamsOP;
procedure ShowfrmPlugParamsOP(var AData: TEasysysPluginParam; AFlag: string);
implementation
{$R *.dfm}
uses
untEasyUtilMethod;
procedure ShowfrmPlugParamsOP(var AData: TEasysysPluginParam; AFlag: string);
begin
try
frmPlugParamsOP := TfrmPlugParamsOP.Create(Application);
if AFlag = 'Add' then
begin
frmPlugParamsOP.FAData := AData;
frmPlugParamsOP.Caption := frmPlugParamsOP.Caption + '-【新增】';
end
else
if AFlag = 'Edit' then
begin
with frmPlugParamsOP do
begin
Caption := frmPlugParamsOP.Caption + '-【编辑】';
edtCName.Text := AData.ParamName;
edtParam.Text := AData.Value;
end;
frmPlugParamsOP.FAData := AData;
end;
frmPlugParamsOP.ShowModal;
finally
FreeAndNil(frmPlugParamsOP);
end;
end;
procedure TfrmPlugParamsOP.btnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmPlugParamsOP.btnOKClick(Sender: TObject);
begin
if Trim(edtCName.Text) = '' then
begin
Application.MessageBox('参数名称不能为空!', '提示', MB_OK +
MB_ICONINFORMATION);
Exit;
end;
if Trim(edtParam.Text) = '' then
begin
Application.MessageBox('参数值不能为空!', '提示', MB_OK +
MB_ICONINFORMATION);
Exit;
end;
FAData.ParamName := Trim(edtCName.Text);
FAData.ValueType := 'S';
FAData.Value := Trim(edtParam.Text);
Close;
end;
end.
|
{ Functions to compute MD5 message digest of files or memory blocks,
according to the definition of MD5 in RFC 1321 from April 1992.
Copyright (C) 1995, 1996, 2000-2005 Free Software Foundation, Inc.
Author: Frank Heckenbach <frank@pascal.gnu.de>
Based on the C code written by Ulrich Drepper
<drepper@gnu.ai.mit.edu>, 1995 as part of glibc.
This file is part of GNU Pascal.
GNU Pascal is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as
published by the Free Software Foundation, version 2.
GNU Pascal is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; see the file COPYING.LIB. If not,
write to the Free Software Foundation, Inc., 59 Temple Place -
Suite 330, Boston, MA 02111-1307, USA. }
{$gnu-pascal,I-}
{$if __GPC_RELEASE__ < 20030303}
{$error This unit requires GPC release 20030303 or newer.}
{$endif}
unit MD5;
interface
uses GPC;
{ Representation of a MD5 value. It is always in little endian byte
order and therefore portable. }
type
Card8 = Cardinal attribute (Size = 8);
TMD5 = array [1 .. 16] of Card8;
const
MD5StrLength = 2 * High (TMD5);
type
MD5String = String (MD5StrLength);
{ Computes MD5 message digest for Length bytes in Buffer. }
procedure MD5Buffer (const Buffer; Length: SizeType; var MD5: TMD5);
{ Computes MD5 message digest for the contents of the file f. }
procedure MD5File (var f: File; var MD5: TMD5); attribute (iocritical);
{ Initializes a MD5 value with zeros. }
procedure MD5Clear (var MD5: TMD5);
{ Compares two MD5 values for equality. }
function MD5Compare (const Value1, Value2: TMD5): Boolean;
{ Converts an MD5 value to a string. }
function MD5Str (const MD5: TMD5) = s: MD5String;
{ Converts a string to an MD5 value. Returns True if successful. }
function MD5Val (const s: String; var MD5: TMD5): Boolean;
{ Composes two MD5 values to a single one. }
function MD5Compose (const Value1, Value2: TMD5) = Dest: TMD5;
implementation
type
Card32 = Cardinal attribute (Size = 32);
Card64 = Cardinal attribute (Size = 64);
TABCD = array [0 .. 3] of Card32;
{ Structure to save state of computation between the single steps. }
TCtx = record
ABCD: TABCD;
Total: Card64;
BufLen: Card32;
Buffer: array [0 .. 127] of Card8
end;
{ Initialize structure containing state of computation. (RFC 1321, 3.3: Step 3) }
procedure InitCtx (var Ctx: TCtx);
const InitABCD: TABCD = ($67452301, $efcdab89, $98badcfe, $10325476);
begin
Ctx.ABCD := InitABCD;
Ctx.Total := 0;
Ctx.BufLen := 0
end;
{ Process Length bytes of Buffer, accumulating context into Ctx.
It is necessary that Length is a multiple of 64! }
procedure ProcessBlock (const Buffer; Length: SizeType; var Ctx: TCtx);
var
ABCD, Save: TABCD;
i: Integer;
WordsTotal: SizeType = Length div SizeOf (Card32);
WordsDone: SizeType;
WordBuffer: array [0 .. Max (0, WordsTotal - 1)] of Card32 absolute Buffer;
CorrectWords: array [0 .. 15] of Card32;
n: Card32;
begin
Assert (Length mod 64 = 0);
{ First increment the byte count. RFC 1321 specifies the possible length
of the file up to 2^64 bits. Here we only compute the number of bytes. }
Inc (Ctx.Total, Length);
{ Process all bytes in the buffer with 64 bytes in each round of the loop. }
ABCD := Ctx.ABCD;
WordsDone := 0;
while WordsDone < WordsTotal do
begin
Save := ABCD;
i := 0;
{ These are the four functions used in the four steps of the MD5 algorithm
and defined in the RFC 1321. The first function is a little bit optimized
(as found in Colin Plumbs public domain implementation). }
{.$define FF(b, c, d) ((b and c) or (not b and d))}
{$define FF(b, c, d) (d xor (b and (c xor d)))}
{$define FG(b, c, d) FF (d, b, c)}
{$define FH(b, c, d) (b xor c xor d)}
{$define FI(b, c, d) (c xor (b or not d))}
{$define RotLeft(w, s) w := (w shl s) or (w shr (32 - s))} { cyclic rotation }
{ First round: using the given function, the context and a constant
the next context is computed. Because the algorithms processing
unit is a 32-bit word and it is determined to work on words in
little endian byte order we perhaps have to change the byte order
before the computation. To reduce the work for the next steps
we store the swapped words in the array CorrectWords. }
{$ifdef __BYTES_BIG_ENDIAN__}
{$define Swap(n)
begin
n := (n shl 16) or (n shr 16);
n := ((n and $ff00ff) shl 8) or ((n and $ff00ff00) shr 8)
end}
{$elif defined (__BYTES_LITTLE_ENDIAN__)}
{$define Swap(n)}
{$else}
{$error Endianness is not defined!}
{$endif}
{$define OP1(a, b, c, d, s, T)
begin
n := WordBuffer[WordsDone];
Inc (WordsDone);
Swap (n);
CorrectWords[i] := n;
Inc (i);
Inc (a, FF (b, c, d) + n + T);
RotLeft (a, s);
Inc (a, b)
end}
{$define A ABCD[0]}
{$define B ABCD[1]}
{$define C ABCD[2]}
{$define D ABCD[3]}
{ Before we start, one word to the strange constants. They are defined
in RFC 1321 as T[i] = Trunc (4294967296 * Abs (Sin (i))), i = 1 .. 64 }
{ Round 1. }
{$local R-} { `Inc' is expected to wrap-around }
OP1 (A, B, C, D, 7, $d76aa478);
OP1 (D, A, B, C, 12, $e8c7b756);
OP1 (C, D, A, B, 17, $242070db);
OP1 (B, C, D, A, 22, $c1bdceee);
OP1 (A, B, C, D, 7, $f57c0faf);
OP1 (D, A, B, C, 12, $4787c62a);
OP1 (C, D, A, B, 17, $a8304613);
OP1 (B, C, D, A, 22, $fd469501);
OP1 (A, B, C, D, 7, $698098d8);
OP1 (D, A, B, C, 12, $8b44f7af);
OP1 (C, D, A, B, 17, $ffff5bb1);
OP1 (B, C, D, A, 22, $895cd7be);
OP1 (A, B, C, D, 7, $6b901122);
OP1 (D, A, B, C, 12, $fd987193);
OP1 (C, D, A, B, 17, $a679438e);
OP1 (B, C, D, A, 22, $49b40821);
{ For the second to fourth round we have the possibly swapped words
in CorrectWords. Define a new macro to take an additional first
argument specifying the function to use. }
{$define OP(f, a, b, c, d, k, s, T)
begin
Inc (a, f (b, c, d) + CorrectWords[k] + T);
RotLeft (a, s);
Inc (a, b)
end}
{ Round 2. }
OP (FG, A, B, C, D, 1, 5, $f61e2562);
OP (FG, D, A, B, C, 6, 9, $c040b340);
OP (FG, C, D, A, B, 11, 14, $265e5a51);
OP (FG, B, C, D, A, 0, 20, $e9b6c7aa);
OP (FG, A, B, C, D, 5, 5, $d62f105d);
OP (FG, D, A, B, C, 10, 9, $02441453);
OP (FG, C, D, A, B, 15, 14, $d8a1e681);
OP (FG, B, C, D, A, 4, 20, $e7d3fbc8);
OP (FG, A, B, C, D, 9, 5, $21e1cde6);
OP (FG, D, A, B, C, 14, 9, $c33707d6);
OP (FG, C, D, A, B, 3, 14, $f4d50d87);
OP (FG, B, C, D, A, 8, 20, $455a14ed);
OP (FG, A, B, C, D, 13, 5, $a9e3e905);
OP (FG, D, A, B, C, 2, 9, $fcefa3f8);
OP (FG, C, D, A, B, 7, 14, $676f02d9);
OP (FG, B, C, D, A, 12, 20, $8d2a4c8a);
{ Round 3. }
OP (FH, A, B, C, D, 5, 4, $fffa3942);
OP (FH, D, A, B, C, 8, 11, $8771f681);
OP (FH, C, D, A, B, 11, 16, $6d9d6122);
OP (FH, B, C, D, A, 14, 23, $fde5380c);
OP (FH, A, B, C, D, 1, 4, $a4beea44);
OP (FH, D, A, B, C, 4, 11, $4bdecfa9);
OP (FH, C, D, A, B, 7, 16, $f6bb4b60);
OP (FH, B, C, D, A, 10, 23, $bebfbc70);
OP (FH, A, B, C, D, 13, 4, $289b7ec6);
OP (FH, D, A, B, C, 0, 11, $eaa127fa);
OP (FH, C, D, A, B, 3, 16, $d4ef3085);
OP (FH, B, C, D, A, 6, 23, $04881d05);
OP (FH, A, B, C, D, 9, 4, $d9d4d039);
OP (FH, D, A, B, C, 12, 11, $e6db99e5);
OP (FH, C, D, A, B, 15, 16, $1fa27cf8);
OP (FH, B, C, D, A, 2, 23, $c4ac5665);
{ Round 4. }
OP (FI, A, B, C, D, 0, 6, $f4292244);
OP (FI, D, A, B, C, 7, 10, $432aff97);
OP (FI, C, D, A, B, 14, 15, $ab9423a7);
OP (FI, B, C, D, A, 5, 21, $fc93a039);
OP (FI, A, B, C, D, 12, 6, $655b59c3);
OP (FI, D, A, B, C, 3, 10, $8f0ccc92);
OP (FI, C, D, A, B, 10, 15, $ffeff47d);
OP (FI, B, C, D, A, 1, 21, $85845dd1);
OP (FI, A, B, C, D, 8, 6, $6fa87e4f);
OP (FI, D, A, B, C, 15, 10, $fe2ce6e0);
OP (FI, C, D, A, B, 6, 15, $a3014314);
OP (FI, B, C, D, A, 13, 21, $4e0811a1);
OP (FI, A, B, C, D, 4, 6, $f7537e82);
OP (FI, D, A, B, C, 11, 10, $bd3af235);
OP (FI, C, D, A, B, 2, 15, $2ad7d2bb);
OP (FI, B, C, D, A, 9, 21, $eb86d391);
{ Add the starting values of the context. }
for i := 0 to 3 do
Inc (ABCD[i], Save[i])
{$endlocal}
{$undef FF}
{$undef FG}
{$undef FH}
{$undef FI}
{$undef RotLeft}
{$undef Swap}
{$undef OP1}
{$undef A}
{$undef B}
{$undef C}
{$undef D}
{$undef OP}
end;
Ctx.ABCD := ABCD
end;
{ Starting with the result of former calls to this function (or
InitCtx) update the context for the next Length bytes in Buffer.
It is not required that Length is a multiple of 64. }
procedure ProcessBytes (const aBuffer; Length: SizeType; var Ctx: TCtx);
var
BytesDone, Block, LeftOver: SizeType;
ByteBuffer: array [0 .. Max (0, Length - 1)] of Card8 absolute aBuffer;
begin
BytesDone := 0;
{ When we already have some bits in our internal buffer concatenate both inputs first. }
with Ctx do
if BufLen <> 0 then
begin
LeftOver := BufLen;
BytesDone := Min (128 - LeftOver, Length);
Move (ByteBuffer, Buffer[LeftOver], BytesDone);
Inc (BufLen, BytesDone);
if BufLen > 64 then
begin
Block := BufLen div 64 * 64;
ProcessBlock (Buffer, Block, Ctx);
BufLen := BufLen mod 64;
Move (Buffer[Block], Buffer, BufLen) { source and destination cannot overlap }
end;
Dec (Length, BytesDone)
end;
{ Process available complete blocks. }
if Length > 64 then
begin
Block := Length div 64 * 64;
ProcessBlock (ByteBuffer[BytesDone], Block, Ctx);
Inc (BytesDone, Block);
Dec (Length, Block)
end;
{ Move remaining bytes into internal buffer. }
if Length > 0 then
begin
Move (ByteBuffer[BytesDone], Ctx.Buffer, Length);
Ctx.BufLen := Length
end
end;
{ Process the remaining bytes in the buffer and put result from Ctx into MD5. }
procedure FinishCtx (var Ctx: TCtx; var MD5: TMD5);
var i, j, Pad: Integer;
begin
with Ctx do
begin
Pad := 56 - BufLen;
if Pad <= 0 then Inc (Pad, 64);
if Pad > 0 then
begin
Buffer[BufLen] := $80;
FillChar (Buffer[BufLen + 1], Pad - 1, 0)
end;
Inc (Total, BufLen);
{ Put the 64-bit total length in *bits* at the end of the buffer. }
for j := 0 to 7 do
Buffer[BufLen + Pad + j] := ((Total * BitSizeOf (Card8)) shr (8 * j)) and $ff;
ProcessBlock (Buffer, BufLen + Pad + 8, Ctx);
for i := 0 to 3 do
for j := 0 to 3 do
MD5[4 * i + j + 1] := (Ctx.ABCD[i] shr (8 * j)) and $ff
end
end;
procedure MD5Buffer (const Buffer; Length: SizeType; var MD5: TMD5);
var Ctx: TCtx;
begin
InitCtx (Ctx);
ProcessBytes (Buffer, Length, Ctx);
FinishCtx (Ctx, MD5)
end;
procedure MD5File (var f: File; var MD5: TMD5);
var
Ctx: TCtx;
Buffer: array [1 .. 4096] of Card8;
BytesRead: SizeType;
begin
InitCtx (Ctx);
Reset (f, 1);
repeat
BlockRead (f, Buffer, SizeOf (Buffer), BytesRead);
if InOutRes <> 0 then Exit;
ProcessBytes (Buffer, BytesRead, Ctx)
until EOF (f);
FinishCtx (Ctx, MD5)
end;
procedure MD5Clear (var MD5: TMD5);
var i: Integer;
begin
for i := Low (MD5) to High (MD5) do MD5[i] := 0
end;
function MD5Compare (const Value1, Value2: TMD5): Boolean;
var i: Integer;
begin
MD5Compare := False;
for i := Low (Value1) to High (Value1) do
if Value1[i] <> Value2[i] then Exit;
MD5Compare := True
end;
function MD5Str (const MD5: TMD5) = s: MD5String;
var i: Integer;
begin
s := '';
for i := Low (MD5) to High (MD5) do
s := s + NumericBaseDigits[MD5[i] div $10] + NumericBaseDigits[MD5[i] mod $10]
end;
function MD5Val (const s: String; var MD5: TMD5): Boolean;
var i, d1, d2: Integer;
function Char2Digit (ch: Char): Integer;
begin
case ch of
'0' .. '9': Char2Digit := Ord (ch) - Ord ('0');
'A' .. 'Z': Char2Digit := Ord (ch) - Ord ('A') + $a;
'a' .. 'z': Char2Digit := Ord (ch) - Ord ('a') + $a;
else Char2Digit := -1
end
end;
begin
MD5Val := False;
if Length (s) <> 2 * (High (MD5) - Low (MD5) + 1) then Exit;
for i := Low (MD5) to High (MD5) do
begin
d1 := Char2Digit (s[2 * (i - Low (MD5)) + 1]);
d2 := Char2Digit (s[2 * (i - Low (MD5)) + 2]);
if (d1 < 0) or (d1 >= $10) or (d2 < 0) or (d2 >= $10) then Exit;
MD5[i] := $10 * d1 + d2
end;
MD5Val := True
end;
function MD5Compose (const Value1, Value2: TMD5) = Dest: TMD5;
var Buffer: array [1 .. 2] of TMD5;
begin
Buffer[1] := Value1;
Buffer[2] := Value2;
MD5Buffer (Buffer, SizeOf (Buffer), Dest)
end;
end.
|
unit ncShellStart;
{
ResourceString: Dario 13/03/13
}
interface
uses
Windows,
SysUtils,
ShellApi;
procedure ShellStart(aCmd: String; aParams: String=''; aDirectory: String=''; FormHWND: HWND = 0);
procedure ShellStartCustom(aCmd, aParams, aDir: String; FormHWND: HWND; nShow: Integer = SW_SHOWNORMAL; aVerb: String = 'open'; aWait:boolean=false; aWaitTime: cardinal = INFINITE); // do not localize
implementation
procedure ShellStart(aCmd: String; aParams: String=''; aDirectory: String=''; FormHWND: HWND = 0);
begin
ShellStartCustom(aCmd, aParams, aDirectory, FormHWND);
end;
procedure ShellStartCustom(aCmd, aParams, aDir: String; FormHWND: HWND; nShow: Integer = SW_SHOWNORMAL; aVerb: String = 'open'; aWait:boolean=false; aWaitTime: Cardinal = INFINITE); // do not localize
var
ExecInfo: TShellExecuteInfo;
begin
if Trim(aCmd)='' then Exit;
ExecInfo.hProcess := 0;
ExecInfo.cbSize := SizeOf(TShellExecuteInfo);
// if aWait then
ExecInfo.fMask := SEE_MASK_NOCLOSEPROCESS;
ExecInfo.Wnd := FormHWND;
ExecInfo.lpVerb := PChar(aVerb);
ExecInfo.lpFile := PChar(aCmd);
ExecInfo.lpParameters := PChar(aParams);
ExecInfo.lpDirectory := PChar(aDir);
ExecInfo.nShow := nShow;
//open - execute the specified file
ShellExecuteEx(@ExecInfo);
if (ExecInfo.hProcess<>0) then begin
if aWait then
WaitforSingleObject(ExecInfo.hProcess, aWaitTime);
CloseHandle( ExecInfo.hProcess );
end;
end;
end.
|
unit vr_zipper;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, zipper,
{$IFDEF UTILS_MIN}vrUtilsMini{$ELSE}vr_utils, vr_classes{$IFDEF VER3},
LazUTF8{$ENDIF}, FileUtil{$ENDIF};
type
{ TvrZipper }
TvrZipper = class(TZipper)
private
FBasePath: string;
FCaseSensitive: Boolean;
procedure SetBasePath(const AValue: string);
protected
procedure ZipOneFile(Item: TZipFileEntry); override;
public
procedure AfterConstruction; override;
property BasePath: string read FBasePath write SetBasePath;
property CaseSensitive: Boolean read FCaseSensitive write FCaseSensitive;
end;
{$IFNDEF UTILS_MIN}
function zip_Dir(const ADir: string; const ADest: string = '';
const ABasePath: string = ''): Boolean;{$ENDIF}
function zip_ExtractAll(const AFileName, AOutputPath: string): Boolean;
implementation
{$IFNDEF UTILS_MIN}
function zip_Dir(const ADir: string; const ADest: string;
const ABasePath: string): Boolean;
var
zip: TvrZipper;
strs: TStringListUTF8;
I: Integer;
begin
Result := False;
strs := TStringListUTF8.Create;
zip := TvrZipper.Create;
try
zip.BasePath := UTF8ToSys(ABasePath);
if ADest = '' then
zip.FileName := UTF8ToSys(ADir) + '.zip'
else
zip.FileName := UTF8ToSys(ADest);
EnumFilesToStrs(ADir, strs);
for I := 0 to strs.Count - 1 do
strs[I] := UTF8ToSys(strs[I]);
zip.Entries.AddFileEntries(strs);
zip.ZipAllFiles;
Result := True;
finally
zip.Free;
strs.Free;
end;
end;
{$ENDIF}
function zip_ExtractAll(const AFileName, AOutputPath: string): Boolean;
var
zip: TUnZipper;
begin
Result := False;
zip := TUnZipper.Create;
try
try
if not dir_Force(AOutputPath) then Exit;
zip.FileName := UTF8ToSys(AFileName);
zip.OutputPath := UTF8ToSys(AOutputPath);
zip.Examine;//new:6.9.2
zip.UnZipAllFiles;
Result := True;
except
end;
finally
zip.Free;
end;
end;
{ TvrZipper }
procedure TvrZipper.SetBasePath(const AValue: string);
begin
FBasePath := IncludeTrailingPathDelimiter(AValue);
end;
procedure TvrZipper.ZipOneFile(Item: TZipFileEntry);
var
Len: Integer;
function _CompareName(const S1, S2: string): Integer;
begin
if FCaseSensitive then
{%H-}Result := AnsiCompareStr(S1, S2)
else
Result := AnsiCompareText(S1, S2);
end;
begin
if (FBasePath <> '') then
begin
Len := Length(FBasePath);
if _CompareName(Copy(Item.DiskFileName, 1, Len), FBasePath) = 0 then
Item.ArchiveFileName := Copy(Item.DiskFileName, Len + 1, MaxInt);
end;
inherited ZipOneFile(Item);
end;
procedure TvrZipper.AfterConstruction;
begin
inherited AfterConstruction;
FCaseSensitive := FilenamesCaseSensitive;
end;
end.
|
unit uRangeList;
interface
uses Generics.Collections, Generics.Defaults, uRange, uRangeElement,
uDataModule, variants;
type
TRangeList = class(TObject)
private
FRangeList: TDictionary<Integer, TRange>;
procedure AddRangeToDB(aRange: TRange);
procedure AddElementToDB(aRangeElement: TRangeElement);
public
constructor Create;
procedure Add(const aRange: TRange);
function GetRangeByID(aRange_ID: Integer): TRange;
procedure LoadFromDB;
procedure SaveToDB;
end;
implementation
constructor TRangeList.Create;
begin
inherited;
FRangeList := TDictionary<Integer, TRange>.Create;
end;
procedure TRangeList.Add(const aRange: TRange);
begin
FRangeList.Add(aRange.Range_ID, aRange);
end;
function TRangeList.GetRangeByID(aRange_ID: Integer): TRange;
begin
result := nil;
if FRangeList.ContainsKey(aRange_ID) then
result := FRangeList.Items[aRange_ID];
end;
procedure TRangeList.LoadFromDB;
var
aRange: TRange;
aRangeElement: TRangeElement;
aRangeSubElement: TRangeElement;
begin
FRangeList.Clear;
with dmDataModule.tblRange do
begin
if active = false then
open;
first;
while not EOF do
begin
aRange := TRange.Create(FieldbyName('Range_ID').AsInteger,
FieldbyName('Description').AsString);
Add(aRange);
next;
end;
end;
with dmDataModule.tblRangeElement do
begin
if active = false then
open;
first;
while not EOF do
begin
aRangeElement := TRangeElement.Create(FieldbyName('Range_ID').AsInteger,
FieldbyName('Element_ID').AsInteger,
FieldbyName('Description').AsString,
FieldbyName('SizeDesc').AsString, FieldbyName('ColourDesc').AsString,
FieldbyName('Quantity').AsInteger);
aRange := GetRangeByID(FieldbyName('Range_ID').AsInteger);
if assigned(aRange) then
begin
aRange.AddRangeElement(aRangeElement)
end;
next;
end;
end;
with dmDataModule.tblRangeSubElement do
begin
if active = false then
open;
first;
while not EOF do
begin
aRange := GetRangeByID(FieldbyName('Range_ID').AsInteger);
if assigned(aRange) then
begin
aRangeElement := aRange.GetElementByID
(FieldbyName('Element_ID').AsInteger);
aRangeSubElement := aRange.GetElementByID
(FieldbyName('SubElement_ID').AsInteger);
if assigned(aRangeElement) and assigned(aRangeSubElement) then
begin
aRangeElement.AddRangeElement(aRangeSubElement);
aRange.RemoveElementById(aRangeSubElement.Element_ID);
end;
end;
next;
end;
end;
end;
procedure TRangeList.SaveToDB;
var
aRange: TRange;
aRangeElement: TRangeElement;
key1, key2: Integer;
begin
with dmDataModule.tblRangeSubElement do
begin
if not Active then Open;
First;
while recordcount>0 do
begin
delete;
end;
end;
with dmDataModule.tblRangeElement do
begin
if not Active then Open;
First;
while recordcount>0 do
begin
delete;
end;
end;
with dmDataModule.tblRange do
begin
if not Active then Open;
First;
while recordcount>0 do
begin
delete;
end;
end;
for key1 in FRangeList.Keys do
begin
aRange := FRangeList.Items[key1];
AddRangeToDB(aRange);
for key2 in aRange.Elements.Keys do
begin
aRangeElement := aRange.Elements.Items[key2];
AddElementToDB(aRangeElement);
end;
end;
end;
procedure TRangeList.AddRangeToDB(aRange: TRange);
begin
with dmDataModule.tblRange do
begin
append;
FieldByName('Range_ID').Value := aRange.Range_ID;
FieldByName('Description').Value := aRange.Description;
post;
end;
end;
procedure TRangeList.AddElementToDB(aRangeElement: TRangeElement);
var
key : Integer;
aRangeSubElement: TRangeElement;
begin
with dmDataModule.tblRangeElement do
begin
append;
FieldByName('Range_ID').Value := aRangeElement.Range_ID;
FieldByName('Element_ID').Value := aRangeElement.Element_ID;
FieldByName('Description').Value := aRangeElement.Description;
FieldByName('SizeDesc').Value := aRangeElement.SizeDesc;
FieldByName('ColourDesc').Value := aRangeElement.ColourDesc;
FieldByName('Quantity').Value := aRangeElement.Quantity;
post;
end;
for key in aRangeElement.Elements.Keys do
begin
aRangeSubElement := aRangeElement.Elements.Items[key];
AddElementToDB(aRangeSubElement);
with dmDataModule.tblRangeSubElement do
begin
append;
FieldByName('Range_ID').Value := aRangeElement.Range_ID;
FieldByName('Element_ID').Value := aRangeElement.Element_ID;
FieldByName('SubElement_ID').Value := aRangeSubElement.Element_ID;
post;
end;
end;
end;
end.
|
unit fPtDemo;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, ORCtrls, ORFn, ComCtrls, fBase508Form,
VA508AccessibilityManager, uReports, U_CPTEditMonitor;
type
TfrmPtDemo = class(TfrmBase508Form)
lblFontTest: TLabel;
memPtDemo: TRichEdit;
dlgPrintReport: TPrintDialog;
CPPtDemo: TCopyEditMonitor;
pnlTop: TPanel;
cmdNewPt: TButton;
cmdClose: TButton;
cmdPrint: TButton;
procedure cmdCloseClick(Sender: TObject);
procedure cmdNewPtClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cmdPrintClick(Sender: TObject);
procedure CopyToMonitor(Sender: TObject; var AllowMonitor: Boolean);
private
{ Private declarations }
FNewPt: Boolean;
public
{ Public declarations }
end;
procedure PatientInquiry(var NewPt: Boolean);
implementation
{$R *.DFM}
uses rCover, rReports, Printers, uCore;
procedure PatientInquiry(var NewPt: Boolean);
{ displays patient demographics, returns true in NewPt if the user pressed 'Select New' btn }
var
frmPtDemo: TfrmPtDemo;
begin
if StrToInt64Def(Patient.DFN, 0) <= 0 then
exit;
frmPtDemo := TfrmPtDemo.Create(Application);
try
with frmPtDemo do
begin
frmPtDemo.ShowModal;
NewPt := FNewPt;
end; { with frmPtDemo }
finally
frmPtDemo.Release;
end;
end;
procedure TfrmPtDemo.FormCreate(Sender: TObject);
var
i, MaxWidth, AWidth, AHeight: Integer;
Rect: TRect;
// RTC #953958 begin
procedure AdjustButtonSize(aButton: TButton);
const
Gap = 5;
var
frm: TForm;
i: Integer;
begin
frm := Application.MainForm;
font.Assign(frm.font);
i := (frm.Canvas.TextWidth(aButton.Caption) + Gap + Gap);
if aButton.Width < i then
aButton.Width := i;
// Buttons are aligned to the right so the height is set based on pnlTop.height
// if aButton.Height < frm.Canvas.TextHeight(aButton.Caption) then
// aButton.Height := (frm.Canvas.TextHeight(aButton.Caption) + Gap);
aButton.Invalidate;
end;
function ButtonWidth(aButton: TButton): Integer;
begin
Result := aButton.Width;
if aButton.AlignWithMargins then
Result := Result + aButton.Margins.Left + aButton.Margins.Right;
end;
// RTC #953958 end
begin
FNewPt := False;
LoadDemographics(memPtDemo.Lines);
memPtDemo.SelStart := 0;
ResizeAnchoredFormToFont(self);
MaxWidth := 350; // make sure at least 350 wide
for i := 0 to memPtDemo.Lines.Count - 1 do
begin
AWidth := lblFontTest.Canvas.TextWidth(memPtDemo.Lines[i]);
if AWidth > MaxWidth then
MaxWidth := AWidth;
end;
{ width = borders + inset of memo box (left=8) }
MaxWidth := MaxWidth + (GetSystemMetrics(SM_CXFRAME) * 2) +
GetSystemMetrics(SM_CXVSCROLL) + 16;
{ height = height of lines + title bar + borders + 4 lines (room for buttons) }
AHeight := ((memPtDemo.Lines.Count + 4) * (lblFontTest.Height + 1)) +
(GetSystemMetrics(SM_CYFRAME) * 3) + GetSystemMetrics(SM_CYCAPTION);
AHeight := HigherOf(AHeight, 250); // make sure at least 250 high
if AHeight > (Screen.Height - 120) then
AHeight := Screen.Height - 120;
if MaxWidth > Screen.Width then
MaxWidth := Screen.Width;
Width := MaxWidth;
Height := AHeight;
Constraints.MinHeight := pnlTop.Height + GetSystemMetrics(SM_CYCAPTION) +
GetSystemMetrics(SM_CYHSCROLL) + 7;
Rect := BoundsRect;
ForceInsideWorkArea(Rect);
BoundsRect := Rect;
// RTC #953958 begin
AdjustButtonSize(cmdNewPt);
AdjustButtonSize(cmdPrint);
AdjustButtonSize(cmdClose);
Constraints.MinWidth := ButtonWidth(cmdNewPt) + ButtonWidth(cmdPrint) +
ButtonWidth(cmdClose) + GetSystemMetrics(SM_CXBORDER) +
GetSystemMetrics(SM_CXBORDER) + 7;
// RTC #953958 end
end;
procedure TfrmPtDemo.cmdNewPtClick(Sender: TObject);
begin
FNewPt := True;
Close;
end;
procedure TfrmPtDemo.cmdCloseClick(Sender: TObject);
begin
Close;
end;
procedure TfrmPtDemo.cmdPrintClick(Sender: TObject);
var
AHeader: TStringList;
memPrintReport: TRichEdit;
StartLine, MaxLines, LastLine, ThisPage, i: Integer;
ErrMsg: string;
RemoteSiteID: string; // for Remote site printing
RemoteQuery: string; // for Remote site printing
const
PAGE_BREAK = '**PAGE BREAK**';
begin
RemoteSiteID := '';
RemoteQuery := '';
if dlgPrintReport.Execute then
begin
AHeader := TStringList.Create;
CreatePatientHeader(AHeader, self.Caption);
memPrintReport := CreateReportTextComponent(self);
try
MaxLines := 60 - AHeader.Count;
LastLine := 0;
ThisPage := 0;
with memPrintReport do
begin
StartLine := 4;
repeat
with Lines do
begin
for i := StartLine to MaxLines do
// if i < memPtDemo.Lines.Count - 1 then
if i < memPtDemo.Lines.Count then
Add(memPtDemo.Lines[LastLine + i])
else
Break;
LastLine := LastLine + i;
Add(' ');
Add(' ');
Add(StringOfChar('-', 74));
if LastLine >= memPtDemo.Lines.Count - 1 then
Add('End of report')
else
begin
ThisPage := ThisPage + 1;
Add('Page ' + IntToStr(ThisPage));
Add(PAGE_BREAK);
StartLine := 0;
end;
end;
until LastLine >= memPtDemo.Lines.Count - 1;
PrintWindowsReport(memPrintReport, PAGE_BREAK, self.Caption,
ErrMsg, True);
end;
finally
memPrintReport.Free;
AHeader.Free;
end;
end;
memPtDemo.SelStart := 0;
memPtDemo.Invalidate;
end;
procedure TfrmPtDemo.CopyToMonitor(Sender: TObject; var AllowMonitor: Boolean);
begin
inherited;
CPPtDemo.ItemIEN := -1;
CPPtDemo.RelatedPackage := self.Caption + ';' + Patient.Name;
AllowMonitor := True;
end;
end.
|
////////////////////////////////////////////////////////////////////////////////
//
//
// FileName : SUISkinForm.pas
// Creator : Shen Min
// Date : 2002-08-06
// Comment :
//
// Copyright (c) 2002-2003 Sunisoft
// http://www.sunisoft.com
// Email: support@sunisoft.com
//
////////////////////////////////////////////////////////////////////////////////
unit SUISkinForm;
interface
{$I SUIPack.inc}
uses Windows, Messages, SysUtils, Classes, Forms, Graphics, Controls;
type
TsuiSkinForm = class(TGraphicControl)
private
m_Form : TForm;
m_Picture : TBitmap;
m_Color: TColor;
m_OnRegionChanged : TNotifyEvent;
m_OnPaint : TNotifyEvent;
procedure SetColor(const Value: TColor);
procedure SetPicture(const Value: TBitmap);
procedure ReSetWndRgn();
procedure WMERASEBKGND(var Msg : TMessage); message WM_ERASEBKGND;
protected
procedure Paint(); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy(); override;
property Canvas;
published
property Glyph : TBitmap read m_Picture write SetPicture;
property TransparentColor : TColor read m_Color write SetColor;
property PopupMenu;
property Cursor;
property OnRegionChanged : TNotifyEvent read m_OnRegionChanged write m_OnRegionChanged;
property OnPaint : TNotifyEvent read m_OnPaint write m_OnPaint;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDock;
property OnStartDrag;
end;
implementation
uses SUIPublic;
{ TsuiSkinForm }
constructor TsuiSkinForm.Create(AOwner: TComponent);
begin
inherited;
if not (AOwner is TForm) then
Exit;
m_Form := AOwner as TForm;
if not (csDesigning in ComponentState) then
m_Form.BorderStyle := bsNone;
m_Picture := TBitmap.Create();
m_Color := clFuchsia;
Width := 200;
Height := 100;
end;
destructor TsuiSkinForm.Destroy;
begin
m_Picture.Free();
m_Picture := nil;
inherited;
end;
procedure TsuiSkinForm.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited;
ReleaseCapture();
m_Form.PerForm(WM_NCLBUTTONDOWN, HTCAPTION, 0);
end;
procedure TsuiSkinForm.Paint;
begin
if (m_Picture.Width <> 0) and (m_Picture.Height <> 0) then
Canvas.Draw(0, 0, m_Picture)
else
begin
Canvas.Brush.Color := clBlack;
Canvas.FrameRect(ClientRect);
end;
if assigned(m_OnPaint) then
m_OnPaint(self);
end;
procedure TsuiSkinForm.ReSetWndRgn;
begin
if m_Picture.Empty then
Exit;
if not (csDesigning in ComponentState) then
SetBitmapWindow(m_Form.Handle, m_Picture, m_Color);
if (
(m_Picture.Height <> 0) and
(m_Picture.Width <> 0)
) then
begin
Height := m_Picture.Height;
Width := m_Picture.Width;
end;
Top := 0;
Left := 0;
m_Form.ClientHeight := Height;
m_Form.ClientWidth := Width;
if Assigned(m_OnRegionChanged) then
m_OnRegionChanged(self);
end;
procedure TsuiSkinForm.SetColor(const Value: TColor);
begin
m_Color := Value;
ReSetWndRgn();
Repaint();
end;
procedure TsuiSkinForm.SetPicture(const Value: TBitmap);
begin
m_Picture.Assign(Value);
ReSetWndRgn();
RePaint();
end;
procedure TsuiSkinForm.WMERASEBKGND(var Msg: TMessage);
begin
// do nothing
end;
end.
|
unit Test.Devices.Altistart22;
interface
uses Windows, TestFrameWork, GMGlobals, Test.Devices.Base.ReqCreator, GMConst,
Test.Devices.Base.ReqParser;
type
TAltistart22ReqCreatorTest = class(TDeviceReqCreatorTestBase)
protected
function GetDevType(): int; override;
procedure DoCheckRequests(); override;
end;
TAltistart22ParserTest = class(TDeviceReqParserTestBase)
private
protected
function GetDevType(): int; override;
function GetThreadClass(): TSQLWriteThreadForTestClass; override;
published
procedure Thread1;
procedure Thread2;
end;
implementation
uses Threads.ResponceParser, Devices.ModbusBase, SysUtils;
{ TAltistart22ReqCreatorTest }
procedure TAltistart22ReqCreatorTest.DoCheckRequests;
begin
CheckReqHexString(0, '$1D, 3, 1, 1, 0, $17, $57, $A4');
end;
function TAltistart22ReqCreatorTest.GetDevType: int;
begin
Result := DEVTYPE_ALTISTART_22;
end;
{ TAltistart22ParserTest }
type TLocalSQLWriteThreadForTest = class(TResponceParserThreadForTest);
function TAltistart22ParserTest.GetDevType: int;
begin
Result := DEVTYPE_ALTISTART_22;
end;
function TAltistart22ParserTest.GetThreadClass: TSQLWriteThreadForTestClass;
begin
Result := TLocalSQLWriteThreadForTest;
end;
procedure TAltistart22ParserTest.Thread1;
var buf: ArrayOfByte;
i: int;
begin
gbv.ReqDetails.rqtp := rqtAltistart22_All;
gbv.gmTime := NowGM();
buf := TextNumbersStringToArray('29 03 46 ' +
'00 01 02 03 04 05 06 07 ' +
'00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ' +
'00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 08 09 ' +
'00 00', false); // под CRC
Modbus_CRC(buf, Length(buf) - 2);
gbv.SetBufRec(buf);
TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_DevType := DEVTYPE_ALTISTART_22;
TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_AI;
TLocalSQLWriteThreadForTest(thread).ChannelIds.NDevNumber := gbv.ReqDetails.DevNumber;
for i := 1 to 4 do
begin
TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := i;
Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData, 'AI' + IntToStr(i));
Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1, 'AI' + IntToStr(i));
Check(TLocalSQLWriteThreadForTest(thread).Values[0].Val = ((i - 1) * 2) * 256 + ((i - 1) * 2 + 1), 'AI' + IntToStr(i));
Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime, 'AI' + IntToStr(i));
end;
i := 1;
TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_DI;
TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := i;
Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData, 'DI' + IntToStr(i));
Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1, 'DI' + IntToStr(i));
Check(TLocalSQLWriteThreadForTest(thread).Values[0].Val = $0809, 'DI' + IntToStr(i));
Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime, 'DI' + IntToStr(i));
end;
procedure TAltistart22ParserTest.Thread2;
var buf: ArrayOfByte;
i: int;
begin
gbv.ReqDetails.rqtp := rqtAltistart22_All;
gbv.gmTime := NowGM();
buf := TextNumbersStringToArray('01 03 2E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 01 40 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 06 00 11 F3 F1');
gbv.SetBufRec(buf);
TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_DevType := DEVTYPE_ALTISTART_22;
TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_AI;
TLocalSQLWriteThreadForTest(thread).ChannelIds.NDevNumber := 1;
for i := 1 to 4 do
begin
TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := i;
Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData, 'AI' + IntToStr(i));
Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1, 'AI' + IntToStr(i));
Check(TLocalSQLWriteThreadForTest(thread).Values[0].Val = 0, 'AI' + IntToStr(i));
Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime, 'AI' + IntToStr(i));
end;
i := 1;
TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_DI;
TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := i;
Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData, 'DI' + IntToStr(i));
Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1, 'DI' + IntToStr(i));
Check(TLocalSQLWriteThreadForTest(thread).Values[0].Val = $0011, 'DI' + IntToStr(i));
Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime, 'DI' + IntToStr(i));
end;
initialization
RegisterTest('GMIOPSrv/Devices/Altistart22', TAltistart22ReqCreatorTest.Suite);
RegisterTest('GMIOPSrv/Devices/Altistart22', TAltistart22ParserTest.Suite);
end.
|
program dltiket;
uses crt;
type
Tiket = record
nokursi : integer;
nama : string[18];
alamat : string[14];
nohape : string[12];
kodetujuan : string;
tujuan : string;
kodekelas : integer;
kelas : string;
harga : integer;
end;
RTiket = Tiket;
Pointer = ^Simpul;
Simpul = record
prev : Pointer;
info : RTiket;
next : Pointer;
end;
var
data,awal,akhir : Pointer;
elemen : RTiket;
pilihan : integer;
total : integer;
{Interface}
procedure Kotak(awalkolom,awalbaris,akhirkolom,akhirbaris:integer; latar:byte); //Kotak Menu
var
i : integer;
begin
textbackground(latar);
window(awalkolom,awalbaris,akhirkolom,akhirbaris);clrscr;window(1,1,80,25);
gotoxy(awalkolom,awalbaris);write(#218);
gotoxy(akhirkolom,awalbaris);write(#191);
gotoxy(akhirkolom,akhirbaris);write(#217);
gotoxy(awalkolom,akhirbaris);write(#192);
for i:=awalkolom+1 to akhirkolom-1 do
begin
gotoxy(i,awalbaris);write(#196);
gotoxy(i,akhirbaris);write(#196);
end;
for i:=awalbaris+1 to akhirbaris-1 do
begin
gotoxy(akhirkolom,i);write(#179);
gotoxy(awalkolom,i);write(#179);
end;
end;
procedure Header;
begin
gotoxy(2,1);textbackground(CYAN);write(' NO ');
gotoxy(7,1);textbackground(CYAN);write(' NAMA ');
gotoxy(26,1);textbackground(CYAN);write(' ALAMAT ');
gotoxy(41,1);textbackground(CYAN);write(' NO. HP ');
gotoxy(54,1);textbackground(CYAN);write(' TUJUAN ');
gotoxy(63,1);textbackground(CYAN);write(' KELAS ');
gotoxy(73,1);textbackground(CYAN);write(' HARGA ');
writeln();
end;
{Prototype}
procedure Isi(var elemen:RTiket);
begin
clrscr();
Kotak(18,5,62,21,5);
gotoxy(31,6);writeln('INPUT DATA PEMBELI');
gotoxy(19,7);writeln('-------------------------------------------');
gotoxy(25,whereY+1);write('Nomor Kursi : '); readln(elemen.nokursi);
gotoxy(25,whereY+1);write('Nama : '); readln(elemen.nama);
gotoxy(25,whereY+1);write('Alamat : '); readln(elemen.alamat);
gotoxy(25,whereY+1);write('No. HP : '); readln(elemen.nohape);
repeat
gotoxy(25,whereY+1);write('Kode Tujuan : '); readln(elemen.kodetujuan);
elemen.kodetujuan:=upcase(elemen.kodetujuan);
until(elemen.kodetujuan='BDG') or (elemen.kodetujuan='CRB') or (elemen.kodetujuan='JKT');
if (elemen.kodetujuan='CRB') then elemen.tujuan:='Cirebon'
else if (elemen.kodetujuan='BDG') then elemen.tujuan:='Bandung'
else if (elemen.kodetujuan='JKT') then elemen.tujuan:='Jakarta';
repeat
gotoxy(25,whereY+1);write('Kode Kelas : '); readln(elemen.kodekelas);
until(elemen.kodekelas > 0) and (elemen.kodekelas < 4);
case (elemen.kodekelas) of
1: elemen.kelas:='Eksekutif';
2: elemen.kelas:='Bisnis';
3: elemen.kelas:='Ekonomi';
end;
if(elemen.kodetujuan='CRB') then
begin
if(elemen.kodekelas=1) then elemen.harga:=100000
else if(elemen.kodekelas=2) then elemen.harga:=80000
else if(elemen.kodekelas=3) then elemen.harga:=45000;
end
else if(elemen.kodetujuan='BDG') then
begin
if(elemen.kodekelas=1) then elemen.harga:=150000
else if(elemen.kodekelas=2) then elemen.harga:=100000
else if(elemen.kodekelas=3) then elemen.harga:=80000;
end
else if(elemen.kodetujuan='JKT') then
begin
if(elemen.kodekelas=1) then elemen.harga:=200000
else if(elemen.kodekelas=2) then elemen.harga:=150000
else if(elemen.kodekelas=3) then elemen.harga:=100000;
end;
end;
procedure Tampil(data:Pointer);
begin
textbackground(0);clrscr();
Header;
data:=awal;
while(data<>nil) do
begin
textbackground(0);
gotoxy(3,whereY);write(data^.info.nokursi);
gotoxy(7,whereY);write(data^.info.nama);
gotoxy(26,whereY);write(data^.info.alamat);
gotoxy(41,whereY);write(data^.info.nohape);
gotoxy(54,whereY);write(data^.info.tujuan);
gotoxy(63,whereY);write(data^.info.kelas);
gotoxy(73,whereY);writeln(data^.info.harga);
data:=data^.next;
end;
readkey();
end;
{Penyisipan}
procedure SisipDepan(elemen:RTiket; var awal,akhir:Pointer); //Sisip Depan
var
baru:Pointer;
begin
new(baru);
baru^.info:=elemen;
baru^.prev:=nil;
if(awal=nil) then
begin
baru^.next:=nil;
akhir:=baru;
end
else
begin
baru^.next:=awal;
awal^.prev:=baru;
end;
awal:=baru;
Tampil(data);
end;
procedure SisipTengah(elemen:RTiket; var awal,akhir:Pointer); //Sisip Tengah
var
baru,bantu:Pointer;
ketemu:boolean;
datasisip:integer;
begin
new(baru);
baru^.info:=elemen;
if(awal=nil) then
begin
baru^.prev:=nil;
baru^.next:=nil;
awal:=baru;
akhir:=baru;
end
else
begin
clrscr();
Tampil(data);
Kotak(18,12,60,14,0);
gotoxy(20,13);write('Data Akan Disisipkan Sebelum Nomor : '); readln(datasisip);
bantu:=awal;
ketemu:=false;
while(not ketemu) and (bantu<>nil) do
begin
if(datasisip=bantu^.info.nokursi) then
begin
ketemu:=true;
end
else
begin
bantu:=bantu^.next;
end;
end;
if(ketemu) then
begin
if(bantu=awal) then
begin
SisipDepan(elemen,awal,akhir);
end
else
begin
baru^.next:=bantu;
baru^.prev:=bantu^.prev;
bantu^.prev^.next:=baru;
bantu^.prev:=baru;
Tampil(data);
end;
end
else
begin
gotoxy(22,16);write('Data dengan Nomor ',datasisip,' tidak ditemukan');
readkey();
end;
end;
end;
procedure SisipBelakang(elemen:RTiket; var awal,akhir:Pointer); //Sisip Belakang
var
baru:Pointer;
begin
new(baru);
baru^.info:=elemen;
baru^.next:=nil;
if(akhir=nil) then
begin
baru^.prev:=nil;
awal:=baru
end
else
begin
baru^.prev:=akhir;
akhir^.next:=baru;
end;
akhir:=baru;
Tampil(data);
end;
{Penghapusan}
procedure HapusDepan(var elemen:RTiket; var awal,akhir:Pointer); //Hapus Depan
var
phapus:Pointer;
begin
clrscr();
phapus:=awal;
elemen:=phapus^.info;
if(awal=akhir) then
begin
awal:=nil;
akhir:=nil;
end
else
begin
awal:=awal^.next;
awal^.prev:=nil;
end;
dispose(phapus);
gotoxy(33,14);write('Data telah dihapus');
readkey();
end;
procedure HapusBelakang(var elemen:RTiket; var awal,akhir:Pointer); //Hapus Belakang
var
phapus:Pointer;
begin
clrscr();
phapus:=akhir;
elemen:=phapus^.info;
if(awal=akhir) then
begin
awal:=nil;
akhir:=nil;
end
else
begin
akhir:=akhir^.prev;
akhir^.next:=nil;
end;
dispose(phapus);
gotoxy(33,14);write('Data Telah Dihapus');
readkey();
end;
procedure HapusTengah(var elemen:RTiket; var awal,akhir:Pointer); //Hapus Tengah
var
phapus:Pointer;
ketemu:boolean;
datahapus:integer;
begin
clrscr();
if(awal=akhir) then
begin
phapus:=awal;
elemen:=phapus^.info;
awal:=nil;
akhir:=nil;
dispose(phapus);
gotoxy(33,14);write('Data Telah Dihapus');
readkey();
end
else
begin
Tampil(data);
Kotak(23,12,54,14,0);
gotoxy(25,13);write('Nomor Yang Akan Dihapus : '); readln(datahapus);
phapus:=awal;
ketemu:=false;
while(not ketemu) and (phapus<>nil) do
begin
if(datahapus=phapus^.info.nokursi) then
begin
ketemu:=true;
end
else
begin
phapus:=phapus^.next;
end;
end;
if(ketemu) then
begin
elemen:=phapus^.info;
if(phapus=awal) then
begin
HapusDepan(elemen,awal,akhir);
end
else if(phapus=akhir) then
begin
HapusBelakang(elemen,awal,akhir);
end
else
begin
phapus^.prev^.next:=phapus^.next;
phapus^.next^.prev:=phapus^.prev;
dispose(phapus);
clrscr();
gotoxy(33,14);write('Data Telah Dihapus');
readkey();
end;
end
else
begin
gotoxy(22,whereY+1);write('Data dengan Nomor ',datahapus,' tidak ditemukan');
readkey();
end;
end;
end;
{Pencarian}
procedure CariKursi(awal:Pointer); //Cari Nomor Kursi(Unik)
var
bantu:Pointer;
ketemu:boolean;
datacari:integer;
begin
clrscr();
Kotak(23,12,55,14,0);
gotoxy(25,13);write('Nomor Kursi yang Dicari : '); readln(datacari);
bantu:=awal;
ketemu:=false;
while(not ketemu) and (bantu<>nil) do
begin
if(datacari=bantu^.info.nokursi) then
begin
ketemu:=true;
end
else
begin
bantu:=bantu^.next;
end;
end;
if(ketemu) then
begin
textbackground(0);clrscr();
Header;
textbackground(0);
gotoxy(3,whereY);write(bantu^.info.nokursi);
gotoxy(7,whereY);write(bantu^.info.nama);
gotoxy(26,whereY);write(bantu^.info.alamat);
gotoxy(41,whereY);write(bantu^.info.nohape);
gotoxy(54,whereY);write(bantu^.info.tujuan);
gotoxy(63,whereY);write(bantu^.info.kelas);
gotoxy(73,whereY);write(bantu^.info.harga);
readkey();
end
else
begin
gotoxy(22,16);write('Data dengan Nomor ',datacari, ' Tidak Ditemukan');
readkey();
end;
end;
procedure CariTujuan(awal:Pointer); //Cari Jurusan(Tidak Unik)
var
bantu:Pointer;
datacari:string;
begin
clrscr();
Kotak(25,12,56,14,0);
gotoxy(27,13);write('Tujuan yang Dicari : '); readln(datacari);
clrscr();
Header;
textbackground(0);
bantu:=awal;
repeat
if(datacari=bantu^.info.tujuan) then
begin
gotoxy(3,whereY);write(bantu^.info.nokursi);
gotoxy(7,whereY);write(bantu^.info.nama);
gotoxy(26,whereY);write(bantu^.info.alamat);
gotoxy(41,whereY);write(bantu^.info.nohape);
gotoxy(54,whereY);write(bantu^.info.tujuan);
gotoxy(63,whereY);write(bantu^.info.kelas);
gotoxy(73,whereY);writeln(bantu^.info.harga);
bantu:=bantu^.next;
end
else
begin
bantu:=bantu^.next;
end;
until(bantu=nil);
readkey();
end;
{Total Harga}
procedure TotalHarga(var total:integer);
begin
data:=awal;
total:=0;
while(data<>nil) do
begin
total:=total+data^.info.harga;
data:=data^.next;
end;
gotoxy(73,whereY);writeln('------+');
gotoxy(59,whereY);write('Total Harga = ',total);
readkey();
end;
{Pengurutan}
procedure UrutKursi(awal,akhir:Pointer);
var
min,i,j:Pointer;
temo:string;
temp:integer;
begin
clrscr();
i:=awal;
while(i<>akhir) do
begin
min:=i;
j:=i^.next;
while(j<>nil) do
begin
if(j^.info.nokursi < min^.info.nokursi) then min:=j;
j:=j^.next;
end;
temp:=i^.info.nokursi;
i^.info.nokursi:=min^.info.nokursi;
min^.info.nokursi:=temp;
temo:=i^.info.nama;
i^.info.nama:=min^.info.nama;
min^.info.nama:=temo;
temo:=i^.info.alamat;
i^.info.alamat:=min^.info.alamat;
min^.info.alamat:=temo;
temo:=i^.info.nohape;
i^.info.nohape:=min^.info.nohape;
min^.info.nohape:=temo;
temo:=i^.info.tujuan;
i^.info.tujuan:=min^.info.tujuan;
min^.info.tujuan:=temo;
temo:=i^.info.kelas;
i^.info.kelas:=min^.info.kelas;
min^.info.kelas:=temo;
temp:=i^.info.harga;
i^.info.harga:=min^.info.harga;
min^.info.harga:=temp;
i:=i^.next;
end;
end;
{Tampil Data}
procedure TampilData;
begin
if(awal<>nil) and (akhir<>nil) then
begin
UrutKursi(awal,akhir);
Tampil(data);
TotalHarga(total);
end
else
begin
clrscr();
gotoxy(34,13);write('List Kosong');
readkey();
end;
end;
{Penghancuran}
procedure Penghancuran(var awal:Pointer);
var
phapus:Pointer;
begin
clrscr();
phapus:=awal;
while(awal<>nil) do
begin
phapus:=awal;
dispose(phapus);
awal:=awal^.next;
end;
awal:=nil;
akhir:=nil;
gotoxy(28,12);write('Semua Data Telah Dihapus');
gotoxy(19,13);write('Terima Kasih telah menggunakan program ini');
readkey();
end;
procedure Keluar; //Keluar
begin
Penghancuran(awal);
end;
{Menu}
procedure Menu(var pil:integer); //Menu Utama
begin
clrscr();
Kotak(28,8,53,19,1);
gotoxy(30,9); writeln(' MENU PENJUALAN TIKET');
gotoxy(30,whereY);writeln('PT KERETA API TORABIKA');
gotoxy(29,whereY);writeln('========================');
gotoxy(30,whereY);writeln('1. Sisip Data Pembeli');
gotoxy(30,whereY);writeln('2. Hapus Data Pembeli');
gotoxy(30,whereY);writeln('3. Cari Data Pembeli');
gotoxy(30,whereY);writeln('4. Tampil Data Pembeli');
gotoxy(30,whereY);writeln('5. Keluar');
gotoxy(29,whereY);writeln('========================');
gotoxy(30,whereY);write (' Pilihan : '); readln(pil);
end;
procedure MenuSisip; //Menu Sisip
var
pil:integer;
begin
repeat
clrscr();
Kotak(27,9,54,18,2);
gotoxy(29,10); writeln(' MENU SISIP DATA');
gotoxy(28,whereY);writeln('==========================');
gotoxy(29,whereY);writeln('1. Sisip Depan');
gotoxy(29,whereY);writeln('2. Sisip Tengah');
gotoxy(29,whereY);writeln('3. Sisip Belakang');
gotoxy(29,whereY);writeln('4. Kembali ke Menu Utama');
gotoxy(28,whereY);writeln('==========================');
gotoxy(29,whereY);write (' Pilihan : '); readln(pil);
case pil of
1: begin
Isi(elemen);
SisipDepan(elemen,awal,akhir);
end;
2: begin
Isi(elemen);
SisipTengah(elemen,awal,akhir);
end;
3: begin
Isi(elemen);
SisipBelakang(elemen,awal,akhir);
end;
end;
until(pil=4);
end;
procedure MenuHapus; //Menu Hapus
var
pil:integer;
begin
repeat
clrscr();
Kotak(27,9,54,18,3);
gotoxy(29,10); writeln(' MENU HAPUS DATA');
gotoxy(28,whereY);writeln('==========================');
gotoxy(29,whereY);writeln('1. Hapus Depan');
gotoxy(29,whereY);writeln('2. Hapus Tengah');
gotoxy(29,whereY);writeln('3. Hapus Belakang');
gotoxy(29,whereY);writeln('4. Kembali ke Menu Utama');
gotoxy(28,whereY);writeln('==========================');
gotoxy(29,whereY);write (' Pilihan : '); readln(pil);
case pil of
1: HapusDepan(elemen,awal,akhir);
2: HapusTengah(elemen,awal,akhir);
3: HapusBelakang(elemen,awal,akhir);
end;
until(pil=4);
end;
procedure MenuCari; //Menu Cari
var
pil:integer;
begin
repeat
clrscr();
Kotak(27,9,54,17,4);
gotoxy(29,10); writeln(' MENU CARI DATA');
gotoxy(28,whereY);writeln('==========================');
gotoxy(29,whereY);writeln('1. Cari Nomor Kursi');
gotoxy(29,whereY);writeln('2. Cari Rute Tujuan');
gotoxy(29,whereY);writeln('3. Kembali ke Menu Utama');
gotoxy(28,whereY);writeln('==========================');
gotoxy(29,whereY);write (' Pilihan : '); readln(pil);
case pil of
1: CariKursi(awal);
2: CariTujuan(awal);
end;
until(pil=3);
end;
begin
{Penciptaan List}
awal:=nil;
akhir:=nil;
{Menu Utama}
repeat
Menu(pilihan);
case pilihan of
1: MenuSisip;
2: MenuHapus;
3: MenuCari;
4: TampilData;
5: Keluar;
end;
until(pilihan=5);
end.
|
unit ncDMcommPlus;
{
ResourceString: Dario 12/03/13
}
interface
uses
SysUtils, Classes, nxdb, nxsdServerEngine, nxreRemoteServerEngine, DB, ExtCtrls,
nxllComponent, nxllTransport, nxptBasePooledTransport, nxtwWinsockTransport, ncCommPlusIndy;
type
TdmCommPlus = class(TDataModule)
nxTCPIP: TnxWinsockTransport;
tProduto: TnxTable;
tProdutoID: TAutoIncField;
tProdutoCodigo: TStringField;
tProdutoDescricao: TStringField;
tProdutoUnid: TStringField;
tProdutoPreco: TCurrencyField;
tProdutoObs: TMemoField;
tProdutoImagem: TGraphicField;
tProdutoCategoria: TStringField;
tProdutoSubCateg: TStringField;
tProdutoEstoqueAtual: TFloatField;
tProdutoCustoUnitario: TCurrencyField;
tProdutoEstoqueACE: TFloatField;
tProdutoEstoqueACS: TFloatField;
tProdutoPodeAlterarPreco: TBooleanField;
tProdutoNaoControlaEstoque: TBooleanField;
tProdutoFidelidade: TBooleanField;
tProdutoFidPontos: TIntegerField;
tProdutoEstoqueMin: TFloatField;
tProdutoEstoqueMax: TFloatField;
tProdutoAbaixoMin: TBooleanField;
tProdutoAbaixoMinDesde: TDateTimeField;
tProdutoEstoqueRepor: TFloatField;
nxRSE: TnxRemoteServerEngine;
nxDB: TnxDatabase;
nxSession: TnxSession;
tParceiros: TnxTable;
tParceirosCodParceiro: TStringField;
tParceirosNomeParceiro: TStringField;
tParceirosurlTimeout: TStringField;
tParceirosAdesao: TBooleanField;
tParceirosKeyIndex: TWordField;
tProdutoFornecedor: TIntegerField;
tProdutoplus: TBooleanField;
tProdutoplusURL: TnxMemoField;
tProdutoplusCodParceiro: TStringField;
tProdutoplusCodProduto: TStringField;
tProdutoAtivo: TBooleanField;
tPlusT: TnxTable;
tPlusTC: TStringField;
tPlusTN: TStringField;
tPlusTP: TStringField;
tPlusTT: TnxMemoField;
private
{ Private declarations }
public
procedure Open;
procedure Close;
procedure UpdateAll(aUpdateAll: TplusReqUpdateAll);
{ Public declarations }
end;
TThreadUpdateAll = class (TThread)
private
FUpd : TplusReqUpdateAll;
FSrv : TnxBaseServerEngine;
protected
procedure Execute; override;
public
constructor Create(aUpd: TplusReqUpdateAll; aSrv: TnxBaseServerEngine);
end;
var
dmCommPlus: TdmCommPlus;
implementation
uses ncClassesBase, ncDebug, ncPlusTeste;
{$R *.dfm}
{ TdmCommPlus }
procedure TdmCommPlus.UpdateAll(aUpdateAll: TplusReqUpdateAll);
var
SL : TStrings;
I : Integer;
A : Boolean;
S : String;
pto : TPlusTesteOptions;
begin
Open;
pto := TPlusTesteOptions.LoadFromIni;
sl := TStringList.Create;
with aUpdateAll do
try
tParceiros.First;
while not tParceiros.Eof do begin
if (pto<>nil) or (not ReqParceiros.ParceiroExiste(tParceirosCodParceiro.Value)) then
sl.Add(tParceirosCodParceiro.Value);
tParceiros.Next;
end;
for I := 0 to sl.Count-1 do
if tParceiros.FindKey([sl[i]]) and ((pto=nil) or (not SameText(pto.ptoCodParceiro, sl[i]))) then tParceiros.Delete;
if pto=nil then
for I := 1 to ReqParceiros.ItemCount do begin
if tParceiros.FindKey([ReqParceiros.Codigo(I)]) then
tParceiros.Edit else
tParceiros.Insert;
try;
tParceirosCodParceiro.Value := ReqParceiros.Codigo(I);
tParceirosNomeParceiro.Value := ReqParceiros.Nome(I);
tParceirosKeyIndex.Value := StrToIntDef(ReqParceiros.KeyIndex(I), 0);
tParceirosUrlTimeout.Value := ReqParceiros.url_timeout(I);
tParceirosAdesao.Value := ReqAdesoes.AdesaoExiste(tParceirosCodParceiro.Value);
tParceiros.Post;
except
on E: Exception do begin
S := E.Message;
if S='asdasdasdasdassad' then Exit; // do not localize
raise;
end;
end;
if (not tParceirosAdesao.Value) then
while tPlusT.FindKey([tParceirosCodParceiro.Value]) do tPlusT.Delete;
end;
tProduto.SetRange([True], [True]);
try
while not tProduto.Eof do begin
with aUpdateAll do
if (pto<>nil) or (not ReqProdutos.ProdutoExiste(tProdutoplusCodParceiro.Value, tProdutoplusCodProduto.Value)) {and ((pto=nil) or (not SameText(pto.ptoCodParceiro, tProdutoplusCodParceiro.Value)) )} then begin
tProduto.Edit;
tProdutoAtivo.Value := False;
tProduto.Post;
end;
tProduto.Next;
end;
finally
tProduto.CancelRange;
end;
if pto=nil then
for I := 1 to ReqProdutos.ItemCount do begin
if tProduto.FindKey([True, ReqProdutos.CodParceiro(I), ReqProdutos.Codigo(I)]) then
tProduto.Edit else
tProduto.Insert;
tProdutoplus.Value := True;
tProdutoDescricao.Value := ReqProdutos.Nome(I);
tProdutoplusCodParceiro.Value := ReqProdutos.CodParceiro(I);
tProdutoplusCodProduto.Value := ReqProdutos.Codigo(I);
tProdutoplusUrl.Value := ReqProdutos.url_vendas(I);
tProdutoAtivo.Value := ReqAdesoes.AdesaoExiste(tProdutoplusCodParceiro.Value) or ((pto<>nil) and SameText(pto.ptoCodParceiro, tProdutoplusCodParceiro.Value));
tProdutoNaoControlaEstoque.Value := True;
tProduto.Post;
end;
if pto<>nil then
SalvaPlusTeste(tParceiros, tProduto, pto);
finally
if assigned(pto) then pto.Free;
sl.Free;
end;
end;
procedure TdmCommPlus.Close;
begin
nxDB.Close;
nxSession.Close;
end;
procedure TdmCommPlus.Open;
var I: Integer;
begin
nxDB.AliasPath := '';
nxDB.AliasName := 'NexCafe'; // do not localize
nxSession.Username := SessionUser;
nxSession.Password := SessionPass;
nxSession.Active := True;
nxDB.Active := True;
for I := 0 to nxDB.DataSetCount-1 do nxDB.DataSets[I].Active := True;
end;
{ TThreadUpdateAll }
constructor TThreadUpdateAll.Create(aUpd: TplusReqUpdateAll;
aSrv: TnxBaseServerEngine);
begin
FSrv := aSrv;
FUpd := aUpd;
inherited Create(False);
end;
procedure TThreadUpdateAll.Execute;
var DM : TdmCommPlus;
begin
DM := nil;
try
DM := TdmCommPlus.Create(nil);
DM.nxSession.ServerEngine := FSrv;
DM.Open;
DM.UpdateAll(FUpd);
except
on E: Exception do
DebugMsgEsp('TThreadUpdateAll.Execute - E.Message: '+E.Message, False, True); // do not localize
end;
if DM<>nil then DM.Free;
FUpd.Free;
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.0 2/10/2005 2:26:36 PM JPMugaas
New UnixTime Service (port 519) components.
}
unit IdUnixTimeServer;
interface
{$i IdCompilerDefines.inc}
uses
IdAssignedNumbers,
IdCustomTCPServer,
IdGlobalProtocols,
IdTimeServer;
{
This is based on a description at
http://amo.net/AtomicTimeZone/help/ATZS_Protocols.htm#Unix
UnixTime and UnixTime Protocol
Unix is an operating system developed in 1969 by Ken Thompson. UnixTime
counts "epochs" or seconds since the Year 1970. UnixTime recently hit it's
billionth birthday.
Because Unix is widely used in many environments, UnixTime was developed into
a loose simple time protocol in the late 80's and early 90's. No formal
UnixTime protocol has ever been officially published as an internet protocol -
until now.
UnixTime operates on the same UnixTime port - 519. Once a connection is
requested on this port, exactly like in Time Protocol, the UnixTime value
is sent back by either tcp/ip or udp/ip. When UDP/IP is used, a small packet
of data must be received by the server in order to respond in the exact same
fashion as Time Protocol. The UnixTime is then sent as an unsigned
"unformatted" integer on the same port.
}
type
TIdUnixTimeServer = class(TIdCustomTimeServer)
protected
procedure InitComponent; override;
published
property DefaultPort default IdPORT_utime;
end;
implementation
{ TIdUnixTimeServer }
procedure TIdUnixTimeServer.InitComponent;
begin
inherited;
DefaultPort := IdPORT_utime;
FBaseDate := UnixStartDate;
end;
end.
|
unit uMisc;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Classes, System.Character, System.Variants,
Generics.Collections, Generics.Defaults,
VCL.Forms;
type
TArg< T > = reference to procedure( const Arg: T );
// Generate Temp FileName uses Windows API GetTempFileName()
function GenerateTempFileName( const Extension: String ): String;
// Generate Temp FileName uses GUID -- CreateGUID()
function GenerateTempFileNameEx( const Extension: String ): String;
// Remove Char < 0x20 or Char > 0x7F, and Merge Multi 0x20 Spaces
function RemoveWhiteSpace( const s: String ): String;
// CopyFile uses TMemoryStream
procedure CopyFile( SourceFileName, DestFileName: string );
// Capture all to Aoutput
function ExecAndCapture( const ACommand, AParameters: String; var AOutput: AnsiString ): Integer;
// Capture Every Line
procedure ExecAndCaptureReal( const ACommand, AParameters: String; CallBack: TArg< PAnsiChar > );
{
procedure TForm1.CaptureToMemo( const Line: PAnsiChar );
begin
Memo1.Lines.Add( String( Line ) );
end;
procedure TForm1.Button1Click( Sender: TObject );
begin
ExecAndCaptureReal( ACommand.Text, AParameters.Text, CaptureToMemo );
end;
procedure TForm1.Button1Click( Sender: TObject );
begin
ExecAndCaptureReal
(
ComboBox1.Text, Edit1.Text,
procedure( const Line: PAnsiChar )
begin
Memo1.Lines.Add( String( Line ) );
end
);
end;
}
implementation
{
function GetTempFileName(lpPathName, lpPrefixString: LPCWSTR; uUnique: UINT; lpTempFileName: LPWSTR): UINT;
Why does GetTempFileName function create new empty file ?
It's in the GetTempFileName function description (emphasized by me):
Creates a name for a temporary file.
If a unique file name is generated, an empty file is created and the handle to it is released;
otherwise, only a file name is generated.
How to avoid creating the new file when using GetTempFileName function ?
Either you can't let the function generate a unique file name (which creates an empty file)
or just delete that created empty file after the GetTempFileName function returns.
From the reference (emphasized by me):
Temporary files whose names have been created by this function are not automatically deleted.
To delete these files call DeleteFile.
}
function GenerateTempFileName( const Extension: String ): String;
var
// This buffer should be MAX_PATH characters to accommodate the path plus the terminating null character.
lpTempFileName: Array [ 0 .. MAX_PATH - 1 ] of Char;
lpTempPathName: Array [ 0 .. MAX_PATH - 1 ] of Char;
begin
Winapi.Windows.GetTempPath( MAX_PATH, lpTempPathName );
// If uUnique is zero, GetTempFileName creates an empty file and closes it.
//
// If uUnique is not zero, you must create the file yourself.
// Only a file name is created, because GetTempFileName is not able to guarantee that the file name is unique.
repeat
Winapi.Windows.GetTempFileName( lpTempPathName, nil, 1, lpTempFileName );
Result := ChangeFileExt( lpTempFileName, Extension );
until not FileExists( Result );
// The GetTempFile function just returns a unique filename but doesn't create the file.
// If uUnique is not zero, you must create the file yourself.
// DeleteFile( lpTempFileName );
end;
{
#ifdef UNICODE
typedef wchar_t TCHAR;
#else
typedef unsigned char TCHAR;
#endif
}
function GenerateTempFileNameEx( const Extension: String ): String;
var
Guid: TGUID;
GuidString: String;
lpTempFileName: String;
lpTempPathName: Array [ 0 .. MAX_PATH - 1 ] of Char;
begin
// Windows.GetTempPath( Sizeof( lpTempPathName ), lpTempPathName );
// nBufferLength = 0x0208 = 520 = MAX_PATH * Sizeof(Char) : 520 * 2 = 1040 Bytes
// Sizeof : Returns the number of bytes occupied by a variable or type.
// nBufferLength : The size of the string buffer identified by lpBuffer, in TCHARs
Winapi.Windows.GetTempPath( MAX_PATH, lpTempPathName );
// nBufferLength = 260 = MAX_PATH : 260 * 2 = 520 Bytes
// nBufferLength : The size of the string buffer identified by lpBuffer, in TCHARs
repeat
CreateGUID( Guid );
GuidString := GUIDToString( Guid );
GuidString := Copy( GuidString, 2, Length( GuidString ) - 2 );
lpTempFileName := lpTempPathName + GuidString + Extension;
until not FileExists( lpTempFileName );
Result := lpTempFileName;
end;
procedure CopyFile( SourceFileName, DestFileName: string );
var
MemoryStream: TMemoryStream;
begin
MemoryStream := TMemoryStream.Create;
try
MemoryStream.LoadFromFile( SourceFileName );
MemoryStream.SaveToFile( DestFileName );
finally
MemoryStream.Free;
end;
end;
function RemoveWhiteSpace( const s: String ): String;
var
i, j: Integer;
HasSpace: Boolean;
begin
SetLength( Result, Length( s ) );
HasSpace := False;
j := 0;
for i := 1 to Length( s ) do
begin
if Ord( s[ i ] ) = $20 then
begin
if HasSpace then
Continue;
HasSpace := True;
Inc( j );
Result[ j ] := s[ i ];
end else if ( Ord( s[ i ] ) > $20 ) and ( Ord( s[ i ] ) < $7F ) then
begin
HasSpace := False;
Inc( j );
Result[ j ] := s[ i ];
end;
end;
SetLength( Result, j );
end;
procedure ExecAndCaptureReal( const ACommand, AParameters: String; CallBack: TArg< PAnsiChar > );
const
CReadBuffer = 2400;
var
saSecurity: TSecurityAttributes;
hRead: THandle;
hWrite: THandle;
suiStartup: TStartupInfo;
piProcess: TProcessInformation;
pBuffer: array [ 0 .. CReadBuffer ] of AnsiChar;
dBuffer: array [ 0 .. CReadBuffer ] of AnsiChar;
dRead: DWORD;
dRunning: DWORD;
dAvailable: DWORD;
CommandAndParameters: string;
begin
saSecurity.nLength := SizeOf( TSecurityAttributes );
saSecurity.bInheritHandle := True;
saSecurity.lpSecurityDescriptor := nil;
CommandAndParameters := ACommand + ' ' + AParameters;
if CreatePipe( hRead, hWrite, @saSecurity, 0 ) then
try
FillChar( suiStartup, SizeOf( TStartupInfo ), #0 );
suiStartup.cb := SizeOf( TStartupInfo );
suiStartup.hStdInput := hRead;
suiStartup.hStdOutput := hWrite;
suiStartup.hStdError := hWrite;
suiStartup.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
suiStartup.wShowWindow := SW_HIDE;
if CreateProcess( nil, PChar( CommandAndParameters ), @saSecurity, @saSecurity, True, NORMAL_PRIORITY_CLASS, nil,
nil, suiStartup, piProcess ) then
try
repeat
dRunning := WaitForSingleObject( piProcess.hProcess, 100 );
PeekNamedPipe( hRead, nil, 0, nil, @dAvailable, nil );
if ( dAvailable > 0 ) then
repeat
dRead := 0;
ReadFile( hRead, pBuffer[ 0 ], CReadBuffer, dRead, nil );
pBuffer[ dRead ] := #0;
OemToCharA( pBuffer, dBuffer );
CallBack( dBuffer );
until ( dRead < CReadBuffer );
Application.ProcessMessages;
until ( dRunning <> WAIT_TIMEOUT );
finally
CloseHandle( piProcess.hProcess );
CloseHandle( piProcess.hThread );
end;
finally
CloseHandle( hRead );
CloseHandle( hWrite );
end;
end;
function ExecAndCapture( const ACommand, AParameters: String; var AOutput: AnsiString ): Integer;
type
TAnoPipe = record
Input: THandle;
Output: THandle;
end;
const
cBufferSize = 2048;
var
ACmdLine: string;
vStartupInfo: TStartupInfo;
vSecurityAttributes: TSecurityAttributes;
vReadBytes: DWORD;
vProcessInfo: TProcessInformation;
vStdInPipe: TAnoPipe;
vStdOutPipe: TAnoPipe;
pBuffer: array [ 0 .. cBufferSize ] of AnsiChar;
dBuffer: array [ 0 .. cBufferSize ] of AnsiChar;
begin
Result := 0;
ACmdLine := ACommand + ' ' + AParameters;
with vSecurityAttributes do
begin
nLength := SizeOf( TSecurityAttributes );
bInheritHandle := True;
lpSecurityDescriptor := nil;
end;
// Create anonymous pipe for standard input
if not CreatePipe( vStdInPipe.Output, vStdInPipe.Input, @vSecurityAttributes, 0 ) then
raise Exception.Create( 'Failed to create pipe for standard input. System error message: ' +
SysErrorMessage( GetLastError ) );
try
// Create anonymous pipe for standard output (and also for standard error)
if not CreatePipe( vStdOutPipe.Output, vStdOutPipe.Input, @vSecurityAttributes, 0 ) then
raise Exception.Create( 'Failed to create pipe for standard output. System error message: ' +
SysErrorMessage( GetLastError ) );
try
// initialize the startup info to match our purpose
FillChar( vStartupInfo, SizeOf( TStartupInfo ), #0 );
vStartupInfo.cb := SizeOf( TStartupInfo );
vStartupInfo.wShowWindow := SW_HIDE; // we don't want to show the process
// assign our pipe for the process' standard input
vStartupInfo.hStdInput := vStdInPipe.Output;
// assign our pipe for the process' standard output
vStartupInfo.hStdOutput := vStdOutPipe.Input;
vStartupInfo.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
if not CreateProcess( nil, PChar( ACmdLine ), @vSecurityAttributes, @vSecurityAttributes, True,
NORMAL_PRIORITY_CLASS, nil, nil, vStartupInfo, vProcessInfo ) then
raise Exception.Create( 'Failed creating the console process. System error msg: ' +
SysErrorMessage( GetLastError ) );
try
// wait until the console program terminated
while WaitForSingleObject( vProcessInfo.hProcess, 50 ) = WAIT_TIMEOUT do
Sleep( 0 );
// clear the output storage
AOutput := '';
// Read text returned by the console program in its StdOut channel
// The problem is that the console application emits UTF-16.
repeat
ReadFile( vStdOutPipe.Output, pBuffer[ 0 ], cBufferSize, vReadBytes, nil );
if vReadBytes > 0 then
begin
pBuffer[ vReadBytes ] := #0;
OemToCharA( pBuffer, dBuffer );
AOutput := AOutput + AnsiString( dBuffer );
Inc( Result, vReadBytes );
end;
until ( vReadBytes < cBufferSize );
finally
CloseHandle( vProcessInfo.hProcess );
CloseHandle( vProcessInfo.hThread );
end;
finally
CloseHandle( vStdOutPipe.Input );
CloseHandle( vStdOutPipe.Output );
end;
finally
CloseHandle( vStdInPipe.Input );
CloseHandle( vStdInPipe.Output );
end;
end;
end.
|
unit ncnxServerPlugin;
interface
{$I NEX.INC}
uses
Classes,
Windows,
ExtCtrls,
nxptBasePooledTransport,
nxllTypes,
nxllList,
nxllComponent,
nxllTransport,
nxllPluginBase,
nxllSync,
ncNetMsg,
ncClassesBase;
type
TncnxServerPlugin = class(TnxBasePluginEngine)
private
FNexServ : TncServidorBase;
FTransp : TnxBaseTransport;
procedure SetNexServ(const Value: TncServidorBase);
protected
class function bpeIsRemote: Boolean; override;
procedure OnEnviaEvento(aMsg: Integer; aDados: Pointer);
public
constructor Create( aOwner: TComponent ); override;
procedure BroadcastKeepAlive;
function spRemoveSession( aSessionId: TnxSessionId ): TnxResult;
function scShowUpTime: Boolean; override;
property Transp: TnxBaseTransport read FTransp write FTransp;
published
property NexServ: TncServidorBase
read FNexServ write SetNexServ;
end;
{
This is the plugin command handler that translates messages from the
remote interface into method calls of the actual plugin engine.
}
TncnxCmdHandler = class(TnxBasePluginCommandHandler)
private
function ServUnlock: TList;
procedure ServLock(aSessionID: TnxSessionID);
procedure SendReply(aEventos : TList;
aMsgID : TnxMsgID;
aErrorCode : TnxResult;
aReplyData : Pointer;
aReplyDataLen : TnxWord32);
protected
function GetPluginEngine: TncnxServerPlugin;
procedure SetPluginEngine( aEngine: TncnxServerPlugin );
procedure bpchRemoveSession( aTransport: TnxBaseTransport;
aSessionId: TnxSessionID); override;
procedure bpchSessionFailed(aTransport : TnxBaseTransport;
aSessionID : TnxSessionID); override;
function Serv: TncServidorBase;
procedure nmLogin (var aMsg: TnxDataMessage);
procedure nmLogout (var aMsg: TnxDataMessage);
procedure nmNovoObj (var aMsg: TnxDataMessage);
procedure nmAlteraObj (var aMsg: TnxDataMessage);
procedure nmApagaObj (var aMsg: TnxDataMessage);
procedure nmObtemLista (var aMsg: TnxDataMessage);
procedure nmLoginMaq (var aMsg: TnxDataMessage);
procedure nmLogoutMaq (var aMsg: TnxDataMessage);
procedure nmDownloadArq (var aMsg: TnxDataMessage);
{
procedure nmDownloadArqInterno (var aMsg: TnxDataMessage);
}
procedure nmUploadArq (var aMsg: TnxDataMessage);
procedure nmObtemVersaoGuard (var aMsg: TnxDataMessage);
procedure nmPreLogoutMaq (var aMsg: TnxDataMessage);
procedure nmCancLogoutMaq (var aMsg: TnxDataMessage);
procedure nmSalvaTelaMaq (var aMsg: TnxDataMessage);
procedure nmCapturaTelaMaq (var aMsg: TnxDataMessage);
procedure nmObtemStreamConfig (var aMsg: TnxDataMessage);
procedure nmPararTempoMaq (var aMsg: TnxDataMessage);
procedure nmTransferirMaq (var aMsg: TnxDataMessage);
procedure nmRefreshPrecos (var aMsg: TnxDataMessage);
procedure nmShutdown (var aMsg: TnxDataMessage);
procedure nmModoManutencao (var aMsg: TnxDataMessage);
procedure nmAdicionaPassaporte (var aMsg: TnxDataMessage);
procedure nmPaginasImpressas (var aMsg: TnxDataMessage);
procedure nmAvisos (var aMsg: TnxDataMessage);
procedure nmObtemPastaServ (var aMsg: TnxDataMessage);
procedure nmArqFundoEnviado (var aMsg: TnxDataMessage);
procedure nmObtemSenhaCli (var aMsg: TnxDataMessage);
procedure nmSalvaSenhaCli (var aMsg: TnxDataMessage);
procedure nmLimpaFundo (var aMsg: TnxDataMessage);
procedure nmEnviaChat (var aMsg: TnxDataMessage);
procedure nmSalvaCredTempo (var aMsg: TnxDataMessage);
procedure nmAlteraSessao (var aMsg: TnxDataMessage);
procedure nmCancelaTran (var aMsg: TnxDataMessage);
procedure nmSalvaMovEst (var aMsg: TnxDataMessage);
procedure nmSalvaDebito (var aMsg: TnxDataMessage);
procedure nmSalvaImpressao (var aMsg: TnxDataMessage);
procedure nmAbreCaixa (var aMsg: TnxDataMessage);
procedure nmFechaCaixa (var aMsg: TnxDataMessage);
procedure nmObtemProcessos (var aMsg: TnxDataMessage);
procedure nmFinalizaProcesso (var aMsg: TnxDataMessage);
procedure nmSalvaProcessos (var aMsg: TnxDataMessage);
procedure nmObtemSitesBloq (var aMsg: TnxDataMessage);
procedure nmRefreshEspera (var aMsg: TnxDataMessage);
procedure nmPermitirDownload (var aMsg: TnxDataMessage);
procedure nmDesativarFWSessao (var aMsg: TnxDataMessage);
procedure nmDesktopSincronizado(var aMsg: TnxDataMessage);
procedure nmMonitorOnOff (var aMsg: TnxDataMessage);
procedure nmSalvaLancExtra (var aMsg: TnxDataMessage);
procedure nmSalvaDebTempo (var aMsg: TnxDataMessage);
procedure nmCorrigeDataCaixa (var aMsg: TnxDataMessage);
procedure nmRefreshSessao (var aMsg: TnxDataMessage);
procedure nmSuporteRem (var aMsg: TnxDataMessage);
procedure nmSalvaLic (var aMsg: TnxDataMessage);
procedure nmObtemPatrocinios (var aMsg: TnxDataMessage);
procedure nmAjustaPontosFid (var aMsg: TnxDataMessage);
procedure nmSalvaAppUrlLog (var aMsg: TnxDataMessage);
procedure nmKeepAlive (var aMsg: TnxDataMessage);
procedure nmDisableAd (var aMsg: TnxDataMessage);
procedure nmSalvaClientPages (var aMsg: TnxDataMessage);
procedure nmJobControl (var aMsg: TnxDataMessage);
procedure nmApagaMsgCli (var aMsg: TnxDataMessage);
procedure nmStartPrintTransfer (var aMsg: TnxDataMessage);
procedure nmSendPTBlock (var aMsg: TnxDataMessage);
procedure nmGetPrintDoc (var aMsg: TnxDataMessage);
procedure nmPrintDocControl (var aMsg: TnxDataMessage);
procedure nmGetLoginData (var aMsg: TnxDataMessage);
procedure nmSalvaApp (var aMsg: TnxDataMessage);
procedure _bpchProcess( aMsg: PnxDataMessage;
var aHandled: Boolean);
public
procedure bpchProcess( aMsg: PnxDataMessage;
var aHandled: Boolean); override;
published
property PluginEngine: TncnxServerPlugin
read GetPluginEngine
write SetPluginEngine;
end;
procedure Register;
implementation
uses SysUtils,
nxllMemoryManager,
nxstMessages,
nxllBDE,
nxllStreams, ncDebug, ncSessao, ncCredTempo, ncDebito, ncDebTempo,
ncImpressao, ncLancExtra, ncMovEst, ncMsgCom, ncErros, ncServBD,
ncPRConsts,
ncsCallbackEvents, ncVersionInfo, uLicEXECryptor, ncServAtualizaLic_Indy;
function BoolStr(B: Boolean): String;
begin
if B then
Result := 'True' else
Result := 'False';
end;
procedure Register;
begin
RegisterComponents('NexCafe',
[ TncnxServerPlugin,
TncnxCmdHandler ]);
end;
{ TncnxServerPlugin }
procedure TncnxServerPlugin.BroadcastKeepAlive;
var
I : Integer;
Dummy : Array[1..128] of Byte;
begin
Fillchar(Dummy, SizeOf(Dummy), $FF);
try
if not ServidorAtivo then Exit;
dmServidorBD.nxTCPIP.Broadcast(ncnmKeepAlive, 0, @Dummy, SizeOf(Dummy), 100);
except
end;
end;
constructor TncnxServerPlugin.Create(aOwner: TComponent);
begin
inherited;
FNexServ := nil;
end;
procedure TncnxServerPlugin.OnEnviaEvento(aMsg: Integer; aDados: Pointer);
var
SS : TArraySessionSocket;
begin
DebugMsg('TncnxServerPlugin.OnEnviaEvento - 1');
if not ServidorAtivo then Exit;
DebugMsg('TncnxServerPlugin.OnEnviaEvento - 2');
FNexServ.ObtemSessionSocketArray(0, SS);
try
DebugMsg('TncnxServerPlugin.OnEnviaEvento - 3');
gCallbackMgr.AddEvent(TncCallbackEvent.CreateMsgCom(aMsg, aDados, SS));
DebugMsg('TncnxServerPlugin.OnEnviaEvento - 4');
finally
FreeDados(aMsg, aDados);
end;
DebugMsg('TncnxServerPlugin.OnEnviaEvento - 5');
end;
function TncnxServerPlugin.spRemoveSession(aSessionId: TnxSessionId): TnxResult;
var FCEList : TList;
begin
Result := DBIERR_NONE;
PostMessage(CliNotifyHandle, wm_removesession, aSessionID, 0);
gCallbackMgr.RemoveSession(aSessionID);
end;
class function TncnxServerPlugin.bpeIsRemote: Boolean;
begin
Result := False;
end;
function TncnxServerPlugin.scShowUpTime: Boolean;
begin
Result := True;
end;
procedure TncnxServerPlugin.SetNexServ(const Value: TncServidorBase);
begin
if FNexServ=Value then Exit;
if FNexServ<>nil then FNexServ.OnEnviaEvento := nil;
FNexServ := Value;
if FNexServ<>nil then FNexServ.OnEnviaEvento := OnEnviaEvento;
end;
{ TncnxCmdHandler }
function TncnxCmdHandler.GetPluginEngine: TncnxServerPlugin;
begin
Result := TncnxServerPlugin(bpchPluginEngine);
end;
procedure TncnxCmdHandler.SendReply(aEventos: TList; aMsgID: TnxMsgID;
aErrorCode: TnxResult; aReplyData: Pointer; aReplyDataLen: TnxWord32);
begin
TnxBaseTransport.Reply(aMsgID, aErrorCode, aReplyData, aReplyDataLen);
end;
function TncnxCmdHandler.Serv: TncServidorBase;
begin
Result := PluginEngine.NexServ;
end;
procedure TncnxCmdHandler.ServLock(aSessionID: TnxSessionID);
begin
DebugMsg('TncnxCmdHandle.ServLock 1');
if not ServidorAtivo then begin
DebugMsg('TncnxCmdHandle.ServLock 2');
Raise Exception.Create('Servidor Inativo');
end;
DebugMsg('TncnxCmdHandle.ServLock 3');
Serv.Lock;
DebugMsg('TncnxCmdHandle.ServLock 4');
if not ServidorAtivo then begin
DebugMsg('TncnxCmdHandle.ServLock 5');
Serv.Unlock;
Raise Exception.Create('Servidor Inativo');
end;
try
DebugMsg('TncnxCmdHandle.ServLock 6');
Serv.ObtemUsernameHandlePorSessionID(aSessionID, UsernameAtual, HandleCliAtual);
DebugMsg('TncnxCmdHandle.ServLock 7');
if SameText(UsernameAtual, 'proxy') then
UsernameAtual := '';
except
UsernameAtual := '';
HandleCliAtual := -1;
end;
end;
function TncnxCmdHandler.ServUnlock: TList;
begin
try
Result := nil;
finally
PluginEngine.FNexServ.Unlock;
end;
end;
procedure TncnxCmdHandler.SetPluginEngine( aEngine: TncnxServerPlugin );
begin
bpchSetPluginEngine(aEngine);
end;
procedure TncnxCmdHandler.nmAbreCaixa(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
R : TnmAbreCaixaRpy;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmAbreCaixaReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmAbreCaixa - nmFunc: ' + nmFunc);
Erro := Serv.AbreCaixa(nmFunc, nmSaldo, R.nmID);
DebugMsg('TncnxCmdHandler.nmAbreCaixa - Res: ' + IntToStr(Erro) + ' - nmID: ' + IntToStr(R.nmID));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmAbreCaixa - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, @R, SizeOf(R));
end;
procedure TncnxCmdHandler.nmCancelaTran(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmCancelaTranReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmCancelaTran - nmTran: ' + IntToStr(nmTran) + ' - nmFunc: ' + nmFunc);
Erro := Serv.CancelaTran(nmTran, nmFunc);
DebugMsg('TncnxCmdHandler.nmCancelaTran - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmCancelaTran - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmCancLogoutMaq(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmLogoutMaqReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmCancLogoutMaq - nmMaq: ' + IntToStr(nmMaq));
Erro := Serv.CancLogoutMaq(nmMaq);
DebugMsg('TncnxCmdHandler.nmCancLogoutMaq - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmCancLogoutMaq - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmCapturaTelaMaq(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
C : TmsgCapturaTela;
SS: TArraySessionSocket;
begin
Erro := 0;
ServLock(aMsg.dmSessionID);
with aMsg, TnmCapturaTela(dmData^) do
try
try
nmSession := aMsg.dmSessionID;
Serv.ObtemSessionSocketArray(nmMaq, SS);
DebugMsg('TncnxCmdHandler.nmCapturaTelaMaq - nmMaq: ' + IntToStr(nmMaq));
C.msgSession := aMsg.dmSessionID;
C.msgMaq := nmMaq;
if Length(SS)>0 then
gCallbackMgr.AddEvent(TncCallbackEvent.CreateMsg(ncnmCapturaTelaEv, dmData, dmDataLen, SS));
{ if Length(SS)>0 then
TnxBaseTransport(SS[0].ssSocket).Post(0, SS[0].ssSession, 0, ncnmCapturaTelaEv, dmData, dmDataLen, 3000);}
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmCapturaTelaMaq - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
{var
Erro : TnxResult; CEList : TList;
A : TSessionArray;
C : TmsgCapturaTela;
begin
Erro := 0;
ServLock(aMsg.dmSessionID);
with aMsg, TnmCapturaTela(dmData^) do
try
try
nmSession := aMsg.dmSessionID;
DebugMsg('TncnxCmdHandler.nmCapturaTelaMaq - nmMaq: ' + IntToStr(nmMaq));
C.msgSession := aMsg.dmSessionID;
C.msgMaq := nmMaq;
Self.PluginEngine.OnEnviaEvento(ncmc_CapturaTela, @C);
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmCapturaTelaMaq - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;}
procedure TncnxCmdHandler.nmCorrigeDataCaixa(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmCorrigeDataCaixaReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmCorrigeDataCaixa - nmFunc: ' + nmFunc +
' - nmCaixa: ' + IntToStr(nmCaixa) +
' - nmNovaAbertura: ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', nmNovaAbertura) +
' - nmNovoFechamento: ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', nmNovoFechamento));
Erro := Serv.CorrigeDataCaixa(nmFunc, nmCaixa, nmNovaAbertura, nmNovoFechamento);
DebugMsg('TncnxCmdHandler.nmCorrigeDataCaixa - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmCorrigeDataCaixa - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmDisableAd(var aMsg: TnxDataMessage);
var Erro: TnxResult; CEList: TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmDisableAdReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmDisableAd - nmSessao: ' + IntToStr(nmSessao) +
' - nmDisable: ' + BoolStr(nmDisable));
Erro := Serv.DisableAd(nmSessao, nmDisable);
DebugMsg('TncnxCmdHandler.nmDisableAd - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmDisableAd - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmDownloadArq(var aMsg: TnxDataMessage);
var
S: TnxMemoryStream;
Str: String;
Erro : TnxResult;
CEList : TList;
begin
S := TnxMemoryStream.Create;
try
ServLock(aMsg.dmSessionID);
try
with aMsg, TnmNomeArq(aMsg.dmData^) do
try
DebugMsg('TncnxCmdHandler.nmDownloadArq - NomeArq: ' + nmNomeArq);
Str := ExtractFilePath(ParamStr(0)) + nmNomeArq;
if FileExists(Str) then begin
Erro := 0;
S.LoadFromFile(Str);
end else
Erro := ncerrArqNaoEncontrado;
DebugMsg('TncnxCmdHandler.nmDownloadArq - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmDownloadArq - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, S.Memory, S.Size);
finally
S.Free;
end;
end;
{
procedure TncnxCmdHandler.nmDownloadArqInterno(var aMsg: TnxDataMessage);
var
S: TnxMemoryStream;
Erro : TnxResult;
DM : TdmArqInt;
begin
S := TnxMemoryStream.Create;
try
with aMsg, TnmDownArqInt(aMsg.dmData^) do
try
DebugMsg('TncnxCmdHandler.nmDownloadArqInterno - nmArq: ' + nmArq + ' - nmVer: ' + IntToStr(nmVer));
DM := TdmArqInt.Create(nil);
try
Erro := DM.getArq(nmArq, nmVer, S)
finally
DM.Free;
end;
DebugMsg('TncnxCmdHandler.nmDownloadArqInterno - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmDownloadArqInterno - Exception: ' + E.Message);
end;
end;
if (Erro<10000) then
SendReply(nil, aMsg.dmMsg, Erro, nil, 0) else
SendReply(nil, aMsg.dmMsg, Erro, S.Memory, S.Size);
finally
S.Free;
end;
end;
}
procedure TncnxCmdHandler.nmEnviaChat(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
SL: TStrings;
De, Para: Integer;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
SL := TStringList.Create;
try
SL.LoadFromStream(TheStream);
De := StrToInt(SL.Values['de']);
Para := StrToInt(SL.Values['para']);
SL.Delete(0);
SL.Delete(0);
SL.Delete(0);
SL.Delete(0);
DebugMsg('TncnxCmdHandler.nmEnviaChat - De: ' + IntToStr(De) +
' - Para: ' + IntToStr(Para) +
' - Texto: ' + SL.Text);
Erro := Serv.EnviarMsg(De, Para, SL.Text);
DebugMsg('TncnxCmdHandler.nmEnviaChat - Res: ' + IntToStr(Erro));
finally
SL.Free;
end;
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmCancLogoutMaq - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmFechaCaixa(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmFechaCaixaReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmFechaCaixa - nmFunc: ' + nmFunc +
' - nmID: ' + IntToStr(nmID));
Erro := Serv.FechaCaixa(nmFunc, nmSaldo, nmID);
DebugMsg('TncnxCmdHandler.nmFechaCaixa - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmFechaCaixa - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmFinalizaProcesso(var aMsg: TnxDataMessage);
var
Erro: TnxResult; CEList: TList;
SS: TArraySessionSocket;
begin
Erro := 0;
ServLock(aMsg.dmSessionID);
with aMsg, TnmFinalizaProcesso(dmData^) do
try
try
Serv.ObtemSessionSocketArray(nmMaq, SS);
DebugMsg('TncnxCmdHandler.nmFinalizaProcesso - nmMaq: ' + IntToStr(nmMaq) +
' - nmProcessID: ' + IntToStr(nmProcessID));
if Length(SS)>0 then
gCallbackMgr.AddEvent(TncCallbackEvent.CreateMsg(ncnmFinalizaProcessoEv, dmData, dmDataLen, SS));
// TnxBaseTransport(SS[0].ssSocket).Post(0, SS[0].ssSession, 0, ncnmFinalizaProcessoEv, dmData, dmDataLen, 1000);
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmFinalizaProcesso - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmGetLoginData(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
I : Integer;
U : TncListaUsuarios;
S : TnxMemoryStream;
SL : TStrings;
begin
S := TnxMemoryStream.Create;
try
ServLock(aMsg.dmSessionID);
with aMsg do
try
try
Erro := 0;
DebugMsg('TncnxCmdHandler.nmGetLoginData');
SL := TStringList.Create;
try
sl.Add(Trim(prefixo_versao+Copy(SelfVersion, 7, 20)));
if gConfig.StatusConta in [scFree, scPremium, scPremiumVenc, scAnt] then
sl.Add(gConfig.Conta) else
sl.Add('');
U := TncListaUsuarios(Serv.ObtemLista(tcUsuario));
for I := 0 to U.Count - 1 do
SL.Add(U.Itens[I].Username+'='+U.Itens[I].Senha);
SL.SaveToStream(S);
finally
SL.Free;
end;
DebugMsg('TncnxCmdHandler.nmGetLoginData - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmGetLoginData - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, S.Memory, S.Size);
finally
S.Free;
end;
end;
procedure TncnxCmdHandler.nmGetPrintDoc(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
R : PnmGetPrintDocReply;
aLast: Boolean;
aTamTotal,
aTamBlock : Int64;
RLen : Integer;
procedure ReadFile(aArq: String; aPos: Int64);
var
F : TFileStream;
A : String;
const
MaxBlockSize = 1024 * 1000;
begin
Erro := 0;
try
A := PRFolder('s') + aArq + '.pdf';
if not FileExists(A) then begin
Erro := ncerrArqNaoEncontrado;
Exit;
end;
F := TFileStream.Create(A, fmOpenRead);
try
aTamTotal := F.Size;
if aPos > aTamTotal then begin
aTamBlock := 0;
aLast := True;
end else begin
aTamBlock := aTamTotal - aPos;
if aTamBlock>MaxBlockSize then
aTamBlock := MaxBlockSize;
F.Position := aPos;
end;
RLen := SizeOf( TnmGetPrintDocReply ) - SizeOf( TnxVarMsgField ) + aTamBlock + 1;
nxGetMem(R, RLen);
R.nmLast := aLast;
R.nmTamTotal := aTamTotal;
R.nmTamBlock := aTamBlock;
if aTamBlock>0 then
F.Read(R.nmBlock, aTamBlock);
finally
F.Free;
end;
except
Erro := 2;
end;
end;
begin
ServLock(aMsg.dmSessionID);
R := nil; RLen := 0;
with aMsg, TnmGetPrintDoc(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmGetPrintDoc'+
' - nmArq: ' + GuidToString(nmArq) +
' - nmPos: ' + IntToStr(nmPos));
ReadFile(GuidToString(nmArq), nmPos);
DebugMsg('TncnxCmdHandler.nmGetPrintDoc - Erro: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmGetPrintDoc - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
try
SendReply(CEList, aMsg.dmMsg, Erro, R, RLen);
finally
if Assigned(R) then nxFreeMem(R);
end;
end;
procedure TncnxCmdHandler.nmJobControl(var aMsg: TnxDataMessage);
var
Erro: TnxResult; CEList: TList;
begin
Erro := 0;
ServLock(aMsg.dmSessionID);
with aMsg, TnmJobControl(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmJobControl - nmPrinterIndex: ' + IntToStr(nmPrinterIndex) +
' - nmJobID: ' + IntToStr(nmJob) +
' - nmControl: ' + IntToStr(nmControl));
Erro := Serv.JobControl(nmPrinterIndex, nmJob, nmControl);
DebugMsg('TncnxCmdHandler.nmJobControl - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmJobControl - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmAdicionaPassaporte(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmAdicionaPassaporteReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmAdicionaPassaporte - nmMaq: ' + IntToStr(nmMaq) +
' - nmSenha: ' + nmSenha);
Erro := Serv.AdicionaPassaporte(nmMaq, nmSenha);
DebugMsg('TncnxCmdHandler.nmAdicionaPassaporte - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmAdicionaPassaporte - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmAjustaPontosFid(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmAjustaPontosFid(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmAjustaPontosFid - nmFunc: ' + nmFunc +
' - nmCliente: ' + IntToStr(nmCliente) +
' - nmFator: ' + IntToStr(nmFator) +
' - nmPontos: ' + FloatToStr(nmPontos) +
' - nmObs: ' + nmObs);
Erro := Serv.AjustaPontosFid(nmFunc, nmCliente, nmFator, nmPontos, nmObs);
DebugMsg('TncnxCmdHandler.nmAjustaPontosFid - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmAjustaPontosFid - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmAlteraObj(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
sCmd : String;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
if dmMsg=ncnmAlteraObj then
sCmd := 'TncnxCmdHandler.nmAlteraObj' else
sCmd := 'TncnxCmdHandler.nmNovoObj';
DebugMsg(sCmd);
Erro := Serv.SalvaStreamObj((dmMsg=ncnmNovoObj), TheStream);
DebugMsg(sCmd + ' - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg(sCmd + ' - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmAlteraSessao(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
S : TncSessao;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
S := TncSessao.Create(False);
try
S.LeStream(TheStream);
DebugMsg('TncnxCmdHandler.nmAlteraSessao - SessionID: ' + IntToStr(S.ID));
Erro := Serv.AlteraSessao(S);
DebugMsg('TncnxCmdHandler.nmAlterassao - Res: ' + IntToStr(Erro));
finally
S.Free;
end;
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmAlteraSessao - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmApagaMsgCli(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with TnmApagaMsgCli(aMsg.dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmApagaMsgCli - nmMsgID: ' + IntToStr(nmMsgID));
Erro := Serv.ApagaMsgCli(nmMsgID);
DebugMsg('TncnxCmdHandler.nmApagaMsgCli- Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmApagaMsgCli - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmApagaObj(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, PnmObj(dmData)^ do
try
try
DebugMsg('TncnxCmdHandler.nmApagaObj - nmCliente: ' + IntToStr(nmCliente) +
' - nmTipoClasse: ' + IntToStr(nmTipoClasse) +
' - nmChave: ' + nmChave);
Erro := Serv.ApagaObj(nmCliente, nmTipoClasse, nmChave);
DebugMsg('TncnxCmdHandler.nmApagaObj - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmApagaObj - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmArqFundoEnviado(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmNomeArq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmArqFundoEnviado - nmNomeArq: ' + nmNomeArq);
Erro := Serv.ArqFundoEnviado(nmNomeArq);
DebugMsg('TncnxCmdHandler.nmArqFundoEnviado - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmArqFundoEnviado - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmAvisos(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
S : TnxMemoryStream;
begin
S := TnxMemoryStream.Create;
try
ServLock(aMsg.dmSessionID);
with aMsg do
try
try
DebugMsg('TncnxCmdHandler.nmAvisos');
Erro := Serv.ObtemStreamAvisos(S);
DebugMsg('TncnxCmdHandler.nmAvisos - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmAvisos - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, S.Memory, S.Size);
finally
S.Free;
end;
end;
procedure TncnxCmdHandler.nmRefreshEspera(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg do
try
try
DebugMsg('TncnxCmdHandler.nmRefreshEspera');
Erro := Serv.RefreshEspera;
DebugMsg('TncnxCmdHandler.nmRefreshEspera - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmRefreshEspera - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmRefreshPrecos(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg do
try
try
DebugMsg('TncnxCmdHandler.nmRefreshPrecos');
Erro := Serv.RefreshPrecos;
DebugMsg('TncnxCmdHandler.nmRefreshPrecos - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmRefreshPrecos - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmRefreshSessao(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmSessao(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmRefreshSessao - nmSessao: ' + IntToStr(nmSessao));
Erro := Serv.ForceRefreshSessao(nmSessao);
DebugMsg('TncnxCmdHandler.nmRefreshSessao - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmRefreshSessao - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaApp(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
SL: TStrings;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
SL := TStringList.Create;
try
SL.LoadFromStream(TheStream);
DebugMsg('TncnxCmdHandler.nmSalvaApp - ' + sl.Text);
PostAppUpdate(sl);
Erro := 0;
DebugMsg('TncnxCmdHandler.nmSalvaApp - Res: ' + IntToStr(Erro));
finally
SL.Free;
end;
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaApp - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaAppUrlLog(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
DebugMsg('TncnxCmdHandler.nmSalvaAppUrlLog');
Erro := Serv.SalvaLogAppUrl(TheStream);
DebugMsg('TncnxCmdHandler.nmSalvaAppUrlLog - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaAppUrlLog - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaCredTempo(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
CT : TncCredTempo;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
DebugMsg('TncnxCmdHandler.nmSalvaCredTempo');
CT := TncCredTempo.Create;
try
CT.LoadFromStream(TheStream);
Erro := Serv.SalvaCredTempo(CT);
finally
CT.Free;
end;
DebugMsg('TncnxCmdHandler.nmSalvaCredTempo - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaCredTempo - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaDebito(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
Deb : TncDebito;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
DebugMsg('TncnxCmdHandler.nmSalvaDebito');
Deb := TncDebito.Create;
try
Deb.LeStream(TheStream);
Erro := Serv.SalvaDebito(Deb);
finally
Deb.Free;
end;
DebugMsg('TncnxCmdHandler.nmSalvaDebito - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaDebito - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaDebTempo(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
Deb : TncDebTempo;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
DebugMsg('TncnxCmdHandler.nmSalvaDebTempo');
Deb := TncDebTempo.Create;
try
Deb.LeStream(TheStream);
Erro := Serv.SalvaDebTempo(Deb);
finally
Deb.Free;
end;
DebugMsg('TncnxCmdHandler.nmSalvaDebTempo - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaDebTempo - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaImpressao(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
Imp : TncImpressao;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
DebugMsg('TncnxCmdHandler.nmSalvaImpressao');
Imp := TncImpressao.Create;
try
Imp.LoadFromStream(TheStream);
Erro := Serv.SalvaImpressao(Imp);
finally
Imp.Free;
end;
DebugMsg('TncnxCmdHandler.nmSalvaImpressao - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaImpressao - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaClientPages(var aMsg: TnxDataMessage);
var
Erro: TnxResult; CEList: TList;
begin
Erro := 0;
ServLock(aMsg.dmSessionID);
with aMsg, TnmClientPages(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmSalvaClientPages - nmImp: ' + nmImp +
' - nmJobID: ' + IntToStr(nmJobID) +
' - nmMaq: ' + IntToStr(nmMaq));
Erro := Serv.SalvaClientPages(nmImp, nmJobID, nmMaq, nmPaginas);
DebugMsg('TncnxCmdHandler.nmSalvaClientPages - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaClientPages - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaLancExtra(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
Le : TncLancExtra;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
DebugMsg('TncnxCmdHandler.nmSalvaLancExtra');
LE := TncLancExtra.Create;
try
LE.LeStream(TheStream);
Erro := Serv.SalvaLancExtra(LE);
finally
LE.Free;
end;
DebugMsg('TncnxCmdHandler.nmSalvaLancExtra - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaLancExtra - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaLic(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
SL : TStrings;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
SL := TStringList.Create;
try
SL.LoadFromStream(TheStream);
DebugMsg('TncnxCmdHandler.nmSalvaLic - Lic: '+SL.Text);
Erro := Serv.SalvaLic(SL.Text);
finally
SL.Free;
end;
DebugMsg('TncnxCmdHandler.nmSalvaLic - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaLic - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaMovEst(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
ME : TncMovEst;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
DebugMsg('TncnxCmdHandler.nmSalvaMovEst - HandleCliAtual: '+IntToStr(HandleCliAtual));
ME := TncMovEst.Create;
try
ME.LeStream(TheStream);
Erro := Serv.SalvaMovEst(ME);
finally
ME.Free;
end;
DebugMsg('TncnxCmdHandler.nmSalvaMovEst - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaMovEst - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaProcessos(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
SL : TStrings;
aIDCliente, aReq : Integer;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
SL := TStringList.Create;
try
SL.LoadFromStream(TheStream);
aIDCliente := StrToIntDef(SL[0], 0);
aReq := StrToIntDef(SL[1], 1);
SL.Delete(0);SL.Delete(0);
DebugMsg('TncnxCmdHandler.nmSalvaProcessos - SL.Text: '+SL.Text);
Erro := Serv.SalvaProcessos(aIDCliente, aReq, SL);
finally
SL.Free;
end;
DebugMsg('TncnxCmdHandler.nmSalvaProcessos - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaProcessos - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaSenhaCli(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmSenhaCli(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmSalvaSenhaCli - nmCodigo: ' + IntToStr(nmCodigo) +
' - nmSenha: ' + nmSenha);
Erro := Serv.SalvaSenhaCli(nmCodigo, nmSenha);
DebugMsg('TncnxCmdHandler.nmSalvaSenhaCli - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaSenhaCli - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaTelaMaq(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
C : TncCliente;
SS : TArraySessionSocket;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmSalvaTela(dmData^) do
try
try
Erro := 0;
DebugMsg('TncnxCmdHandler.nmSalvaTelaMaq - nmSession: ' + IntToStr(nmSession));
SetLength(SS, 1);
SS[0].ssSession := nmSession;
// C := Serv.ObtemClientePorSessionID(nmSession);
// if (C<>nil) and (C.SessionID>0) and (C.Socket<>0) then
gCallbackMgr.AddEvent(TncCallbackEvent.CreateMsg(ncnmSalvaTelaEv, dmData, dmDataLen, SS));
// TnxBaseTransport(C.Socket).Post(0, nmSession, 0, ncnmSalvaTelaEv, dmData, dmDataLen, 3000);
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaTelaMaq - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSendPTBlock(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmSendPTBlock(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmSendPTBlock'+
' - nmArq: ' + GuidToString(nmArq) +
' - nmLast: ' + BoolStr(nmLast) +
' - nmPos: ' + IntToStr(nmPos) +
' - nmTamanho: ' + IntToStr(nmTamanho));
Erro := Serv.SendPTBlock(nmArq, nmLast, nmTamanho, nmPos, @nmBlock);
DebugMsg('TncnxCmdHandler.nmSendPTBlock - Erro: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSendPTBlock - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmShutdown(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
SS: TArraySessionSocket;
I : Integer;
begin
Erro := 0;
ServLock(aMsg.dmSessionID);
with aMsg, TnmShutdown(dmData^) do
try
try
Serv.ObtemSessionSocketArray(nmMaq, SS);
DebugMsg('TncnxCmdHandler.nmShutdown - nmMaq: ' + IntToStr(nmMaq) +
' - nmOper: ' + IntToStr(nmOper));
if (nmMaq=High(Word)) then
for I := High(SS) downto 0 do
if (TncSessoes(Serv.ObtemLista(tcSessao)).PorMaq[SS[I].ssMaq]<>nil) then
DeleteFromArraySessionSocket(SS, I);
if Length(SS)>0 then
gCallbackMgr.AddEvent(TncCallbackEvent.CreateMsg(ncnmShutdownEv, dmData, dmDataLen, SS));
{ if (nmMaq<>High(Word)) or (TncSessoes(Serv.ObtemLista(tcSessao)).PorMaq[SS[I].ssMaq]=nil) then
try
TnxBaseTransport(SS[I].ssSocket).Post(0, SS[I].ssSession, 0, ncnmShutdownEv, dmData, dmDataLen, 1000);
except
end;}
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmShutdown - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmStartPrintTransfer(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
SL: TStrings;
S : String;
aPos: Int64;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
SL := TStringList.Create;
try
SL.LoadFromStream(TheStream);
DebugMsg('TncnxCmdHandler.nmStartPrintTransfer: ' + sLineBreak + SL.Text);
Erro := Serv.StartPrintTransfer(SL, aPos);
DebugMsg('TncnxCmdHandler.nmStartPrintTransfer: ' + IntToStr(Erro));
finally
SL.Free;
end;
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmStartPrintTransfer - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, @aPos, SizeOf(aPos));
end;
procedure TncnxCmdHandler.nmSuporteRem(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
SS: TArraySessionSocket;
I : Integer;
begin
Erro := 0;
ServLock(aMsg.dmSessionID);
with aMsg, TnmSuporteRem(dmData^) do
try
try
Serv.ObtemSessionSocketArray(nmMaq, SS);
DebugMsg('TncnxCmdHandler.nmSuporteRem - nmMaq: ' + IntToStr(nmMaq) +
' - nmTec: ' + IntToStr(nmTec));
if Length(SS)>0 then
gCallbackMgr.AddEvent(TncCallbackEvent.CreateMsg(ncnmSuporteRemEv, dmData, dmDataLen, SS));
{ for I := 0 to High(SS) do
TnxBaseTransport(SS[I].ssSocket).Post(0, SS[I].ssSession, 0, ncnmSuporteRemEv, dmData, dmDataLen, 1000);}
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSuporteRem - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmTransferirMaq(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmTransferirMaqReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmTransferirMaq - nmOrigem: ' + IntToStr(nmOrigem) +
' - nmDestino: ' + IntToStr(nmDestino));
Erro := Serv.TransferirMaq(nmOrigem, nmDestino);
DebugMsg('TncnxCmdHandler.nmTransferirMaq - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmTransferirMaq - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmUploadArq(var aMsg: TnxDataMessage);
var
S: TnxMemoryStream;
Str: String;
Erro : TnxResult;
CEList : TList;
begin
S := TnxMemoryStream.Create;
try
ServLock(aMsg.dmSessionID);
try
with aMsg, TnmUpload(aMsg.dmData^) do
try
DebugMsg('TncnxCmdHandler.nmUploadArq - NomeArq: ' + nmNomeArq +
' - Tamanho: ' + IntToStr(nmTamanho));
Str := ExtractFilePath(ParamStr(0)) + nmNomeArq;
if FileExists(Str) then
DeleteFile(Str);
S.SetSize(nmTamanho);
Move(nmArq, S.Memory^, nmTamanho);
S.SaveToFile(Str);
Erro := 0;
DebugMsg('TncnxCmdHandler.nmUploadArq - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmUploadArq - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
finally
S.Free;
end;
end;
procedure TncnxCmdHandler.nmKeepAlive(var aMsg: TnxDataMessage);
var Erro : Integer;
begin
if {getPluginEngine.SessaoTerminou(aMsg.dmSessionID)} not gCallbackMgr.SessionExists(aMsg.dmSessionID) then
Erro := 1 else {qualquer resultado diferente de zero força a cliente a desconectar}
Erro := 0;
TnxBaseTransport.Reply(aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmLimpaFundo(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmLimpaFundoReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmLimpaFundo - nmDesktop: ' + BoolStr(nmDesktop));
Erro := Serv.LimpaFundo(nmDesktop);
DebugMsg('TncnxCmdHandler.nmLimpaFundo - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmLimpaFundo - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
type
THackTransp = Class (TnxBasePooledTransport )
function GetRemoteAddress(aSessionID: TnxSessionID): String;
End;
procedure TncnxCmdHandler.nmLogin(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
R : TnmLoginRpy;
I : Integer;
S : String;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmLoginReq(dmData^) do
try
try
DebugMsg(
'TncnxCmdHandler.nmLogin - dmSessionID: ' + IntToStr(aMsg.dmSessionID) +
' - nmUsername: ' + nmUsername +
' - nmSenha: ' + nmSenha +
' - nmFuncAtual: ' + BoolStr(nmFuncAtual) +
' - nmMaq: ' + IntToStr(nmMaq) +
' - nmProxyHandle: ' + IntToStr(nmProxyHandle));
S := '';
I := Integer(TnxBaseTransport.CurrentTransport);
try
S := dmServidorBD.GetSessionIP(aMsg.dmSessionID);
if Pos(':', S)>0 then Delete(S, Pos(':', S), 100);
except
S := '';
end;
try
gCallbackMgr.AddSession(TncSessionCallback.Create(aMsg.dmSessionID, nmMaq, TnxBaseTransport.CurrentTransport));
Erro := Serv.Login(nmUsername, nmSenha, nmMaq, nmFuncAtual, True, 0, nmProxyHandle,
I, aMsg.dmSessionID, S, R.nmHandle);
except
gCallbackMgr.RemoveSession(aMsg.dmSessionID);
raise;
end;
DebugMsg('TncnxCmdHandler.nmLogin - dmSessionID: ' + IntToStr(aMsg.dmSessionID) +
' - nmUsername: ' + nmUsername +
' - nmSenha: ' + nmSenha +
' - nmFuncAtual: ' + BoolStr(nmFuncAtual) +
' - nmMaq: ' + IntToStr(nmMaq) +
' - nmHandle: ' + IntToStr(R.nmHandle) +
' - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmLogin - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, @R, SizeOf(R));
end;
procedure TncnxCmdHandler.nmLoginMaq(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
S : TncSessao;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
S := TncSessao.Create(False);
try
S.LeStream(TheStream);
DebugMsg(
'TncnxCmdHandler.nmLoginMaq - dmSessionID: ' + IntToStr(aMsg.dmSessionID) +
' - Username: ' + S.UsernameLogin +
' - Senha: ' + S.SenhaLogin);
Erro := Serv.LoginMaq(S);
DebugMsg('TncnxCmdHandler.nmLoginMaq - Res: ' + IntToStr(Erro));
finally
S.Free;
end;
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmLoginMaq - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmLogout(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg do
try
try
DebugMsg('TncnxCmdHandler.nmLogout - nmCliente: ' + IntToStr(Integer(dmData^)));
Serv.Logout(Integer(dmData^));
Erro := 0;
DebugMsg('TncnxCmdHandler.nmLogout - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmLogout - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmLogoutMaq(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmLogoutMaqReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmLogoutMaq - dmSessionID: ' + IntToStr(aMsg.dmSessionID) +
' - nmMaq: ' + IntToStr(nmMaq));
Erro := Serv.LogoutMaq(nmMaq);
DebugMsg('TncnxCmdHandler.nmLogoutMaq - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmLogoutMaq - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmModoManutencao(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmModoManutencaoReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmModoManutencao - nmMaq: ' + IntToStr(nmMaq) +
' - nmUsername: ' + nmUsername +
' - Senha: ' + nmSenha +
' - Entrar: ' + BoolStr(nmEntrar));
Erro := Serv.ModoManutencao(nmMaq, nmUsername, nmSenha, nmEntrar);
DebugMsg('TncnxCmdHandler.nmModoManutencao - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmModoManutencao - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmMonitorOnOff(var aMsg: TnxDataMessage);
var
Erro : TnxResult;
CEList : TList;
SS: TArraySessionSocket;
begin
Erro := 0;
ServLock(aMsg.dmSessionID);
with aMsg, TnmMonitorOnOff(dmData^) do
try
try
Serv.ObtemSessionSocketArray(nmMaq, SS);
DebugMsg('TncnxCmdHandler.nmMonitorOnOff - nmMaq: ' + IntToStr(nmMaq));
if Length(SS)>0 then
gCallbackMgr.AddEvent(TncCallbackEvent.CreateMsg(ncnmMonitorOnOffEv, dmData, dmDataLen, SS))
// TnxBaseTransport(SS[0].ssSocket).Post(0, SS[0].ssSession, 0, ncnmMonitorOnOffEv, dmData, dmDataLen, 3000)
else
DebugMsg('TncnxCmdHandler.nmMonitorOnOff - SS = 0');
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmMonitorOnOff - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmNovoObj(var aMsg: TnxDataMessage);
begin
nmAlteraObj(aMsg);
end;
procedure TncnxCmdHandler.nmObtemLista(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
S : TnxMemoryStream;
begin
S := TnxMemoryStream.Create;
try
ServLock(aMsg.dmSessionID);
with aMsg, TnmObtemListaReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmObtemLista - nmCliente: '+IntToStr(nmCliente) +
' - nmTipoClasse: ' + IntToStr(nmTipoClasse));
Erro := Serv.ObtemStreamListaObj(nmCliente, nmTipoClasse, S);
DebugMsg('TncnxCmdHandler.nmObtemLista - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmObtemLista - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, S.Memory, S.Size);
finally
S.Free;
end;
end;
procedure TncnxCmdHandler.nmObtemPastaServ(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
R : TnmNomeArq;
S : String;
begin
ServLock(aMsg.dmSessionID);
with aMsg do
try
try
Erro := Serv.ObtemPastaServ(S);
R.nmNomeArq := S;
DebugMsg('TncnxCmdHandler.nmObtemPastaServ - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmObtemPastaServ - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, @R, SizeOf(R));
end;
procedure TncnxCmdHandler.nmObtemPatrocinios(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
S : TnxMemoryStream;
SL : TStrings;
begin
S := TnxMemoryStream.Create;
try
ServLock(aMsg.dmSessionID);
with aMsg do
try
try
DebugMsg('TncnxCmdHandler.nmObtemPatrocinios');
SL := TStringList.Create;
try
Erro := Serv.ObtemPatrocinios(SL);
SL.SaveToStream(S);
finally
SL.Free;
end;
DebugMsg('TncnxCmdHandler.nmObtemPatrocinios - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmObtemPatrocinios - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, S.Memory, S.Size);
finally
S.Free;
end;
end;
procedure TncnxCmdHandler.nmObtemProcessos(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
SS: TArraySessionSocket;
begin
Erro := 0;
ServLock(aMsg.dmSessionID);
with aMsg, TnmObtemProcessos(dmData^) do
try
try
Serv.ObtemSessionSocketArray(nmMaq, SS);
DebugMsg('TncnxCmdHandler.nmObtemProcessos - nmIDCliente: ' + IntToStr(nmIDCliente) +
' - nmIDRequest: ' + IntToStr(nmIDRequest) +
' - nmMaq: ' + IntToStr(nmMaq));
if Length(SS)>0 then
gCallbackMgr.AddEvent(TncCallbackEvent.CreateMsg(ncnmObtemProcessosEv, dmData, dmDataLen, SS));
// TnxBaseTransport(SS[0].ssSocket).Post(0, SS[0].ssSession, 0, ncnmObtemProcessosEv, dmData, dmDataLen, 1000);
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmCapturaTelaMaq - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmObtemSenhaCli(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
R : TnmSenhaCli;
S : String;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmSenhaCli(dmData^) do
try
try
DebugMsg('TncnxCmdHandle.nmObtemSenhaCli - nmCodigo: ' + IntToStr(nmCodigo));
Erro := Serv.ObtemSenhaCli(nmCodigo, S);
R.nmSenha := S;
DebugMsg('TncnxCmdHandler.nmObtemSenhaCli - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmObtemSenhaCli - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, @R, SizeOf(R));
end;
procedure TncnxCmdHandler.nmObtemSitesBloq(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
S : TnxMemoryStream;
SL : TStrings;
Str : String;
begin
S := TnxMemoryStream.Create;
try
ServLock(aMsg.dmSessionID);
with aMsg do
try
try
DebugMsg('TncnxCmdHandler.nmObtemSitesBloq');
Erro := Serv.ObtemSitesBloqueados(Str);
if Erro=0 then begin
SL := TStringList.Create;
try
SL.Text := Str;
SL.SaveToStream(S);
finally
SL.Free;
end;
end;
DebugMsg('TncnxCmdHandler.nmObtemSitesBloq - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmObtemSitesBloq - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, S.Memory, S.Size);
finally
S.Free;
end;
end;
procedure TncnxCmdHandler.nmObtemStreamConfig(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
S : TnxMemoryStream;
begin
S := TnxMemoryStream.Create;
try
ServLock(aMsg.dmSessionID);
with aMsg do
try
try
DebugMsg('TncnxCmdHandler.nmObtemStreamConfig');
Erro := Serv.ObtemStreamConfig(S);
DebugMsg('TncnxCmdHandler.nmObtemStreamConfig - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmObtemStreamConfig - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, S.Memory, S.Size);
finally
S.Free;
end;
end;
procedure TncnxCmdHandler.nmObtemVersaoGuard(var aMsg: TnxDataMessage);
var
Erro : TnxResult;
CEList : TList;
Ver : Integer;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmPaginasImpressasReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmObtemVersaoGuard');
Erro := Serv.ObtemVersaoGuard(Ver);
DebugMsg('TncnxCmdHandler.nmObtemVersaoGuard - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmObtemVersaoGuard - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, @Ver, SizeOf(Integer));
end;
procedure TncnxCmdHandler.nmPaginasImpressas(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmPaginasImpressasReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmPaginasImpressas - nmMaq: ' + IntToStr(nmMaq) +
' - nmJobId: ' + IntToStr(nmJobID) +
' - nmPaginas: ' + IntToStr(nmPag) +
' - nmImp: ' + nmImp +
' - nmDoc: ' + nmDoc);
Erro := Serv.RegistraPaginasImpressas(nmJobID, nmMaq, nmPag, nmImp, nmDoc);
DebugMsg('TncnxCmdHandler.nmPaginasImpressas - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmPaginasImpressas - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmPararTempoMaq(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmPararTempoMaqReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmPararTempoMaq - nmMaq: ' + IntToStr(nmMaq) +
' - nmParar: ' + BoolStr(nmParar));
Erro := Serv.PararTempoMaq(nmMaq, nmParar);
DebugMsg('TncnxCmdHandler.nmPararTempoMaq - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmPararTempoMaq - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmPermitirDownload(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmPermitirDownloadReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmPermitirDownload - nmSessao: ' + IntToStr(nmSessao) +
' - nmExe: ' + BoolStr(nmExe) + '- nmPerm: ' + BoolStr(nmPerm));
Erro := Serv.PermitirDownload(nmSessao, nmExe, nmPerm);
DebugMsg('TncnxCmdHandler.nmPermitirDownload - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmPermitirDownload - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmDesativarFWSessao(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmDesativarFWSessaoReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmDesativarFWSessao - nmSessao: ' + IntToStr(nmSessao) +
' - nmPerm: ' + BoolStr(nmDesativar));
Erro := Serv.DesativarFWSessao(nmSessao, nmDesativar);
DebugMsg('TncnxCmdHandler.nmDesativarFWSessao - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmDesativarFWSessao - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmDesktopSincronizado(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmSessao(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmDesktopSincronizado - nmSessao: ' + IntToStr(nmSessao) +
' - nmPerm: ' + IntToStr(nmSessao));
Erro := Serv.DesktopSincronizado(nmSessao);
DebugMsg('TncnxCmdHandler.nmDesktopSincronizado - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmDesktopSincronizado - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmPreLogoutMaq(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmLogoutMaqReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmPreLogountMaq - nmMaq: ' + IntToStr(nmMaq));
Erro := Serv.PreLogoutMaq(nmMaq);
DebugMsg('TncnxCmdHandler.nmPreLogoutMaq - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmPreLogoutMaq - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmPrintDocControl(var aMsg: TnxDataMessage);
var
Erro : TnxResult;
CEList : TList;
S : AnsiString;
SL : TStrings;
begin
ServLock(aMsg.dmSessionID);
with aMsg do
try
SetLength(S, aMsg.dmDataLen);
Move(aMsg.dmData^, S[1], aMsg.dmDataLen);
try
SL := TStringList.Create;
try
SL.Text := S;
DebugMsg('TncnxCmdHandler.nmPrintDocControl - ' + S);
Erro := Serv.PrintDocControl(SL);
DebugMsg('TncnxCmdHandler.nmPrintDocControl - Res: ' + IntToStr(Erro));
finally
SL.Free;
end;
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmPrintDocControl - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.bpchProcess( aMsg: PnxDataMessage; var aHandled: Boolean );
begin
aHandled := False;
if (Serv=nil) or (not ServidorAtivo) then Exit;
IncPend;
try
try
if not ServidorAtivo then Exit;
_bpchProcess(aMsg, aHandled);
except
end;
finally
DecPend;
end;
end;
procedure TncnxCmdHandler._bpchProcess( aMsg: PnxDataMessage; var aHandled: Boolean );
begin
aHandled := True;
case aMsg^.dmMsg of
ncnmLogin : nmLogin(aMsg^);
ncnmLogout : nmLogout(aMsg^);
ncnmNovoObj : nmNovoObj(aMsg^);
ncnmAlteraObj : nmAlteraObj(aMsg^);
ncnmApagaObj : nmApagaObj(aMsg^);
ncnmObtemLista : nmObtemLista(aMsg^);
ncnmLoginMaq : nmLoginMaq(aMsg^);
ncnmLogoutMaq : nmLogoutMaq(aMsg^);
ncnmDownloadArq : nmDownloadArq(aMsg^);
// ncnmDownloadArqInterno : nmDownloadArqInterno(aMsg^);
ncnmUploadArq : nmUploadArq(aMsg^);
ncnmObtemVersaoGuard : nmObtemVersaoGuard(aMsg^);
ncnmPreLogoutMaq : nmPreLogoutMaq(aMsg^);
ncnmCancLogoutMaq : nmCancLogoutMaq(aMsg^);
ncnmSalvaTelaMaq : nmSalvaTelaMaq(aMsg^);
ncnmCapturaTelaMaq : nmCapturaTelaMaq(aMsg^);
ncnmObtemStreamConfig : nmObtemStreamConfig(aMsg^);
ncnmPararTempoMaq : nmPararTempoMaq(aMsg^);
ncnmTransferirMaq : nmTransferirMaq(aMsg^);
ncnmRefreshPrecos : nmRefreshPrecos(aMsg^);
ncnmShutdown : nmShutdown(aMsg^);
ncnmModoManutencao : nmModoManutencao(aMsg^);
ncnmAdicionaPassaporte : nmAdicionaPassaporte(aMsg^);
ncnmPaginasImpressas : nmPaginasImpressas(aMsg^);
ncnmAvisos : nmAvisos(aMsg^);
ncnmObtemPastaServ : nmObtemPastaServ(aMsg^);
ncnmArqFundoEnviado : nmArqFundoEnviado(aMsg^);
ncnmObtemSenhaCli : nmObtemSenhaCli(aMsg^);
ncnmSalvaSenhaCli : nmSalvaSenhaCli(aMsg^);
ncnmLimpaFundo : nmLimpaFundo(aMsg^);
ncnmEnviaChat : nmEnviaChat(aMsg^);
ncnmSalvaApp : nmSalvaApp(aMsg^);
ncnmSalvaCredTempo : nmSalvaCredTempo(aMsg^);
ncnmAlteraSessao : nmAlteraSessao(aMsg^);
ncnmCancelaTran : nmCancelaTran(aMsg^);
ncnmSalvaMovEst : nmSalvaMovEst(aMsg^);
ncnmSalvaDebito : nmSalvaDebito(aMsg^);
ncnmSalvaImpressao : nmSalvaImpressao(aMsg^);
ncnmAbreCaixa : nmAbreCaixa(aMsg^);
ncnmFechaCaixa : nmFechaCaixa(aMsg^);
ncnmObtemProcessos : nmObtemProcessos(aMsg^);
ncnmFinalizaProcesso : nmFinalizaProcesso(aMsg^);
ncnmSalvaProcessos : nmSalvaProcessos(aMsg^);
ncnmObtemSitesBloq : nmObtemSitesBloq(aMsg^);
ncnmRefreshEspera : nmRefreshEspera(aMsg^);
ncnmPermitirDownload : nmPermitirDownload(aMsg^);
ncnmDesativarFWSessao : nmDesativarFWSessao(aMsg^);
ncnmDesktopSincronizado: nmDesktopSincronizado(aMsg^);
ncnmMonitorOnOff : nmMonitorOnOff(aMsg^);
ncnmSalvaLancExtra : nmSalvaLancExtra(aMsg^);
ncnmSalvaDebTempo : nmSalvaDebTempo(aMsg^);
ncnmCorrigeDataCaixa : nmCorrigeDataCaixa(aMsg^);
ncnmRefreshSessao : nmRefreshSessao(aMsg^);
ncnmSuporteRem : nmSuporteRem(aMsg^);
ncnmSalvaLic : nmSalvaLic(aMsg^);
ncnmObtemPatrocinios : nmObtemPatrocinios(aMsg^);
ncnmAjustaPontosFid : nmAjustaPontosFid(aMsg^);
ncnmSalvaAppUrlLog : nmSalvaAppUrlLog(aMsg^);
ncnmKeepAlive : nmKeepAlive(aMsg^);
ncnmDisableAd : nmDisableAd(aMsg^);
ncnmSalvaClientPages : nmSalvaClientPages(aMsg^);
ncnmJobControl : nmJobControl(aMsg^);
ncnmApagaMsgCli : nmApagaMsgCli(aMsg^);
ncnmStartPrintTransfer : nmStartPrintTransfer(aMsg^);
ncnmSendPTBlock : nmSendPTBlock(aMsg^);
ncnmGetPrintDoc : nmGetPrintDoc(aMsg^);
ncnmPrintDocControl : nmPrintDocControl(aMsg^);
ncnmGetLoginData : nmGetLoginData(aMsg^);
else
aHandled := False;
end;
end;
procedure TncnxCmdHandler.bpchRemoveSession(aTransport: TnxBaseTransport;
aSessionId: TnxSessionID);
begin
inherited;
if not ServidorAtivo then Exit;
PluginEngine.spRemoveSession( aSessionID );
end;
procedure TncnxCmdHandler.bpchSessionFailed(aTransport: TnxBaseTransport;
aSessionID: TnxSessionID);
begin
inherited;
if not ServidorAtivo then Exit;
PluginEngine.spRemoveSession( aSessionID );
end;
{ THackTransp }
type
THackSession = class ( TnxBaseRemoteSession );
THackRemTransp = class ( TnxBaseRemoteTransport )
function IsSessionID(aSessionID: TnxSessionID): Boolean;
end;
function THackTransp.GetRemoteAddress(aSessionID: TnxSessionID): String;
var
i: Integer;
begin
Result := '';
with btRemoteTransports, BeginRead do try
for I := 0 to Count - 1 do
with THackRemTransp(Items[i]) do
if IsSessionID(aSessionID) then begin
Result := RemoteAddress;
if Trim(Result)<>'' then
Exit;
end;
finally
EndRead;
end
end;
{ THackRemTransp }
function THackRemTransp.IsSessionID(aSessionID: TnxSessionID): Boolean;
var i: Integer;
begin
Result := False;
with brtSessions, BeginRead do
try
for i := 0 to Count - 1 do
if THackSession(Items[I]).brsSessionID=aSessionID then begin
Result := True;
Exit;
end;
finally
EndRead;
end
end;
{ TncEventoFalhou }
initialization
TncnxServerPlugin.rcRegister;
TncnxCmdHandler.rcRegister;
finalization
TncnxServerPlugin.rcUnregister;
TncnxCmdHandler.rcUnregister;
end.
|
unit TestSortUses;
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestSortUses, released Sept 2004.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2000 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
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.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
{ AFS 12 Sept 04
Test the uses sort }
uses
TestFrameWork,
BaseTestProcess,
SetTransform;
type
TTestSortUses = class(TBaseTestProcess)
private
fbSaveSortInterfaceUses: Boolean;
fbSaveSortImplementationUses: Boolean;
fbSaveSortProgramUses: Boolean;
fbSaveBreakUsesSortOnReturn: Boolean;
fbSaveBreakUsesSortOnComment: Boolean;
feSaveUsesSortOrder: TUsesSortOrder;
fbSaveSortUsesNoComments: boolean;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmpty;
procedure Test1;
procedure Test2;
procedure Test2_outofOrder;
procedure Test2_outofOrder_DotNet;
procedure Test2_outofOrder_DotNet2;
procedure Test4_outofOrder_DotNet;
procedure Test6_outofOrder_DotNet;
procedure Test3;
procedure Test3_outofOrder;
procedure Test10_outofOrder;
procedure TestSectionsReturn1;
procedure TestSectionsReturn2;
procedure TestSectionsReturn3;
procedure TestSectionsReturnComma;
procedure TestComment1;
procedure TestComment2;
procedure TestComment3;
procedure TestSortByCommentSection1;
procedure TestSortByCommentSection2;
procedure TestProgram;
procedure TestIfDef1;
procedure TestIfDef2;
end;
implementation
uses
JcfStringUtils,
SortUses,
JcfSettings;
const
TEST_UNIT_START =
'unit TestUnit;' + NativeLineBreak + NativeLineBreak +
'interface' + NativeLineBreak;
TEST_UNIT_END =
NativeLineBreak +
'implementation' + NativeLineBreak + NativeLineBreak +
'end.';
procedure SetTestSortState;
begin
JcfFormatSettings.Transform.SortInterfaceUses := True;
JcfFormatSettings.Transform.UsesSortOrder := eAlpha;
JcfFormatSettings.Transform.BreakUsesSortOnReturn := False;
JcfFormatSettings.Transform.BreakUsesSortOnComment := False;
end;
procedure TTestSortUses.Setup;
begin
inherited;
{ save the sort uses state before we monkey with it }
fbSaveSortInterfaceUses := JcfFormatSettings.Transform.SortInterfaceUses;
fbSaveSortImplementationUses := JcfFormatSettings.Transform.SortImplementationUses;
fbSaveSortProgramUses := JcfFormatSettings.Transform.SortProgramUses;
fbSaveBreakUsesSortOnReturn := JcfFormatSettings.Transform.BreakUsesSortOnReturn;
fbSaveBreakUsesSortOnComment := JcfFormatSettings.Transform.BreakUsesSortOnComment;
feSaveUsesSortOrder := JcfFormatSettings.Transform.UsesSortOrder;
fbSaveSortUsesNoComments := JcfFormatSettings.Transform.SortUsesNoComments;
end;
procedure TTestSortUses.Teardown;
begin
{ restore sort uses state }
JcfFormatSettings.Transform.SortInterfaceUses := fbSaveSortInterfaceUses;
JcfFormatSettings.Transform.SortImplementationUses := fbSaveSortImplementationUses;
JcfFormatSettings.Transform.SortProgramUses := fbSaveSortProgramUses;
JcfFormatSettings.Transform.BreakUsesSortOnReturn := fbSaveBreakUsesSortOnReturn;
JcfFormatSettings.Transform.BreakUsesSortOnComment := fbSaveBreakUsesSortOnComment;
JcfFormatSettings.Transform.UsesSortOrder := feSaveUsesSortOrder;
fbSaveSortUsesNoComments := JcfFormatSettings.Transform.SortUsesNoComments;
inherited;
end;
procedure TTestSortUses.TestEmpty;
const
IN_UNIT_TEXT = TEST_UNIT_START + TEST_UNIT_END;
begin
SetTestSortState;
TestProcessResult(TSortUses, IN_UNIT_TEXT, IN_UNIT_TEXT);
end;
procedure TTestSortUses.Test1;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' uses aUnit;' + NativeLineBreak +
TEST_UNIT_END;
begin
SetTestSortState;
TestProcessResult(TSortUses, IN_UNIT_TEXT, IN_UNIT_TEXT);
end;
procedure TTestSortUses.Test2;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' uses aUnit, bUnit;' + NativeLineBreak +
TEST_UNIT_END;
begin
SetTestSortState;
TestProcessResult(TSortUses, IN_UNIT_TEXT, IN_UNIT_TEXT);
end;
procedure TTestSortUses.Test2_outofOrder;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' uses bUnit, aUnit;' + NativeLineBreak +
TEST_UNIT_END;
OUT_UNIT_TEXT = TEST_UNIT_START +
' uses aUnit, bUnit;' + NativeLineBreak +
TEST_UNIT_END;
begin
SetTestSortState;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSortUses.Test2_outofOrder_DotNet;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' uses Foo.bUnit, Foo.aUnit;' + NativeLineBreak +
TEST_UNIT_END;
OUT_UNIT_TEXT = TEST_UNIT_START +
' uses Foo.aUnit, Foo.bUnit;' + NativeLineBreak +
TEST_UNIT_END;
begin
SetTestSortState;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSortUses.Test2_outofOrder_DotNet2;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' uses Foo.bUnit, Bar.bUnit;' + NativeLineBreak +
TEST_UNIT_END;
OUT_UNIT_TEXT = TEST_UNIT_START +
' uses Bar.bUnit, Foo.bUnit;' + NativeLineBreak +
TEST_UNIT_END;
begin
SetTestSortState;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSortUses.Test4_outofOrder_DotNet;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' uses Foo.bUnit, Bar.aUnit, Bar.bUnit, Foo.aUnit;' + NativeLineBreak +
TEST_UNIT_END;
OUT_UNIT_TEXT = TEST_UNIT_START +
' uses Bar.aUnit, Bar.bUnit, Foo.aUnit, Foo.bUnit;' + NativeLineBreak +
TEST_UNIT_END;
begin
SetTestSortState;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSortUses.Test6_outofOrder_DotNet;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' uses Zed.Bee, Foo.bUnit, Bar.aUnit, Bar.bUnit, Foo.aUnit, System.Type;' + NativeLineBreak +
TEST_UNIT_END;
OUT_UNIT_TEXT = TEST_UNIT_START +
' uses Bar.aUnit, Bar.bUnit, Foo.aUnit, Foo.bUnit, System.Type, Zed.Bee;' + NativeLineBreak +
TEST_UNIT_END;
begin
SetTestSortState;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSortUses.Test3;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' uses aUnit, bUnit, cUnit;' + NativeLineBreak +
TEST_UNIT_END;
begin
SetTestSortState;
TestProcessResult(TSortUses, IN_UNIT_TEXT, IN_UNIT_TEXT);
end;
procedure TTestSortUses.Test3_outofOrder;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' uses cUnit, aUnit, bUnit;' + NativeLineBreak +
TEST_UNIT_END;
OUT_UNIT_TEXT = TEST_UNIT_START +
' uses aUnit, bUnit, cUnit;' + NativeLineBreak +
TEST_UNIT_END;
begin
SetTestSortState;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSortUses.Test10_outofOrder;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' uses dUnit, cUnit, wUnit, zUnit, fUnit, aUnit, bUnit, jUnit, nUnit, pUnit;' + NativeLineBreak +
TEST_UNIT_END;
OUT_UNIT_TEXT = TEST_UNIT_START +
' uses aUnit, bUnit, cUnit, dUnit, fUnit, jUnit, nUnit, pUnit, wUnit, zUnit;' + NativeLineBreak +
TEST_UNIT_END;
begin
SetTestSortState;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSortUses.TestSectionsReturn1;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' uses cUnit, aUnit,' + NativeLineBreak +
' zUnit, bUnit;' + NativeLineBreak +
TEST_UNIT_END;
OUT_UNIT_TEXT = TEST_UNIT_START +
' uses aUnit, cUnit, ' + NativeLineBreak +
' bUnit, zUnit;' + NativeLineBreak +
TEST_UNIT_END;
begin
SetTestSortState;
JcfFormatSettings.Transform.BreakUsesSortOnReturn := True;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSortUses.TestSectionsReturn2;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' uses aUnit,' + NativeLineBreak +
' zUnit, bUnit;' + NativeLineBreak +
TEST_UNIT_END;
OUT_UNIT_TEXT = TEST_UNIT_START +
' uses aUnit,' + NativeLineBreak +
' bUnit, zUnit;' + NativeLineBreak +
TEST_UNIT_END;
begin
SetTestSortState;
JcfFormatSettings.Transform.BreakUsesSortOnReturn := True;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);end;
procedure TTestSortUses.TestSectionsReturn3;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' uses cUnit, aUnit,' + NativeLineBreak +
' fUnit,' + NativeLineBreak +
' zUnit, bUnit;' + NativeLineBreak +
TEST_UNIT_END;
OUT_UNIT_TEXT = TEST_UNIT_START +
' uses aUnit, cUnit, ' + NativeLineBreak +
' fUnit,' + NativeLineBreak +
' bUnit, zUnit;' + NativeLineBreak +
TEST_UNIT_END;
begin
SetTestSortState;
JcfFormatSettings.Transform.BreakUsesSortOnReturn := True;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
{ Test for bug 1423817 - exta comma added at end of line
before comma at the start of the next line }
procedure TTestSortUses.TestSectionsReturnComma;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' Uses SysUtils {Exception}' + NativeLineBreak +
', WinTypes' +
';' + NativeLineBreak +
TEST_UNIT_END;
OUT_UNIT_TEXT = TEST_UNIT_START +
' Uses SysUtils {Exception}, ' + NativeLineBreak +
' WinTypes' +
';' + NativeLineBreak +
TEST_UNIT_END;
begin
SetTestSortState;
JcfFormatSettings.Transform.BreakUsesSortOnReturn := True;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSortUses.TestComment1;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' uses bUnit {a comment}, aUnit;' + NativeLineBreak +
TEST_UNIT_END;
OUT_UNIT_TEXT = TEST_UNIT_START +
' uses aUnit, bUnit {a comment};' + NativeLineBreak +
TEST_UNIT_END;
begin
SetTestSortState;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSortUses.TestComment2;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' uses bUnit, aUnit {a comment};' + NativeLineBreak +
TEST_UNIT_END;
OUT_UNIT_TEXT = TEST_UNIT_START +
' uses aUnit {a comment}, bUnit;' + NativeLineBreak +
TEST_UNIT_END;
begin
SetTestSortState;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSortUses.TestComment3;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' uses bUnit, // a comment' + NativeLineBreak +
' aUnit;' + NativeLineBreak +
TEST_UNIT_END;
OUT_UNIT_TEXT = TEST_UNIT_START +
' uses aUnit, bUnit, // a comment' + NativeLineBreak +
';' + NativeLineBreak + TEST_UNIT_END;
begin
SetTestSortState;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSortUses.TestSortByCommentSection1;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' uses bDUnit,' + NativeLineBreak +
' zDUnit,' + NativeLineBreak +
' fDUnit,' + NativeLineBreak +
' { new section }' + NativeLineBreak +
' gUnit,' + NativeLineBreak +
' aUnit,' + NativeLineBreak +
' cUnit; ' + NativeLineBreak +
TEST_UNIT_END;
OUT_UNIT_TEXT = TEST_UNIT_START +
' uses bDUnit,' + NativeLineBreak +
' fDUnit,' + NativeLineBreak +
' zDUnit,' + NativeLineBreak +
' { new section }' + NativeLineBreak +
' aUnit,' + NativeLineBreak +
' cUnit, gUnit; ' + NativeLineBreak + TEST_UNIT_END;
begin
SetTestSortState;
JcfFormatSettings.Transform.BreakUsesSortOnComment := True;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSortUses.TestSortByCommentSection2;
const
IN_UNIT_TEXT = TEST_UNIT_START +
' uses bDUnit,' + NativeLineBreak +
' zDUnit,' + NativeLineBreak +
' fDUnit,' + NativeLineBreak +
' // new section' + NativeLineBreak +
' gUnit,' + NativeLineBreak +
' aUnit,' + NativeLineBreak +
' cUnit; ' + NativeLineBreak +
TEST_UNIT_END;
OUT_UNIT_TEXT = TEST_UNIT_START +
' uses bDUnit,' + NativeLineBreak +
' fDUnit,' + NativeLineBreak +
' zDUnit,' + NativeLineBreak +
' // new section' + NativeLineBreak +
' aUnit,' + NativeLineBreak +
' cUnit, gUnit; ' + NativeLineBreak + TEST_UNIT_END;
begin
SetTestSortState;
JcfFormatSettings.Transform.BreakUsesSortOnComment := True;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSortUses.TestIfDef1;
const
IN_UNIT_TEXT = TEST_UNIT_START +
'uses' + NativeLineBreak +
' aZUnit, qZUnit, bZUnit, fZUNit,' + NativeLineBreak +
' {$IFDEF foo}' + NativeLineBreak +
' aUnit, gUnit, bUnit;' + NativeLineBreak +
' {$ELSE}' + NativeLineBreak +
' aQUnit, gQUnit, bQUnit;' + NativeLineBreak +
' {$ENDIF}' + NativeLineBreak +
TEST_UNIT_END;
OUT_UNIT_TEXT = TEST_UNIT_START +
'uses' + NativeLineBreak +
' aZUnit, bZUnit, fZUNit,' + NativeLineBreak +
' qZUnit, {$IFDEF foo}' + NativeLineBreak +
' aUnit, gUnit, bUnit;' + NativeLineBreak +
' {$ELSE}' + NativeLineBreak +
' aQUnit, bQUnit, gQUnit;' + NativeLineBreak +
' {$ENDIF}' + NativeLineBreak +
TEST_UNIT_END;
begin
SetTestSortState;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSortUses.TestIfDef2;
const
IN_UNIT_TEXT = TEST_UNIT_START +
'uses' + NativeLineBreak +
'aZUnit, qZUnit, bZUnit, fZUNit,' + NativeLineBreak +
'{$IFDEF foo}' + NativeLineBreak +
'aUnit, gUnit, bUnit,' + NativeLineBreak +
'{$ELSE}' + NativeLineBreak +
'aQUnit, gQUnit, bQUnit,' + NativeLineBreak +
'{$ENDIF}' + NativeLineBreak +
'xMUnit, gMUnit, rMUnit;' + NativeLineBreak +
TEST_UNIT_END;
OUT_UNIT_TEXT = TEST_UNIT_START +
'uses' + NativeLineBreak +
'aZUnit, bZUnit, fZUNit,' + NativeLineBreak +
'qZUnit, {$IFDEF foo}' + NativeLineBreak +
'aUnit, gUnit, bUnit,' + NativeLineBreak +
'{$ELSE}' + NativeLineBreak +
'aQUnit, bQUnit,' + NativeLineBreak +
'gQUnit, {$ENDIF}' + NativeLineBreak +
'gMUnit, rMUnit, xMUnit;' + NativeLineBreak +
TEST_UNIT_END;
begin
SetTestSortState;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSortUses.TestProgram;
const
IN_UNIT_TEXT =
' program Project1;' + NativeLineBreak + NativeLineBreak +
'{$APPTYPE CONSOLE}' + NativeLineBreak + NativeLineBreak +
'uses' + NativeLineBreak +
' SysUtils, Windows, Controls, Messages; ' + NativeLineBreak + NativeLineBreak +
'begin' + NativeLineBreak +
' Writeln(''Hello World !'');' + NativeLineBreak +
'end.';
OUT_UNIT_TEXT =
' program Project1;' + NativeLineBreak + NativeLineBreak +
'{$APPTYPE CONSOLE}' + NativeLineBreak + NativeLineBreak +
'uses' + NativeLineBreak +
' Controls, Messages, SysUtils, Windows; ' + NativeLineBreak + NativeLineBreak +
'begin' + NativeLineBreak +
' Writeln(''Hello World !'');' + NativeLineBreak +
'end.';
begin
SetTestSortState;
JcfFormatSettings.Transform.SortProgramUses := False;
{ no sorting for a program uses clause }
TestProcessResult(TSortUses, IN_UNIT_TEXT, IN_UNIT_TEXT);
{ now it will be sorted }
JcfFormatSettings.Transform.SortProgramUses := True;
TestProcessResult(TSortUses, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
initialization
TestFramework.RegisterTest('Processes', TTestSortUses.Suite);
end.
|
Program testeFeldZweitMax (input, output);
{ testet die Funktion FeldZweitMax }
Const
FELDGROESSE = 10;
Type
tIndex = 1..FELDGROESSE;
tFeld = array [tIndex] Of integer;
Var
Feld : tFeld;
i : integer;
function FeldZweitMax (Var inFeld : tFeld) : integer;
var
Max, ZweitMax: integer;
j: integer; {Laufzeitvariable für for-Schleife}
begin
{Anfangswerte setzen}
Max := inFeld[1];
ZweitMax := inFeld[2];
if(ZweitMax > Max) then {Ggf. vertauschen}
begin
Max := ZweitMax;
ZweitMax := inFeld[1];
end;
for j := 2 to FELDGROESSE do
begin
if(Max < inFeld[j]) then
begin
ZweitMax := Max; {Max-Wert ist nun der Zweitgrößte-Wert, da es noch größer als Max gibt}
Max := inFeld[j];
end
else {Auch wenn kein Wert größer als Max, gibt es eventuell noch einen zweitgrößten Wert im Array}
if(ZweitMax < inFeld[j]) then
ZweitMax := inFeld[j];
end; {for}
FeldZweitMax := ZweitMax;
end; { FeldZweitMax}
Begin { Testprogramm }
writeln('Bitte geben Sie ', FELDGROESSE, ' Zahlen ein:');
For i := 1 To FELDGROESSE Do
read (Feld [i]);
writeln('Die zweitgroesste Zahl ist ', FeldZweitMax (Feld), '.');
End. { testeFeldZweitMax }
|
program Sample;
var
H, G : String;
procedure hello(s : String);
var hstr : String;
begin
hstr := 'Hello';
WriteLn(hstr, ' ', s);
end;
begin
H := 'World';
G := H;
hello(G);
end.
|
{ **********************************************************}
{ }
{ DeskMetrics Installer Library }
{ Copyright (c) 2011 }
{ http://deskmetrics.com }
{ }
{ The entire contents of this file is protected by }
{ International Copyright Laws. Unauthorized }
{ reproduction, reverse-engineering, and distribution }
{ of all or any portion of the code contained in this }
{ file is strictly prohibited and may result in severe }
{ civil and criminal penalties and will be prosecuted }
{ to the maximum extent possible under the law. }
{ }
{ **********************************************************}
unit dskMetricsMSI;
interface
uses
Windows, SysUtils;
procedure _MSILogString(InstallHandle: Integer; FMessage: string);
function _MSITrackInstallation(const hInstall: Integer): UINT;
function _MSITrackUninstallation(const hInstall: Integer): UINT;
implementation
uses
dskMetricsInternals, dskMetricsVars, JwaMsi, JwaMsiQuery;
procedure _MSILogString(InstallHandle: Integer; FMessage: string);
var
FRecordHandle : Integer;
begin
if Length(FMessage) = 0 then
Exit;
FRecordHandle := MsiCreateRecord(2);
try
MsiRecordSetStringW(FRecordHandle, 0, PChar('DeskMetrics - ' + FMessage));
MsiProcessMessage(InstallHandle, INSTALLMESSAGE(INSTALLMESSAGE_INFO), FRecordHandle);
finally
MsiCloseHandle(FRecordHandle);
end;
end;
function _MSITrackInstallation(const hInstall: Integer): UINT;
var
FProductVersion: PAnsiChar;
FProductVersionSize: Cardinal;
FDeskMetricsID: PAnsiChar;
FDeskMetricsIDSize: Cardinal;
begin
try
try
FDeskMetricsID := AnsiStrAlloc(MAX_PATH);
FDeskMetricsIDSize := MAX_PATH;
FProductVersion := AnsiStrAlloc(MAX_PATH);
FProductVersionSize := MAX_PATH;
try
{ Retrieve the application data }
Result := MsiGetPropertyA(hInstall, 'DeskMetricsID', FDeskMetricsID, FDeskMetricsIDSize);
_MSILogString(hInstall, 'DeskMetricsID = ' + IntToStr(Result));
Result := MsiGetPropertyA(hInstall, 'ProductVersion', FProductVersion, FProductVersionSize);
_MSILogString(hInstall, 'ProductVersion = ' + IntToStr(Result));
{ Set variables }
FAppID := StrPas(FDeskMetricsID);
FAppVersion := StrPas(FProductVersion);
_MSILogString(hInstall, 'Application ID: ' + FAppID);
_MSILogString(hInstall, 'Application Version: ' + FAppVersion);
{ Track Installation }
case _TrackInstallation of
0: _MSILogString(hInstall, 'Installation tracked.');
10: _MSILogString(hInstall, 'Application ID not found.');
else
_MSILogString(hInstall, 'Error! Installation not tracked.')
end;
except
_MSILogString(hInstall, 'Unknown exception');
end;
Result := ERROR_SUCCESS;
finally
StrDispose(FDeskMetricsID);
StrDispose(FProductVersion);
end;
Result := ERROR_SUCCESS;
except
Result := ERROR_UNKNOWN_COMPONENT;
end;
end;
function _MSITrackUninstallation(const hInstall: Integer): UINT;
var
FProductVersion: PAnsiChar;
FProductVersionSize: Cardinal;
FDeskMetricsID: PAnsiChar;
FDeskMetricsIDSize: Cardinal;
begin
try
try
FDeskMetricsID := AnsiStrAlloc(MAX_PATH);
FDeskMetricsIDSize := MAX_PATH;
FProductVersion := AnsiStrAlloc(MAX_PATH);
FProductVersionSize := MAX_PATH;
try
{ Retrieve the application data }
Result := MsiGetPropertyA(hInstall, 'DeskMetricsID', FDeskMetricsID, FDeskMetricsIDSize);
_MSILogString(hInstall, 'DeskMetricsID = ' + IntToStr(Result));
Result := MsiGetPropertyA(hInstall, 'ProductVersion', FProductVersion, FProductVersionSize);
_MSILogString(hInstall, 'ProductVersion = ' + IntToStr(Result));
{ Set variables }
FAppID := StrPas(FDeskMetricsID);
FAppVersion := StrPas(FProductVersion);
_MSILogString(hInstall, 'Application ID: ' + FAppID);
_MSILogString(hInstall, 'Application Version: ' + FAppVersion);
{ Track Installation }
case _TrackUninstallation of
0: _MSILogString(hInstall, 'Uninstallation tracked.');
10: _MSILogString(hInstall, 'Application ID not found.');
else
_MSILogString(hInstall, 'Error! Uninstallation not tracked.')
end;
except
_MSILogString(hInstall, 'Unknown exception');
end;
Result := ERROR_SUCCESS;
finally
StrDispose(FDeskMetricsID);
StrDispose(FProductVersion);
end;
Result := ERROR_SUCCESS;
finally
Result := ERROR_UNKNOWN_COMPONENT;
end;
end;
end.
|
unit uZYZLogic;
interface
uses
System.Classes, System.UITypes,System.SysUtils, System.Types,System.Generics.Collections,
FMX.Dialogs,FMX.Types, uPublic,uEngine2DSprite,uEngine2DExtend;
const
SQUIRREL_INTERVAL = 5000;
BOARDER_BLINK_INTERVAL = 500;
START_APPLE_RANGE = 4; // 在1-4随机选取一个appleSprite为第一个
TOTAL_APPLE_COUNT = 8; //appleSprite总个数
LEAST_APPLE_COUNT = 4; //每道题至少显示的apple数
MAX_APPLE_COUNT = 7;
SHOW_STAR_COUNT = 7; //星星数量
FULL_STAR = 'x-1.png';
HALF_STAR = 'x-2.png';
EMPTY_STAR = 'x-3.png';
Type
TZYZLogic = class(TLogicWithStar)
private
FCurDragImage : TEngine2DImage;
FCopyDragSprite : TEngine2DSprite;
FEnter : boolean;
FCorrectList : TStringList;
FCurConfigName : String; //当前读取的配置文件名
FCurCorrectCount : Integer; //当前答对题数
FCurScore : Integer; //当前分数
FSquirrelTimer : TTimer;
FShowBoarderTimer : TTimer;
procedure ArrangeAppleTree;
procedure PlayAnimation(AIsRight:boolean);
procedure ReadScoreFromLocal;
procedure UpdateScore(AIsAdd : boolean = true);
procedure OnSquirrelTimer(Sender : TObject);
procedure OnBoarderBlink(Sender : TObject);
protected
procedure ClearAll;
procedure CopySpriteFromSrc(AImage : TEngine2DImage);
procedure CopySrcFromSprite(ASprite : TEngine2DSprite);
procedure UpdateStarStatus;
procedure OnNextTimer(Sender : TObject);override;
public
Destructor Destroy;override;
procedure Init;override;
procedure NextSight;override;
procedure MouseDownHandler(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);override;
procedure MouseMoveHandler(Sender: TObject; Shift: TShiftState; X, Y: Single);override;
procedure MouseUpHandler(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);override;
end;
implementation
uses
uEngineUtils,uEngineConfig,uEngine2DInvade,Math;
{ TZYZLogic }
procedure TZYZLogic.ArrangeAppleTree;
var
LStr,LTitle,LContent,LAnswer : String;
LList : TStringList;
LSprite : TEngine2DSprite;
LImage : TEngine2DImage;
LStartIndex,LShowCount,LMaxIndex,LAnswerIndex : Integer;
i: Integer;
LFileName : String;
begin
LStr := FIndexList.Strings[FCurIndex];
FCurConfigName := GetHeadString(LStr,'`');
LTitle := GetHeadString(LStr,'`');
LContent := GetHeadString(LStr,'`');
LAnswer := GetHeadString(LStr,'`');
LSprite := FEngineModel.SpriteList.Has('boardSprite');
LImage := TEngine2DImage(LSprite.Children.Has('TipImage'));
LImage.ImageConfig.SetNormalImg(LTitle+'.png');
try
LList := SplitString(LContent,' ');
LStartIndex := Random(START_APPLE_RANGE)+1;
LShowCount := LEAST_APPLE_COUNT + Random(TOTAL_APPLE_COUNT - LEAST_APPLE_COUNT);
LMaxIndex := LStartIndex + LShowCount - 1 ;
if LMaxIndex > TOTAL_APPLE_COUNT then
LMaxIndex := TOTAL_APPLE_COUNT;
LAnswerIndex := LStartIndex + Random(LMaxIndex - LStartIndex + 1);
LSprite := FEngineModel.SpriteList.Has('treeSprite');
for i := LStartIndex to LMaxIndex do
begin
if i = LAnswerIndex then
begin
LFileName := LAnswer + '.png';
FCorrectList.Add('cp_apple'+LAnswerIndex.ToString()+'Image');
end else
begin
LFileName := LList.Strings[Random(LList.Count)];
if LFileName.Equals(LAnswer) then
begin
FCorrectList.Add('cp_apple'+i.ToString()+'Image');
end;
LFileName := LFileName + '.png';
end;
LImage := TEngine2DImage(LSprite.Children.Has('apple'+i.ToString()+'Image'));
LImage.ImageConfig.SetNormalImg(LFileName);
LImage.Visible := true;
end;
finally
LList.DisposeOf;
end;
end;
procedure TZYZLogic.ClearAll;
var
LSprite : TEngine2DSprite;
LImage : TEngine2DImage;
i: Integer;
begin
FCorrectList.Clear;
FCurDragImage := nil;
FEnter := false;
FSquirrelTimer.Enabled := true;
FCurCorrectCount := 0;
LSprite := FEngineModel.SpriteList.Has('treeSprite');
for i := 1 to TOTAL_APPLE_COUNT do
begin
LImage := TEngine2DImage(LSprite.Children.Has('apple'+i.ToString()+'Image'));
if LImage <> nil then
LImage.Visible := false;
end;
end;
procedure TZYZLogic.CopySpriteFromSrc(AImage: TEngine2DImage);
var
LParentSprite : TEngine2DSprite;
LImage : TEngine2DImage;
LName : String;
begin
LParentSprite := FEngineModel.SpriteList.Has('treeSprite');
LName := 'cp_'+AImage.SpriteName;
if FEngineModel.SpriteList.Contains(LName) then
begin
FCopyDragSprite := FEngineModel.SpriteList.Has(LName);
FCopyDragSprite.Visible := true;
end else
begin
FCopyDragSprite := TEngine2DSprite.Create(LParentSprite.Image);
FCopyDragSprite.ResManager := LParentSprite.ResManager;
FCopyDragSprite.SetParentSize(LParentSprite.ParentPosition.InitWidth,LParentSprite.ParentPosition.InitHeight);
FCopyDragSprite.Name := LName;
FCopyDragSprite.InitWidth := FCurDragImage.InitWidth;
FCopyDragSprite.InitHeight := FCurDragImage.InitHeight;
FCopyDragSprite.InitX := AImage.InitX + LParentSprite.InitX;
FCopyDragSprite.InitY := AImage.InitY + LParentSprite.InitY;
FCopyDragSprite.HitTest := true;
FCopyDragSprite.OnMouseMove := MouseMoveHandler;
FCopyDragSPrite.OnMouseUp := MouseUpHandler;
FCopyDragSprite.Visible := true;
FCopyDragSprite.Align := GetAlignNew('7');
LImage := TEngine2DImage.Create(FCopyDragSprite.BackDrawCanvas);
LImage.SpriteName := 'cp_'+AImage.SpriteName;
LImage.ImageStatus := AImage.ImageStatus;
LImage.Align := GetAlignNew('9');
LImage.Visible := true;
LImage.ImageConfig := TImageConfig.Create(nil, FCopyDragSprite.ResManager);
LImage.ImageConfig.NormalBitmap.Assign(AImage.ImageConfig.NormalBitmap);
FCopyDragSprite.Children.Add(LImage.SpriteName, LImage);
FEngineModel.SpriteList.Add(FCopyDragSprite.Name,FCopyDragSprite);
end;
FCopyDragSprite.Resize(LParentSprite.ParentPosition.Width, LParentSprite.ParentPosition.Height);
FCopyDragSprite.X := AImage.X + LParentSprite.X;
FCopyDragSprite.Y := AImage.Y + LParentSprite.Y;
FCopyDragSprite.InitPosition := PointF(FCopyDragSprite.X, FCopyDragSprite.Y);
FCopyDragSprite.MouseDownPoint := PointF(LParentSprite.X + FCurDragImage.MouseDownPoint.X , LParentSprite.Y + FCurDragImage.MouseDownPoint.Y);
FCopyDragSprite.MouseIsDown := true;
FEngineModel.BringToFront(FCopyDragSprite);
end;
procedure TZYZLogic.CopySrcFromSprite(ASprite: TEngine2DSprite);
var
LParentSprite : TEngine2DSprite;
LSrcImage, LImage : TEngine2DImage;
LX,LY,LN : Single;
begin
LParentSprite := FEngineModel.SpriteList.Has('boarderSprite');
LX := LParentSprite.Width/LParentSprite.InitWidth;
LY := LParentSprite.Height/LParentSprite.InitHeight;
// LN := Math.min(LX,LY);
LSrcImage := TEngine2DImage(ASprite.Children.Items[0]);
LImage := TEngine2DImage.Create(LParentSprite.BackDrawCanvas);
LImage.SpriteName := 'dul_'+LSrcImage.SpriteName;
LImage.ImageStatus := LSrcImage.ImageStatus;
LImage.Align := GetAlignNew('7');
LImage.Visible := true;
LImage.ImageConfig := TImageConfig.Create(nil, LSrcImage.ResManager);
LImage.ImageConfig.NormalBitmap.Assign(LSrcImage.ImageConfig.NormalBitmap);
LImage.InitWidth := FCurDragImage.InitWidth;
LImage.InitHeight := FCurDragImage.InitHeight;
LImage.X := ASprite.X - LParentSprite.X;
LImage.Y := ASprite.Y - LParentSprite.Y;
LImage.Width := LSrcImage.Width;
LImage.Height := LSrcImage.Height;
LImage.InitX := (LImage.X + LImage.Width/2)/LX - LImage.InitWidth/2; //trunc((LImage.X)/LX);
LImage.InitY := (LImage.Y + LImage.Height/2)/LY - LImage.InitHeight/2; //trunc((LImage.Y)/LY);
LParentSprite.Children.Add(LImage.SpriteName,LImage);
end;
destructor TZYZLogic.Destroy;
begin
if Assigned(FSquirrelTimer) then
FSquirrelTimer.DisposeOf;
if Assigned(FCorrectList) then
FCorrectList.DisposeOf;
if Assigned(FShowBoarderTimer) then
FShowBoarderTimer.DisposeOf;
inherited;
end;
procedure TZYZLogic.Init;
begin
if Not Assigned(FCorrectList) then
FCorrectList := TStringList.Create;
if not Assigned(FSquirrelTimer) then
begin
FSquirrelTimer := TTimer.Create(nil);
FSquirrelTimer.Interval := SQUIRREL_INTERVAL;
FSquirrelTimer.OnTimer := OnSquirrelTimer;
FSquirrelTimer.Enabled := false;
end;
if Not Assigned(FShowBoarderTimer) then
begin
FShowBoarderTimer := TTimer.Create(nil);
FShowBoarderTimer.Interval := BOARDER_BLINK_INTERVAL;
FShowBoarderTimer.OnTimer := OnBoarderBlink;
FShowBoarderTimer.Enabled := false;
end;
FFullStarName := FULL_STAR;
FHalfStarName := HALF_STAR;
FEmptyStarName := EMPTY_STAR;
ClearAll;
ReadScoreFromLocal;
ArrangeAppleTree;
end;
procedure TZYZLogic.MouseDownHandler(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
var
LParentSprite,LSprite : TEngine2DSprite;
LImage : TEngine2DImage;
begin
if Sender.ClassName.Equals('TEngine2DImage') then
begin
if FCurIndex >= TotalCount then
begin
end else
begin
LSprite := FEngineModel.SpriteList.Has('treeSprite');
FCurDragImage := TEngine2DImage(Sender);
CopySpriteFromSrc(FCurDragImage);
FCurDragImage.Visible := false;
FShowBoarderTimer.Enabled := true;
end;
end;
end;
procedure TZYZLogic.MouseMoveHandler(Sender: TObject; Shift: TShiftState; X,
Y: Single);
var
LCon : TConvexPolygon;
begin
if Sender.ClassName.Equals('TEngine2DSprite') then
begin
if FCurIndex >= TotalCount then
begin
end else
begin
if FCopyDragSprite <> Sender then
exit;
if FCopyDragSprite.MouseIsDown then
begin
FCopyDragSprite.X := FCopyDragSprite.InitPosition.X + (X - FCopyDragSprite.MouseDownPoint.X);
FCopyDragSprite.Y := FCopyDragSprite.InitPosition.Y + (Y - FCopyDragSprite.MouseDownPoint.Y);
end;
LCon := FEngineModel.InvadeManager.GetInvadeObject(FCopyDragSprite.GetConvexPoints);
if LCon <> nil then
begin
FEnter := true;
end else
FEnter := false;
end;
end;
end;
procedure TZYZLogic.MouseUpHandler(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
var
LProc : TProc;
LRight : boolean;
LSprite : TEngine2DSprite;
LImage : TEngine2DImage;
begin
if Sender.ClassName.Equals('TEngine2DSprite') then
begin
if FCurIndex >= TotalCount then
begin
end else
begin
LRight := false;
FShowBoarderTimer.Enabled := false;
LSprite := FEngineModel.SpriteList.Has('boarderSprite');
LImage := TEngine2DImage(LSprite.Children.Has('boarderImage'));
LImage.Opacity := 0.1;
if FEnter then
begin
FCopyDragSprite.MouseIsDown := false;
FCopyDragSprite.Visible := false;
FEnter := false;
CopySrcFromSprite(FCopyDragSprite);
if FCorrectList.IndexOf(FCopyDragSprite.Name)>=0 then
LRight := true;
end else
begin
LProc := procedure()
begin
FCopyDragSprite.MouseIsDown := false;
FCurDragImage.Visible := true;
FCopyDragSprite.Visible := false;
end;
FCopyDragSprite.CreateMoveAnimation(PointF(X,Y),FCopyDragSprite.InitPosition, LProc);
end;
PlayAnimation(LRight);
end;
end else
if Sender.ClassName.Equals('TEngine2DImage') then
begin
LImage := TEngine2DImage(Sender);
if LImage.SpriteName.Equals('PlayAgain') then
begin
LSprite :=FEngineModel.SpriteList.Has('GraySprite');
LSprite.Visible := false;
LSprite := FEngineModel.SpriteList.Has('ResultSprite');
LSprite.Visible := false;
FCurIndex := -1;
NextSight;
end;
end;
end;
procedure TZYZLogic.NextSight;
var
LStr : String;
LSprite : TEngine2DSprite;
LImage : TEngine2DImage;
begin
inc(FCurIndex);
if FCurIndex >= TotalCount then
begin
LSprite :=FEngineModel.SpriteList.Has('GraySprite');
LSprite.Visible := true;
LSprite := FEngineModel.SpriteList.Has('ResultSprite');
LSprite.Visible := true;
FEngineModel.BringToFront(LSprite);
end else
begin
ClearAll;
LStr := FIndexList.Strings[FCurIndex];
FCurConfigName := GetHeadString(LStr,'`');
FEngineModel.LoadNextConfig(FCurConfigName);
UpdateScore(false); //加载新场景时 需重绘一下分数
ArrangeAppleTree;
end;
inherited;
end;
procedure TZYZLogic.OnBoarderBlink(Sender: TObject);
var
LSprite : TEngine2DSprite;
LImage : TEngine2DImage;
begin
LSprite := FEngineModel.SpriteList.Has('boarderSprite');
LImage := TEngine2DImage(LSprite.Children.Has('boarderImage'));
if LImage.Opacity = 1 then
LImage.Opacity := 0.1 else
LImage.Opacity := 1;
end;
procedure TZYZLogic.OnNextTimer(Sender: TObject);
begin
FNextTimer.Enabled := false;
NextSight;
end;
procedure TZYZLogic.OnSquirrelTimer(Sender: TObject);
var
I,J : Integer;
LSprite : TEngine2DSprite;
LImage : TEngine2DImage;
LParentWidth,LSquirrelRatio : Single;
LFinish : TProc;
begin
I := Random(5);
LSprite := FEngineModel.SpriteList.Has('squirrelSprite');
LImage := TEngine2DImage(LSprite.Children.Items[0]);
if I < 2 then
begin
LImage.Opacity := 0.01;
end else
begin
if Not (LImage.Opacity =1) then
begin
LImage.Opacity := 1;
LParentWidth := LSprite.ParentPosition.Width;
LSquirrelRatio := (LParentWidth * 0.2 + Random(trunc(LParentWidth * 0.4)))/LParentWidth;
LSprite.X := LParentWidth * LSquirrelRatio;
end;
FSquirrelTimer.Enabled := false;
J := Random(2);
LFinish := procedure()
begin
FSquirrelTimer.Enabled := true;
end;
if J = 0 then
LImage.ImageConfig.SwitchNormalControlerByName('squirrel2',LFinish) else
LImage.ImageConfig.SwitchNormalControlerByName('squirrel1',LFinish);
end;
end;
procedure TZYZLogic.PlayAnimation(AIsRight: boolean);
var
LSprite : TEngine2DSprite;
LImage : TEngine2DImage;
LFinish : TProc;
begin
LSprite := FEngineModel.SpriteList.Has('animalSprite');
LImage := LSprite.Children.Has('animalImage') as TEngine2DImage;
LFinish := procedure()
begin
LImage.ImageConfig.SwitchNormalControlerByName('Blink',nil);
end;
if AIsRight then
begin
UpdateScore;
LImage.ImageConfig.SwitchNormalControlerByName('right',LFinish);
inc(FCurCorrectCount);
if FCurCorrectCount >= FCorrectList.Count then
begin
PlayStarAnimationWhenDone(SHOW_STAR_COUNT);
FNextTimer.Enabled := true;
end;
end else
begin
LImage.ImageConfig.SwitchNormalControlerByName('wrong',LFinish);
dec(FCurIndex);
FNextTimer.Enabled := true;
end;
end;
procedure TZYZLogic.ReadScoreFromLocal;
begin
FCurScore := 0;
FStarCount := 3;
UpdateStarStatus;
end;
procedure TZYZLogic.UpdateScore(AIsAdd: boolean);
var
LSprite : TEngine2DSprite;
LText : TEngine2DText;
begin
if AIsAdd then
Inc(FCurScore);
LSprite := FEngineModel.SpriteList.Has('scoreSprite');
LText := TEngine2DText(LSprite.Children.Has('score'));
LText.Text := FCurScore.ToString();
end;
procedure TZYZLogic.UpdateStarStatus;
var
i: Integer;
begin
if Not Assigned(FEngineModel) then
raise Exception.Create('FEngineModel is Not Assigned,FEngineModel Should be Used After Engine Create');
for i := 1 to SHOW_STAR_COUNT do
begin
UpdateASingleStarStatus(i);
end;
end;
Initialization
RegisterLogicUnit(TZYZLogic,'ZYZLogic');
end.
|
unit Annotation.Utils;
interface
uses
System.Types;
function ViewportToImage(const ViewportPoint: TPoint;
const ViewportWidth, ViewportHeight, ImageWidth, ImageHeight: integer) :TPoint;
function IsOnImage(const Point: TPoint;
const ViewportWidth, ViewportHeight, ImageWidth, ImageHeight: integer): boolean;
procedure GetOffset(const ViewportWidth, ViewportHeight, ImageWidth, ImageHeight: integer; var XOffset, YOffset: integer);
implementation
uses
Math;
function ViewportToImage(const ViewportPoint: TPoint;
const ViewportWidth, ViewportHeight, ImageWidth, ImageHeight: integer) :TPoint;
var
XOffset, YOffset: integer;
X, Y: integer;
begin
Result:= TPoint.Create(0, 0);
GetOffset(ViewportWidth, ViewportHeight, ImageWidth, ImageHeight, XOffset, YOffset);
X:= ViewportPoint.X - XOffset;
Y:= ViewportPoint.Y - YOffset;
Result.X:= Round(ImageWidth * (X / (ViewportWidth - 2 * XOffset)));
Result.Y:= Round(ImageHeight * (Y / (ViewportHeight - 2 * YOffset)));
end;
function IsOnImage(const Point: TPoint;
const ViewportWidth, ViewportHeight, ImageWidth, ImageHeight: integer): boolean;
var
XOffset, YOffset: integer;
begin
GetOffset(ViewportWidth, ViewportHeight, ImageWidth, ImageHeight, XOffset, YOffset);
Result:= true;
if (Point.X < XOffset) or (Point.X > ImageWidth + XOffset) then
begin
Result:= false;
Exit;
end;
if (Point.Y < YOffset) or (Point.Y > ImageHeight + YOffset) then
begin
Result:= false;
Exit;
end;
end;
procedure GetOffset(const ViewportWidth, ViewportHeight, ImageWidth, ImageHeight: integer; var XOffset, YOffset: integer);
var
WidthRatio, HeightRatio: double;
ScaledImageWidth, ScaledImageHeight: integer;
begin
WidthRatio:= ImageWidth / ViewportWidth;
HeightRatio:= ImageHeight / ViewportHeight;
if Max(WidthRatio, HeightRatio) < 1 then
begin
XOffset:= (ViewportWidth - ImageWidth) div 2;
YOffset:= (ViewportHeight - ImageHeight) div 2;
Exit;
end;
ScaledImageWidth:= Round(ImageWidth / Max(WidthRatio, HeightRatio));
ScaledImageHeight:= Round(ImageHeight / Max(WidthRatio, HeightRatio));
XOffset:= (ViewportWidth - ScaledImageWidth) div 2;
YOffset:= (ViewportHeight - ScaledImageHeight) div 2;
end;
end.
|
unit u_select_inscription;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls;
type
{ Tf_select_inscription }
Tf_select_inscription = class(TForm)
btn_ok: TButton;
edt_code: TEdit;
edt_nom: TEdit;
edt_num: TEdit;
lbl_code: TLabel;
lbl_nom: TLabel;
lbl_num: TLabel;
pnl_ok: TPanel;
pnl_filiere_edit: TPanel;
pnl_filiere_btn: TPanel;
pnl_filiere: TPanel;
pnl_etud_edit: TPanel;
pnl_etud_btn: TPanel;
pnl_etud: TPanel;
pnl_tous_edit: TPanel;
pnl_tous_btn: TPanel;
pnl_tous: TPanel;
pnl_choix: TPanel;
pnl_titre: TPanel;
procedure btn_okClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Init;
procedure NonSelectionPanel (pnl : TPanel);
procedure AucuneSelection;
procedure pnl_choix_btnClick (Sender: TObject);
procedure pnl_okClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
f_select_inscription: Tf_select_inscription;
implementation
{$R *.lfm}
uses u_feuille_style, u_list_inscription, u_modele;
{ Tf_select_inscription }
var
pnl_actif : TPanel;
procedure Tf_select_inscription.FormCreate(Sender: TObject);
begin
end;
procedure Tf_select_inscription.btn_okClick(Sender: TObject);
begin
btn_ok.visible := false;
pnl_actif.enabled := false;
if pnl_tous_edit.Visible then
f_list_inscription.affi_data(modele.inscription_liste_tous)
else if pnl_etud_edit.visible then
f_list_inscription.affi_data(modele.inscription_liste_etudiant(edt_num.text, edt_nom.text))
else if pnl_filiere_edit.visible then
f_list_inscription.affi_data(modele.inscription_liste_filiere(edt_code.text))
end;
procedure Tf_select_inscription.Init;
begin
style.panel_defaut(pnl_choix);
style.panel_selection(pnl_titre);
style.panel_defaut(pnl_ok);
pnl_choix_btnClick (pnl_tous_btn);
end;
procedure Tf_select_inscription.pnl_choix_btnClick (Sender : TObject);
var pnl : TPanel;
begin
AucuneSelection; // retirer la sélection en cours
pnl := TPanel(Sender) ;
style.panel_selection (pnl);
pnl := TPanel(pnl.Parent); // récupération du panel parent "pnl_xxx"
style.panel_selection (pnl);
pnl := TPanel(f_select_inscription.FindComponent(pnl.name +'_edit'));
style.panel_selection (pnl);
pnl.show;
pnl_actif := pnl; pnl_actif.enabled := true;
btn_ok.visible := true;
end;
procedure Tf_select_inscription.pnl_okClick(Sender: TObject);
begin
end;
procedure Tf_select_inscription.NonSelectionPanel (pnl : TPanel);
var pnl_enfant : TPanel;
begin
style.panel_defaut(pnl); // affectation des paramètres Fonte et Couleur du panel pnl_choix
// récupération du panel '_btn'
pnl_enfant := TPanel(f_select_inscription.FindComponent(pnl.name +'_btn'));
style.panel_bouton(pnl_enfant);
// récupération du panel '_edit'
pnl_enfant := TPanel(f_select_inscription.FindComponent(pnl.name +'_edit'));
pnl_enfant.Hide;
end;
procedure Tf_select_inscription.AucuneSelection;
begin
NonSelectionPanel (pnl_tous); NonSelectionPanel (pnl_etud);
NonSelectionPanel (pnl_filiere);
end;
end.
|
{Except for source code formatting, this is a verbatim copy of:
Niklaus Wirth, "Algorithms + Data Structures = Programs", Program 4.7,
pp 252--257, Prentice-Hall, 1976. Compiled and tested with GNU Pascal.}
program Btree(input, output);
{B-tree search, insertion and deletion}
const
n = 2;
nn = 4; {page size}
type
ref = ^page;
item = record
key : integer;
p : ref;
count : integer;
end;
page = record
m : 0..nn; {no. of items}
p0 : ref;
e : array [1..nn] of item;
end;
var
root, q : ref;
x : integer;
h : boolean;
u : item;
procedure search(x : integer; a : ref; var h : boolean; var v : item);
{Search key x on B-tree with root a; if found, increment counter,
otherwise insert an item with key x and count 1 in tree. If an item
emerges to be passed to a lower level, then assign it to v;
h := "tree a has become higher"}
var k, l, r : integer; q : ref; u : item;
procedure insert;
var i : integer; b : ref;
begin {insert u to the right of a^.e[r]}
with a^ do
begin
if m < nn then
begin
m := m+1;
h := false;
for i := m downto r+2 do e[i] := e[i-1];
e[r+1] := u
end
else
begin
{page a^ is full; split it and assign the emerging item to v}
new(b);
if r <= n then
begin
if r = n then v := u
else
begin
v := e[n];
for i := n downto r+2 do e[i] := e[i-1];
e[r+1] := u
end;
for i := 1 to n do b^.e[i] := a^.e[i+n]
end
else
begin
{insert u in right page}
r := r-n;
v := e[n+1];
for i := 1 to r-1 do b^.e[i] := a^.e[i+n+1];
b^.e[r] := u;
for i := r+1 to n do b^.e[i] := a^.e[i+n]
end;
m := n;
b^.m := n;
b^.p0 := v.p;
v.p := b
end
end {with}
end {insert};
begin
{search key x on page a^; h = false}
if a = nil then
begin
{item with key x is not in tree}
h := true;
with v do
begin
key := x;
count := 1;
p := nil
end
end
else
with a^ do
begin
l := 1;
r := m;
{binary array search}
repeat
k := (l+r) div 2;
if x <= e[k].key then r := k-1;
if x >= e[k].key then l := k+1;
until r < l;
if l-r > 1 then
begin
{found}
e[k].count := e[k].count+1;
h := false
end
else
begin
{item is not on this page}
if r = 0 then q := p0 else q := e[r].p;
search(x, q, h, u);
if h then insert
end
end
end {search};
procedure delete(x : integer; a : ref; var h : boolean);
{search and delete key x in b-tree a; if a page underflow is
necessary, balance with adjacent page if possible, otherwise merge;
h := "page a is undersize"}
var i, k, l, r : integer; q : ref;
procedure underflow(c, a : ref; s : integer; var h : boolean);
{a = underflow page, c = ancestor page}
var b : ref; i, k, mb, mc : integer;
begin
mc := c^.m;
{h = true, a^.m = n-1}
if s < mc then
begin
{b := page to the right of a}
s := s+1;
b := c^.e[s].p;
mb := b^.m;
k := (mb-n+1) div 2;
{k = no. of items available on adjacent page b}
a^.e[n] := c^.e[s];
a^.e[n].p := b^.p0;
if k > 0 then
begin
{move k items from b to a}
for i := 1 to k-1 do a^.e[i+n] := b^.e[i];
c^.e[s] := b^.e[k];
c^.e[s].p := b;
b^.p0 := b^.e[k].p;
mb := mb-k;
for i := 1 to mb do b^.e[i] := b^.e[i+k];
b^.m := mb;
a^.m := n-1+k;
h := false
end
else
begin
{merge pages a and b}
for i := 1 to n do a^.e[i+n] := b^.e[i];
for i := s to mc-1 do c^.e[i] := c^.e[i+1];
a^.m := nn;
c^.m := mc-1;
{dispose(b)}
h := c^.m < n
end
end
else
begin
{b := page to the left of a}
if s = 1 then b := c^.p0
else b := c^.e[s-1].p;
mb := b^.m + 1;
k := (mb-n) div 2;
if k > 0 then
begin
{move k items from page b to a}
for i := n-1 downto 1 do a^.e[i+k] := a^.e[i];
a^.e[k] := c^.e[s];
a^.e[k].p := a^.p0;
mb := mb-k;
for i := k-1 downto 1 do a^.e[i] := b^.e[i+mb];
a^.p0 := b^.e[mb].p;
c^.e[s] := b^.e[mb];
c^.e[s].p := a;
b^.m := mb-1;
a^.m := n-1+k;
h := false
end
else
begin
{merge pages a and b}
b^.e[mb] := c^.e[s];
b^.e[mb].p := a^.p0;
for i := 1 to n-1 do b^.e[i+mb] := a^.e[i];
b^.m := nn;
c^.m := mc-1;
{dispose(a)}
h := c^.m < n
end
end
end {underflow};
procedure del(p : ref; var h : boolean);
var q : ref; {global a,k}
begin
with p^ do
begin
q := e[m].p;
if q <> nil then
begin
del(q, h);
if h then underflow(p, q, m, h)
end
else
begin
p^.e[m].p := a^.e[k].p;
a^.e[k] := p^.e[m];
m := m-1;
h := m < n
end
end
end {del};
begin {delete}
if a = nil then
begin
writeln('KEY IS NOT IN TREE');
h := false
end
else
with a^ do
begin
l := 1;
r := m;
{binary array search}
repeat
k := (l+r) div 2;
if x <= e[k].key then r := k-1;
if x >= e[k].key then l := k+1;
until l > r;
if r = 0 then q := p0 else q := e[r].p;
if l-r > 1 then
begin
{found, now delete e[k]}
if q = nil then
begin
{a is a terminal page}
m := m-1;
h := m < n;
for i := k to m do e[i] := e[i+1];
end
else
begin
del(q, h);
if h then underflow(a, q, r, h)
end
end
else
begin
delete(x, q, h);
if h then underflow(a, q, r, h)
end
end
end {delete};
procedure printtree(p : ref; l : integer);
var i : integer;
begin
if p <> nil then
with p^ do
begin
for i := 1 to l do write(' ');
for i := 1 to m do write(e[i].key : 4);
writeln;
printtree(p0, l+1);
for i := 1 to m do printtree(e[i].p, l+1)
end
end;
begin
root := nil;
read(x);
while x <> 0 do
begin
writeln('SEARCH KEY ', x);
search(x, root, h, u);
if h then
begin
{insert new base page}
q := root;
new(root);
with root^ do
begin
m := 1;
p0 := q;
e[1] := u
end
end;
printtree(root, 1);
read(x)
end;
read(x);
while x <> 0 do
begin
writeln('DELETE KEY ', x);
delete(x, root, h);
if h then
begin
{base page size was reduced}
if root^.m = 0 then
begin
q := root;
root := q^.p0;
{dispose(q)}
end
end;
printtree(root, 1);
read(x)
end
end.
|
{-------------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is: SynUniHighlighter.pas, released 2003-01
All Rights Reserved.
Alternatively, the contents of this file may be used under the terms of the
GNU General Public License Version 2 or later (the "GPL"), in which case
the provisions of the GPL are applicable instead of those above.
If you wish to allow use of your version of this file only under the terms
of the GPL and not to allow others to use your version of this file
under the MPL, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the GPL.
If you do not delete the provisions above, a recipient may use your version
of this file under either the MPL or the GPL.
{
@abstract(Provides EditPlus highlighting schemes import)
@authors(Fantasist [walking_in_the_sky@yahoo.com], Vit [nevzorov@yahoo.com],
Vitalik [vetal-x@mail.ru], Quadr0 [quadr02005@yahoo.com])
@created(2003)
@lastmod(2004-05-12)
}
unit SynUniImportEditPlus;
interface
uses
Classes,
Graphics,
SysUtils,
SynUniImport,
SynUniClasses,
SynUniRules;
type
{ Base class of EditPlus highlighting schemes importer }
TSynUniImportEditPlus = class(TSynUniImport)
{ List of files }
FileList: TStringList;
{ Constructor of TSynUniImportEditPlus }
constructor Create();
{ Destructor of TSynUniImportEditPlus }
destructor Destroy();
procedure Import(Rules: TSynRange; Info: TSynInfo);
{ Imports from stream }
function LoadFromStream(Stream: TStream): boolean;
{ Imports from file }
function LoadFromFile(FileName: string): boolean;
end;
implementation
constructor TSynUniImportEditPlus.Create();
begin
FileList := TStringList.Create;
end;
destructor TSynUniImportEditPlus.Destroy();
begin
FileList.Free;
end;
procedure TSynUniImportEditPlus.Import(Rules: TSynRange; Info: TSynInfo);
var
qn1, qn2, bn1, bn2, curKwd, i: integer;
key, value, buf: string;
const
kwcolors: array [0..4] of TColor = (clBlue, clRed, clTeal, clOlive, clMaroon);
begin
Rules.Clear;
qn1 := -1; qn2 := -1; bn1 := -1; bn2 := -1;
curKwd := -1;
for i := 0 to FileList.Count-1 do begin
buf := FileList.Strings[i];
if buf = '' then
continue;
if buf[1] = '#' then begin
key := copy(buf, 1, pos('=', buf)-1);
value := copy(buf, pos('=', buf)+1, length(buf)-pos('=', buf));
if key = '#TITLE' then begin
Info.General.Name := value
end
else if key = '#DELIMITER' then
Rules.TermSymbols := StrToSet(value)
else if key = '#CONTINUE_QUOTE' then begin
if value = 'y' then begin
if qn1 > -1 then Rules.Ranges[qn1].fRule.fCloseOnEol := False;
if qn2 > -1 then Rules.Ranges[qn2].fRule.fCloseOnEol := False;
end
else begin
if qn1 > -1 then Rules.Ranges[qn1].fRule.fCloseOnEol := True;
if qn2 > -1 then Rules.Ranges[qn2].fRule.fCloseOnEol := True;
end
end
else if key = '#CASE' then begin
if value = 'y' then
Rules.CaseSensitive := True
else
Rules.CaseSensitive := False;
end
else if (key = '#KEYWORD') or (buf = '#KEYWORD') then begin
inc(curKwd);
if key = '' then
Rules.AddKeyList('Keyword '+IntToStr(curKwd+1), kwcolors[curKwd])
else
Rules.AddKeyList(value, kwcolors[curKwd]);
end
else if value <> '' then
if key = '#QUOTATION1' then begin
qn1 := Rules.RangeCount;
Rules.AddRange(value[1], value[1], 'Quotaion', clFuchsia);
end else
if key = '#QUOTATION2' then begin
qn2 := Rules.RangeCount;
Rules.AddRange(value[1], value[1], 'Quotaion2', clFuchsia);
end else
if key = '#LINECOMMENT' then begin
//ln1 := Rules.RangeCount;
with Rules.AddRange(value, '', 'Line comment', clGreen) do
fRule.fCloseOnEol := True;
end else
if key = '#LINECOMMENT2' then begin
//ln2 := Rules.RangeCount;
with Rules.AddRange(value, '', 'Line comment 2', clGreen) do
fRule.fCloseOnEol := True;
end else
if key = '#COMMENTON' then begin
if bn1 = -1 then begin
bn1 := Rules.RangeCount;
Rules.AddRange(value, '', 'Block comment', clGreen);
end else
Rules.Ranges[bn1].fRule.fOpenSymbol.Symbol := value
end else
if key = '#COMMENTOFF' then begin
if bn1 = -1 then begin
bn1 := Rules.RangeCount;
Rules.AddRange('', value, 'Block comment', clGreen);
end else
Rules.Ranges[bn1].fRule.fCloseSymbol.Symbol := value
end else
if key = '#COMMENTON2' then begin
if bn2 = -1 then begin
bn2 := Rules.RangeCount;
Rules.AddRange(value, '', 'Block comment 2', clGreen);
end else
Rules.Ranges[bn2].fRule.fOpenSymbol.Symbol := value
end else
if key = '#COMMENTOFF2' then begin
if bn2 = -1 then begin
bn2 := Rules.RangeCount;
Rules.AddRange('', value, 'Block comment 2', clGreen);
end else
Rules.Ranges[bn2].fRule.fCloseSymbol.Symbol := value
end else
if copy(key, 1, 7) = '#PREFIX' then begin
with Rules.AddRange(value, '', 'Prefix '+key[8],
kwColors[StrToInt(key[8])]) do
fRule.fCloseOnTerm := True;
end
end
else if buf[1] = ';' then
else begin
Rules.KeyLists[curKwd].KeyList.Add(buf);
end
end;
Rules.SetDelimiters(Rules.TermSymbols);
Info.Author.Remark := 'Created with EditPlus Converter (c) Vitalik';
end;
function TSynUniImportEditPlus.LoadFromStream(Stream: TStream): boolean;
begin
FileList.LoadFromStream(Stream);
end;
function TSynUniImportEditPlus.LoadFromFile(FileName: string): boolean;
begin
FileList.LoadFromFile(FileName);
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLStrings<p>
String constants that are used in many GLScene units<p>
<b>History :</b><font size=-1><ul>
<li>16/09/10 - YP - Added glsUnknownParam
<li>23/02/07 - DaStr - Added glsDot, glsUnsupportedType, glsUncompatibleTypes,
glsUnknownType, glsShaderNeedsAtLeastOneLightSource(Ex),
glsCadencerNotDefined(Ex), glsSceneViewerNotDefined
<li>16/02/07 - DaStr - Added glsOCProxyObjects, glsError, glsErrorEx,
glsMatLibNotDefined, glsMaterialNotFoundInMatlib(Ex)
<li>26/08/02 - EG - Added missing header, added glsUnknownExtension
</ul></font>
}
unit GLStrings;
interface
resourcestring
// General
glsDot = '.';
glsError = 'Error!';
glsErrorEx = 'Error: ';
// SceneViewer
glsNoRenderingContext = 'Could not create a rendering context';
glsWrongVersion = 'Need at least OpenGL version 1.1';
glsTooManyLights = 'Too many lights in the scene';
glsDisplayList = 'Failed to create a new display list for object ''%s''';
glsWrongBitmapCanvas = 'Couldn''t create a rendering context for the given bitmap';
glsWrongPrinter = 'Couldn''t render to printer';
glsAlreadyRendering = 'Already rendering';
glsSceneViewerNotDefined = 'SceneViewer not defined!';
// GLCadencer
glsCadencerNotDefined = 'Cadencer not defined!';
glsCadencerNotDefinedEx = 'Cadencer not defined for the ''%s'' component';
// Shaders
glsShaderNeedsAtLeastOneLightSource = 'This shader needs at least one LightSource!';
glsShaderNeedsAtLeastOneLightSourceEx = 'Shader ''%s'' needs at least one LightSource!';
// GLTree
glsSceneRoot = 'Scene root';
glsObjectRoot = 'Scene objects';
glsCameraRoot = 'Cameras';
glsCamera = 'Camera';
// GLTexture
glsImageInvalid = 'Could not load texture, image is invalid';
glsNoNewTexture = 'Could not get new texture name';
// GLMaterials
glsMatLibNotDefined = 'Material Library not defined!';
glsMaterialNotFoundInMatlib = 'Material not found in current Material Library!';
glsMaterialNotFoundInMatlibEx = 'Material "%s" not found in current Material Library!';
// GLObjects
glsSphereTopBottom = 'The top angle must be higher than the bottom angle';
glsSphereStartStop = 'The start angle must be smaller than then stop angle';
glsMaterialNotFound = 'Loading failed: could not find material %s';
glsInterleaveNotSupported = 'Interleaved Array format not supported yet. Sorry.';
// common messages
glsUnknownArchive = '%s : unknown archive version %d';
glsOutOfMemory = 'Fatal: Out of memory';
glsFileNotFound = 'File %s not found';
glsFailedOpenFile = 'Could not open file: %s';
glsFailedOpenFileFromCurrentDir = 'Could not open file: %s'#13#10'(Current directory is %s)';
glsNoDescriptionAvailable = 'No description available';
glsUnBalancedBeginEndUpdate = 'Unbalanced Begin/EndUpdate';
glsUnknownExtension = 'Unknown file extension (%s), maybe you forgot to add the support '
+'unit to your uses? (%s?)' ;
glsMissingResource = 'Missing application resource: %s: %s';
glsIncompatibleTypes = 'Incompatible types!';
glsUnknownType = 'Unknown type!';
glsUnsupportedType = 'Unsupported type!';
// object categories
glsOCBasicGeometry = 'Basic geometry';
glsOCAdvancedGeometry = 'Advanced geometry';
glsOCMeshObjects = 'Mesh objects';
glsOCParticleSystems = 'Particle systems';
glsOCEnvironmentObjects = 'Environment objects';
glsOCSpecialObjects = 'Special objects';
glsOCGraphPlottingObjects = 'Graph-plotting objects';
glsOCDoodad = 'Doodad objects';
glsOCHUDObjects = 'HUD objects';
glsOCGuiObjects = 'GUI objects';
glsOCProxyObjects = 'Proxy objects';
glsOCExperimental = 'Experimental objects';
glsUnknownParam =
'Unknown %s "%s" for "%s" or program not in use';
implementation
end.
|
1 program TextFileCounter;
2 { Etienne van Delden, 0618959, <date> }
3 { Dit programma telt het aantal woorden, getallen, regels en tekens van de
4 input file die men ingeeft.}
5
6
7
8 const
9 letter = ['a' .. 'z', 'A' .. 'Z']; // type letter
10 cijfer = ['0' .. '9']; // type cijfer
11 underscore = ['_']; // type underscore
12 FileNotFoundError = 2; // Run-Time Error Code
13
14 procedure CountText ( var f: Text; var i_regels, i_woord, i_getal, i_teken: Integer );
15 { pre: f is geopend om te lezen, leeskop staat vooraan
16 post: r = aantal regels in f
17 t = aantal tekens in f
18 f is geopend om te lezen, leeskop staat achteraan }
19 var
20 teken: Char; // om teken in te lezen
21 Toestand: ( Elders, InWoord, InGetal ); // waar is de leeskop
22
23 temp: String;
24
25
26 begin
27 i_regels := 0; // init var aantal regels gelezen uit f
28 i_teken := 0; // init var aantal tekens gelezen uit f
29 i_getal := 0; // init var aantal getallen gelezen uitf
30 i_woord := 0; // init var aantal woorden gelezen uit f
31 Toestand := Elders; // init var, toestand begint in Elders
32
33 while not Eof( f ) do begin { verwerk eerstvolgende regel }
34
35 while not Eoln( f ) do begin { verwerk eerstvolgende teken }
36 read( f, teken );
37
38 // We gaan nu kijken wat de toestand is
39 // van het vorige karakter en
40 // vergelijken dat met het type van het
41 // huidige karakter, om te bepalen of
42 // de toestand moet worden aangepast
43 case Toestand of
44 Elders: begin // Als het vorige teken in Elders zit...
45 // ... en het huidige teken een
46 if (teken in letter) then // letter is, tel 1 woord meer
47 begin
48 i_woord := i_woord + 1;
49 Toestand := InWoord;
50 temp := 'InWoord'
51 end // end controle 1
52 // ... en het huidige teken een
53 // underscore is, tel 1 woor meer
54 else if ( teken in underscore ) then
55 begin
56 i_woord := i_woord + 1;
57 Toestand := InWoord;
58 temp := 'InWoord'
59 end // end controle 2
60 // ... en het huidige teken een
61 else if (teken in cijfer) then // cijfer is, tel 1 cijfer meer
62 begin
63 i_getal := i_getal + 1;
64 Toestand := InGetal;
65 temp := 'InGetal'
66 end // end controle 3
67 // ... en het huidige teken geen letter,
68 // cijfer of underscore is
69 else if not (( teken in letter) or (teken in cijfer) or
70 (teken in underscore)) then
71 begin
72 Toestand := Elders;
73 temp := 'Elders'
74 end; // end controle 4
75 end; // end Elders
76
77 // Als het vorige teken in InGetal
78 // zit...
79 InGetal: begin
80 // .. en het huidige teken is een
81 if (teken in underscore ) then // underscore
82 begin
83 i_woord := i_woord + 1;
84 Toestand := InWoord;
85 temp := 'InGetal'
86 end // end controle 1
87 // ... en het huidige teken geen letter,
88 // cijfer of underscore is
89 else if not (( teken in letter) or (teken in cijfer) or
90 (teken in underscore)) then
91 begin
92 Toestand := Elders;
93 temp := 'Elders'
94 end; // end controle 2
95 end; // end Ingetal
96
97 // Als het vorige teken in InWoord
98 InWoord: begin // zit...
99 // .. en het huidige teken geen letter,
100 // cijfer of underscore is
101 if not (( teken in letter) or (teken in cijfer) or
102 (teken in underscore)) then
103 begin
104 Toestand := Elders;
105 temp := 'Elders'
106 end; // end controle 1
107 end;
108 end; // end case
109
110 writeln( temp );
111 i_teken := i_teken + 1;
112 writeln( i_teken );
113
114 end; // end while Eoln
115 Toestand := Elders;
116 readln( f );
117 i_regels := i_regels + 1
118 end // end while Eof
119
120 end; // end procedure CountText
121
122 var
123 inFile : Text; // file om te tellen
124 outFile : Text; // voor output file
125 aantalRegels: Integer; // aantal regels in inFile
126 aantalTekens: Integer; // aantal tekens in inFile
127 aantalWoorden: Integer; // aantal woorden in inFile
128 aantalGetal: Integer; // aantal getallen in inFile
129
130 begin
131 // initialisatie file toekennen
132 AssignFile( inFile, 'woorden.in' );
133 AssignFile( outFile, 'woorden.out' );
134 Rewrite ( outFile );
135 Reset( inFile);
136 // Voor de procedure uit
137 CountText( inFile, aantalRegels, aantalWoorden, aantalGetal, aantalTekens );
138 // schrijf de output naar het bestand
139 writeln( outfile, aantalRegels, ' regel(s)' );
140 writeln( outfile, aantalWoorden, ' woord(en)' );
141 writeln( outfile, aantalGetal, ' getal(len)');
142 writeln( outfile, aantalTekens, ' teken(s)' );
143 // sluit het bestand
144 CloseFile ( inFile );
145 CloseFile ( outFile );
146 end. |
unit uDemo;
interface
uses
System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
//GLS
GLScene, GLVectorGeometry, GLCadencer, GLWin32Viewer, GLCrossPlatform,
GLBaseClasses, GLSimpleNavigation, GLObjects, GLCoordinates, GLContext,
GLSCUDA, GLSCUDACompiler, GLSCUDAContext, GLSCUDAGraphics,
GLMaterial, GLCustomShader, GLSLShader;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLCadencer1: TGLCadencer;
GLCamera1: TGLCamera;
GLDummyCube1: TGLDummyCube;
GLSimpleNavigation1: TGLSimpleNavigation;
GLSCUDADevice1: TGLSCUDADevice;
GLSCUDA1: TGLSCUDA;
GLSCUDACompiler1: TGLSCUDACompiler;
MainModule: TCUDAModule;
DotFieldMapper: TCUDAGLGeometryResource;
GLSLShader1: TGLSLShader;
MakeDotField: TCUDAFunction;
GLFeedBackMesh1: TGLFeedBackMesh;
procedure GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
procedure MakeVertexBufferParameterSetup(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure GLSLShader1Apply(Shader: TGLCustomGLSLShader);
procedure GLSCUDA1OpenGLInteropInit(out Context: TGLContext);
private
{ Private declarations }
public
{ Public declarations }
FieldWidth: Integer;
FieldHeight: Integer;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
FieldWidth := 256;
FieldHeight := 256;
GLFeedBackMesh1.VertexNumber := FieldWidth * FieldHeight;
GLFeedBackMesh1.Visible := True;
MakeDotField.Grid.SizeX := FieldWidth div MakeDotField.BlockShape.SizeX;
MakeDotField.Grid.SizeY := FieldWidth div MakeDotField.BlockShape.SizeY;
end;
procedure TForm1.GLSCUDA1OpenGLInteropInit(out Context: TGLContext);
begin
Context := GLSceneViewer1.Buffer.RenderingContext;
end;
procedure TForm1.GLSLShader1Apply(Shader: TGLCustomGLSLShader);
begin
with GLSceneViewer1.Buffer.RenderingContext.PipelineTransformation do
Shader.Param['ModelViewProjectionMatrix'].AsMatrix4f :=
MatrixMultiply(ModelViewMatrix, ProjectionMatrix);
end;
procedure TForm1.MakeVertexBufferParameterSetup(Sender: TObject);
begin
with MakeDotField do
begin
SetParam(DotFieldMapper.AttributeDataAddress[GLFeedBackMesh1.Attributes[0].Name]);
SetParam(FieldWidth);
SetParam(FieldHeight);
SetParam(GLCadencer1.CurrentTime);
end;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
begin
GLSceneViewer1.Invalidate;
end;
end.
|
unit settingsScreen;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, uEncrypt;
type
TfrmSettings = class(TForm)
Label1: TLabel;
edtOldPassword: TEdit;
edtNewPassword: TEdit;
edtRepeatPassword: TEdit;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
btnChange: TButton;
procedure btnChangeClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmSettings: TfrmSettings;
implementation
{$R *.dfm}
{If the change password button is clicked then 1) a passwordTool class
is instantiated
2) a nested if statement performs an error check that displays an error
message if the old password entered does not match the one recorded in an
encrypted file in the project folder, or if the new passwords entered do not
match. If the error check returns no errors then the new password is encrypted
and overwrites the old password in the text file stored in the project folder.
A message is displayed to confirm the change.}
procedure TfrmSettings.btnChangeClick(Sender: TObject);
var
old, new1, new2 : string;
passwordTool : TEncryption;
begin
passwordTool := TEncryption.Create();
if edtOldPassword.Text = passwordTool.getPassword() then
begin
if edtNewPassword.Text = edtRepeatPassword.Text then
begin
passwordTool.setPassword(edtNewPassword.Text);
ShowMessage('Password Change Effective');
settingsScreen.frmSettings.Close;
end
else
begin
ShowMessage('Passwords do not match');
end;
end
else
begin
ShowMessage('Old Password Incorrect');
end;
end;
end.
|
unit CustomDrawTreeView;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, ExtDlgs, StdCtrls, ExtCtrls, ColorGrd, ImgList, Menus;
type
TCustomDrawForm = class(TForm)
TV: TTreeView;
ImageList: TImageList;
MainMenu1: TMainMenu;
Drawing1: TMenuItem;
Font1: TMenuItem;
Background1: TMenuItem;
Color1: TMenuItem;
Bitmap1: TMenuItem;
DefaultDrawing1: TMenuItem;
OnCustomDraw1: TMenuItem;
OnCustomDrawItem1: TMenuItem;
BrushStyle1: TMenuItem;
Solid1: TMenuItem;
Clear1: TMenuItem;
Horizontal1: TMenuItem;
Vertical1: TMenuItem;
FDiagonal1: TMenuItem;
BDiagonal1: TMenuItem;
Cross1: TMenuItem;
DiagCross1: TMenuItem;
File1: TMenuItem;
Exit1: TMenuItem;
N2: TMenuItem;
TVFontDialog: TFontDialog;
Tile1: TMenuItem;
Stretch1: TMenuItem;
None1: TMenuItem;
Selection1: TMenuItem;
SelectedFontDialog: TFontDialog;
BkgColorDialog: TColorDialog;
SelBkgColorDialog: TColorDialog;
SelectionBackground1: TMenuItem;
ButtonColor1: TMenuItem;
ButtonSize1: TMenuItem;
ButtonColorDialog: TColorDialog;
Image1: TImage;
TreeView1: TMenuItem;
Color2: TMenuItem;
TVColorDialog: TColorDialog;
CustomDraw1: TMenuItem;
Font2: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure TVCustomDraw(Sender: TCustomTreeView; const ARect: TRect;
var DefaultDraw: Boolean);
procedure TVCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode;
State: TCustomDrawState; var DefaultDraw: Boolean);
procedure TVGetImageIndex(Sender: TObject; Node: TTreeNode);
procedure TVGetSelectedIndex(Sender: TObject; Node: TTreeNode);
procedure Exit1Click(Sender: TObject);
procedure Selection1Click(Sender: TObject);
procedure Color1Click(Sender: TObject);
procedure SelectionBackground1Click(Sender: TObject);
procedure Solid1Click(Sender: TObject);
procedure None1Click(Sender: TObject);
procedure OnCustomDraw1Click(Sender: TObject);
procedure OnCustomDrawItem1Click(Sender: TObject);
procedure TVExpanded(Sender: TObject; Node: TTreeNode);
procedure ButtonColor1Click(Sender: TObject);
procedure ButtonSize1Click(Sender: TObject);
procedure Drawing1Click(Sender: TObject);
procedure Color2Click(Sender: TObject);
procedure CustomDraw1Click(Sender: TObject);
procedure Font2Click(Sender: TObject);
private
FButtonSize: Integer;
FDefaultDraw,
FDefaultDrawItem: Boolean;
FBackgroundColor: TColor;
FBrushStyle: TBrushStyle;
procedure DrawButton(ARect: TRect; Node: TTreeNode);
procedure DrawImage(NodeRect: TRect; ImageIndex: Integer);
procedure SetCustomDraw(Value: Boolean);
{ Private declarations }
public
{ Public declarations }
end;
var
CustomDrawForm: TCustomDrawForm;
implementation
{$R *.DFM}
procedure TCustomDrawForm.FormCreate(Sender: TObject);
begin
FBackgroundColor := clWindow;
FDefaultDraw := True;
FDefaultDrawItem := True;
FBrushStyle := bsSolid;
FButtonSize := 5;
BkgColorDialog.Color := clWindow;
SelBkgColorDialog.Color := clHighlight;
TVFontDialog.Font.Assign(TV.Font);
SelectedFontDialog.Font.Assign(TV.Font);
SelectedFontDialog.Font.Color := clHighlightText;
SelBkgColorDialog.Color := clHighlight;
TVColorDialog.Color := TV.Color;
end;
procedure TCustomDrawForm.TVCustomDraw(Sender: TCustomTreeView; const ARect: TRect;
var DefaultDraw: Boolean);
begin
//This event should be used to draw any background colors or images.
//ARect represents the entire client area of the TreeView.
//Use the TreeView's canvas to do the drawing.
//Note that drawing a background bitmap is not really supported by CustomDraw,
//so scrolling can get messy. Best to subclass the TreeView and handle scrolling
//messages.
with TV.Canvas do
begin
if None1.Checked then //no picture
begin
Brush.Color := BkgColorDialog.Color;
Brush.Style := FBrushStyle;
FillRect(ARect);
end else
if Tile1.Checked then //tile bitmap
begin
Brush.Bitmap := Image1.Picture.Bitmap;
FillRect(ARect);
end else //Stretch across the canvas.
StretchDraw(ARect, Image1.Picture.Bitmap);
end;
DefaultDraw := FDefaultDraw;
//setting DefaultDraw to false here prevents all calls to OnCustomDrawItem.
end;
procedure TCustomDrawForm.DrawButton(ARect: TRect; Node: TTreeNode);
var
cx, cy: Integer;
begin
cx := ARect.Left + TV.Indent div 2;
cy := ARect.Top + (ARect.Bottom - ARect.Top) div 2;
with TV.Canvas do
begin
Pen.Color := ButtonColorDialog.Color;
//draw horizontal line.
if Node.HasChildren then
begin
PenPos := Point(cx+FButtonSize, cy);
LineTo(ARect.Left + TV.Indent + FButtonSize, cy);
end else
begin
PenPos := Point(cx, cy);
LineTo(ARect.Left + TV.Indent + FButtonSize, cy);
end;
//draw half vertical line, top portion.
PenPos := Point(cx, cy);
LineTo(cx, ARect.Top-1);
if ((Node.GetNextVisible <> nil) and (Node.GetNextVisible.Level = Node.Level))
or (Node.GetNextSibling <> nil) then
//draw bottom portion of half vertical line.
begin
PenPos := Point(cx, cy);
LineTo(cx, ARect.Bottom+1);
end;
if Node.HasChildren then
begin
//Let's try a circular button instead
Ellipse(cx-FButtonSize, cy-FButtonSize, cx+FButtonSize, cy+FButtonSize);
//draw the horizontal indicator.
PenPos := Point(cx-FButtonSize+2, cy);
LineTo(cx+FButtonSize-2, cy);
//draw the vertical indicator if the node is collapsed
if not Node.Expanded then
begin
PenPos := Point(cx, cy-FButtonSize+2);
LineTo(cx, cy+FButtonSize-2);
end;
end;
//now connect vertical lines of higher level nodes.
Node := Node.Parent;
while Node <> nil do
begin
cx := cx - TV.Indent;
if Node.GetNextSibling <> nil then
begin
PenPos := Point(cx, ARect.Top);
LineTo(cx, ARect.Bottom);
end;
Node := Node.Parent;
end;
end;
end;
procedure TCustomDrawForm.DrawImage(NodeRect: TRect; ImageIndex: Integer);
var
cy: Integer;
begin
cy := NodeRect.Top + (NodeRect.Bottom - NodeRect.Top) div 2;
//center image in NodeRect.
ImageList.Draw(TV.Canvas, NodeRect.Left, cy - TV.Images.Height div 2,
ImageIndex, True);
end;
procedure TCustomDrawForm.TVCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode;
State: TCustomDrawState; var DefaultDraw: Boolean);
var
NodeRect: TRect;
begin
with TV.Canvas do
begin
//If DefaultDraw it is true, any of the node's font properties can be
//changed. Note also that when DefaultDraw = True, Windows draws the
//buttons and ignores our font background colors, using instead the
//TreeView's Color property.
if cdsSelected in State then
begin
Font.Assign(SelectedFontDialog.Font);
Brush.Color := SelBkgColorDialog.Color;
end;
DefaultDraw := FDefaultDrawItem;
//DefaultDraw = False means you have to handle all the item drawing yourself,
//including the buttons, lines, images, and text.
if not DefaultDraw then
begin
//draw the selection rect.
if cdsSelected in State then
begin
NodeRect := Node.DisplayRect(True);
FillRect(NodeRect);
end;
NodeRect := Node.DisplayRect(False);
if None1.Checked then
//no bitmap, so paint in the background color.
begin
Brush.Color := BkgColorDialog.Color;
Brush.Style := FBrushStyle;
FillRect(NodeRect)
end
else
//don't paint over the background bitmap.
Brush.Style := bsClear;
NodeRect.Left := NodeRect.Left + (Node.Level * TV.Indent);
//NodeRect.Left now represents the left-most portion of the expand button
DrawButton(NodeRect, Node);
NodeRect.Left := NodeRect.Left + TV.Indent + FButtonSize;
//NodeRect.Left is now the leftmost portion of the image.
DrawImage(NodeRect, Node.ImageIndex);
NodeRect.Left := NodeRect.Left + ImageList.Width;
//Now we are finally in a position to draw the text.
TextOut(NodeRect.Left, NodeRect.Top, Node.Text);
end;
end;
end;
procedure TCustomDrawForm.TVGetImageIndex(Sender: TObject; Node: TTreeNode);
begin
if Node.HasChildren then
if Node.Expanded then
Node.ImageIndex := 3
else
Node.ImageIndex := 0
else
Node.ImageIndex := 1;
end;
procedure TCustomDrawForm.TVGetSelectedIndex(Sender: TObject; Node: TTreeNode);
begin
Node.SelectedIndex := Node.ImageIndex;
end;
procedure TCustomDrawForm.Exit1Click(Sender: TObject);
begin
Close;
end;
procedure TCustomDrawForm.Selection1Click(Sender: TObject);
begin
if SelectedFontDialog.Execute then
TV.Repaint;
end;
procedure TCustomDrawForm.Color1Click(Sender: TObject);
begin
if BkgColorDialog.Execute then
TV.Repaint;
end;
procedure TCustomDrawForm.SelectionBackground1Click(Sender: TObject);
begin
if SelBkgColorDialog.Execute then
TV.Repaint;
end;
procedure TCustomDrawForm.Solid1Click(Sender: TObject);
begin
with Sender as TMenuItem do
begin
FBrushStyle := TBrushStyle(Tag);
Checked := True;
end;
TV.Repaint;
end;
procedure TCustomDrawForm.None1Click(Sender: TObject);
begin
(Sender as TMenuItem).Checked := True;
TV.Repaint;
end;
procedure TCustomDrawForm.OnCustomDraw1Click(Sender: TObject);
begin
FDefaultDraw := not FDefaultDraw;
OnCustomDraw1.Checked := FDefaultDraw;
TV.Repaint;
end;
procedure TCustomDrawForm.OnCustomDrawItem1Click(Sender: TObject);
begin
FDefaultDrawItem := not FDefaultDrawItem;
OnCustomDrawItem1.Checked := FDefaultDrawItem;
TV.Repaint;
end;
procedure TCustomDrawForm.TVExpanded(Sender: TObject; Node: TTreeNode);
begin
TV.Repaint;
end;
procedure TCustomDrawForm.ButtonColor1Click(Sender: TObject);
begin
if ButtonColorDialog.Execute then TV.Repaint;
end;
procedure TCustomDrawForm.ButtonSize1Click(Sender: TObject);
var
S: string;
begin
S := IntToStr(FButtonSize);
if InputQuery('Change button size', 'Enter new size', S) then
FButtonSize := StrToInt(S);
TV.Repaint;
end;
procedure TCustomDrawForm.Drawing1Click(Sender: TObject);
begin
ButtonColor1.Enabled := not OnCustomDrawItem1.Checked;
ButtonSize1.Enabled := ButtonColor1.Enabled;
end;
procedure TCustomDrawForm.Color2Click(Sender: TObject);
begin
if TVColorDialog.Execute then
begin
TV.Color := TVColorDialog.Color;
TV.Repaint;
end;
end;
procedure TCustomDrawForm.SetCustomDraw(Value: Boolean);
begin
if not Value then
begin
TV.OnCustomDraw := nil;
TV.OnCustomDrawItem := nil;
end else
begin
TV.OnCustomDraw := Self.TVCustomDraw;
TV.OnCustomDrawItem := Self.TVCustomDrawItem;
end;
Drawing1.Enabled := Value;
TV.Repaint;
end;
procedure TCustomDrawForm.CustomDraw1Click(Sender: TObject);
begin
CustomDraw1.Checked := not CustomDraw1.Checked;
SetCustomDraw(CustomDraw1.Checked);
end;
procedure TCustomDrawForm.Font2Click(Sender: TObject);
begin
if TVFontDialog.Execute then
TV.Font.Assign(TVFontDialog.Font);
end;
end.
|
unit GridSystem.ColumnEditor;
interface
uses
FMX.Dialogs, System.SysUtils, System.Classes, System.UITypes, DesignEditors, DesignIntf, GridSystem.ColumnDlg, GridSystem.Types;
type
TGridSystemColumnComponentEditor = class(TComponentEditor)
private
procedure ShowDesigner;
public
function GetVerbCount: Integer; override;
function GetVerb(Index: Integer): string; override;
procedure ExecuteVerb(Index: Integer); override;
end;
TGridSystemColumnPropertyEditor = class(TClassProperty)
private
procedure ShowDesigner;
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
implementation
{ TGridSystemColumnComponentEditor }
procedure TGridSystemColumnComponentEditor.ExecuteVerb(Index: Integer);
begin
inherited;
case Index of
0:
ShowDesigner;
else
raise ENotImplemented.Create('TClockLabelEditor has only one verb (index = 0) supported.');
end;
end;
function TGridSystemColumnComponentEditor.GetVerb(Index: Integer): string;
begin
inherited;
case Index of
0:
Result := '&Edit columns';
else
raise ENotImplemented.Create('TGridSystemColumnComponentEditor has only one verb (index = 0) supported.');
end;
end;
function TGridSystemColumnComponentEditor.GetVerbCount: Integer;
begin
inherited;
Result := 1;
end;
procedure TGridSystemColumnComponentEditor.ShowDesigner;
var
DesignerForm: TGridSystemColumnDlg;
Key: TScreenType;
begin
DesignerForm := TGridSystemColumnDlg.Create(nil);
try
if Supports(Component, IGSCol) then
begin
for Key in (Component as IGSCol).Columns.Keys do
begin
DesignerForm.Columns.Add(Key, (Component as IGSCol).Columns.Items[Key]);
end;
end;
if DesignerForm.ShowModal = mrOk then
begin
(Component as IGSCol).Columns.Clear;
for Key in DesignerForm.Columns.Keys do
begin
(Component as IGSCol).Columns.Add(Key, DesignerForm.Columns.Items[Key]);
end;
end;
Designer.Modified;
finally
DesignerForm.Free;
end;
end;
{ TGridSystemColumnPropertyEditor }
procedure TGridSystemColumnPropertyEditor.Edit;
begin
inherited;
ShowDesigner;
end;
function TGridSystemColumnPropertyEditor.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paDialog, paReadOnly];
end;
procedure TGridSystemColumnPropertyEditor.ShowDesigner;
var
DesignerForm: TGridSystemColumnDlg;
ColumnsDictionary: TGSColumnsDictionary;
Key: TScreenType;
begin
DesignerForm := TGridSystemColumnDlg.Create(nil);
try
ColumnsDictionary:=TGSColumnsDictionary(Self.GetOrdValue);
for Key in TGSColumnsDictionary(Self.GetOrdValue).Keys do
begin
DesignerForm.Columns.Add(Key, ColumnsDictionary.Items[Key]);
end;
if DesignerForm.ShowModal = mrOk then
begin
ColumnsDictionary.Clear;
for Key in DesignerForm.Columns.Keys do
begin
ColumnsDictionary.Add(Key, DesignerForm.Columns.Items[Key]);
end;
end;
Designer.Modified;
finally
DesignerForm.Free;
end;
end;
end.
|
unit MetroVisCom;
//# BEGIN TODO Completed by: author name, id.nr., date
{ Etienne van Delden, 0618959, 09-05-2008}
//# END TODO
interface
uses
Classes, Contnrs, Graphics, IniFiles,
Planner, VisCom, StringValidators;
type
TVisLine = class; // forward
//============================================================================
// TVisStation is an abstract base class for visualization of stations.
// It has:
// - X, Y coordinates
//============================================================================
TVisStation =
class(TVisCom)
protected
FX: Integer;
FY: Integer;
public
// construction/destruction-------------------------------------------------
constructor Create(ACode: String; AData: TObject; AX, AY: Integer);
// pre: True
// post: inherited Create.post
// primitive queries--------------------------------------------------------
function X: Integer;
// pre: True
// ret: FX
function Y: Integer;
// pre: True
// ret: FY
// commands-----------------------------------------------------------------
procedure Relocate(AX, AY: Integer);
// pre: True
// post: FX = AX and FY = AY
// invariants --------------------------------------------------------------
// I0: ValidStationCode(ACode)
end;
//============================================================================
// TVisStationStop visualizes a normal stop on a line.
//============================================================================
TVisStationStop =
class(TVisStation)
public
// construction/destruction-------------------------------------------------
constructor Create(ACode: String; AData: TObject; AX, AY: Integer);
// pre: True
// post: inherited Create.post
// primitive queries--------------------------------------------------------
function CanSelect: Boolean; override;
// pre: True
// ret: True
function CanMark(AMark: String): Boolean; override;
// pre: True
// ret: AMark in {'mkStart', 'mkVia', 'mkFinish'}
function Contains(AMap: TMap; AX, AY: Integer): Boolean; override;
// pre: True
// ret: "the image of this object drawn on map AMap contains point (AX, AY)"
// commands ----------------------------------------------------------------
procedure Draw(AMap: TMap); override;
// pre: True
// effect: draws a stop on AMap
end;
//============================================================================
// TVisStationTransfer visualizes a transfer station.
//============================================================================
TVisStationTransfer =
class(TVisStation)
// construction/destruction-------------------------------------------------
constructor Create(ACode: String; AData: TObject; AX, AY: Integer);
// pre: True
// post: inherited Create.post
// primitive queries--------------------------------------------------------
function CanSelect: Boolean; override;
// pre: True
// ret: True
function CanMark(AMark: String): Boolean; override;
// pre: True
// ret: AMark in {mkStart, mkVia, mkFinish}
function Contains(AMap: TMap; AX, AY: Integer): Boolean; override;
// pre: True
// ret: "the image of this object drawn on map AMap contains point (AX, AY)"
// commands ----------------------------------------------------------------
procedure Draw(AMap: TMap); override;
// pre: True
// effect: draws a transfer station on AMap
end;
//============================================================================
// TVisStationDummy is not really a visualisation of a station. It only serves
// to force a line to pass through a particular position on the map.
//============================================================================
TVisStationDummy =
class(TVisStation)
// construction/destruction-------------------------------------------------
constructor Create(ACode: String; AX, AY: Integer);
// pre: True
// post: inherited Create.post
// primitive queries--------------------------------------------------------
function CanSelect: Boolean; override;
// pre: True
// ret: True
function Contains(AMap: TMap; AX, AY: Integer): Boolean; override;
// pre: True
// ret: "the image of this object drawn on map AMap contains point (AX, AY)"
// commands ----------------------------------------------------------------
procedure Draw(AMap: TMap); override;
// pre: True
// effect: draws a station dummy on AMap
end;
//============================================================================
// TVisLine visualizes a metro line. It has:
// - a list of TVisStations
// - a color
//============================================================================
TVisLine =
class(TVisCom)
protected
FColor: TColor;
FList: TObjectList; // shared references to TVisStations
public
// construction/destruction-------------------------------------------------
constructor Create(ACode: String; AData: TObject; AColor: TColor);
// pre: True
// post: inherited Create.post and Abstr = [] and GetColor = AColor
destructor Destroy; override;
// pre: True
// effect: FList is freed
// primitive queries--------------------------------------------------------
function CanSelect: Boolean; override;
// pre: True
// ret: True
function CanMark(AMark: String): Boolean; override;
// pre: True
// ret: (AMark = 'mkLine')
function Contains(AMap: TMap; AX, AY: Integer): Boolean; override;
// pre: True
// ret: "the image of this object drawn on map AMap contains point (AX, AY)"
function GetColor: TColor;
// pre: True
// ret: FColor
function StationCount: Integer;
// pre: True
// ret: |Abstr|
function GetIndexOfStation(AStation: TVisStation): Integer;
// pre: True
// ret: I, such that GetStation(I) = AStation
function GetStation(I: Integer): TVisStation;
// pre: 0 <= I < StationCount
// ret: Abstr[I]
function HasStation(AStation: TVisStation): Boolean;
// pre: True
// ret: AStation in Abstr
// commands ----------------------------------------------------------------
procedure AddStation(AStation: TVisStation);
// pre: not(HasStation(AStation))
// post: Abstr = old Abstr ++ [AStation]
procedure DeleteStation(AStation: TVisStation);
// pre: HasStation(AStation)
// post: Abstr = old Abstr - [AStation]
procedure InsertStation(AIndex: Integer; AStation: TVisStation);
// pre: True
// post: let X1 = old Abstr[0..AIndex)
// X2 = old Abstr[AIndex..Count)
// in Abstr = X1 ++ [AStation] ++ X2
procedure ReplaceStation(AOldStation: TVisStation; ANewStation: TVisStation);
// pre: True
// post: let old Abstr[I] = AOldStation
// in let X1 = old Abstr[0..I)
// X2 = old Abstr(I..Count)
// in Abstr = X1 ++ [ANewStation] ++ X2
procedure SetColor(AColor: TColor);
// pre: True
// post: FColor = AColor
procedure Draw(AMap: TMap); override;
// pre: True
// effect: The line is drawn on AMap
procedure DrawFromTo(AMap: TMap; AFrom, ATo: TVisStation);
// pre: True
// effect: The linesegment from AFrom to ATo is drawn on AMap
// model variables ---------------------------------------------------------
// Abstr: seq of TVisStation
// invariants --------------------------------------------------------------
// I0: ValidLineCode(GetCode)
//
// A0: Abstr = (seq I: 0 <= I < StationCount: GetStation(I))
end;
//============================================================================
// TVisLandmark
//============================================================================
TVisLandmark =
class(TVisCom)
protected
FX: Integer;
FY: Integer;
FBitmap: TBitmap;
FBitmapFileName: String;
public
// construction/destruction-------------------------------------------------
constructor Create(ACode: String; AData: TObject; AX, AY: Integer;
ABitmap: TBitmap; ABitmapFileName: String);
// pre: True
// post: inherited Create.post and FX = AX and FY = AY and
// FBitmap = ABitmap and FBitmapFileName = ABitmapFileName
destructor Destroy; override;
// pre: True
// effect: FBitmap is freed
// primitive queries -------------------------------------------------------
function CanSelect: Boolean; override;
// pre: True
// ret: True
function Contains(AMap: TMap; AX, AY: Integer): Boolean; override;
// pre: True
// ret: "the image of this object drawn on map AMap contains point (AX, AY)"
function X: Integer;
// pre: True
// ret: FX
function Y: Integer;
// pre: True
// ret: FY
function GetBitmap: TBitmap;
// pre: True
// ret: FBitmap
function GetBitmapFileName: String;
// pre: True
// ret: FBitmapFileName
// commands ----------------------------------------------------------------
procedure Draw(AMap: TMap); override;
// pre: True
// effect: draws the bitmap on AMap
procedure SetBitmap(ABitmap: TBitmap);
// pre: FBitmap <> nil
// post: FBitmap = ABitmap
procedure SetBitmapFileName(AFileName: String);
// pre: True
// post: FBitmapFileName = AFileName
procedure Relocate(AX, AY: Integer);
// pre: True
// post: FX = AX and FY = AY
// invariants --------------------------------------------------------------
// I0: ValidLandmarkCode(GetCode)
end;
//============================================================================
// TVisFlag
//============================================================================
TVisFlag =
class(TVisCom)
protected
FX: Integer;
FY: Integer;
FVisible: Boolean;
FBitmap: TBitmap;
public
// construction/destruction-------------------------------------------------
constructor Create(ACode: String; AData: TObject; AX, AY: Integer;
ABitmap: TBitmap);
// pre: True
// effect: inherited Create
// post: FX = AX and FY = AY and FBitmap = ABitmap and FVisible = False
// primitive queries -------------------------------------------------------
function Contains(AMap: TMap; AX, AY: Integer): Boolean; override;
// pre: True
// ret: False
function X: Integer;
// pre: True
// ret: FX
function Y: Integer;
// pre: True
// ret: FY
function Visible: Boolean;
// pre: True
// ret: FVisible
// commands ----------------------------------------------------------------
procedure Draw(AMap: TMap); override;
// effect: draws the bitmap on AMap
procedure MoveTo(AX, AY: Integer);
// pre: True
// post: FX = AX and FY = AY
procedure Show;
// pre: True
// post: FVisible = True
procedure Hide;
// pre: True
// post: FVisible = False
end;
//============================================================================
// TVisText visualizes text on the map.
// It has at least the following features:
// - X, Y coordinates
// - the text to be visualized
// - a TextPos value indicating the relative positions of the (X,Y) point
// and the text
//============================================================================
TTextPos = (tpNorth, tpNorthEast, tpEast, tpSouthEast, tpSouth, tpSouthWest,
tpWest, tpNorthWest);
TVisText =
class(TVisCom)
protected
FX: Integer;
FY: Integer;
FText: String;
FTextPos: TTextPos;
public
// construction/destruction
constructor Create(ACode: String; AData: TObject; AX, AY: Integer;
AText: String; ATextPos: TTextPos);
// pre: True
// effect: inherited Create
// post: FX = AX and FY = AY and FText = AText and FTextPos = ATextPos
// primitive queries -------------------------------------------------------
function CanSelect: Boolean; override;
// pre: True
// ret: True
function Contains(AMap: TMap; AX, AY: Integer): Boolean; override;
// pre: True
// ret: "the image of this object drawn on map AMap contains point (AX, AY)"
function X: Integer;
// pre: True
// ret: FX
function Y: Integer;
// pre: True
// ret: FY
function GetText: String;
// pre: True
// ret: FText
function GetTextPos: TTextPos;
// pre: True
// ret: FTextPos
// commands ----------------------------------------------------------------
procedure Draw(AMap: TMap); override;
// effect: draws Text on AMap;
// position of (X,Y) w.r.t. Text is determined by TextPos
procedure SetText(AText: String);
// pre: True
// post: FText = AText
procedure SetTextPos(ATextPos: TTextPos);
// pre: True
// post: FTextPos = ATextPos
procedure Relocate(AX, AY: Integer);
// pre: True
// post: FX = AX and FY = AY
// invariants --------------------------------------------------------------
// I0: ValidTextCode(GetCode)
end;
//============================================================================
// TMetroMap is a specialization of TMap.
// It serves to visualize a metro network.
//============================================================================
TMetroMap =
class(TMap)
protected
FStartFlag: TVisFlag;
FStopFlag: TVisFlag;
procedure SetStartFlag(AFlag: TVisFlag); virtual;
// pre: True
// post: FStartFlag = AFlag
procedure SetStopFlag(AFlag: TVisFlag); virtual;
// pre: True
// post: FStopFlag = AFlag
public
// derived queries ---------------------------------------------------------
function GetStation(ACode: String): TVisStation;
// pre: True
// ret: S in AbstrStations such that (S.GetCode = ACode),
// nil if such an S does not exist.
function GetLine(ACode: String): TVisLine;
// pre: True
// ret: L in AbstrLines such that (L.GetCode = ACode),
// nil if such an L does not exist.
function GetLandmark(ACode: String): TVisLandmark;
// pre: True
// ret: L in AbstrLandmarks such that (L.GetCode = ACode),
// nil if such an L does not exist.
function GetText(ACode: String): TVisText;
// pre: True
// ret: T in AbstrTexts such that (T.GetCode = ACode),
// nil is such a T does not exist.
function LandmarkContaining(AX, AY: Integer): TVisLandmark;
// pre: True
// ret: L in AbstrLandmarks containing (AX, AY), nil if there is
// no such L
function LineContaining(AX, AY: Integer): TVisLine;
// pre: True
// ret: L in AbstrLines containing (AX, AY), nil if there is no such L
function StationContaining(AX, AY: Integer): TVisStation;
// pre: True
// ret: S in AbstrStations containing (AX, AY), nil if there is no
// such S
function TextContaining(AX, AY: Integer): TVisText;
// pre: True
// ret: T in AbstrTexts containing (AX, AY), nil if there is no such T
// preconditions -----------------------------------------------------------
function CanSetLandmarkCode(ALandmark: TVisLandmark; ACode: String): Boolean;
// pre: True
// ret: not(HasLandmark(ACode)) and ValidLandmarkCode(ACode) and
// HasLandmark(ALandmark.GetCode)
function CanSetLineCode(ALine: TVisLine; ACode: String): Boolean;
// pre: True
// ret: not(HasLine(ACode)) and ValidLineCode(ACode) and
// HasLine(ALine.GetCode)
function CanSetStationCode(AStation: TVisStation; ACode: String): Boolean;
// pre: True
// ret: not(HasStation(ACode)) and ValidStationCode(ACode) and
// HasStation(AStation.GetCode)
function CanSetTextCode(AText: TVisText; ACode: String): Boolean;
// pre: True
// ret: not(HasText(ACode)) and ValidTextCode(ACode) and
// HasText(AText.GetCode)
function HasStation(ACode: String): Boolean;
// pre: True
// ret: (exists S: S in AbstrStations: S.GetCode = ACode)
function HasLine(ACode: String): Boolean;
// pre: True
// ret: (exists L: L in AbstrLines: L.GetCode = ACode)
function HasLandmark(ACode: String): Boolean;
// pre: True
// ret: (exists L: L in AbstrLandmarks: L.GetCode = ACode)
function HasText(ACode: String): Boolean;
// pre: True
// ret: (exists T: T in AbstrTexts: T.GetCode = ACode)
// commands ----------------------------------------------------------------
procedure SetBackground(ABitmap: TBitmap);
// pre: True
// post: FBackgroundBitmap = ABitmap
// and
// FBlankBitmap is a blank bitmap with the same size and
// height as FBackgroundBitmap
procedure HideAll; override;
// pre: True
// effect: only the background picture is shown, if BackgroundShown
// only the blank background is shown, if not BackgroundShown
procedure ShowAll; override;
// pre: True
// effect: Stations, Lines, Landmarks, Texts and Flags are drawn
procedure MarkStartStation(AStationCode: String);
// pre: True
// effect: The S in AbstrStations with S.GetCode = AStationCode is
// marked with the startflag, if this S exists
procedure MarkStopStation(AStationCode: String);
// pre: True
// effect: The S in AbstrStations with S.GetCode = AStationCode is
// marked with the stopflag, if this S exists
procedure ClearFlags;
// pre: True
// post: not(FStartFlag.Visible or FStopFlag.Visible)
procedure ClearSelectedLines;
// pre: True
// post: (forall L: L in AbstrLines: not(I.Selected))
procedure DeleteStation(AStation: TVisStation);
// pre: True
// post: AbstrStations = old AbstrStations \ {AStation} and
// (forall L: L in AbstrLines: L.Abstr = old L.Abstr \ {AStation})
procedure DeleteStationFromLine(AStation: TVisStation; ALine: TVisLine);
// pre: AStation in ALine.Abstr
// post: ALine.Abstr = old ALine.Abstr \ {AStation}
procedure ReplaceStation(AOldStation: TVisStation; ANewStation: TVisStation);
// pre: True
// post: (forall L:
// L in AbstrLines and AOldStation in old L.Abstr:
// let old L.Abstr = X ++ [OldStation] ++ Y
// in L.Abstr = X ++ [ANewStation] ++ Y)
// and
// AbstrStations = (old AbstrStations \ {AOldStation}) U {ANewStation}
procedure SetStationCode(AStation: TVisStation; ACode: String);
// pre: CanSetStationCode(AStation, ACode)
// post: AStation.GetCode = ACode
procedure SetLandmarkCode(ALandmark: TVisLandmark; ACode: String);
// pre: CanSetLandmarkCode(ALandmark, ACode)
// post: ALandmark.GetCode = ACode
procedure SetLineCode(ALine: TVisLine; ACode: String);
// pre: CanSetLineCode(ALine, ACode)
// post: ALine.GetCode = ACode
procedure SetTextCode(AText: TVisText; ACode: String);
// pre: CanSetTextCode(AText, ACode)
// post: AText.GetCode = ACode
procedure ShowFlags;
// pre: True
// effect: Flags are drawn on the map, provided their Visible property is
// True
procedure ShowStations;
// pre: True
// post: The stop and transfer stations are drawn on the map
procedure ShowStationDummies;
// pre: True
// post: The station dummies are drawn on the map
procedure ShowLines;
// pre: True
// post: The lines are drawn on the map
procedure ShowSelectedLines;
// pre: True
// post: The selected lines are drawn on the map
procedure ShowLandmarks;
// pre: True
// post: The landmarks are drawn on the map
procedure ShowTexts;
// pre: True
// post: The Texts are drawn on the map
procedure ShowRoute(ARoute: TRouteR);
// pre: True
// post: The route ARoute is drawn on the map
property StartFlag: TVisFlag read FStartFlag write SetStartFlag;
property StopFlag: TVisFlag read FStopFlag write SetStopFlag;
// model variables ---------------------------------------------------------
// AbstrStations: set of TVisStation
// AbstrLines: set of TVisLine
// AbstrLandmarks: set of TVisLandmark
// AbstrTexts: set of TVisText
// invariants --------------------------------------------------------------
// A0: AbstrStations =
// (set S: 0 <= S < VisComCount and GetVisCom(S) is TVisStation:
// GetVisCom(S) as TVisStation)
// A1: AbstrLines =
// (set L: 0 <= L < VisComCount and GetVisCom(L) is TVisLine:
// GetVisCom(L) as TVisLine)
// A2: AbstrLandmarks =
// (set L: 0 <= L < VisComCount and GetVisCom(L) is TVisLandmark:
// GetVisCom(L) as TVisLandmark)
// A3: AbstrTexts =
// (set T: 0 <= T < VisComCount and GetVisCom(T) is TVisText:
// GetVisCom(T) as TVisText)
end;
implementation //===============================================================
uses Math, SysUtils;
{ TVisStation }
constructor TVisStation.Create(ACode: String; AData: TObject;
AX, AY: Integer);
begin
inherited Create(ACode, AData);
FX := AX;
FY := AY;
end;
function TVisStation.X: Integer;
begin
Result := FX;
end;
function TVisStation.Y: Integer;
begin
Result := FY;
end;
procedure TVisStation.Relocate(AX, AY: Integer);
begin
FX := AX;
FY := AY
end;
{ TVisStationStop }
function TVisStationStop.CanMark(AMark: String): Boolean;
begin
Result := (AMark = 'mkStart') or (AMark = 'mkVia') or (AMark = 'mkFinish');
end;
function TVisStationStop.CanSelect: Boolean;
begin
Result := True;
end;
function TVisStationStop.Contains(AMap: TMap; AX, AY: Integer): Boolean;
begin
// Hardcoded and sloppy <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Result := (X - 3 <= AX) and (AX <= X + 3) and (Y - 3 <= AY) and (AY <= Y + 3);
end;
constructor TVisStationStop.Create(ACode: String; AData: TObject;
AX, AY: Integer);
begin
inherited Create(ACode, AData, AX, AY);
end;
procedure TVisStationStop.Draw(AMap: TMap);
var
VR: Integer;
begin
VR := 4; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< should not be hardcoded
with AMap.Picture.Bitmap.Canvas do begin
if IsSelected then begin
Pen.Width := 2;
Pen.Color := clRed;
Brush.Color := clBlack;
Ellipse(X - VR - 2, Y - VR - 2, X + VR + 2, Y + VR + 2)
end;
Pen.Width := 0;
Pen.Color := clBlack;
Brush.Color := clWhite;
Ellipse(X - VR, Y - VR, X + VR, Y + VR)
end
end;
{ TVisStationTransfer }
function TVisStationTransfer.CanMark(AMark: String): Boolean;
begin
Result := (AMark = 'mkStart') or (AMark = 'mkVia') or (AMark = 'mkFinish');
end;
function TVisStationTransfer.CanSelect: Boolean;
begin
Result := True;
end;
function TVisStationTransfer.Contains(AMap: TMap; AX, AY: Integer): Boolean;
begin
// Hardcoded and sloppy <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Result := (X - 6 <= AX) and (AX <= X + 6) and (Y - 6 <= AY) and (AY <= Y + 6);
end;
constructor TVisStationTransfer.Create(ACode: String; AData: TObject; AX,
AY: Integer);
begin
inherited Create(ACode, AData, AX, AY);
end;
procedure TVisStationTransfer.Draw(AMap: TMap);
var
VR: Integer;
begin
VR := 6; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< should not be hardcoded
with AMap.Picture.Bitmap.Canvas do begin
if IsSelected then begin
Pen.Width := 2;
Pen.Color := clRed;
Brush.Color := clBlack;
Ellipse(X - VR - 2, Y - VR - 2, X + VR + 2, Y + VR + 2)
end;
Pen.Width := 1;
Pen.Color := clBlack;
Brush.Color := clWhite;
Ellipse(X - VR, Y - VR, X + VR, Y + VR);
end;
end;
{ TVisStationDummy }
function TVisStationDummy.CanSelect;
begin
Result := True
end;
function TVisStationDummy.Contains(AMap: TMap; AX, AY: Integer): Boolean;
begin
// Hardcoded and sloppy <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Result := (X - 3 <= AX) and (AX <= X + 3) and (Y - 3 <= AY) and (AY <= Y + 3);
end;
constructor TVisStationDummy.Create(ACode: String; AX, AY: Integer);
begin
inherited Create(ACode, nil, AX, AY);
end;
procedure TVisStationDummy.Draw(AMap: TMap);
var
VR: Integer;
begin
VR := 2; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< should not be hardcoded
with AMap.Picture.Bitmap.Canvas do begin
if IsSelected then begin
Pen.Width := 2;
Pen.Color := clRed;
Brush.Color := clBlack;
Ellipse(X - VR - 2, Y - VR - 2, X + VR + 2, Y + VR + 2);
end;
Pen.Width := 0;
Pen.Color := clBlack;
Brush.Color := clBlack;
Ellipse(X - VR, Y - VR, X + VR, Y + VR)
end
end;
{ TVisLine }
procedure TVisLine.AddStation(AStation: TVisStation);
begin
Assert(not(HasStation(AStation)),
'TVisLine.AddStation.Pre: not(HasStation(AStation))');
FList.Add(AStation)
end;
function TVisLine.CanMark(AMark: String): Boolean;
begin
Result := AMark = 'mkLine';
end;
function TVisLine.CanSelect: Boolean;
begin
Result := True;
end;
function TVisLine.Contains(AMap: TMap; AX, AY: Integer): Boolean;
function OnSegment(AX,AY: Integer; AStation1,AStation2: TVisStation): Boolean;
var
X1, Y1, X2, Y2: Integer;
VA, VB, VC: Integer;
D: Real;
begin
X1 := AStation1.X;
Y1 := AStation1.Y;
X2 := AStation2.X;
Y2 := AStation2.Y;
if (Min(X1,X2) - 2 <= AX) and (AX <= Max(X1,X2) + 2) and
(Min(Y1,Y2) - 2 <= AY) and (AY <= Max(Y1,Y2) + 2)
then
begin
// compute distance D from (AX,AY) to straight line through the two
// stations:
VA := (Y2 - Y1);
VB := (X1 - X2);
VC := Y1 * (X2 - X1) - X1 * (Y2 - Y1);
D := (VA*AX + VB*AY + VC) / Sqrt(Sqr(VA) + Sqr(VB));
Result := (-3 <= D) and (D <= 3); // "close enough"
end
else
Result := False;
end;
var
I: Integer;
begin
Result := False;
if StationCount > 1 then
for I := 1 to StationCount - 1 do
if OnSegment(AX, AY, GetStation(I-1), GetStation(I))
then
begin
Result := True;
Exit
end;
end;
constructor TVisLine.Create(ACode: String; AData: TObject; AColor: TColor);
begin
inherited Create(ACode, AData);
FColor := AColor;
FList := TObjectlist.Create(False);
end;
procedure TVisLine.DeleteStation(AStation: TVisStation);
begin
FList.Remove(AStation);
end;
procedure TVisLine.ReplaceStation(AOldStation: TVisStation; ANewStation: TVisStation);
begin
with FList do begin
Add(ANewStation);
Exchange(IndexOf(AOldStation), IndexOf(ANewStation));
Remove(AOldStation)
end
end;
destructor TVisLine.Destroy;
begin
FList.Free;
inherited;
end;
procedure TVisLine.SetColor(AColor: TColor);
begin
FColor := AColor
end;
procedure TVisLine.Draw(AMap: TMap);
//# BEGIN TODO
var I: Integer;
//# END TODO
begin
//# BEGIN TODO
// Replace these lines with code which draws the metro line on the canvas
// AMap.Picture.Bitmap.Canvas
// pre: True
// effect: The line is drawn on AMap
if (StationCount > 0) then
begin
with AMap.Picture.Bitmap.Canvas do
begin
Pen.Color := GetColor;
Pen.Width := 5;
MoveTo(GetStation(0).X, GetStation(0).Y );
for I := 1 to StationCount - 1 do
begin
LineTo(GetStation(I).X, GetStation(I).Y);
end;
end;
end;
//# END TODO
end;
procedure TVisLine.DrawFromTo(AMap: TMap; AFrom, ATo: TVisStation);
var
I, L, H, M: Integer;
begin
L := FList.IndexOf(AFrom);
H := FList.IndexOf(ATo);
if H < L then
begin {swap}
M := L; L := H; H := M;
end;
with AMap.Picture.Bitmap.Canvas do
begin
Pen.Color := GetColor;
Pen.Width := 5;
MoveTo(GetStation(L).X, GetStation(L).Y);
for I := L + 1 to H do
LineTo(GetStation(I).X, GetStation(I).Y);
end;
end;
function TVisLine.GetColor: TColor;
begin
Result := FColor;
end;
function TVisLine.GetStation(I: Integer): TVisStation;
begin
Assert((0 <= I) and (I < StationCount), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Result := FList.Items[I] as TVisStation;
end;
function TVisLine.HasStation(AStation: TVisStation): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to StationCount - 1 do begin
if GetStation(I) = AStation then begin
Result := True
end
end
end;
function TVisLine.StationCount: Integer;
begin
Result := FList.Count;
end;
function TVisLine.GetIndexOfStation(AStation: TVisStation): Integer;
begin
Result := FList.IndexOf(AStation)
end;
procedure TVisLine.InsertStation(AIndex: Integer; AStation: TVisStation);
begin
FList.Insert(AIndex, AStation)
end;
{ TVisLandmark }
function TVisLandmark.CanSelect: Boolean;
begin
Result := True
end;
function TVisLandmark.Contains(AMap: TMap; AX, AY: Integer): Boolean;
begin
Result := (X <= AX) and (AX <= X + FBitmap.Width) and
(Y <= AY) and (AY <= Y + FBitmap.Height);
end;
constructor TVisLandmark.Create(ACode: String; AData: TObject; AX,
AY: Integer; ABitmap: TBitmap; ABitmapFileName: String);
begin
inherited Create(ACode, Adata);
FX := AX;
FY := AY;
FBitmap := ABitmap;
FBitmapFileName := ABitmapFileName
end;
procedure TVisLandmark.Draw(AMap: TMap);
begin
//# BEGIN TODO
// Replace these lines which draw the bitmap FBitmap at position (FX,FY) on
// the canvas AMap.Picture.Bitmap.Canvas
// pre: True
// effect: draws the bitmap on AMap
AMap.Picture.Bitmap.Canvas.Draw( FX, FY, FBitmap );
//# END TODO
end;
procedure TVisLandmark.SetBitmap(ABitmap: TBitmap);
begin
FBitmap.Free;
FBitmap := ABitmap
end;
procedure TVisLandmark.SetBitmapFileName(AFileName: String);
begin
FBitmapFileName := AFileName;
end;
procedure TVisLandmark.Relocate(AX, AY: Integer);
begin
FX := AX;
FY := AY
end;
function TVisLandmark.X: Integer;
begin
Result := FX;
end;
function TVisLandmark.Y: Integer;
begin
Result := FY;
end;
function TVisLandmark.GetBitmap: TBitmap;
begin
Result := FBitmap
end;
function TVisLandmark.GetBitmapFileName: String;
begin
Result := FBitmapFileName
end;
destructor TVisLandmark.Destroy;
begin
FBitmap.Free
end;
{ TVisText }
function TVisText.CanSelect: Boolean;
begin
Result := True
end;
function TVisText.Contains(AMap: TMap; AX, AY: Integer): Boolean;
var
H, W: Integer;
VLeft, VTop: Integer;
begin
// Eliminating superfluous warnings
Vleft := 0;
VTop := 0;
with AMap.Picture.Bitmap.Canvas do
begin
H := TextHeight(GetText);
W := TextWidth(GetText);
case GetTextPos of
tpNorth:
begin
VLeft := X - W div 2;
VTop := Y + 3;
end;
tpNorthEast:
begin
VLeft := X - W - 3;
VTop := Y + 3;
end;
tpEast:
begin
VLeft := X - W - 3;
VTop := Y - H div 2;
end;
tpSouthEast:
begin
VLeft := X - W - 3;
VTop := Y - H - 3;
end;
tpSouth:
begin
VLeft := X - W div 2;
VTop := Y - H - 3;
end;
tpSouthWest:
begin
VLeft := X + 3;
VTop := Y - H - 3;
end;
tpWest:
begin
VLeft := X + 3;
VTop := Y - H div 2;
end;
tpNorthWest:
begin
VLeft := X + 3;
VTop := Y + 3;
end;
end{case};
end{with};
Result := (VLeft <= AX) and (AX <= VLeft + W) and
(VTop <= AY) and (AY <= VTop + H);
end;
constructor TVisText.Create(ACode: String; AData: TObject; AX, AY: Integer;
AText: String; ATextPos: TTextPos);
begin
inherited Create(ACode, AData);
FX := AX;
FY := AY;
FText := AText;
FTextPos := ATextPos;
end;
procedure TVisText.Draw(AMap: TMap);
//# BEGIN TODO
// Replace this line with your own declarations
// effect: draws Text on AMap;
// position of (X,Y) w.r.t. Text is determined by TextPos
var
iHeight, iWidth: Integer;
VLeft, VTop: Integer;
//# END TODO
begin
//# BEGIN TODO
// Replace these lines with code which displays a text on a yellow background
// on the canvas AMap.Picture.Bitmap.Canvas .
//
// - The text to be displayed is given by function GetText.
// - The coordinates of the reference point are given by functions X and Y .
// - The relative position of the reference point w.r.t. the text is given by
// function GettextPos .
// E.g., when GettextPos returns the value tpSouthEast, the text rectangle
// should be positioned in such a way that its lower right corner coincides
// with the reference point * :
//
// MyText
// *
//
with AMap.Picture.Bitmap.Canvas do
begin
iHeight := TextHeight( GetText );
iWidth := TextWidth( GetText );
case GetTextPos of
tpNorth:
begin
VLeft := X - (iWidth div 2);
VTop := Y + 3;
end;
tpNorthEast:
begin
VLeft := X - iWidth - 3;
VTop := Y + 3;
end;
tpEast:
begin
VLeft := X - iWidth - 3;
VTop := Y - (iHeight div 2);
end;
tpSouthEast:
begin
VLeft := X - iWidth - 3;
VTop := Y - iHeight - 3;
end;
tpSouth:
begin
VLeft := X - ( iWidth div 2 );
VTop := Y - iHeight - 3;
end;
tpSouthWest:
begin
VLeft := X + 3;
VTop := Y - iHeight - 3;
end;
tpWest:
begin
VLeft := X + 3;
VTop := Y - ( iHeight div 2);
end;
tpNorthWest:
begin
VLeft := X + 3;
VTop := Y + 3;
end;
end; // end case
Brush.Color := clYellow;
TextOut(VLeft, VTop, GetText);
end; // end with
//# END TODO
end;
procedure TVisText.SetText(AText: String);
begin
FText := AText
end;
procedure TVisText.SetTextPos(ATextPos: TTextPos);
begin
FTextPos := ATextPos
end;
procedure TVisText.Relocate(AX, AY: Integer);
begin
FX := AX;
FY := AY
end;
function TVisText.GetText: String;
begin
Result := FText;
end;
function TVisText.GetTextPos: TTextPos;
begin
Result := FTextPos;
end;
function TVisText.X: Integer;
begin
Result := FX;
end;
function TVisText.Y: Integer;
begin
Result := FY;
end;
{ TMetroMap }
procedure TMetroMap.ClearFlags;
begin
FStartFlag.Hide;
FStopFlag.Hide;
end;
procedure TMetroMap.ClearSelectedLines;
var
I: Integer;
VVisCom: TVisCom;
begin
for I := 0 to VisComCount - 1 do
begin
VVisCom := GetVisCom(I);
if VVisCom is TVisLine
then VVisCom.UnSelect;
end;
end;
procedure TMetroMap.ReplaceStation(AOldStation: TVisStation; ANewStation: TVisStation);
var
I: Integer;
begin
for I := 0 to FVisComs.Count - 1 do begin
if (GetVisCom(I) is TVisLine) then begin
if TVisLine(GetVisCom(I)).HasStation(AOldStation) then begin
TVisLine(GetVisCom(I)).ReplaceStation(AOldStation, ANewStation)
end
end
end;
Replace(AOldStation, ANewStation)
end;
function TMetroMap.GetLine(ACode: String): TVisLine;
var
I: Integer;
begin
Result := nil;
for I := 0 to VisComCount - 1 do
if (GetVisCom(I) is TVisLine) and (GetVisCom(I).GetCode = ACode)
then Result := GetVisCom(I) as TVisLine;
end;
function TMetroMap.GetStation(ACode: String): TVisStation;
var
I: Integer;
begin
Result := nil;
for I := 0 to VisComCount - 1 do
if (GetVisCom(I) is TVisStation) and (GetVisCom(I).GetCode = ACode)
then Result := GetVisCom(I) as TVisStation;
end;
function TMetroMap.GetLandmark(ACode: String): TVisLandmark;
var
I: Integer;
begin
Result := nil;
for I := 0 to VisComCount - 1 do
if (GetVisCom(I) is TVisLandmark) and (GetVisCom(I).GetCode = ACode)
then Result := GetVisCom(I) as TVisLandmark;
end;
function TMetroMap.GetText(ACode: String): TVisText;
var
I: Integer;
begin
Result := nil;
for I := 0 to VisComCount - 1 do
if (GetVisCom(I) is TVisText) and (GetVisCom(I).GetCode = ACode)
then Result := GetVisCom(I) as TVisText;
end;
function TMetroMap.HasLine(ACode: String): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to VisComCount - 1 do
if (GetVisCom(I) is TVisLine) and (GetVisCom(I).GetCode = ACode)
then Result := True;
end;
function TMetroMap.HasStation(ACode: String): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to VisComCount - 1 do
if (GetVisCom(I) is TVisStation) and (GetVisCom(I).GetCode = ACode)
then Result := True;
end;
function TMetroMap.HasLandmark(ACode: String): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to VisComCount - 1 do
if (GetVisCom(I) is TVisLandmark) and (GetVisCom(I).GetCode = ACode)
then Result := True;
end;
function TMetroMap.HasText(ACode: String): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to VisComCount - 1 do
if (GetVisCom(I) is TVisText) and (GetVisCom(I).GetCode = ACode)
then Result := True;
end;
procedure TMetroMap.SetBackground(ABitmap: TBitmap);
var
VBlankBitmap: TBitmap;
begin
SetBackgroundBitmap(ABitmap);
VBlankBitmap := TBitmap.Create;
VBlankBitmap.Height := ABitmap.Height;
VBlankBitmap.Width := ABitmap.Width;
VBlankBitmap.Canvas.Pen.Color := clWhite;
VBlankBitmap.Canvas.Brush.Color := clWhite;
VBlankBitmap.Canvas.Rectangle(0, 0, ABitmap.Width, ABitmap.Height);
SetBlankBitmap(VBlankBitmap)
end;
procedure TMetroMap.HideAll;
begin
if BackgroundShown
then Picture.Assign(FBackgroundBitmap)
else Picture.Assign(FBlankBitmap);
end;
procedure TMetroMap.MarkStartStation(AStationCode: String);
var
VStation: TVisStation;
begin
VStation := GetStation(AStationCode);
if VStation <> nil then
begin
FStartFlag.MoveTo(VStation.X, VStation.Y);
FStartFlag.Show;
end;
end;
procedure TMetroMap.MarkStopStation(AStationCode: String);
var
VStation: TVisStation;
begin
VStation := GetStation(AStationCode);
if VStation <> nil then
begin
FStopFlag.MoveTo(VStation.X, VStation.Y);
FStopFlag.Show;
end;
end;
procedure TMetroMap.SetStartFlag(AFlag: TVisFlag);
begin
FStartFlag := AFlag;
end;
procedure TMetroMap.SetStopFlag(AFlag: TVisFlag);
begin
FStopFlag := AFlag;
end;
procedure TMetroMap.ShowAll;
begin
// N.B.: order is important
ShowLines;
ShowStations;
ShowLandmarks;
ShowTexts;
ShowFlags;
end;
procedure TMetroMap.ShowFlags;
begin
if FStartFlag.Visible then FStartFlag.Draw(Self);
if FStopFlag.Visible then FStopFlag.Draw(Self);
end;
procedure TMetroMap.ShowLandmarks;
var
I: Integer;
begin
for I := 0 to VisComCount - 1 do
if GetVisCom(I) is TVisLandmark
then GetVisCom(I).Draw(Self);
end;
procedure TMetroMap.ShowLines;
var
I: Integer;
begin
for I := 0 to VisComCount - 1 do
if GetVisCom(I) is TVisLine
then GetVisCom(I).Draw(Self);
end;
procedure TMetroMap.ShowRoute(ARoute: TRouteR);
var
I: Integer;
VVisLine: TVisLine;
VFromStation, VToStation: TVisStation;
begin
with ARoute do
for I := 0 to SegmentCount - 1 do
with GetSegment(I) do
begin
VVisLine := GetLine(Line.GetCode);
VFromStation := GetStation(FromStation.GetCode);
VToStation := GetStation(ToStation.GetCode);
VVisLine.DrawFromTo(Self, VFromStation, VToStation);
end;
end;
procedure TMetroMap.ShowSelectedLines;
var
I: Integer;
VVisCom: TVisCom;
begin
for I := 0 to VisComCount - 1 do
begin
VVisCom := GetVisCom(I);
if (VVisCom is TVisLine) and (VVisCom.IsSelected)
then VVisCom.Draw(Self);
end;
end;
procedure TMetroMap.ShowStations;
var
I: Integer;
begin
for I := 0 to VisComCount - 1 do
if (GetVisCom(I) is TVisStationStop) or
(GetVisCom(I) is TVisStationTransfer)
then GetVisCom(I).Draw(Self);
end;
procedure TMetroMap.ShowStationDummies;
var
I: Integer;
begin
for I := 0 to VisComCount - 1 do
if GetVisCom(I) is TVisStationDummy
then GetVisCom(I).Draw(Self);
end;
procedure TMetroMap.ShowTexts;
var
I: Integer;
begin
for I := 0 to VisComCount - 1 do
if GetVisCom(I) is TVisText
then GetVisCom(I).Draw(Self);
end;
function TMetroMap.LandmarkContaining(AX, AY: Integer): TVisLandmark;
var
I: Integer;
VVisCom: TVisCom;
begin
Result := nil;
for I := 0 to VisComCount - 1 do
begin
VVisCom := GetVisCom(I);
if (VVisCom is TVisLandmark) and VVisCom.Contains(Self, AX, AY)
then
Result := VVisCom as TVisLandmark;
end{for};
end;
function TMetroMap.LineContaining(AX, AY: Integer): TVisLine;
var
I: Integer;
VVisCom: TVisCom;
begin
Result := nil;
for I := 0 to VisComCount - 1 do
begin
VVisCom := GetVisCom(I);
if (VVisCom is TVisLine) then begin
if VVisCom.Contains(Self, AX, AY) then begin
Result := VVisCom as TVisLine;
end
end
end{for}
end;
function TMetroMap.StationContaining(AX, AY: Integer): TVisStation;
var
I: Integer;
VVisCom: TVisCom;
begin
Result := nil;
for I := 0 to VisComCount - 1 do
begin
VVisCom := GetVisCom(I);
if (VVisCom is TVisStation) and VVisCom.Contains(Self, AX, AY)
then
Result := VVisCom as TVisStation;
end{for};
end;
function TMetroMap.TextContaining(AX, AY: Integer): TVisText;
var
I: Integer;
VVisCom: TVisCom;
begin
Result := nil;
for I := 0 to VisComCount - 1 do
begin
VVisCom := GetVisCom(I);
if (VVisCom is TVisText) and VVisCom.Contains(Self, AX, AY)
then
Result := VVisCom as TVisText;
end{for};
end;
procedure TMetroMap.DeleteStation(AStation: TVisStation);
var
I: Integer;
begin
for I := 0 to FVisComs.Count - 1 do begin
if (GetVisCom(I) is TVisLine) then begin
if TVisLine(GetVisCom(I)).HasStation(AStation) then begin
TVisLine(GetVisCom(I)).DeleteStation(AStation)
end
end
end;
Delete(AStation)
end;
procedure TMetroMap.DeleteStationFromLine(AStation: TVisStation;
ALine: TVisLine);
begin
Assert(ALine.HasStation(AStation),
'TMetroMap.DeleteStationFromLine.Pre: ALine.HasStation(AStation)');
ALine.DeleteStation(AStation)
end;
procedure TMetroMap.SetLandmarkCode(ALandmark: TVisLandmark;
ACode: String);
begin
Assert(CanSetLandmarkCode(ALandmark, ACode),
'TMetroMap.SetLandmarkCode.Pre: CanSetLandmarkCode(ALandmark, ACode)');
ALandmark.FCode := ACode
end;
procedure TMetroMap.SetLineCode(ALine: TVisLine; ACode: String);
begin
Assert(CanSetLineCode(ALine, ACode),
'TMetroMap.SetLineCode.Pre: CanSetLineCode(ALine, ACode)');
ALine.FCode := ACode
end;
procedure TMetroMap.SetStationCode(AStation: TVisStation; ACode: String);
begin
Assert(CanSetStationCode(AStation, ACode),
'TMetroMap.SetStationCode.Pre: CanSetStationCode(AStation, ACode)');
AStation.FCode := ACode
end;
procedure TMetroMap.SetTextCode(AText: TVisText; ACode: String);
begin
Assert(CanSetTextCode(AText, ACode),
'TMetroMap.SetTextCode.Pre: CanSetTextCode(AText, ACode)');
AText.FCode := ACode
end;
function TMetroMap.CanSetLandmarkCode(ALandmark: TVisLandmark;
ACode: String): Boolean;
begin
Result := not(HasLandmark(ACode)) and ValidLandmarkCode(ACode) and
HasLandmark(ALandmark.GetCode)
end;
function TMetroMap.CanSetLineCode(ALine: TVisLine; ACode: String): Boolean;
begin
Result := not(HasLine(ACode)) and ValidLineCode(ACode) and
HasLine(ALine.GetCode)
end;
function TMetroMap.CanSetStationCode(AStation: TVisStation;
ACode: String): Boolean;
begin
Result := not(HasStation(ACode)) and ValidStationCode(ACode) and
HasStation(AStation.GetCode)
end;
function TMetroMap.CanSetTextCode(AText: TVisText; ACode: String): Boolean;
begin
Result := not(HasText(ACode)) and ValidTextCode(ACode) and
HasText(AText.GetCode)
end;
{ TVisFlag }
function TVisFlag.Contains(AMap: TMap; AX, AY: Integer): Boolean;
begin
Result := False;
end;
constructor TVisFlag.Create(ACode: String; AData: TObject; AX, AY: Integer;
ABitmap: TBitmap);
begin
inherited Create(ACode, AData);
FX := AX;
FY := AY;
FVisible := False;
FBitmap := ABitmap;
end;
procedure TVisFlag.Draw(AMap: TMap);
begin
AMap.Picture.Bitmap.Canvas.Draw(FX - 24, FY - 32, FBitmap);
end;
procedure TVisFlag.Hide;
begin
FVisible := False;
end;
procedure TVisFlag.MoveTo(AX, AY: Integer);
begin
FX := AX;
FY := AY;
end;
procedure TVisFlag.Show;
begin
FVisible := True;
end;
function TVisFlag.Visible: Boolean;
begin
Result := FVisible;
end;
function TVisFlag.X: Integer;
begin
Result := FX;
end;
function TVisFlag.Y: Integer;
begin
Result := FY;
end;
end.
|
unit BCEditor.Editor.Undo;
interface
uses
Classes, BCEditor.Consts, BCEditor.Types;
type
TBCEditorUndo = class(TPersistent)
strict private
FMaxActions: Integer;
FOnChange: TNotifyEvent;
FOptions: TBCEditorUndoOptions;
procedure DoChange;
procedure SetMaxActions(Value: Integer);
procedure SetOptions(const Value: TBCEditorUndoOptions);
public
constructor Create;
procedure Assign(Source: TPersistent); override;
published
property MaxActions: Integer read FMaxActions write SetMaxActions default BCEDITOR_MAX_UNDO_ACTIONS;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property Options: TBCEditorUndoOptions read FOptions write SetOptions default [uoGroupUndo];
end;
implementation
constructor TBCEditorUndo.Create;
begin
inherited;
FMaxActions := BCEDITOR_MAX_UNDO_ACTIONS;
FOptions := [uoGroupUndo];
end;
procedure TBCEditorUndo.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TBCEditorUndo.Assign(Source: TPersistent);
begin
if Source is TBCEditorUndo then
with Source as TBCEditorUndo do
begin
Self.FMaxActions := FMaxActions;
Self.FOptions := FOptions;
Self.DoChange;
end
else
inherited Assign(Source);
end;
procedure TBCEditorUndo.SetMaxActions(Value: Integer);
begin
if Value <> FMaxActions then
begin
FMaxActions := Value;
DoChange;
end;
end;
procedure TBCEditorUndo.SetOptions(const Value: TBCEditorUndoOptions);
begin
if Value <> FOptions then
begin
FOptions := Value;
DoChange;
end;
end;
end.
|
UNIT TreeUnit;
INTERFACE
TYPE NodePtr = ^Node;
Node = RECORD
left, right: NodePtr;
val: string;
count: integer;
END;
Tree = NodePtr;
FUNCTION NewNode(x: string): NodePtr;
PROCEDURE DisposeTree(var t: Tree);
FUNCTION GetHighestCount(t: Tree): NodePtr;
(* FUNCTIONS For Search Trees *)
FUNCTION IsSorted(t: Tree): boolean;
PROCEDURE Insert(var t: Tree; x: string);
FUNCTION FindNode(t: Tree; x: string): NodePtr;
IMPLEMENTATION
PROCEDURE DisposeTree(var t: Tree);
BEGIN
if t <> NIL then begin
DisposeTree(t^.left);
DisposeTree(t^.right);
Dispose(t);
t := NIL;
end;
END; (* DisposeTree *)
FUNCTION FindNode(t: Tree; x: string): NodePtr;
BEGIN
if t = NIL then
FindNode := NIL
else if x = t^.val then
FindNode := t
else if x < t^.val then
FindNode := FindNode(t^.left, x)
else
FindNode := FindNode(t^.right, x);
END;
FUNCTION IsSorted(t: Tree): boolean;
BEGIN
if t = NIL then
IsSorted := true
else begin
if (t^.left <> NIL) AND (t^.left^.val > t^.val) then
IsSorted := false
else if(t^.right <> NIL) AND (t^.right^.val < t^.val) then
IsSorted := false
else if IsSorted(t^.left) AND (IsSorted(t^.right)) then
IsSorted := true
else
IsSorted := false;
end;
END;
PROCEDURE Insert(var t: Tree; x: string);
var n: NodePtr;
BEGIN
//if not(IsSorted(t)) then HALT;
if t = NIL then begin
n := NewNode(x);
t := n;
end else if t^.val = x then
Inc(t^.count)
else if x <= t^.val then
Insert(t^.left, x)
else
Insert(t^.right, x);
END;
FUNCTION NewNode(x: string): NodePtr;
var n: NodePtr;
BEGIN
New(n);
n^.val := x;
n^.count := 1;
n^.left := NIL;
n^.right := NIL;
NewNode := n;
END;
FUNCTION GetHighestCount(t: Tree): NodePtr;
var l, r: NodePtr;
BEGIN
if (t^.left = NIL) AND (t^.right = NIL) then begin
GetHighestCount := t;
end else if (t^.left <> NIL) AND (t^.right <> NIL) then begin
l := GetHighestCount(t^.left);
r := GetHighestCount(t^.right);
if l^.count > r^.count then begin
if l^.count > t^.count then GetHighestCount := l
else GetHighestCount := t;
end else begin
if r^.count > t^.count then GetHighestCount := r
else GetHighestCount := t;
end; (* IF *)
end else if (t^.left <> NIL) then begin
l := GetHighestCount(t^.left);
if t^.count > l^.count then GetHighestCount := t
else GetHighestCount := l;
end else if (t^.right <> NIL) then begin
r := GetHighestCount(t^.right);
if t^.count > r^.count then GetHighestCount := t
else GetHighestCount := r;
end; (* IF *)
END;
BEGIN
END. |
program recdemo(input,output);
type
TEmployee = record
name : string[25];
address : string[40];
age : byte;
position : string[10];
commision : real;
end;
var
x : TEmployee;
begin
x.name := 'Paul Doherty';
x.address := '11th Kingston Avenue';
x.age := 35;
x.position := 'Salesman';
x.commision := 0.10;
end.
|
unit u_Downloader_Indy;
{$ifdef fpc}
{$mode delphi}
{$endif}
interface
uses Classes,
IdHTTP,
IdComponent,
IdHeaderList;
type TDownloadAbordEvent = procedure(aSender : TObject; anError : integer) of object;
{ TDownloader }
TDownloader = class
private
IdHTTP: TIdHTTP;
XMLStream : TMemoryStream;
fSourceURL : string;
fDestFolder : string;
fFileName : string;
FOnWork: TWorkEvent;
FOnWorkBegin: TWorkBeginEvent;
FOnWorkEnd: TWorkEndEvent;
FOnAbort : TDownloadAbordEvent;
procedure HeadersAvailable(Sender: TObject; AHeaders: TIdHeaderList; var VContinue: Boolean);
procedure WorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64);
procedure Work(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
procedure WorkEnd({%h-}ASender: TObject; AWorkMode: TWorkMode);
procedure SetProxy(const aProxyInf : string);
public
constructor Create;
destructor Destroy; override;
procedure Start(const aSource, aDestination : string);
property OnWork: TWorkEvent read FOnWork write FOnWork;
property OnWorkBegin: TWorkBeginEvent read FOnWorkBegin write FOnWorkBegin;
property OnWorkEnd: TWorkEndEvent read FOnWorkEnd write FOnWorkEnd;
property OnWorkAbort : TDownloadAbordEvent read fOnAbort write fOnAbort;
property Source : string read fSourceURL;
end;
function HTTPDownload(const aSource, aDestination, aProxyInf : string) : boolean;
implementation // =============================================================
uses RegExpr
, SysUtils
;
function HTTPDownload(const aSource, aDestination, aProxyInf : string) : boolean;
begin
Result := True;
with TDownloader.Create do try
try
SetProxy(aProxyInf);
Start(aSource,aDestination);
except
Result := False;
end;
finally
Free;
end;
end;
constructor TDownloader.Create;
begin
IdHTTP := TIdHTTP.Create(nil);
IdHTTP.HandleRedirects := true;
IdHTTP.OnHeadersAvailable := HeadersAvailable;
IdHTTP.OnWorkBegin := WorkBegin;
IdHTTP.OnWorkEnd := WorkEnd;
IdHTTP.OnWork := Work;
XMLStream := TMemoryStream.Create;
XMLStream.SetSize(64000);
end;
procedure TDownloader.HeadersAvailable(Sender: TObject; AHeaders: TIdHeaderList; var VContinue: Boolean);
begin
vContinue := (fFileName<>''); // either we have a filename provided by the program
if not vContinue then with TRegExpr.Create do begin // either we try to find it in the http header
Expression := 'filename=(.*?);';
vContinue := Exec(aHeaders.Text);
if vContinue then fFileName := Match[1]; // If the filename is present in the http header
Free;
end;
if not vContinue and Assigned(fOnAbort) then fOnAbort(self, 404);
end;
procedure TDownloader.Start(const aSource, aDestination : string);
begin
fSourceURL := aSource;
fDestFolder := ExtractFilePath(aDestination);
fFileName := ExtractFileName(aDestination);
try
IdHTTP.Get(fSourceURL,XMLStream);
except
On E : EIdHTTPProtocolException do if Assigned(fOnAbort) then fOnAbort(self, E.ErrorCode);
end;
end;
procedure TDownloader.WorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64);
begin
if Assigned(fOnWorkBegin) then fOnWorkBegin(aSender, aWorkMode, aWorkCountMax);
end;
procedure TDownloader.Work(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
begin
if Assigned(fOnWork) then fOnWork(aSender, aWorkMode, aWorkCount);
end;
procedure TDownloader.WorkEnd(ASender: TObject; AWorkMode: TWorkMode);
begin
XMLStream.Seek(0,soFromBeginning);
if XMLStream.Size<>0 then begin;
DeleteFile(fDestFolder + fFileName); // Be sure the file doesn't already exist with this name
with TFileStream.Create(fDestFolder + fFileName, fmCreate) do begin
CopyFrom(XMLStream,XMLStream.Size);
Free;
end;
end else if Assigned(fOnAbort) then fOnAbort(self, 400);
XMLStream.Clear;
if Assigned(fOnWorkEnd) then fOnWorkEnd(self, aWorkMode);
end;
procedure TDownloader.SetProxy(const aProxyInf: string);
var sl : TStringList;
begin
if length(aProxyInf)<>0 then begin
sl := TStringList.Create;
sl.Delimiter := ':';
sl.DelimitedText:=aProxyInf;
IdHTTP.ProxyParams.ProxyServer :=sl[0];
IdHTTP.ProxyParams.ProxyPort := StrToInt(sl[1]);
sl.Free;
end;
end;
destructor TDownloader.Destroy;
begin
IdHTTP.Free;
XMLStream.Free;
inherited Destroy;
end;
end.
|
unit ResltFrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, DB, DBTables, Grids, DBGrids, StdCtrls;
type
TQueryForm = class(TForm)
QueryLabel: TLabel;
DBGrid1: TDBGrid;
DataSource: TDataSource;
Query: TQuery;
Session: TSession;
StatusLine: TLabel;
Database: TDatabase;
private
{ Private declarations }
public
{ Public declarations }
end;
procedure BackgroundQuery(const QueryName, Alias, User, Password,
QueryText: string);
implementation
{$R *.DFM}
{ TQueryThread }
type
TQueryThread = class(TThread)
private
QueryForm: TQueryForm;
MessageText: string;
procedure ConnectQuery;
procedure DisplayMessage;
protected
procedure Execute; override;
public
constructor Create(AQueryForm: TQueryForm);
end;
constructor TQueryThread.Create(AQueryForm: TQueryForm);
begin
QueryForm := AQueryForm;
FreeOnTerminate := True;
inherited Create(False);
end;
var
Guard: Integer;
Numbers: Integer;
{ Thread safe increment of Numbers to guarantee the result is unique }
function GetUniqueNumber: Integer;
asm
@@1: MOV EDX,1
XCHG Guard,EDX
OR EDX,EDX
JNZ @@2
MOV EAX,Numbers
INC EAX
MOV Numbers,EAX
MOV Guard,EDX
RET
@@2: PUSH 0
CALL Sleep
JMP @@1
end;
procedure TQueryThread.Execute;
var
UniqueNumber: Integer;
begin
try
with QueryForm do
begin
{ Ensure the Query has a unique session and database. A unique session
is required for each thread. Since databases are session specific
it must be unique as well }
UniqueNumber := GetUniqueNumber;
Session.SessionName := Format('%s%x', [Session.Name, UniqueNumber]);
Database.SessionName := Session.SessionName;
Database.DatabaseName := Format('%s%x', [Database.Name, UniqueNumber]);
Query.SessionName := Database.SessionName;
Query.DatabaseName := Database.DatabaseName;
{ Open the query }
Query.Open;
{ Connect the query to the grid. This must be done in a synchronzied
method since assigning the query to the DataSource will modify the
contents of the grid and the grid can only be modified from the main
VCL thread }
Synchronize(ConnectQuery);
{ Update the status line. Since the label is a VCL control this must
also be done in the main VCL thread }
MessageText := 'Query openned';
Synchronize(DisplayMessage);
end;
except
on E: Exception do
begin
{ Display any error we receive on the status line }
MessageText := Format('%s: %s.', [E.ClassName, E.Message]);
Synchronize(DisplayMessage);
end;
end;
end;
procedure TQueryThread.ConnectQuery;
begin
with QueryForm do DataSource.Dataset := Query;
end;
procedure TQueryThread.DisplayMessage;
begin
with QueryForm do StatusLine.Caption := MessageText;
end;
{ BackgroundQuery }
procedure BackgroundQuery(const QueryName, Alias, User, Password,
QueryText: string);
var
QueryForm: TQueryForm;
begin
QueryForm := TQueryForm.Create(Application);
with QueryForm, Database do
begin
Caption := QueryName;
QueryLabel.Caption := QueryText;
Show;
AliasName := Alias;
Params.Values['USER'] := User;
Params.Values['PASSWORD'] := Password;
Query.Sql.Text := QueryText;
end;
{ Create the background thread to execute the query. Since the thread
will free itself on termination we do not neet to maintain a reference
to it. Creating it is enough }
TQueryThread.Create(QueryForm);
end;
end.
|
unit classe.professor_disciplina;
interface
Uses TEntity, AttributeEntity, SysUtils, classe.disciplina;
type
[TableName('Professor_Disciplina')]
TProfessor_Disciplina = class(TGenericEntity)
private
// FDisciplina : TDisciplina;
FIdProfessor:integer;
FIdDisciplina:integer;
procedure setIdProfessor(const Value: integer);
procedure setIdDisciplina(const Value: integer);
public
[KeyField('IDPROFESSOR')]
[FieldName('IDPROFESSOR')]
property CodigoProfessor: integer read FIdProfessor write setIdProfessor;
[FieldName('IDDISCIPLINA')]
property CodigoDisciplina: integer read FIdDisciplina write setIdDisciplina;
// [Association(ftEager, orRequired, ctCascadeAll)]
// [JoinColumn('IDDISCIPLINA')]
// property Disciplina: TDisciplina read FDisciplina write FDisciplina;
function ToString:string; override;
end;
implementation
procedure TProfessor_Disciplina.setIdDisciplina(const Value: integer);
begin
FIdDisciplina := Value;
end;
procedure TProfessor_Disciplina.setIdProfessor(const Value: integer);
begin
FIdProfessor := Value;
end;
function TProfessor_Disciplina.toString;
begin
result := ' Código Prof. : '+ IntToStr(CodigoProfessor) +' Código Deisc. : '+IntToStr(CodigoDisciplina);
end;
end.
|
{-------------------------------------------------------------------------------
// Authentication Demo
//
// Description: Three Handlers to Know, They Are (In Order):
// ApacheOnAccessChecker......Access Control
// ApacheOnCheckUserId........Authentication
// ApacheOnAuthChecker........Authorization {This Demo}
//
// Access Control:
// Access control is any type of restriction that doesn't
// require the identity of the remote user.
// Use this handler to deny or grant access based on
// Host, IP , Domain....etc.
//
// Authentication:
// May I see your ID Please ? Who are you and can you
// Prove it ? Use this handler to implement your desired
// Authentication Scheme.
//
// Authorization:
// OK, So you _ARE_ Mr.Foo, However I still can't Let you
// in ! Once you know Who the person is, use the
// Authorization handler to determine if the individual
// user can enter.
//
//
// This Demo Will Authorize the _Authenticated_ user. Use the
// Authentication of your Choice. It will authorize only the user
// named kylix.
//-----------------------------------------------------------------------------}
unit Authorization_u;
interface
uses
SysUtils, Classes, HTTPApp, ApacheApp, HTTPD;
type
TWebModule1 = class(TWebModule)
procedure WebModule1Actions0Action(Sender: TObject;
Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
private
{ Private declarations }
public
{ Public declarations }
end;
var
WebModule1: TWebModule1;
path : String;
implementation
uses WebReq;
{$R *.xfm}
procedure TWebModule1.WebModule1Actions0Action(Sender: TObject;
Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
begin
// this only fires if the SetHandler directive is used....
response.content:='You have been authorized: '+ Request.Content;
end;
function Apache_OnAuthChecker(Request: Prequest_rec): integer;
var
c_req: Pconn_rec;
begin
c_req := Request^.connection;
if strcomp('kylix', c_req.user) = 0 then
result := AP_OK
else
begin
ap_log_error(Request.server.error_fname , APLOG_ALERT, APLOG_ALERT, Request.server,
PChar('access to ' + Request.uri + ' failed, reason: user ' +
c_req.user + ' not allowed access '));
result := HTTP_UNAUTHORIZED;
end;
end;
initialization
//ApacheOnCreateDirConfig := create_auth_dir_config;
//ApacheOnAccessChecker := Apache_OnAccessChecker;
//ApacheOnCheckUserId := Apache_OnCheckUserID;
ApacheOnAuthChecker := Apache_OnAuthChecker;
end.
|
unit String_Handle;
interface
uses Classes, SysUtils, ASGSQLite3, StdCtrls;
function getString_List(inputString: String): TStringList;
procedure getList_fromDB(asqQU_Temp: TASQLite3Query; sql_str: String; fieldNM: String;
var ccb_box: TComboBox);
implementation
function getString_List(inputString: String): TStringList;
var getList: TStringList;
i: Integer;
begin
inputString:= stringreplace(inputString, ' ', '***___???', [rfReplaceAll, rfIgnoreCase]);
getList := TStringList.Create;
getList.CommaText:= inputString;
getList.Delimiter:= ',';
if(getList.Count > 0) then
begin
for i := 0 to getList.Count - 1 do
begin
getList[i]:= stringreplace(getList[i], '***___???', ' ', [rfReplaceAll, rfIgnoreCase]);
end;
end;
result:= getList;
FreeAndNil(getList);
end;
procedure getList_fromDB(asqQU_Temp: TASQLite3Query; sql_str: String; fieldNM: String;
var ccb_box: TComboBox);
var
i: Integer;
begin
asqQU_Temp.Close;
asqQU_Temp.SQL.Text:= sql_str;
asqQU_Temp.Open;
ccb_box.Items.Clear;
asqQU_Temp.First;
for I := 0 to asqQU_Temp.RecordCount - 1 do begin
if asqQU_Temp.FieldByName(fieldNM).Text = '' then begin
asqQU_Temp.Next;
continue;
end;
ccb_box.Items.Add(asqQU_Temp.FieldByName(fieldNM).Text);
asqQU_Temp.Next;
end;
{
if asqQU_Temp.FieldByName(fieldNM).Text <> '' then begin
for I := 0 to asqQU_Temp.RecordCount - 1 do begin
ccb_box.Items.Add(asqQU_Temp.FieldByName(fieldNM).Text);
asqQU_Temp.Next;
end;
end;
}
end;
end.
|
unit TreeEditorCommands;
interface
uses
UndoRedo, Nodes, TreeEditor, Repr, Dialogs, SysUtils,
RE, RERepr, Prop, PropRepr, MyMath, MathRepr;
type
// ===== DoClear ===================================================
TCommand_DoClear =
class(TCommand)
protected
// command parameters
FTreeEditor: TTreeEditor;
// additional data for reverse
FDeletedTree: TNode;
public
constructor Create(ATreeEditor: TTreeEditor);
procedure Execute; override;
procedure Reverse; override;
function Reversible: Boolean; override;
end;
// ===== DoCut ===================================================
TCommand_DoCut =
class(TCommand)
protected
// command parameters
FTreeEditor: TTreeEditor;
// additional data for reverse
FDeletedTree: TNode;
public
constructor Create(ATreeEditor: TTreeEditor);
procedure Execute; override;
procedure Reverse; override;
function Reversible: Boolean; override;
end;
// ===== DoDelete ===================================================
TCommand_DoDelete =
class(TCommand)
protected
// command parameters
FTreeEditor: TTreeEditor;
// additional data for reverse
FDeletedTree: TNode;
public
constructor Create;
procedure Execute; override;
procedure Reverse; override;
function Reversible: Boolean; override;
end;
// ===== DoExpand ===================================================
TCommand_DoExpand =
class(TCommand)
protected
// command parameters
FNew: TNode;
FTreeEditor: TTreeEditor;
// additional data for reverse
FDeletedTree: TNode;
// geen FDeletedTree, want Expand word alleen gebruikt op holes
public
constructor Create(ATreeEditor: TTreeEditor; ANew: TNode);
procedure Execute; override;
procedure Reverse; override;
function Reversible: Boolean; override;
end;
// ===== DoPaste ===================================================
TCommand_DoPaste =
class(TCommand)
protected
// command parameters
FTreeEditor: TTreeEditor;
FClip: TNode;
// additional data for reverse
FDeletedTree: TNode;
public
constructor Create(ATreeEditor: TTreeEditor; AClip: TNode);
procedure Execute; override;
procedure Reverse; override;
function Reversible: Boolean; override;
end;
//****************************************************************
//*** Implementation ***
//****************************************************************
implementation
// ===== DoClear ===================================================
constructor TCommand_DoClear.Create(ATreeEditor: TTReeEditor);
begin
inherited Create;
FTreeEditor := ATreeEditor;
end;
procedure TCommand_DoClear.Execute;
var
VNew: TNode;
begin
// remember tree to be deleted
FDeletedTree := FTreeEditor.Tree.Clone;
// *** DoClear *****************
// pre: true
// effect: - FTreeEditor.Tree wordt opgeruimd en vevangen door een gat
// - FTreeEditor.Focus verwijst naar dat gat
if FTreeEditor.Tree is TRE then
begin
VNew := TRE_Hole.Create;
end
else if FTreeEditor.Tree is TProp then
begin
VNew := TProp_Hole.Create;
end
else if FTreeEditor.Tree is TMath then
begin
VNew := TMath_Hole.Create;
end;
FTReeEditor.Replace( VNew, FTreeEditor.Tree );
end;
procedure TCommand_DoClear.Reverse;
begin
// FTRee := FDelete tree
FTreeEditor.Replace( FDeletedTree, FTreeEditor.Tree);
end;
function TCommand_DoClear.Reversible: Boolean;
begin
Result := true;
end;
// ===== DoCut ===================================================
constructor TCommand_DoCut.Create(ATreeEditor:TTReeEditor);
begin
inherited Create;
FTreeEditor := ATreeEditor;
end;
procedure TCommand_DoCut.Execute;
var VNew: TNode;
begin
// Save Deleted tree
FDeletedTree := FTreeEditor.Tree.Clone;
//*** DoCut ******************************
// replace with hole
// pre: - FTreeEditor.Focus <> nil
// - FTreeEditor.Focus verwijst niet naar een gat
// effect: - de door FTreeEditor.Focus aangewezen boom wordt vervangen door
// een gat
// - FTreeEditor.Focus verwijst naar dat gat
// - verwijderde boom wordt op clipboard geplaatst
// Set the New to empty
if FTreeEditor.Tree is TRE then
begin
VNew := TRE_Hole.Create;
end
else if FTreeEditor.Tree is TProp then
begin
VNew := TProp_Hole.Create;
end
else if FTreeEditor.Tree is TMath then
begin
VNew := TMath_Hole.Create;
end;
FTreeEditor.Replace( VNew, FTreeEditor.Focus );
FTreeEditor.Focus := VNew;
end;
procedure TCommand_DoCut.Reverse;
begin
FTreeEditor.Replace(FDeletedTree, FTreeEditor.Tree);
end;
function TCommand_DoCut.Reversible: Boolean;
begin
Result := true;
end;
// ===== DoDelete ===================================================
constructor TCommand_DoDelete.Create;
begin
inherited Create;
end;
procedure TCommand_DoDelete.Execute;
begin
// Save Deleted tree
// replace with hole
end;
procedure TCommand_DoDelete.Reverse;
begin
// Vervang Gat met FDeletedTree
end;
function TCommand_DoDelete.Reversible: Boolean;
begin
Result := true;
end;
// ===== DoExpand ===================================================
constructor TCommand_DoExpand.Create(ATreeEditor: TTreeEditor; ANew: TNode);
begin
inherited Create;
FNew := ANew;
FTreeEditor:= ATreeEditor;
end;
procedure TCommand_DoExpand.Execute;
begin
// Save father of deleted node
FDeletedTree := FTreeEditor.Tree.Clone;
//# BEGIN TODO
// pre: - FTreeEditor.Focus verwijst naar een gat
// - ANew is wortel van goedgevormde boom
// effect: - in FTreeEditor.Tree wordt het door FFocus aangegeven gat
// vervangen door boom met wortel ANew
// - FTreeEditor.Focus wijst naar Anew
FTreeEditor.Replace(FNew, FTreeEditor.Focus);
FTreeEditor.Focus := FNew;
// replace with ANew
end;
procedure TCommand_DoExpand.Reverse;
begin
// Replace ANew with hole
FTreeEditor.Replace(FDeletedTree, FTreeEditor.Tree);
end;
function TCommand_DoExpand.Reversible: Boolean;
begin
Result := true;
end;
// ===== DoPaste ===================================================
constructor TCommand_DoPaste.Create(ATreeEditor:TTreeEditor; AClip:TNode);
begin
inherited Create;
FTreeEditor:= ATreeEditor;
FClip := AClip;
end;
procedure TCommand_DoPaste.Execute;
var VNew,VOld: TNode;
begin
FDeletedTree := FTreeEditor.Tree.Clone;
// Save father of holy
VNew := FClip;
VOld := FTreeEditor.Focus;
FTreeEditor.Replace(VNew, VOld);
FTreeEditor.Focus := VNew;
// replace hole with tree in clipboard
end;
procedure TCommand_DoPaste.Reverse;
begin
// Replace son of saven father with hole
end;
function TCommand_DoPaste.Reversible: Boolean;
begin
Result := true;
end;
end.
|
unit Vigilante.Aplicacao.DI;
interface
uses
System.Generics.Collections, ContainerDI.Base, ContainerDI.Base.Impl;
type
TAplicacaoDI = class(TContainerDI)
public
class function New: IContainerDI;
procedure Build; override;
end;
implementation
uses
System.SysUtils, ContainerDI,
Vigilante.Compilacao.DI,
Vigilante.Build.DI,
Module.ValueObject.URL.Impl, Module.ValueObject.URL,
Vigilante.Module.GerenciadorDeArquivoDataSet.Impl, Vigilante.Module.GerenciadorDeArquivoDataSet,
Vigilante.Controller.Mediator, Vigilante.Controller.Mediator.Impl,
Vigilante.Controller.Configuracao, Vigilante.Controller.Configuracao.Impl;
procedure TAplicacaoDI.Build;
begin
CDI.RegisterType<TURL>.Implements<IURL>;
CDI.RegisterType<TControllerMediator>.Implements<IControllerMediator>.AsSingleton;
CDI.RegisterType<TConfiguracaoController>.Implements<IConfiguracaoController>;
CDI.RegisterType<TGerenciadorDeArquivoDataSet>.Implements<IGerenciadorDeArquivoDataSet>;
TCompilacaoDI.New.Build;
TBuildDI.New.Build;
end;
class function TAplicacaoDI.New: IContainerDI;
begin
Result := Create;
end;
end.
|
program parcialjulio18;
const
MAX_LETRAS = 6;
MAX_PALABRAS = 4;
type
TLetras = 'a'..'z';
Texto = record
letras : array[1..MAX_LETRAS] of TLetras;
tope : 0 .. MAX_LETRAS;
end;
Diccionario = array[1..MAX_PALABRAS] of Texto;
procedure LeerTexto(var entrada:Texto);
var tmp : char;
i : integer;
begin
i := 1;
entrada.tope := 0;
read(tmp);
while (not eoln) do
begin
entrada.letras[i] := tmp;
entrada.tope := entrada.tope + 1;
i := i +1;
read(tmp);
end;
end;
function prefijo(t1,t2:Texto):boolean;
var i : integer;
begin
i := 1;
while ((i<=t1.tope) and (t1.letras[i]=t2.letras[i])) do
i := i + 1;
if (i>t1.tope)then
prefijo := true
else
prefijo := false
end;
var t1, t2 : Texto
begin
LeerTexto(t1);
LeerTexto(t2);
writeln('Prefijo = ',prefijo(t1,t2));
end. |
unit nkMQTTClient;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, MQTT, MQTTReadThread;
type
{ TnkMQTTClient }
TnkMQTTClient = class(TComponent)
private
FClient:TMQTTClient;
FClientId: string;
FPingInterval: integer;
FPort: integer;
FServer: string;
function GetConnAckEvent: TConnAckEvent;
function GetPingRespEvent: TPingRespEvent;
function GetPublishEvent: TPublishEvent;
function GetSubAckEvent: TSubAckEvent;
function GetUnSubAckEvent: TUnSubAckEvent;
procedure SetConnAckEvent(AValue: TConnAckEvent);
procedure SetPingRespEvent(AValue: TPingRespEvent);
procedure SetPublishEvent(AValue: TPublishEvent);
procedure SetSubAckEvent(AValue: TSubAckEvent);
procedure SetUnSubAckEvent(AValue: TUnSubAckEvent);
protected
public
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
procedure Init;
function isConnected: boolean;
procedure Connect;
function Disconnect: boolean;
procedure ForceDisconnect;
function Publish(Topic: ansistring; sPayload: ansistring): boolean; overload;
function Publish(Topic: ansistring; sPayload: ansistring;Retain: boolean): boolean; overload;
function Subscribe(Topic: ansistring): integer;
function Unsubscribe(Topic: ansistring): integer;
function PingReq: boolean;
function getMessage: TMQTTMessage;
function getMessageAck: TMQTTMessageAck;
published
property Server:string read FServer write FServer;
property Port:integer read FPort write FPort;
property PingInterval:integer read FPingInterval write FPingInterval;
property ClientId:string read FClientId write FClientId;
property OnConnAck: TConnAckEvent read GetConnAckEvent write SetConnAckEvent;
property OnPublish: TPublishEvent read GetPublishEvent write SetPublishEvent;
property OnPingResp: TPingRespEvent read GetPingRespEvent write SetPingRespEvent;
property OnSubAck: TSubAckEvent read GetSubAckEvent write SetSubAckEvent;
property OnUnSubAck: TUnSubAckEvent read GetUnSubAckEvent write SetUnSubAckEvent;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Additional',[TnkMQTTClient]);
end;
{ TnkMQTTClient }
function TnkMQTTClient.GetConnAckEvent: TConnAckEvent;
begin
Result:=FClient.OnConnAck;
end;
function TnkMQTTClient.GetPingRespEvent: TPingRespEvent;
begin
Result:=FClient.OnPingResp;
end;
function TnkMQTTClient.GetPublishEvent: TPublishEvent;
begin
Result:=FClient.OnPublish;
end;
function TnkMQTTClient.GetSubAckEvent: TSubAckEvent;
begin
Result:=FClient.OnSubAck;
end;
function TnkMQTTClient.GetUnSubAckEvent: TUnSubAckEvent;
begin
Result:=FClient.OnUnSubAck;
end;
procedure TnkMQTTClient.SetConnAckEvent(AValue: TConnAckEvent);
begin
FClient.OnConnAck:=AValue;
end;
procedure TnkMQTTClient.SetPingRespEvent(AValue: TPingRespEvent);
begin
FClient.OnPingResp:=AValue;
end;
procedure TnkMQTTClient.SetPublishEvent(AValue: TPublishEvent);
begin
FClient.OnPublish:=AValue;
end;
procedure TnkMQTTClient.SetSubAckEvent(AValue: TSubAckEvent);
begin
FClient.OnSubAck:=AValue;
end;
procedure TnkMQTTClient.SetUnSubAckEvent(AValue: TUnSubAckEvent);
begin
FClient.OnUnSubAck:=AValue;
end;
constructor TnkMQTTClient.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FPort:=1883;
end;
destructor TnkMQTTClient.Destroy;
begin
inherited Destroy;
end;
procedure TnkMQTTClient.Init;
begin
FClient:=TMQTTClient.Create(FServer,FPort);
if Trim(FClientID)<>'' then
FClient.ClientID:=FClientID;
end;
function TnkMQTTClient.isConnected: boolean;
begin
Result:=FClient.isConnected;
end;
procedure TnkMQTTClient.Connect;
begin
FClient.Connect;
end;
function TnkMQTTClient.Disconnect: boolean;
begin
Result:=FClient.Disconnect;
end;
procedure TnkMQTTClient.ForceDisconnect;
begin
FClient.ForceDisconnect;
end;
function TnkMQTTClient.Publish(Topic: ansistring; sPayload: ansistring
): boolean;
begin
Result:=FClient.Publish(Topic, sPayload);
end;
function TnkMQTTClient.Publish(Topic: ansistring; sPayload: ansistring;
Retain: boolean): boolean;
begin
Result:=Fclient.Publish(Topic, sPayload, Retain);
end;
function TnkMQTTClient.Subscribe(Topic: ansistring): integer;
begin
Result:=FClient.Subscribe(Topic);
end;
function TnkMQTTClient.Unsubscribe(Topic: ansistring): integer;
begin
Result:=FClient.Unsubscribe(Topic);
end;
function TnkMQTTClient.PingReq: boolean;
begin
Result:=FClient.PingReq;
end;
function TnkMQTTClient.getMessage: TMQTTMessage;
begin
Result:=(FClient.getMessage as MQTT.TMQTTMessage);
end;
function TnkMQTTClient.getMessageAck: TMQTTMessageAck;
begin
Result:=FClient.getMessageAck;
end;
end.
|
(* fib.pas - Compute fibonacci numbers *)
program fibonacci;
const LAST = 30; (* A constant declaration *)
var n : integer; { Variable declaration }
(* A function declaration *)
function fib(n : int) : int ;
begin
if n <= 1 then (* Conditionals *)
fib := 1;
fib := fib(n-1) + fib(n-2)
end;
begin
n := 0;
while n < LAST do { Looping (while) }
begin
write(fibonacci(n)); { Printing }
n := n + 1 { Assignment }
end
end.
|
unit ltr43api;
interface
uses SysUtils, ltrapitypes, ltrapidefine, ltrapi;
const
// Коды ошибок
LTR43_NO_ERR =0;
LTR43_ERR_WRONG_MODULE_DESCR =-4001;
LTR43_ERR_CANT_OPEN =-4002;
LTR43_ERR_INVALID_CRATE_SN =-4003;
LTR43_ERR_INVALID_SLOT_NUM =-4004;
LTR43_ERR_CANT_SEND_COMMAND =-4005;
LTR43_ERR_CANT_RESET_MODULE =-4006;
LTR43_ERR_MODULE_NO_RESPONCE =-4007;
LTR43_ERR_CANT_SEND_DATA =-4008;
LTR43_ERR_CANT_CONFIG =-4009;
LTR43_ERR_CANT_RS485_CONFIG =-4010;
LTR43_ERR_CANT_LAUNCH_SEC_MARK =-4011;
LTR43_ERR_CANT_STOP_SEC_MARK =-4012;
LTR43_ERR_CANT_LAUNCH_START_MARK =-4013;
LTR43_ERR_CANT_STOP_RS485RCV =-4014;
LTR43_ERR_RS485_CANT_SEND_BYTE =-4015;
LTR43_ERR_RS485_FRAME_ERR_RCV =-4016;
LTR43_ERR_RS485_PARITY_ERR_RCV =-4017;
LTR43_ERR_WRONG_IO_GROUPS_CONF =-4018;
LTR43_ERR_RS485_WRONG_BAUDRATE =-4019;
LTR43_ERR_RS485_WRONG_FRAME_SIZE =-4020;
LTR43_ERR_RS485_WRONG_PARITY_CONF =-4021;
LTR43_ERR_RS485_WRONG_STOPBIT_CONF =-4022;
LTR43_ERR_DATA_TRANSMISSON_ERROR =-4023;
LTR43_ERR_RS485_CONFIRM_TIMEOUT =-4024;
LTR43_ERR_RS485_SEND_TIMEOUT =-4025;
LTR43_ERR_LESS_WORDS_RECEIVED =-4026;
LTR43_ERR_PARITY_TO_MODULE =-4027;
LTR43_ERR_PARITY_FROM_MODULE =-4028;
LTR43_ERR_WRONG_IO_LINES_CONF =-4029;
LTR43_ERR_WRONG_SECOND_MARK_CONF =-4030;
LTR43_ERR_WRONG_START_MARK_CONF =-4031;
LTR43_ERR_CANT_READ_DATA =-4032;
LTR43_ERR_RS485_CANT_SEND_PACK =-4033;
LTR43_ERR_RS485_CANT_CONFIGURE =-4034;
LTR43_ERR_CANT_WRITE_EEPROM =-4035;
LTR43_ERR_CANT_READ_EEPROM =-4036;
LTR43_ERR_WRONG_EEPROM_ADDR =-4037;
LTR43_ERR_RS485_WRONG_PACK_SIZE =-4038;
LTR43_ERR_RS485_WRONG_OUT_TIMEOUT =-4039;
LTR43_ERR_RS485_WRONG_IN_TIMEOUT =-4040;
LTR43_ERR_CANT_READ_CONF_REC =-4041;
LTR43_ERR_WRONG_CONF_REC =-4042;
LTR43_ERR_RS485_CANT_STOP_TST_RCV =-4043;
LTR43_ERR_CANT_START_STREAM_READ =-4044;
LTR43_ERR_CANT_STOP_STREAM_READ =-4045;
LTR43_ERR_WRONG_IO_DATA =-4046;
LTR43_ERR_WRONG_STREAM_READ_FREQ_SETTINGS =-4047;
LTR43_ERR_ERROR_OVERFLOW =-4048;
LTR43_EEPROM_SIZE = 512;
LTR43_MARK_MODE_INTERNAL = 0;
LTR43_MARK_MODE_MASTER = 1;
LTR43_MARK_MODE_EXTERNAL = 2;
LTR43_RS485_PARITY_NONE = 0;
LTR43_RS485_PARITY_EVEN = 1;
LTR43_RS485_PARITY_ODD = 2;
LTR43_PORT_DIR_IN = 0;
LTR43_PORT_DIR_OUT = 1;
LTR43_RS485_FLAGS_USE_INTERVAL_TOUT = 1;
type
{$A4}
// Структура описания модуля
TINFO_LTR43=record
Name :array[0..15]of AnsiChar;
Serial:array[0..23]of AnsiChar;
FirmwareVersion:array[0..7]of AnsiChar;// Версия БИОСа
FirmwareDate :array[0..15]of AnsiChar; // Дата создания данной версии БИОСа
end;
pTINFO_LTR43 = ^TINFO_LTR43;
TLTR43_IO_Ports = record
Port1:integer; // направление линий ввода/вывода группы 1
Port2:integer; // направление линий ввода/вывода группы 2
Port3:integer; // направление линий ввода/вывода группы 3
Port4:integer; // направление линий ввода/вывода группы 4
end;
TLTR43_RS485 = record
FrameSize:integer; // Кол-во бит в кадре
Baud:integer; // Скорость обмена в бодах
StopBit:integer; // Кол-во стоп-бит
Parity:integer; // Включение бита четности
SendTimeoutMultiplier:integer; // Множитель таймаута отправки
ReceiveTimeoutMultiplier:integer; // Множитель таймаута приема подтверждения
end;
TLTR43_Marks=record
SecondMark_Mode:integer; // Режим меток. 0 - внутр., 1-внутр.+выход, 2-внешн
StartMark_Mode:integer; //
end;
TLTR43=record
size:integer; // размер структуры
Channel:TLTR;
StreamReadRate:double;
IO_Ports:TLTR43_IO_Ports;
RS485:TLTR43_RS485; // Структура для конфигурации RS485
Marks:TLTR43_Marks; // Структура для работы с временными метками
ModuleInfo:TINFO_LTR43;
end;
pTLTR43=^TLTR43;// Структура описания модуля
{$A+}
Function LTR43_Init (module:pTLTR43):Integer; {$I ltrapi_callconvention};
Function LTR43_IsOpened (module:pTLTR43):Integer; {$I ltrapi_callconvention};
Function LTR43_Open (module:pTLTR43; net_addr:LongWord;net_port:WORD; crate_snCHAR:Pointer; slot_num:integer):Integer; {$I ltrapi_callconvention};
Function LTR43_Close (module:pTLTR43):Integer; {$I ltrapi_callconvention};
Function LTR43_WritePort (module:pTLTR43; OutputData:LongWord):Integer; {$I ltrapi_callconvention};
Function LTR43_WriteArray (module:pTLTR43; OutputArrayDWORD:Pointer; ArraySize:byte):Integer; {$I ltrapi_callconvention};
Function LTR43_ReadPort (module:pTLTR43; InputDataDWORD:Pointer):Integer; {$I ltrapi_callconvention};
Function LTR43_StartStreamRead (module:pTLTR43):Integer; {$I ltrapi_callconvention};
Function LTR43_StopStreamRead (module:pTLTR43):Integer; {$I ltrapi_callconvention};
Function LTR43_Recv (module:pTLTR43; dataDWORD:Pointer;tmarkDWORD:Pointer;size:LongWord;timeout:LongWord):Integer; {$I ltrapi_callconvention};
Function LTR43_ProcessData (module:pTLTR43; srcDWORD:Pointer;destDWORD:Pointer; sizeDWORD:Pointer):Integer; {$I ltrapi_callconvention};
Function LTR43_Config (module:pTLTR43):Integer; {$I ltrapi_callconvention};
Function LTR43_StartSecondMark (module:pTLTR43):Integer; {$I ltrapi_callconvention};
Function LTR43_StopSecondMark (module:pTLTR43):Integer; {$I ltrapi_callconvention};
Function LTR43_GetErrorString (err:integer):string; {$I ltrapi_callconvention};
Function LTR43_MakeStartMark (module:pTLTR43):Integer; {$I ltrapi_callconvention};
Function LTR43_RS485_SetResponseTout (module:pTLTR43; tout: LongWord):Integer; {$I ltrapi_callconvention};
Function LTR43_RS485_SetIntervalTout (module:pTLTR43; tout: LongWord):Integer; {$I ltrapi_callconvention};
Function LTR43_RS485_SetTxActiveInterval(module:pTLTR43; start_of_packet: LongWord; end_of_packet: LongWord):Integer; {$I ltrapi_callconvention};
Function LTR43_RS485_Exchange (module:pTLTR43; PackToSendSHORT:Pointer; ReceivedPack:Pointer; OutPackSize:integer; InPackSize:integer):Integer; {$I ltrapi_callconvention};
Function LTR43_RS485_ExchangeEx (module:pTLTR43; PackToSendSHORT:Pointer; ReceivedPack:Pointer; OutPackSize:integer; InPackSize:integer;
flags: LongWord; out ReceivedSize: Integer):Integer; {$I ltrapi_callconvention};
Function LTR43_WriteEEPROM (module:pTLTR43; Address:integer;val:byte):Integer; {$I ltrapi_callconvention};
Function LTR43_ReadEEPROM (module:pTLTR43; Address:integer;valBYTE:Pointer):Integer; {$I ltrapi_callconvention};
Function LTR43_RS485_TestReceiveByte (module:pTLTR43; OutBytesQnt:integer;InBytesQnt:integer):Integer; {$I ltrapi_callconvention};
Function LTR43_RS485_TestStopReceive (module:pTLTR43):Integer; {$I ltrapi_callconvention};
implementation
Function LTR43_Init (module:pTLTR43):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_IsOpened (module:pTLTR43):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_Open (module:pTLTR43; net_addr:LongWord;net_port:WORD; crate_snCHAR:Pointer; slot_num:integer):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_Close (module:pTLTR43):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_WritePort (module:pTLTR43; OutputData:LongWord):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_WriteArray (module:pTLTR43; OutputArrayDWORD:Pointer; ArraySize:byte):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_ReadPort (module:pTLTR43; InputDataDWORD:Pointer):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_StartStreamRead (module:pTLTR43):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_StopStreamRead (module:pTLTR43):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_Recv (module:pTLTR43; dataDWORD:Pointer;tmarkDWORD:Pointer;size:LongWord;timeout:LongWord):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_ProcessData (module:pTLTR43; srcDWORD:Pointer;destDWORD:Pointer; sizeDWORD:Pointer):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_Config (module:pTLTR43):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_StartSecondMark (module:pTLTR43):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_StopSecondMark (module:pTLTR43):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_MakeStartMark (module:pTLTR43):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_RS485_SetResponseTout (module:pTLTR43; tout: LongWord):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_RS485_SetIntervalTout (module:pTLTR43; tout: LongWord):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_RS485_SetTxActiveInterval(module:pTLTR43; start_of_packet: LongWord; end_of_packet: LongWord):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_RS485_Exchange (module:pTLTR43; PackToSendSHORT:Pointer; ReceivedPack:Pointer; OutPackSize:integer; InPackSize:integer):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_RS485_ExchangeEx (module:pTLTR43; PackToSendSHORT:Pointer; ReceivedPack:Pointer; OutPackSize:integer; InPackSize:integer;
flags: LongWord; out ReceivedSize: Integer):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_WriteEEPROM (module:pTLTR43; Address:integer;val:byte):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_ReadEEPROM (module:pTLTR43; Address:integer;valBYTE:Pointer):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_RS485_TestReceiveByte (module:pTLTR43; OutBytesQnt:integer;InBytesQnt:integer):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function LTR43_RS485_TestStopReceive (module:pTLTR43):Integer; {$I ltrapi_callconvention}; external 'ltr43api';
Function _get_err_str(err : integer) : PAnsiChar; {$I ltrapi_callconvention}; external 'ltr43api' name 'LTR43_GetErrorString';
Function LTR43_GetErrorString(err: Integer) : string; {$I ltrapi_callconvention};
begin
LTR43_GetErrorString:=string(_get_err_str(err));
end;
end.
|
unit Router;
{$MODE Delphi}
interface
uses
speed,
uProcess,
sysutils, httpdefs, fpjson, jsonparser,
Generics.Collections; // TList
// global methods
procedure RouterInit(_c : config; _l : list; _h : hook);
procedure jsonResponse(var res: TResponse; data: String; code : integer=200);
procedure SetProcess(req: TRequest; res: TResponse);
procedure SetSpeed(req: TRequest; res: TResponse);
procedure SetDisable(req: TRequest; res: TResponse);
procedure GetProcessList(req: TRequest; res: TResponse);
implementation
var
c : config;
l : list;
h : hook;
procedure jsonResponse(var res : TResponse; data: String; code : integer =200);
begin
// needed for axios:
res.SetCustomHeader('Access-Control-Allow-Origin','*');
res.SetCustomHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.SetCustomHeader('Access-Control-Allow-Headers', 'Content-Type');
res.SetCustomHeader('Access-Control-Allow-Credentials','true');
res.Content := data;
res.Code := code;
res.ContentType := 'application/json';
res.ContentLength := length(res.Content);
res.SendContent;
end;
procedure GetProcessList(req: TRequest; res: TResponse);
var
jObject : TJSONObject;
jArray : TJSONArray;
jElem : TJSONObject;
ps : TList<process>;
p : process;
e : Exception;
code : integer; // exit code
begin
try
jObject := TJSONObject.Create;
ps:=l.GetList;
jArray := TJSONArray.Create;
for p in ps do
begin
jElem := TJSONObject.Create;
jElem.Add('name', p.Name);
jElem.Add('id', p.ID);
jArray.Add(jElem);
end;
jObject.Add('Processes', jArray);
jsonResponse(res, jObject.AsJSON);
finally
jObject.Free;
end;
end;
procedure SetSpeed(req: TRequest; res: TResponse);
var
jObject : TJSONObject;
name : string;
spd : single;
p : process;
e : Exception;
code : integer; // exit code
begin
try
jObject := TJSONObject.Create;
name:=req.RouteParams['name'];
spd:=StrToFloat(req.RouteParams['speed']);
jObject.Strings['name'] := name;
jObject.Add('speed', spd);
// check we have a process
p:=h.GetProcess;
if p = nil then
begin
code := 500; // generic error
e := Exception.Create('No process hooked.');
jObject.Strings['error'] := e.ToString;
jsonResponse(res, jObject.AsJSON, code);
Exit;
end;
jObject.Strings['hookedProcessName'] := p.Name;
// check it's the right process
if (length(name) > 0) and // default to currently hooked proc if none given
(CompareText(uppercase(p.Name) , uppercase(name)) <> 0) then
begin
e := Exception.Create('Process hook mismatch');
jObject.Strings['error'] := e.ToString;
code := 500; // generic error
jsonResponse(res, jObject.AsJSON, code);
Exit;
end;
// set the speed
e := h.SetSpeed(spd);
if e <> nil then
begin
jObject.Strings['error'] := e.ToString;
code := 500; // generic error
jsonResponse(res, jObject.AsJSON, code);
Exit;
end;
jsonResponse(res, jObject.AsJSON);
finally
jObject.Free;
end;
end;
procedure SetDisable(req: TRequest; res: TResponse);
var
jObject : TJSONObject;
e : Exception;
code : integer;
begin
try
jObject := TJSONObject.Create;
// unhook
e:= h.Unhook;
if e<> nil then
begin
jObject.Strings['error'] := e.ToString;
code := 500; // generic error
jsonResponse(res, jObject.AsJSON, code);
Exit;
end;
// success
jsonResponse(res, jObject.AsJSON);
finally
jObject.Free;
end;
end;
procedure SetProcess(req: TRequest; res: TResponse);
var
name : string;
proc : process;
foundproc : process;
procs : TList<process>;
jObject : TJSONObject;
e : Exception;
code : integer;
begin
try
jObject := TJSONObject.Create;
name:=req.RouteParams['name'];
foundproc:=nil;
procs := l.GetList;
for proc in procs do
begin
if CompareText(proc.Name, uppercase(name)) = 0 then
begin
foundproc := proc;
break;
end;
end;
e := nil;
if foundproc <> nil then
e := h.Hook(proc)
else
e := Exception.Create('Process not found.');
if e <> nil then
begin
code := 500; // generic error
jObject.Strings['error'] := e.ToString;
end
else
begin
code := 200; // generic success
jObject.Add('found', true);
jObject.Strings['name'] := foundproc.Name;
jObject.Add('id', foundproc.ID);
end;
jsonResponse(res, jObject.AsJSON, code);
finally
jObject.Free;
end;
end;
procedure RouterInit(_c : config; _l : list; _h : hook);
begin
c:=_c;
l:=_l;
h:=_h;
end;
end.
|
unit Persistence.Entity.State;
interface
uses
System.Classes,
Spring,
Spring.Persistence.Mapping.Attributes,
Persistence.Consts;
type
TCommonState = class(TObject)
strict private
FId: int;
FName: string;
FStateId: int;
protected
property Id: int read FId write FId;
property Name: string read FName write FName;
property StateId: int read FStateId write FStateId;
end;
[Entity]
[Table(STATE_TABLE, PUBLIC_SCHEMA)]
[Sequence(STATE_ID_SEQ, 1, 1)]
TState = class(TCommonState)
public
[Column(ID_COL, [cpRequired])]
property Id;
[Column(NAME_COL, [], 50)]
property Name;
[Column(STATE_ID_COL, [])]
property StateId;
end;
implementation
end.
|
unit ImageKnifeDocument;
{$MODE Delphi}
interface
uses RectGrid, Classes, Graphics, SysUtils;
type
TImageKnifeDocument = class
private
FNormalImageFilename: String;
FOverImageFilename: String;
FRectGrid: TRectGrid;
FFilename: String;
FNormalImage: TPicture;
FOverImage: TPicture;
function IsEmpty: Boolean;
procedure SetNormalImageFilename(const str: String);
procedure SetOverImageFilename(const str: String);
function GetWidth: Integer;
function GetHeight: Integer;
public
constructor Create;
destructor Destroy; override;
procedure NewDocument;
procedure LoadFromFile(const Filename: String);
procedure SaveToFile(const Filename: String);
property Empty: Boolean read IsEmpty;
property Width: Integer read GetWidth;
property Height: Integer read GetHeight;
property NormalImage: TPicture read FNormalImage;
property OverImage: TPicture read FOverImage;
published
property NormalImageFilename: String read FNormalImageFilename
write SetNormalImageFilename;
property OverImageFilename: String read FOverImageFilename
write SetOverImageFilename;
property Grid: TRectGrid read FRectGrid write FRectGrid;
property Filename: String read FFilename write FFilename;
end;
implementation
uses FileUtils, xml;
constructor TImageKnifeDocument.Create;
begin
FNormalImageFilename := '';
FOverImageFilename := '';
FFilename := '';
FRectGrid := nil;
FNormalImage := TPicture.Create;
FOverImage := TPicture.Create;
end;
destructor TImageKnifeDocument.Destroy;
begin
FNormalImage.Free;
FOverImage.Free;
if FRectGrid <> nil then
FRectGrid.Free;
inherited;
end;
procedure TImageKnifeDocument.NewDocument;
begin
if FRectGrid <> nil then
FRectGrid.Free;
FRectGrid := nil;
FNormalImageFilename := '';
FOverImageFilename := '';
FFilename := '';
end;
function TImageKnifeDocument.IsEmpty: Boolean;
begin
Result := FRectGrid = nil;
end;
function TImageKnifeDocument.GetWidth: Integer;
begin
if IsEmpty then
Result := 0
else
Result := FRectGrid.Rect.Right;
end;
function TImageKnifeDocument.GetHeight: Integer;
begin
if IsEmpty then
Result := 0
else
Result := FRectGrid.Rect.Bottom;
end;
procedure TImageKnifeDocument.SetNormalImageFilename(const str: String);
var
p: TPicture;
begin
p := TPicture.Create;
try
p.LoadFromFile(str);
if (IsEmpty) then
begin
FNormalImage.Assign(p);
FNormalImageFileName := str;
FRectGrid := TRectGrid.Create(Rect(0, 0, p.Width, p.Height));
end
else
begin
if (p.Width <> Self.Width) or (p.Height <> Self.Height) then
raise Exception.Create('New normal image is not the same size as the current');
FNormalImage.Assign(p);
FNormalImageFileName := str;
end;
finally
p.Free;
end;
end;
procedure TImageKnifeDocument.SetOverImageFilename(const str: String);
var
p: TPicture;
begin
p := TPicture.Create;
try
p.LoadFromFile(str);
if (IsEmpty) then
begin
FOverImage.Assign(p);
FOverImageFileName := str;
FRectGrid := TRectGrid.Create(Rect(0, 0, p.Width, p.Height));
end
else
begin
if (p.Width <> Self.Width) or (p.Height <> Self.Height) then
raise Exception.Create('New normal image is not the same size as the current');
FOverImage.Assign(p);
FOverImageFileName := str;
end;
finally
p.Free;
end;
end;
procedure TImageKnifeDocument.LoadFromFile(const Filename: String);
var
f: TFileStream;
r: TXMLReader;
root: TXMLNode;
enum: TXMLNodeEnum;
begin
f := TFileStream.Create(Filename, fmOpenRead);
r := TXMLReader.Create(f);
root := r.Read;
r.Free;
f.Free;
if root.Name <> 'root' then
raise Exception.Create('root tag expected');
FNormalImageFilename := root.Attributes['NormalImageFilename'];
FOverImageFilename := root.Attributes['OverImageFilename'];
enum := root.GetNodesByName('cell');
if enum.Count <> 1 then
raise Exception.Create('Only one master cell is allowed');
if FRectGrid <> nil then
FRectGrid.Free;
FRectGrid := TRectGrid.Create(Rect(0, 0, 0, 0));
FRectGrid.LoadFromXML(enum[0]);
enum.Free;
root.Free;
NormalImage.LoadFromFile(NormalImageFilename);
if OverImageFilename <> '' then
begin
OverImage.LoadFromFile(OverImageFilename);
if (NormalImage.Width <> OverImage.Width) or
(NormalImage.Height <> OverImage.Height) then
raise Exception.Create('Image dimensions must be the same');
if (Grid.Rect.Right <> NormalImage.Width) or (Grid.Rect.Bottom <>
NormalImage.Height) then
raise Exception.Create('Grid dimensions dont match images');
if (Grid.Rect.Left <> 0) or (Grid.Rect.Top <> 0) then
raise Exception.Create('Master rect must begin at top left');
end;
end;
procedure TImageKnifeDocument.SaveToFile(const Filename: String);
var
f: TFileStream;
w: TXMLWriter;
root: TXMLNode;
begin
if Empty then
Exit;
f := TFileStream.Create(Filename, fmCreate);
w := TXMLWriter.Create(f);
root := TXMLNode.Create;
root.Name := 'root';
root.Attributes['NormalImageFilename'] := FNormalImageFilename;
root.Attributes['OverImageFilename'] := FOverImageFilename;
FRectGrid.SaveToXML(root);
w.Write(root);
root.Free;
w.Free;
f.Free;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 2018-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Vcl.BaseImageCollection;
interface
uses
Winapi.Windows, Winapi.Messages, System.Classes, Vcl.Graphics, System.Messaging;
type
/// <summary>
/// TCustomImageCollection is a base class for image collection.
/// </summary>
TCustomImageCollection = class(TComponent)
private
FOnChange: TNotifyEvent;
protected
function GetCount: Integer; virtual;
procedure DoChange; virtual;
public
/// <summary>
/// Call Change method if collection was changed.
/// </summary>
procedure Change;
/// <summary>
/// Use IsIndexAvailable to detect that item with specific index is available in collection
/// and ready to use.
/// </summary>
function IsIndexAvailable(AIndex: Integer): Boolean; virtual;
/// <summary>
/// Get item name from specific index.
/// </summary>
function GetNameByIndex(AIndex: Integer): String; virtual;
/// <summary>
/// Get item index from specific name.
/// </summary>
function GetIndexByName(const AName: String): Integer; virtual;
/// <summary>
/// Get TBitmap from item with specific index.
/// </summary>
function GetBitmap(AIndex: Integer; AWidth, AHeight: Integer): TBitmap; overload; virtual;
/// <summary>
/// Draw images from collection to TCanvas.
/// </summary>
procedure Draw(ACanvas: TCanvas; ARect: TRect; AIndex: Integer; AProportional: Boolean = False); overload; virtual;
/// <summary>
/// Count of items in collection.
/// </summary>
property Count: Integer read GetCount;
published
property OnChange: TNotifyEvent
read FOnChange write FOnChange;
end;
/// <summary>
/// TImageCollectionChangedMessage is a base message, which image collection sends to subcribers
/// about that all collection is changed or some item with specific index changed.
/// </summary>
TImageCollectionChangedMessage = class(System.Messaging.TMessage)
private
FCollection: TCustomImageCollection;
FIndex: Integer;
FName: String;
public
property Collection: TCustomImageCollection read FCollection;
property Index: Integer read FIndex;
property Name: String read FName;
constructor Create(ACollection: TCustomImageCollection; AIndex: Integer; const AName: String);
end;
/// <summary>
/// Get Category name from item name.
/// Category name is separated by the symbol "\".
/// </summary>
function ExtractImageCollectionCategory(const S: String): String;
/// <summary>
/// Get name of the item without Category.
/// </summary>
function ExtractImageCollectionName(const S: String): String;
implementation
Uses System.SysUtils;
function ExtractImageCollectionName(const S: String): String;
begin
Result := S.SubString(S.IndexOf('\') + 1);
end;
function ExtractImageCollectionCategory(const S: String): String;
begin
Result := S.Substring(0, S.IndexOf('\'));
end;
procedure TCustomImageCollection.DoChange;
begin
TMessageManager.DefaultManager.SendMessage(nil,
TImageCollectionChangedMessage.Create(Self, -1, ''));
end;
procedure TCustomImageCollection.Change;
begin
DoChange;
if Assigned(FOnChange) then
FOnChange(Self);
end;
function TCustomImageCollection.GetNameByIndex(AIndex: Integer): String;
begin
Result := '';
end;
function TCustomImageCollection.GetIndexByName(const AName: String): Integer;
begin
Result := -1;
end;
function TCustomImageCollection.GetCount: Integer;
begin
Result := 0;
end;
function TCustomImageCollection.IsIndexAvailable(AIndex: Integer): Boolean;
begin
Result := False;
end;
function TCustomImageCollection.GetBitmap(AIndex: Integer; AWidth, AHeight: Integer): TBitmap;
begin
Result := nil;
end;
procedure TCustomImageCollection.Draw(ACanvas: TCanvas; ARect: TRect; AIndex: Integer; AProportional: Boolean = False);
begin
end;
constructor TImageCollectionChangedMessage.Create(ACollection: TCustomImageCollection; AIndex: Integer; const AName: String);
begin
inherited Create;
FCollection := ACollection;
FIndex := AIndex;
FName := AName;
end;
end.
|
{*!
* Fano Web Framework (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT)
*}
unit RouterImpl;
interface
{$MODE OBJFPC}
uses
contnrs,
RouteHandlerIntf,
RouterIntf,
RouteCollectionIntf,
RouteMatcherIntf,
RouteListIntf,
DependencyIntf,
RouteDataTypes;
type
(*!------------------------------------------------
* basic class that can manage and retrieve routes
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
* -----------------------------------------------*)
TRouter = class(TInterfacedObject, IDependency, IRouter, IRouteMatcher)
private
routeList : IRouteList;
function findRouteData(const routeName: string) : PRouteRec;
function createEmptyRouteData(const routeName: string) : PRouteRec;
function resetRouteData(const routeData : PRouteRec) : PRouteRec;
function getRouteHandler(const requestMethod : string; const routeData :PRouteRec) : IRouteHandler;
public
constructor create(const routes : IRouteList);
destructor destroy(); override;
(*!------------------------------------------
* set route handler for HTTP GET
* ------------------------------------------
* @param routeName regex pattern for route
* @param routeHandler instance route handler
* @return route handler instance
*-------------------------------------------*)
function get(
const routeName: string;
const routeHandler : IRouteHandler
) : IRouteHandler;
(*!------------------------------------------
* set route handler for HTTP POST
* ------------------------------------------
* @param routeName regex pattern for route
* @param routeHandler instance route handler
* @return route handler instance
*-------------------------------------------*)
function post(
const routeName: string;
const routeHandler : IRouteHandler
) : IRouteHandler;
(*!------------------------------------------
* set route handler for HTTP PUT
* ------------------------------------------
* @param routeName regex pattern for route
* @param routeHandler instance route handler
* @return route handler instance
*-------------------------------------------*)
function put(
const routeName: string;
const routeHandler : IRouteHandler
) : IRouteHandler;
(*!------------------------------------------
* set route handler for HTTP PATCH
* ------------------------------------------
* @param routeName regex pattern for route
* @param routeHandler instance route handler
* @return route handler instance
*-------------------------------------------*)
function patch(
const routeName: string;
const routeHandler : IRouteHandler
) : IRouteHandler;
(*!------------------------------------------
* set route handler for HTTP DELETE
* ------------------------------------------
* @param routeName regex pattern for route
* @param routeHandler instance route handler
* @return route handler instance
*-------------------------------------------*)
function delete(
const routeName: string;
const routeHandler : IRouteHandler
) : IRouteHandler;
(*!------------------------------------------
* set route handler for HTTP HEAD
* ------------------------------------------
* @param routeName regex pattern for route
* @param routeHandler instance route handler
* @return route handler instance
*-------------------------------------------*)
function head(
const routeName: string;
const routeHandler : IRouteHandler
) : IRouteHandler;
(*!------------------------------------------
* set route handler for HTTP OPTIONS
* ------------------------------------------
* @param routeName regex pattern for route
* @param routeHandler instance route handler
* @return route handler instance
*-------------------------------------------*)
function options(
const routeName: string;
const routeHandler : IRouteHandler
) : IRouteHandler;
(*!----------------------------------------------
* find route handler based request method and uri
* ----------------------------------------------
* @param requestMethod GET, POST,.., etc
* @param requestUri requested Uri
* @return route handler instance
*-----------------------------------------------*)
function match(const requestMethod : string; const requestUri: string) : IRouteHandler;
end;
implementation
uses
ERouteHandlerNotFoundImpl,
EMethodNotAllowedImpl;
resourcestring
sRouteNotFound = 'Route not found. Method: %s Uri: %s';
sMethodNotAllowed = 'Method not allowed. Method: %s Uri: %s';
constructor TRouter.create(const routes : IRouteList);
begin
routeList := routes;
end;
function TRouter.resetRouteData(const routeData : PRouteRec) : PRouteRec;
begin
routeData^.getRoute := nil;
routeData^.postRoute := nil;
routeData^.putRoute := nil;
routeData^.patchRoute := nil;
routeData^.deleteRoute := nil;
routeData^.optionsRoute := nil;
routeData^.headRoute := nil;
routeData^.placeholders := nil;
result := routeData;
end;
destructor TRouter.destroy();
var i, len:integer;
routeData : PRouteRec;
begin
inherited destroy();
len := routeList.count();
for i := len-1 downto 0 do
begin
routeData := routeList.get(i);
resetRouteData(routeData);
dispose(routeData);
end;
routeList := nil;
end;
function TRouter.createEmptyRouteData(const routeName: string) : PRouteRec;
var routeData : PRouteRec;
begin
//route not yet found, create new data
new(routeData);
routeData := resetRouteData(routeData);
routeList.add(routeName, routeData);
result := routeData;
end;
function TRouter.findRouteData(const routeName: string) : PRouteRec;
var routeData : PRouteRec;
begin
routeData := routeList.find(routeName);
if (routeData = nil) then
begin
//route not yet found, create new data
result := createEmptyRouteData(routeName);
end else
begin
result := routeData;
end;
end;
(*!------------------------------------------
* set route handler for HTTP GET
* ------------------------------------------
* @param routeName regex pattern for route
* @param routeHandler instance route handler
* @return route handler instance
*-------------------------------------------*)
function TRouter.get(
const routeName: string;
const routeHandler : IRouteHandler
) : IRouteHandler;
var routeData : PRouteRec;
begin
routeData := findRouteData(routeName);
routeData^.getRoute := routeHandler;
result := routeHandler;
end;
(*!------------------------------------------
* set route handler for HTTP POST
* ------------------------------------------
* @param routeName regex pattern for route
* @param routeHandler instance route handler
* @return route handler instance
*-------------------------------------------*)
function TRouter.post(
const routeName: string;
const routeHandler : IRouteHandler
) : IRouteHandler;
var routeData : PRouteRec;
begin
routeData := findRouteData(routeName);
routeData^.postRoute := routeHandler;
result := routeHandler;
end;
(*!------------------------------------------
* set route handler for HTTP PUT
* ------------------------------------------
* @param routeName regex pattern for route
* @param routeHandler instance route handler
* @return route handler instance
*-------------------------------------------*)
function TRouter.put(
const routeName: string;
const routeHandler : IRouteHandler
) : IRouteHandler;
var routeData : PRouteRec;
begin
routeData := findRouteData(routeName);
routeData^.putRoute := routeHandler;
result := routeHandler;
end;
(*!------------------------------------------
* set route handler for HTTP PATCH
* ------------------------------------------
* @param routeName regex pattern for route
* @param routeHandler instance route handler
* @return route handler instance
*-------------------------------------------*)
function TRouter.patch(
const routeName: string;
const routeHandler : IRouteHandler
) : IRouteHandler;
var routeData : PRouteRec;
begin
routeData := findRouteData(routeName);
routeData^.patchRoute := routeHandler;
result := routeHandler;
end;
(*!------------------------------------------
* set route handler for HTTP DELETE
* ------------------------------------------
* @param routeName regex pattern for route
* @param routeHandler instance route handler
* @return route handler instance
*-------------------------------------------*)
function TRouter.delete(
const routeName: string;
const routeHandler : IRouteHandler
) : IRouteHandler;
var routeData : PRouteRec;
begin
routeData := findRouteData(routeName);
routeData^.deleteRoute := routeHandler;
result := routeHandler;
end;
(*!------------------------------------------
* set route handler for HTTP HEAD
* ------------------------------------------
* @param routeName regex pattern for route
* @param routeHandler instance route handler
* @return route handler instance
*-------------------------------------------*)
function TRouter.head(
const routeName: string;
const routeHandler : IRouteHandler
) : IRouteHandler;
var routeData : PRouteRec;
begin
routeData := findRouteData(routeName);
routeData^.headRoute := routeHandler;
result := routeHandler;
end;
(*!------------------------------------------
* set route handler for HTTP OPTIONS
* ------------------------------------------
* @param routeName regex pattern for route
* @param routeHandler instance route handler
* @return route handler instance
*-------------------------------------------*)
function TRouter.options(
const routeName: string;
const routeHandler : IRouteHandler
) : IRouteHandler;
var routeData : PRouteRec;
begin
routeData := findRouteData(routeName);
routeData^.optionsRoute := routeHandler;
result := routeHandler;
end;
(*!------------------------------------------
* get route handler based on request method
* ------------------------------------------
* @param requestMethod GET, POST, etc
* @param routeData instance route data
* @return route handler instance or nil if not found
*-------------------------------------------*)
function TRouter.getRouteHandler(const requestMethod : string; const routeData :PRouteRec) : IRouteHandler;
var routeHandler : IRouteHandler;
begin
routeHandler := nil;
case requestMethod of
'GET' : routeHandler := routeData^.getRoute;
'POST' : routeHandler := routeData^.postRoute;
'PUT' : routeHandler := routeData^.putRoute;
'DELETE' : routeHandler := routeData^.deleteRoute;
'PATCH' : routeHandler := routeData^.patchRoute;
'OPTIONS' : routeHandler := routeData^.optionsRoute;
'HEAD' : routeHandler := routeData^.headRoute;
end;
result := routeHandler;
end;
(*!----------------------------------------------
* find route handler based request method and uri
* ----------------------------------------------
* @param requestMethod GET, POST,.., etc
* @param requestUri requested Uri
* @return route handler instance
*-----------------------------------------------*)
function TRouter.match(const requestMethod : string; const requestUri : string) : IRouteHandler;
var routeData : PRouteRec;
begin
routeData := routeList.match(requestUri);
if (routeData = nil) then
begin
raise ERouteHandlerNotFound.createFmt(
sRouteNotFound,
[requestMethod, requestUri]
);
end;
result := getRouteHandler(requestMethod, routeData);
if (result = nil) then
begin
raise EMethodNotAllowed.createFmt(
sMethodNotAllowed,
[requestMethod, requestUri]
);
end;
result.setArgs(routeData^.placeholders);
end;
end.
|
unit FamilySearchQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, 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, Vcl.StdCtrls,
SearchInterfaceUnit, CustomComponentsQuery, ApplyQueryFrame, BaseFamilyQuery,
DSWrap, SearchFamOrCompoQuery, System.Generics.Collections;
type
TFamilySearchW = class(TBaseFamilyW)
private
FMode: TContentMode;
public
procedure AppendRows(AFieldName: string; AValues: TArray<String>); override;
property Mode: TContentMode read FMode;
end;
TQueryFamilySearch = class(TQueryBaseFamily)
strict private
private const
FEmptyAmount = 1;
var
FGetModeClone: TFDMemTable;
FClone: TFDMemTable;
FqSearchFamilyOrComp: TQuerySearchFamilyOrComp;
procedure DoAfterOpen(Sender: TObject);
function GetCurrentMode: TContentMode;
function GetFamilySearchW: TFamilySearchW;
function GetIsClearEnabled: Boolean;
function GetIsSearchEnabled: Boolean;
function GetqSearchFamilyOrComp: TQuerySearchFamilyOrComp;
{ Private declarations }
protected
procedure ApplyDelete(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override;
procedure ApplyInsert(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override;
procedure ApplyUpdate(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override;
function CreateDSWrap: TDSWrap; override;
function GetHaveAnyChanges: Boolean; override;
property qSearchFamilyOrComp: TQuerySearchFamilyOrComp
read GetqSearchFamilyOrComp;
public
constructor Create(AOwner: TComponent); override;
procedure AfterConstruction; override;
procedure ClearSearchResult;
procedure SearchByValue(AValues: TArray<String>; ALike: Boolean);
property FamilySearchW: TFamilySearchW read GetFamilySearchW;
property IsClearEnabled: Boolean read GetIsClearEnabled;
property IsSearchEnabled: Boolean read GetIsSearchEnabled;
{ Public declarations }
end;
implementation
Uses NotifyEvents, System.Math, DBRecordHolder, StrHelper;
{$R *.dfm}
{ TfrmQueryComponentsContent }
constructor TQueryFamilySearch.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
// В режиме поиска - транзакции автоматом
AutoTransaction := True;
// Создаём два клона
FGetModeClone := W.AddClone(Format('%s > 0', [W.ID.FieldName]));
FClone := W.AddClone(Format('%s <> null', [W.Value.FieldName]));
// Подписываемся на событие
TNotifyEventWrap.Create(W.AfterOpen, DoAfterOpen, W.EventList);
end;
procedure TQueryFamilySearch.AfterConstruction;
begin
inherited;
// Подставляем заведомо ложное условие чтобы очистить список
FDQuery.SQL.Text := ReplaceInSQL(SQL, '0=1', 0);
end;
procedure TQueryFamilySearch.ApplyDelete(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
begin
if FamilySearchW.Mode = RecordsMode then
inherited;
end;
procedure TQueryFamilySearch.ApplyInsert(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
begin
// Ничего не сохраняем на сервер
end;
procedure TQueryFamilySearch.ApplyUpdate(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
begin
if FamilySearchW.Mode = RecordsMode then
inherited;
end;
procedure TQueryFamilySearch.ClearSearchResult;
begin
// Подставляем заведомо ложное условие чтобы очистить список
FDQuery.SQL.Text := ReplaceInSQL(SQL, '0=1', 0);
W.RefreshQuery;
end;
function TQueryFamilySearch.CreateDSWrap: TDSWrap;
begin
Result := TFamilySearchW.Create(FDQuery);
end;
procedure TQueryFamilySearch.DoAfterOpen(Sender: TObject);
var
I: Integer;
begin
W.SubGroup.F.ReadOnly := False;
// Добавляем пустую запись для поиска, если она необходима
AutoTransaction := True;
for I := FDQuery.RecordCount to FEmptyAmount - 1 do
begin
FDQuery.Append;
FDQuery.Fields[1].AsString := '';
FDQuery.Post;
end;
FDQuery.First;
// Вычисляем в какой режим мы перешли
FamilySearchW.FMode := GetCurrentMode;
// Выбираем нужный режим транзакции
AutoTransaction := FamilySearchW.Mode = SearchMode;
if FamilySearchW.Mode = RecordsMode then
W.SetFieldsReadOnly(False);
end;
function TQueryFamilySearch.GetCurrentMode: TContentMode;
begin
if (FDQuery.RecordCount = 0) or (FGetModeClone.RecordCount > 0) then
Result := RecordsMode
else
Result := SearchMode;
end;
function TQueryFamilySearch.GetFamilySearchW: TFamilySearchW;
begin
Result := W as TFamilySearchW;
end;
// Есть-ли изменения не сохранённые в БД
function TQueryFamilySearch.GetHaveAnyChanges: Boolean;
begin
Result := False;
case FamilySearchW.Mode of
RecordsMode:
Result := inherited;
SearchMode:
Result := False;
else
Assert(False);
end;
end;
function TQueryFamilySearch.GetIsClearEnabled: Boolean;
begin
Result := (FamilySearchW.Mode = RecordsMode);
if not Result then
begin
Result := FClone.RecordCount > 0;
end;
end;
function TQueryFamilySearch.GetIsSearchEnabled: Boolean;
begin
Result := (FamilySearchW.Mode = SearchMode) and (FClone.RecordCount > 0);
end;
function TQueryFamilySearch.GetqSearchFamilyOrComp: TQuerySearchFamilyOrComp;
begin
if FqSearchFamilyOrComp = nil then
FqSearchFamilyOrComp := TQuerySearchFamilyOrComp.Create(Self);
Result := FqSearchFamilyOrComp;
end;
procedure TQueryFamilySearch.SearchByValue(AValues: TArray<String>;
ALike: Boolean);
var
AStipulation: string;
begin
// Готовим SQL запрос для поиска семейств
qSearchFamilyOrComp.PrepareSearchByValue(AValues, ALike, True);
AStipulation := Format('%s in (%s)',
[W.ID.FullName, qSearchFamilyOrComp.FDQuery.SQL.Text]);
FDQuery.SQL.Text := ReplaceInSQL(SQL, AStipulation, 0);
W.RefreshQuery;
end;
procedure TFamilySearchW.AppendRows(AFieldName: string;
AValues: TArray<String>);
var
AValues2: TArray<String>;
l: Integer;
begin
// Если вставлять нечего
if Length(AValues) = 0 then
Exit;
if Mode = SearchMode then
begin
// Сохраняем первое значение в пустой строке
if Value.F.AsString.IsEmpty then
begin
TryEdit;
Value.F.AsString := AValues[0];
TryPost;
end;
l := Length(AValues);
if l = 1 then
Exit;
SetLength(AValues2, Length(AValues) - 1);
TArray.Copy<String>(AValues, AValues2, 1, 0, l - 1);
inherited AppendRows(AFieldName, AValues2);
end;
end;
end.
|
unit webservice1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,
blcksock, sockets, Synautil, LazLogger, fpsimplejsonexport, fpjson,
sqldb, strutils, Windows;
type
TAction = (acInsert, acSelect, acUpdate, acDelete);
TRoute = class(TObject)
path: string;
query: TSQLQuery;
action: TAction;
end;
TFilter = class(TObject)
Name: string;
Value: variant;
end;
TResponse = (JSON, XML, SQL);
{ TWebService }
TWebService = class(TComponent)
private
FHost: string;
FPort: integer;
FResponse: TResponse;
procedure SetHost(AValue: string);
procedure SetPort(AValue: integer);
procedure SetResponse(AValue: TResponse);
protected
published
property Host: string read FHost write SetHost;
property Port: integer read FPort write SetPort;
property Response: TResponse read FResponse write SetResponse default JSON;
public
constructor Create(AOwner: TComponent); override;
procedure Start;
procedure Stop;
procedure Restart;
procedure SetRoute(ARoute: string; AQuery: TSQLQuery; AAction: TAction = acSelect);
procedure Send(AValue: string);
function isActive(): boolean;
end;
{ TWebServiceThread }
TWebServiceThread = class(TThread)
private
FHost: string;
FPort: integer;
procedure AttendConnection(ASocket: TTCPBlockSocket);
procedure SetHost(AValue: string);
procedure SetPort(AValue: integer);
function Get(URI, filter: string): string;
function Post(URI: string; AData: string): string; overload;
procedure Split(Delimiter: char; Str: string; ListOfStrings: TStrings);
function ParseValue(str: string): variant;
protected
procedure Execute; override;
published
property Host: string read FHost write SetHost;
property Port: integer read FPort write SetPort;
end;
var
ws: TWebServiceThread;
ListenerSocket, ConnectionSocket: TTCPBlockSocket;
routes: array of TRoute;
filters: array of TFilter;
s_routes: array of string;
procedure Register;
implementation
procedure Register;
begin
{$I webservice1_icon.lrs}
RegisterComponents('Web', [TWebService]);
end;
{ TWebService }
procedure TWebServiceThread.AttendConnection(ASocket: TTCPBlockSocket);
var
timeout, i: integer;
s, res: string;
method, uri, protocol: string;
OutputDataString: string;
arq: TextFile;
body: string;
filter: string;
message: TStringList;
without_body: word;
content: word = 0;
begin
timeout := 120000;
DebugLn('Received headers+document from browser:');
//read request line
s := ASocket.RecvString(timeout);
DebugLn(s);
method := fetch(s, ' ');
uri := fetch(s, ' ');
filter := '';
if (uri.Contains('&')) then
begin
filter := copy(uri, pos('&', uri) + 1, Length(uri));
uri := copy(uri, 0, pos('&', uri) - 1);
end;
protocol := fetch(s, ' ');
//read request headers
repeat
s := ASocket.RecvString(Timeout);
DebugLn(s);
until s = '';
if (method = 'POST') then
begin
res := ASocket.RecvPacket(timeout);
body := copy(res, Pos('{', res) - 1, Length(res));
if (body = '') then
body := copy(res, Pos('[', res) - 1, Length(res));
AssignFile(arq, 'headers.txt');
Rewrite(arq);
Write(arq, res);
Close(arq);
end;
if (AnsiIndexStr(uri, s_routes) > -1) then
begin
if (AnsiIndexStr(uri, s_routes) = 0) then
begin
OutputDataString :=
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' +
' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' +
CRLF + '<html><h1>Server running at: ' + Host + ':' +
IntToStr(Port) + '</h1></html>' + CRLF;
// Write the headers back to the client
ASocket.SendString('HTTP/1.0 200' + CRLF);
ASocket.SendString('Content-type: Text/Html' + CRLF);
ASocket.SendString('Content-length: ' + IntToStr(Length(OutputDataString)) + CRLF);
ASocket.SendString('Connection: close' + CRLF);
ASocket.SendString('Date: ' + Rfc822DateTime(now) + CRLF);
ASocket.SendString('Server: Ws Lazarus' + CRLF);
ASocket.SendString('' + CRLF);
// Write the document back to the browser
ASocket.SendString(OutputDataString);
end
else
begin
DebugLn(method);
if (trim(method) = 'GET') then
res := Get(uri, filter);
if (trim(method) = 'POST') then
begin
res := Post(uri, body);
end;
OutputDataString := res;
// Write the headers back to the client
ASocket.SendString('HTTP/1.0 200' + CRLF);
ASocket.SendString('Content-type: application/json' + CRLF);
ASocket.SendString('Content-length: ' + IntToStr(Length(OutputDataString)) + CRLF);
ASocket.SendString('Connection: close' + CRLF);
ASocket.SendString('Date: ' + Rfc822DateTime(now) + CRLF);
ASocket.SendString('Server: Ws Lazarus' + CRLF);
ASocket.SendString('' + CRLF);
// Write the document back to the browser
ASocket.SendString(OutputDataString);
end;
end
else
ASocket.SendString('HTTP/1.0 404' + CRLF);
end;
procedure TWebServiceThread.SetHost(AValue: string);
begin
if FHost = AValue then
Exit;
FHost := AValue;
end;
procedure TWebServiceThread.SetPort(AValue: integer);
begin
if FPort = AValue then
Exit;
FPort := AValue;
end;
procedure TWebServiceThread.Execute;
begin
ListenerSocket := TTCPBlockSocket.Create;
ConnectionSocket := TTCPBlockSocket.Create;
ListenerSocket.CreateSocket;
ListenerSocket.setLinger(True, 1000);
ListenerSocket.bind(Host, IntToStr(Port));
ListenerSocket.HTTPTunnelIP := Host;
ListenerSocket.HTTPTunnelPort := IntToStr(Port);
ListenerSocket.listen;
repeat
if ListenerSocket.canread(1000) then
begin
ConnectionSocket.Socket := ListenerSocket.accept;
debugLn('Attending Connection. Error code (0=Success): ' +
IntToStr(ConnectionSocket.lasterror));
AttendConnection(ConnectionSocket);
ConnectionSocket.CloseSocket;
end;
until ws.Finished;
//False;
ListenerSocket.Free;
ConnectionSocket.Free;
end;
procedure TWebService.SetHost(AValue: string);
begin
if FHost = AValue then
Exit;
FHost := AValue;
end;
procedure TWebService.SetPort(AValue: integer);
begin
if FPort = AValue then
Exit;
FPort := AValue;
end;
procedure TWebService.SetResponse(AValue: TResponse);
begin
if FResponse = AValue then
Exit;
FResponse := AValue;
end;
function TWebServiceThread.Get(URI, filter: string): string;
var
I, J: integer;
jsonExp: TSimpleJSONExporter;
st: TFileStream;
bytes: TBytes;
res, sql, paramField, orderBy: string;
params: TStringList;
begin
jsonExp := TSimpleJSONExporter.Create(nil);
params := TStringList.Create;
for I := 0 to Length(routes) - 1 do
begin
if (routes[I].path = uri) then
begin
sql := routes[i].query.SQL.Text;
jsonExp.Dataset := routes[i].query;
jsonExp.FileName := 'data.json';
try
routes[i].query.Close;
Split('?', filter, params);
if (params.Count > 0) then
begin
for J := 0 to params.Count - 1 do
begin
paramField := StringReplace(copy(params[J], 0, pos('=', params[J]) - 1),
'?', '', [rfReplaceAll]);
if ((paramField <> 'orderBy') and (paramField <> 'desc')) then
begin
if (J = 0) then
routes[i].query.SQL.Add(' where ' + paramField)
else
routes[i].query.SQL.Add(' and ' + paramField);
if (params[J].Contains('=%')) then
routes[i].query.SQL.Add(' containing :PAR' + IntToStr(J))
else
routes[i].query.SQL.Add(' = :PAR' + IntToStr(J));
routes[i].query.Params[J].Value :=
ParseValue(StringReplace(copy(params[J], pos('=', params[J]) +
1, Length(params[J])), '%', '', [rfReplaceAll]));
end
else
begin
if (paramField = 'orderBy') then
orderBy := ' order by ' +
copy(params[J], pos('=', params[J]) + 1, Length(params[J]));
if ((orderBy <> '') and (paramField = 'desc')) then
orderBy := orderBy + ' desc';
end;
end;
routes[i].query.SQL.Add(orderBy);
end;
routes[i].query.Open;
jsonExp.Execute;
st := TFileStream.Create('data.json', fmOpenRead or fmShareDenyWrite);
if (st.Size > 0) then
begin
SetLength(bytes, st.Size);
st.Read(bytes[0], st.Size);
end;
DeleteFile('data.json');
res := StringReplace(TEncoding.ASCII.GetString(bytes), ';', ',', [rfReplaceAll]);
res := StringReplace(res, #13#10, '', [rfReplaceAll]);
res := copy(res, 0, pos(']', res) - 2);
if (res = '') then
res := res + '[';
res := res + ']';
FreeAndNil(jsonExp);
FreeAndNil(st);
routes[i].query.Close;
routes[i].query.SQL.Text := sql;
Result := res;
except
on E: Exception do
begin
Result := '{error: "' + e.Message + '"}';
routes[i].query.SQL.Text := sql;
end;
end;
break;
end;
end;
end;
function TWebServiceThread.Post(URI: string; AData: string): string;
var
I, F: integer;
jData: TJSONData;
JSON: TJSONObject;
auxSql, where: string;
begin
jData := GetJSON(AData);
JSON := TJSONObject(jData);
for I := 0 to Length(routes) - 1 do
begin
if (routes[I].path = uri) then
begin
if (AData = '') then
Result := '{error: "No Records found!"}';
try
case routes[I].action of
acDelete:
begin
with routes[I] do
begin
try
where := JSON.Get('where');
except
Result := '{error: "No where clause for delete method"}';
Exit;
end;
auxSql := query.SQL.Text;
if auxSql.Contains('where') then
query.SQL.Add(' and ' + JSON.Get('where'))
else
query.SQL.Add(' where ' + JSON.Get('where'));
query.Open;
if (query.IsEmpty) then
begin
Result := '{error: "Record not found"}';
Exit;
end;
query.Delete;
(query.Transaction as TSQLTransaction).Commit;
query.SQL.Text := auxSql;
Result := '{action: "Delete", error: false}';
end;
end;
acInsert:
begin
with routes[I] do
begin
query.Open;
query.Insert;
for F := 0 to query.FieldCount - 1 do
query.Fields[F].Value := JSON.Get(LowerCase(query.Fields[F].FieldName));
query.Post;
query.ApplyUpdates();
(query.Transaction as TSQLTransaction).Commit;
Result := '{action: "Insert", error: false}';
end;
end;
acUpdate:
begin
with routes[I] do
begin
try
where := JSON.Get('where');
except
Result := '{error: "No where clause for update method"}';
Exit;
end;
auxSql := query.SQL.Text;
if auxSql.Contains('where') then
query.SQL.Add(' and ' + JSON.Get('where'))
else
query.SQL.Add(' where ' + JSON.Get('where'));
query.Open;
if (query.IsEmpty) then
begin
Result := '{error: "Record not found"}';
Exit;
end;
query.Edit;
for F := 0 to query.FieldCount - 1 do
query.Fields[F].Value := JSON.Get(LowerCase(query.Fields[F].FieldName));
query.Post;
query.ApplyUpdates();
(query.Transaction as TSQLTransaction).Commit;
query.SQL.Text := auxSql;
Result := '{action: "Update", error: false}';
end;
end;
else
Result := '{error: "No Action Assigned!"}';
end;
//Result := AData;
except
on E: Exception do
Result := '{error: "' + e.Message + '"}';
end;
break;
end;
end;
end;
procedure TWebServiceThread.Split(Delimiter: char; Str: string;
ListOfStrings: TStrings);
begin
ListOfStrings.Clear;
ListOfStrings.Delimiter := Delimiter;
ListOfStrings.StrictDelimiter := True;
ListOfStrings.DelimitedText := Str;
end;
function TWebServiceThread.ParseValue(str: string): variant;
var
I: integer;
isInteger: boolean;
begin
isInteger := True;
for I := 0 to length(str) - 1 do
begin
if not (str[I] in ['0'..'9']) then
begin
isInteger := False;
break;
end;
end;
if (isInteger) then
Result := StrToInt(str)
else
Result := str;
end;
constructor TWebService.Create(AOwner: TComponent);
var
route: TRoute;
begin
inherited Create(AOwner);
route := TRoute.Create;
SetLength(routes, Length(routes) + 1);
SetLength(s_routes, Length(routes));
route.path := '/';
route.query := nil;
s_routes[Length(routes) - 1] := route.path;
routes[Length(routes) - 1] := route;
end;
procedure TWebService.Start;
begin
ws := TWebServiceThread.Create(False);
ws.Host := Host;
ws.Port := Port;
ws.Start;
end;
procedure TWebService.Stop;
begin
if (ws <> nil) then
begin
ws.Terminate;
//while not ws.Terminated do;
//begin
// TerminateThread(ws.Handle,0);
//end;
end;
end;
procedure TWebService.Restart;
begin
Stop;
Start;
end;
procedure TWebService.SetRoute(ARoute: string; AQuery: TSQLQuery;
AAction: TAction = acSelect);
var
route: TRoute;
begin
route := TRoute.Create;
route.path := ARoute;
route.query := AQuery;
route.action := AAction;
SetLength(routes, Length(routes) + 1);
SetLength(s_routes, Length(routes));
s_routes[Length(routes) - 1] := route.path;
routes[Length(routes) - 1] := route;
end;
procedure TWebService.Send(AValue: string);
var
timeout: integer;
s: string;
method, uri, protocol: string;
OutputDataString: string;
ResultCode: integer;
begin
timeout := 120000;
try
if AValue <> '' then
begin
// Write the output document to the stream
OutputDataString :=
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' +
' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' +
CRLF + '<html><h1>' + AValue + '</h1></html>' + CRLF;
// Write the headers back to the client
ConnectionSocket.SendString('HTTP/1.0 200' + CRLF);
ConnectionSocket.SendString('Content-type: Text/Html' + CRLF);
ConnectionSocket.SendString('Content-length: ' +
IntToStr(Length(OutputDataString)) + CRLF);
ConnectionSocket.SendString('Connection: close' + CRLF);
ConnectionSocket.SendString('Date: ' + Rfc822DateTime(now) + CRLF);
ConnectionSocket.SendString('Server: Ws Lazarus' + CRLF);
ConnectionSocket.SendString('' + CRLF);
// Write the document back to the browser
ConnectionSocket.SendString(OutputDataString);
end
else
ConnectionSocket.SendString('HTTP/1.0 404' + CRLF);
except
end;
end;
function TWebService.isActive(): boolean;
begin
Result := not ws.Finished;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.