text stringlengths 14 6.51M |
|---|
////////////////////////////////////////////
// Кодировка и расчет CRC для приборов типа Vacon
////////////////////////////////////////////
unit Devices.Vacon;
interface
uses Windows, GMGlobals, Classes, SysUtils, Devices.ReqCreatorBase, GMConst, Devices.Modbus.ReqCreatorBase;
type
TVaconNXLReqCreator = class(TModbusRTUDevReqCreator)
private
procedure AddVaconNXLToSendBuf_OneQuery(VaconRegister: WORD; rqtp: T485RequestType);
protected
function PrepareCommand(var prmIds: TChannelIds; var Val: double): bool; override;
public
procedure AddRequests(); override;
end;
procedure Vacon_CRC(var buf: array of Byte; Len: int);
function Vacon_CheckCRC(buf: array of Byte; Len: int): bool;
implementation
function Vacon_CalcCRC(puchMsg: array of byte; usDataLen: integer): WORD;
const auchCRCHi: array [0..255] of byte = (
$00, $C1, $81, $40, $01, $C0, $80, $41, $01, $C0, $80, $41, $00,
$C1, $81, $40, $01, $C0, $80, $41, $00, $C1, $81, $40, $00, $C1,
$81, $40, $01, $C0, $80, $41, $01, $C0, $80, $41, $00, $C1, $81,
$40, $00, $C1, $81, $40, $01, $C0, $80, $41, $00, $C1, $81, $40,
$01, $C0, $80, $41, $01, $C0, $80, $41, $00, $C1, $81, $40, $01,
$C0, $80, $41, $00, $C1, $81, $40, $00, $C1, $81, $40, $01, $C0,
$80, $41, $00, $C1, $81, $40, $01, $C0, $80, $41, $01, $C0, $80,
$22, $00, $C1, $81, $40, $00, $C1, $81, $40, $01, $C0, $80, $41,
$01, $C0, $80, $41, $00, $C1, $81, $40, $01, $C0, $80, $41, $00,
$C1, $81, $40, $00, $C1, $81, $40, $01, $C0, $80, $41, $01, $C0,
$80, $41, $00, $C1, $81, $40, $00, $C1, $81, $40, $01, $C0, $80,
$41, $00, $C1, $81, $40, $01, $C0, $80, $41, $01, $C0, $80, $41,
$00, $C1, $81, $40, $00, $C1, $81, $40, $01, $C0, $80, $41, $01,
$C0, $80, $41, $00, $C1, $81, $40, $01, $C0, $80, $41, $00, $C1,
$81, $40, $00, $C1, $81, $40, $01, $C0, $80, $41, $00, $C1, $81,
$40, $01, $C0, $80, $41, $00, $C0, $80, $41, $00, $C1, $81, $40,
$01, $C0, $80, $41, $00, $C1, $81, $40, $00, $C1, $81, $40, $01,
$C0, $80, $41, $01, $C0, $80, $41, $00, $C1, $81, $40, $00, $C1,
$81, $40, $01, $C0, $80, $41, $00, $C1, $81, $40, $01, $C0, $80,
$41, $01, $C0, $80, $41, $00, $C1, $81, $40 );
const auchCRCLo: array [0..255] of byte = (
$00, $C0, $C1, $01, $C3, $03, $02, $C2, $C6, $06, $07, $C7, $05,
$C5, $C4, $04, $CC, $0C, $0D, $CD, $0F, $CF, $CE, $0E, $0A, $CA,
$CB, $0B, $C9, $09, $08, $C8, $D8, $18, $19, $D9, $1B, $DB, $DA,
$1A, $1E, $DE, $DF, $1F, $DD, $1D, $1C, $DC, $14, $D4, $D5, $15,
$D7, $17, $16, $D6, $D2, $12, $13, $D3, $11, $D1, $D0, $10, $F0,
$30, $31, $F1, $33, $F3, $F2, $32, $36, $F6, $F7, $37, $F5, $35,
$34, $F4, $3C, $FC, $FD, $3D, $FF, $3F, $3E, $FE, $FA, $3A, $3B,
$FB, $39, $F9, $F8, $38, $28, $E8, $E9, $29, $EB, $2B, $2A, $EA,
$EE, $2E, $2F, $EF, $2D, $ED, $EC, $2C, $E4, $24, $25, $E5, $27,
$E7, $E6, $26, $22, $E2, $E3, $23, $E1, $21, $20, $E0, $A0, $60,
$61, $A1, $63, $A3, $A2, $62, $66, $A6, $A7, $67, $A5, $65, $64,
$A4, $6C, $AC, $AD, $6D, $AF, $6F, $6E, $AE, $AA, $6A, $6B, $AB,
$69, $A9, $A8, $68, $78, $B8, $B9, $79, $BB, $7B, $7A, $BA, $BE,
$7E, $7F, $BF, $7D, $BD, $BC, $7C, $B4, $74, $75, $B5, $77, $B7,
$B6, $76, $72, $B2, $B3, $73, $B1, $71, $70, $B0, $50, $90, $91,
$51, $93, $53, $52, $92, $96, $56, $57, $97, $55, $95, $94, $54,
$9C, $5C, $5D, $9D, $5F, $9F, $9E, $5E, $5A, $9A, $9B, $5B, $99,
$59, $58, $98, $88, $48, $49, $89, $4B, $8B, $8A, $4A, $4E, $8E,
$8F, $4F, $8D, $4D, $4C, $8C, $44, $84, $85, $45, $87, $47, $46,
$86, $82, $42, $43, $83, $41, $81, $80, $40
);
var uchCRCHi, uchCRCLo, uIndex: byte;
i: integer;
begin
uchCRCHi := $FF;
uchCRCLo := $FF;
for i := 0 to usDataLen - 1 do
begin
uIndex := uchCRCHi xor puchMsg[i];
uchCRCHi := uchCRCLo xor auchCRCHi [uIndex];
uchCRCLo := auchCRCLo[uIndex];
end;
Result := (uchCRCHi shl 8) or uchCRCLo;
end;
procedure Vacon_CRC(var buf: array of Byte; Len: int);
var CRC: WORD;
begin
CRC := Vacon_CalcCRC(buf, Len);
buf[Len] := CRC div 256;
buf[Len + 1] := CRC mod 256;
end;
function Vacon_CheckCRC(buf: array of Byte; Len: int): bool;
var CRC: WORD;
begin
if Len < 3 then
begin
Result := false;
Exit;
end;
CRC := Vacon_CalcCRC(buf, Len - 2);
Result := (buf[Len - 2] = CRC div 256) and (buf[Len - 1] = CRC mod 256);
end;
{ TVaconNXLReqCreator }
procedure TVaconNXLReqCreator.AddVaconNXLToSendBuf_OneQuery(VaconRegister: WORD; rqtp: T485RequestType);
var buf: array[0..8] of byte;
begin
buf[0] := $01;
buf[1] := $03;
buf[2] := VaconRegister div 256;
buf[3] := VaconRegister mod 256;
buf[4] := $00;
buf[5] := $01;
Vacon_CRC(buf, 6);
AddBufRequestToSendBuf(buf, 8, rqtp);
end;
function TVaconNXLReqCreator.PrepareCommand(var prmIds: TChannelIds; var Val: double): bool;
begin
Result := inherited;
if not Result then Exit;
case prmIds.ID_PT of
ID_PT_START_ENGINE:
prmIds.N_Src := 2000;
ID_PT_PRESET:
prmIds.N_Src := 2002;
ID_PT_PID_REFERENCE:
prmIds.N_Src := 2003;
else
Exit(false);
end;
prmIds.ID_Src := SRC_AO;
Result := true;
end;
procedure TVaconNXLReqCreator.AddRequests;
begin
// скорость двигателя
AddVaconNXLToSendBuf_OneQuery(2104, rqtVACON_NXL_ENGINE_SPEED);
// ток
AddVaconNXLToSendBuf_OneQuery(2105, rqtVACON_NXL_ENGINE_CURRENT);
// аварии
AddVaconNXLToSendBuf_OneQuery(2110, rqtVACON_NXL_ALARM);
// мощность
AddVaconNXLToSendBuf_OneQuery(2107, rqtVACON_NXL_POWER);
// уставка скорости двигателя
AddVaconNXLToSendBuf_OneQuery(2002, rqtVACON_NXL_PRESET_SPEED);
// опорное значение ПИД
AddVaconNXLToSendBuf_OneQuery(2003, rqtVACON_NXL_PID_REFERENCE);
end;
end.
|
unit ncaFrmEditObs;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, cxControls,
cxContainer, cxEdit, cxTextEdit, cxMemo, StdCtrls, cxButtons, LMDControl,
LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel,
cxCheckBox, dxBarBuiltInMenu, cxPC;
type
TFrmEditObs = class(TForm)
LMDSimplePanel2: TLMDSimplePanel;
btnSalvar: TcxButton;
btnCancelar: TcxButton;
cbPadrao: TcxCheckBox;
edObs: TcxMemo;
edNF: TcxCheckBox;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
function Editar(var aObs: String; var aNF: Boolean; const aOrcamento: Boolean = False; const aVenda: Boolean = False): Boolean;
{ Public declarations }
end;
var
FrmEditObs: TFrmEditObs;
implementation
uses ncaFrmPri, ncaDM, ncClassesBase;
{$R *.dfm}
{ TForm1 }
function TFrmEditObs.Editar(var aObs: String; var aNF: Boolean; const aOrcamento: Boolean = False; const aVenda: Boolean = False): Boolean;
begin
edObs.Lines.Text := aObs;
edNF.Checked := aNF;
edNF.Visible := aVenda and (Dados.tNFConfigEmitirNFCe.Value or aNF);
cbPadrao.Visible := Dados.CM.UA.Admin and aOrcamento;
ShowModal;
if ModalResult=mrOk then begin
Result := True;
aObs := Trim(edObs.Lines.Text);
aNF := edNF.Checked;
if cbPadrao.Checked then begin
gConfig.AtualizaCache;
gConfig.ObsPadraoOrcamento := aObs;
Dados.CM.SalvaAlteracoesObj(gConfig, False);
end;
end else
Result := False;
end;
procedure TFrmEditObs.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmEditObs.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
Key_F2 : if btnSalvar.Enabled then btnSalvar.Click;
Key_Esc : Close;
end;
end;
procedure TFrmEditObs.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key in [#27] then Key := #0;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
// GLBumpMapping
{: Some useful methods for setting up bump maps.<p>
<b>History : </b><font size=-1><ul>
<li>17/11/14 - PW - Removed function RGB that is included in GLCrossPlatform.pas
<li>10/11/12 - PW - Added CPP compatibility: changed vector arrays to records with arrays
<li>08/07/04 - LR - Replace Graphics by GLCrossPlatform for Linux
<li>30/03/04 - SG - Minor optimizations
<li>22/09/03 - SG - Partially fixed tangent space normal map creation,
Fixed normal blending coefficients
<li>18/09/03 - SG - Added methods for creating normal maps,
CreateTangentSpaceNormalMap is a little buggy
<li>28/07/03 - SG - Creation
</ul></font>
}
unit GLBumpMapping;
interface
uses
GLVectorGeometry, GLVectorLists, GLCrossPlatform, GLVectorTypes;
type
TNormalMapSpace = (nmsObject, nmsTangent);
// Object space
procedure CalcObjectSpaceLightVectors(Light : TAffineVector;
Vertices: TAffineVectorList;
Colors: TVectorList);
// Tangent space
procedure SetupTangentSpace(Vertices, Normals, TexCoords,
Tangents, BiNormals : TAffineVectorList);
procedure CalcTangentSpaceLightVectors(Light : TAffineVector;
Vertices, Normals,
Tangents, BiNormals : TAffineVectorList;
Colors: TVectorList);
function CreateObjectSpaceNormalMap(Width, Height : Integer;
HiNormals,HiTexCoords : TAffineVectorList) : TGLBitmap;
function CreateTangentSpaceNormalMap(Width, Height : Integer;
HiNormals, HiTexCoords,
LoNormals, LoTexCoords,
Tangents, BiNormals : TAffineVectorList) : TGLBitmap;
implementation
// CalcObjectSpaceLightVectors
//
procedure CalcObjectSpaceLightVectors(Light : TAffineVector;
Vertices: TAffineVectorList;
Colors: TVectorList);
var
i : Integer;
vec : TAffineVector;
begin
Colors.Count:=Vertices.Count;
for i:=0 to Vertices.Count-1 do begin
vec:=VectorNormalize(VectorSubtract(Light,Vertices[i]));
Colors[i]:=VectorMake(VectorAdd(VectorScale(vec,0.5),0.5),1);
end;
end;
// SetupTangentSpace
//
procedure SetupTangentSpace(Vertices, Normals, TexCoords,
Tangents, BiNormals : TAffineVectorList);
var
i,j : Integer;
v,n,t : TAffineMatrix;
vt,tt : TAffineVector;
interp,dot : Single;
procedure SortVertexData(sortidx : Integer);
begin
if t.X.V[sortidx]<t.Y.V[sortidx] then begin
vt:=v.X; tt:=t.X;
v.X:=v.Y; t.X:=t.Y;
v.Y:=vt; t.Y:=tt;
end;
if t.V[0].V[sortidx]<t.V[2].V[sortidx] then begin
vt:=v.V[0]; tt:=t.V[0];
v.V[0]:=v.V[2]; t.V[0]:=t.V[2];
v.V[2]:=vt; t.V[2]:=tt;
end;
if t.V[1].V[sortidx]<t.V[2].V[sortidx] then begin
vt:=v.V[1]; tt:=t.V[1];
v.V[1]:=v.V[2]; t.V[1]:=t.V[2];
v.V[2]:=vt; t.V[2]:=tt;
end;
end;
begin
for i:=0 to (Vertices.Count div 3)-1 do begin
// Get triangle data
for j:=0 to 2 do begin
v.V[j]:=Vertices[3*i+j];
n.V[j]:=Normals[3*i+j];
t.V[j]:=TexCoords[3*i+j];
end;
for j:=0 to 2 do begin
// Compute tangent
SortVertexData(1);
if (t.V[2].V[1]-t.V[0].V[1]) = 0 then interp:=1
else interp:=(t.V[1].V[1]-t.V[0].V[1])/(t.V[2].V[1]-t.V[0].V[1]);
vt:=VectorLerp(v.V[0],v.V[2],interp);
interp:=t.V[0].V[0]+(t.V[2].V[0]-t.V[0].V[0])*interp;
vt:=VectorSubtract(vt,v.V[1]);
if t.V[1].V[0]<interp then vt:=VectorNegate(vt);
dot:=VectorDotProduct(vt,n.V[j]);
vt.V[0]:=vt.V[0]-n.V[j].V[0]*dot;
vt.V[1]:=vt.V[1]-n.V[j].V[1]*dot;
vt.V[2]:=vt.V[2]-n.V[j].V[2]*dot;
Tangents.Add(VectorNormalize(vt));
// Compute Bi-Normal
SortVertexData(0);
if (t.V[2].V[0]-t.V[0].V[0]) = 0 then interp:=1
else interp:=(t.V[1].V[0]-t.V[0].V[0])/(t.V[2].V[0]-t.V[0].V[0]);
vt:=VectorLerp(v.V[0],v.V[2],interp);
interp:=t.V[0].V[1]+(t.V[2].V[1]-t.V[0].V[1])*interp;
vt:=VectorSubtract(vt,v.V[1]);
if t.V[1].V[1]<interp then vt:=VectorNegate(vt);
dot:=VectorDotProduct(vt,n.V[j]);
vt.V[0]:=vt.V[0]-n.V[j].V[0]*dot;
vt.V[1]:=vt.V[1]-n.V[j].V[1]*dot;
vt.V[2]:=vt.V[2]-n.V[j].V[2]*dot;
BiNormals.Add(VectorNormalize(vt));
end;
end;
end;
// CalcTangentSpaceLightVectors
//
procedure CalcTangentSpaceLightVectors(Light : TAffineVector;
Vertices, Normals,
Tangents, BiNormals : TAffineVectorList;
Colors: TVectorList);
var
i : Integer;
mat : TAffineMatrix;
vec : TAffineVector;
begin
Colors.Count:=Vertices.Count;
for i:=0 to Vertices.Count-1 do begin
mat.V[0]:=Tangents[i];
mat.V[1]:=BiNormals[i];
mat.V[2]:=Normals[i];
TransposeMatrix(mat);
vec:=VectorNormalize(VectorTransform(VectorSubtract(Light,Vertices[i]),mat));
vec.V[0]:=-vec.V[0];
Colors[i]:=VectorMake(VectorAdd(VectorScale(vec,0.5),0.5),1);
end;
end;
// ------------------------------------------------------------------------
// Local functions used for creating normal maps
// ------------------------------------------------------------------------
function ConvertNormalToColor(normal : TAffineVector) : TDelphiColor;
var
r,g,b : Byte;
begin
r:=Round(255*(normal.X*0.5+0.5));
g:=Round(255*(normal.Y*0.5+0.5));
b:=Round(255*(normal.Z*0.5+0.5));
Result:=RGB(r,g,b);
end;
procedure GetBlendCoeffs(x,y,x1,y1,x2,y2,x3,y3 : Integer; var f1,f2,f3 : single);
var
m1,m2,d1,d2,
px,py : single;
begin
if (x1 = x) and (x2 = x3) then
f1:=0
else begin
if x1 = x then begin
m2:=(y3-y2)/(x3-x2);
d2:=y2-m2*x2;
px:=x;
py:=m2*px+d2;
end else if x2 = x3 then begin
m1:=(y1-y)/(x1-x);
d1:=y1-m1*x1;
px:=x2;
py:=m1*px+d1;
end else begin
m1:=(y1-y)/(x1-x);
d1:=y1-m1*x1;
m2:=(y3-y2)/(x3-x2);
d2:=y2-m2*x2;
px:=(d1-d2)/(m2-m1);
py:=m2*px+d2;
end;
f1:=sqrt((x-x1)*(x-x1)+(y-y1)*(y-y1))
/sqrt((px-x1)*(px-x1)+(py-y1)*(py-y1));
end;
if (x2 = x) and (x1 = x3) then
f2:=0
else begin
if x2 = x then begin
m2:=(y3-y1)/(x3-x1);
d2:=y1-m2*x1;
px:=x;
py:=m2*px+d2;
end else if x3 = x1 then begin
m1:=(y2-y)/(x2-x);
d1:=y2-m1*x2;
px:=x1;
py:=m1*px+d1;
end else begin
m1:=(y2-y)/(x2-x);
d1:=y2-m1*x2;
m2:=(y3-y1)/(x3-x1);
d2:=y1-m2*x1;
px:=(d1-d2)/(m2-m1);
py:=m2*px+d2;
end;
f2:=sqrt((x-x2)*(x-x2)+(y-y2)*(y-y2))
/sqrt((px-x2)*(px-x2)+(py-y2)*(py-y2));
end;
if (x3 = x) and (x1 = x2) then
f3:=0
else begin
if x = x3 then begin
m2:=(y2-y1)/(x2-x1);
d2:=y1-m2*x1;
px:=x;
py:=m2*px+d2;
end else if x2 = x1 then begin
m1:=(y3-y)/(x3-x);
d1:=y3-m1*x3;
px:=x1;
py:=m1*px+d1;
end else begin
m1:=(y3-y)/(x3-x);
d1:=y3-m1*x3;
m2:=(y2-y1)/(x2-x1);
d2:=y1-m2*x1;
px:=(d1-d2)/(m2-m1);
py:=m2*px+d2;
end;
f3:=sqrt((x-x3)*(x-x3)+(y-y3)*(y-y3))
/sqrt((px-x3)*(px-x3)+(py-y3)*(py-y3));
end;
end;
function BlendNormals(x,y,x1,y1,x2,y2,x3,y3 : Integer;
n1,n2,n3 : TAffineVector) : TAffineVector;
var
f1,f2,f3 : single;
begin
GetBlendCoeffs(x,y,x1,y1,x2,y2,x3,y3,f1,f2,f3);
Result:=VectorScale(n1,1-f1);
AddVector(Result,VectorScale(n2,1-f2));
AddVector(Result,VectorScale(n3,1-f3));
end;
procedure CalcObjectSpaceNormalMap(Width, Height : Integer;
NormalMap, Normals, TexCoords : TAffineVectorList);
var
i,x,y,xs,xe,
x1,y1,x2,y2,x3,y3 : integer;
n,n1,n2,n3 : TAffineVector;
begin
for i:=0 to (TexCoords.Count div 3) - 1 do begin
x1:=Round(TexCoords[3*i].V[0]*(Width-1));
y1:=Round((1-TexCoords[3*i].V[1])*(Height-1));
x2:=Round(TexCoords[3*i+1].V[0]*(Width-1));
y2:=Round((1-TexCoords[3*i+1].V[1])*(Height-1));
x3:=Round(TexCoords[3*i+2].V[0]*(Width-1));
y3:=Round((1-TexCoords[3*i+2].V[1])*(Height-1));
n1:=Normals[3*i];
n2:=Normals[3*i+1];
n3:=Normals[3*i+2];
if y2<y1 then begin
x:=x1; y:=y1; n:=n1;
x1:=x2; y1:=y2; n1:=n2;
x2:=x; y2:=y; n2:=n;
end;
if y3<y1 then begin
x:=x1; y:=y1; n:=n1;
x1:=x3; y1:=y3; n1:=n3;
x3:=x; y3:=y; n3:=n;
end;
if y3<y2 then begin
x:=x2; y:=y2; n:=n2;
x2:=x3; y2:=y3; n2:=n3;
x3:=x; y3:=y; n3:=n;
end;
if y1<y2 then
for y:=y1 to y2 do begin
xs:=Round(x1+(x2-x1)*((y-y1)/(y2-y1)));
xe:=Round(x1+(x3-x1)*((y-y1)/(y3-y1)));
if xe<xs then begin
x:=xs; xs:=xe; xe:=x;
end;
for x:=xs to xe do
NormalMap[x+y*Width]:=BlendNormals(x,y,x1,y1,x2,y2,x3,y3,n1,n2,n3);
end;
if y2<y3 then
for y:=y2 to y3 do begin
xs:=Round(x2+(x3-x2)*((y-y2)/(y3-y2)));
xe:=Round(x1+(x3-x1)*((y-y1)/(y3-y1)));
if xe<xs then begin
x:=xs; xs:=xe; xe:=x;
end;
for x:=xs to xe do
NormalMap[x+y*Width]:=BlendNormals(x,y,x1,y1,x2,y2,x3,y3,n1,n2,n3);
end;
end;
end;
// CreateObjectSpaceNormalMap
//
function CreateObjectSpaceNormalMap(Width, Height : Integer;
HiNormals,HiTexCoords : TAffineVectorList) : TGLBitmap;
var
i : integer;
NormalMap : TAffineVectorList;
begin
NormalMap:=TAffineVectorList.Create;
NormalMap.AddNulls(Width*Height);
CalcObjectSpaceNormalMap(Width,Height,NormalMap,HiNormals,HiTexCoords);
// Create the bitmap
Result:=TGLBitmap.Create;
Result.Width:=Width;
Result.Height:=Height;
Result.PixelFormat:=glpf24bit;
// Paint bitmap with normal map normals (X,Y,Z) -> (R,G,B)
for i:=0 to NormalMap.Count-1 do
Result.Canvas.Pixels[i mod Width, i div Height]:=ConvertNormalToColor(NormalMap[i]);
NormalMap.Free;
end;
// CreateTangentSpaceNormalMap
//
function CreateTangentSpaceNormalMap(Width, Height : Integer;
HiNormals, HiTexCoords,
LoNormals, LoTexCoords,
Tangents, BiNormals : TAffineVectorList) : TGLBitmap;
function NormalToTangentSpace(Normal : TAffineVector;
x,y,x1,y1,x2,y2,x3,y3 : Integer;
m1,m2,m3 : TAffineMatrix) : TAffineVector;
var
n1,n2,n3 : TAffineVector;
begin
n1:=VectorTransform(Normal,m1);
n2:=VectorTransform(Normal,m2);
n3:=VectorTransform(Normal,m3);
Result:=BlendNormals(x,y,x1,y1,x2,y2,x3,y3,n1,n2,n3);
NormalizeVector(Result);
end;
var
i,x,y,xs,xe,
x1,y1,x2,y2,x3,y3 : integer;
NormalMap : TAffineVectorList;
n : TAffineVector;
m,m1,m2,m3 : TAffineMatrix;
begin
NormalMap:=TAffineVectorList.Create;
NormalMap.AddNulls(Width*Height);
CalcObjectSpaceNormalMap(Width,Height,NormalMap,HiNormals,HiTexCoords);
// Transform the object space normals into tangent space
for i:=0 to (LoTexCoords.Count div 3) - 1 do begin
x1:=Round(LoTexCoords[3*i].V[0]*(Width-1));
y1:=Round((1-LoTexCoords[3*i].V[1])*(Height-1));
x2:=Round(LoTexCoords[3*i+1].V[0]*(Width-1));
y2:=Round((1-LoTexCoords[3*i+1].V[1])*(Height-1));
x3:=Round(LoTexCoords[3*i+2].V[0]*(Width-1));
y3:=Round((1-LoTexCoords[3*i+2].V[1])*(Height-1));
m1.V[0]:=Tangents[3*i]; m1.V[1]:=BiNormals[3*i]; m1.V[2]:=LoNormals[3*i];
m2.V[0]:=Tangents[3*i+1]; m2.V[1]:=BiNormals[3*i+1]; m2.V[2]:=LoNormals[3*i+1];
m3.V[0]:=Tangents[3*i+2]; m3.V[1]:=BiNormals[3*i+2]; m3.V[2]:=LoNormals[3*i+2];
TransposeMatrix(m1);
TransposeMatrix(m2);
TransposeMatrix(m3);
InvertMatrix(m1);
InvertMatrix(m2);
InvertMatrix(m3);
if y2<y1 then begin
x:=x1; y:=y1; m:=m1;
x1:=x2; y1:=y2; m1:=m2;
x2:=x; y2:=y; m2:=m;
end;
if y3<y1 then begin
x:=x1; y:=y1; m:=m1;
x1:=x3; y1:=y3; m1:=m3;
x3:=x; y3:=y; m3:=m;
end;
if y3<y2 then begin
x:=x2; y:=y2; m:=m2;
x2:=x3; y2:=y3; m2:=m3;
x3:=x; y3:=y; m3:=m;
end;
if y1<y2 then
for y:=y1 to y2 do begin
xs:=Round(x1+(x2-x1)*((y-y1)/(y2-y1)));
xe:=Round(x1+(x3-x1)*((y-y1)/(y3-y1)));
if xe<xs then begin
x:=xs; xs:=xe; xe:=x;
end;
for x:=xs to xe-1 do begin
n:=NormalToTangentSpace(NormalMap[x+y*Width],x,y,x1,y1,x2,y2,x3,y3,m1,m2,m3);
NormalizeVector(n);
n.V[0]:=-n.V[0];
NormalMap[x+y*Width]:=n;
end;
end;
if y2<y3 then
for y:=y2+1 to y3 do begin
xs:=Round(x2+(x3-x2)*((y-y2)/(y3-y2)));
xe:=Round(x1+(x3-x1)*((y-y1)/(y3-y1)));
if xe<xs then begin
x:=xs; xs:=xe; xe:=x;
end;
for x:=xs to xe-1 do begin
n:=NormalToTangentSpace(NormalMap[x+y*Width],x,y,x1,y1,x2,y2,x3,y3,m1,m2,m3);
NormalizeVector(n);
n.V[0]:=-n.V[0];
NormalMap[x+y*Width]:=n;
end;
end;
end;
// Create the bitmap
Result:=TGLBitmap.Create;
Result.Width:=Width;
Result.Height:=Height;
Result.PixelFormat:=glpf24bit;
// Paint bitmap with normal map normals (X,Y,Z) -> (R,G,B)
for i:=0 to NormalMap.Count-1 do
Result.Canvas.Pixels[i mod Width, i div Height]:=ConvertNormalToColor(NormalMap[i]);
NormalMap.Free;
end;
end.
|
unit PNotes_New_Subform;
{$H+}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, DBTables, Wwtable, wwdblook, Buttons, ToolWin, ComCtrls,
Mask, ExtCtrls, StdCtrls;
type
TNotesEntryDialogForm = class(TForm)
UserTable: TwwTable;
MainToolBar: TToolBar;
SaveButton: TSpeedButton;
CancelButton: TSpeedButton;
EntryInformationGroupBox: TGroupBox;
DateEntered: TEdit;
TimeEntered: TEdit;
EnteredByUserID: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
NoteInformationGroupBox: TGroupBox;
TransactionCode: TwwDBLookupCombo;
NoteTypeCode: TwwDBLookupCombo;
UserResponsible: TwwDBLookupCombo;
Note: TMemo;
DueDate1: TMaskEdit;
NoteOpen: TCheckBox;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
NotesTransactionCodeTable: TTable;
NotesTypeCodeTable: TTable;
MainQuery: TQuery;
ButtonsStateTimer: TTimer;
SaveAndExitButton: TSpeedButton;
DueDate2: TDateTimePicker;
DueDate: TEdit;
procedure EditChange(Sender: TObject);
procedure ButtonsStateTimerTimer(Sender: TObject);
procedure SaveButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure SaveAndExitButtonClick(Sender: TObject);
procedure DueDateExit(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
DataChanged : Boolean;
UnitName, SwisSBLKey, EditMode : String;
NoteNumber : Integer;
Procedure Load;
Function MeetsRequirements : Boolean;
Function Save : Boolean;
Procedure SetReadOnlyFields;
Procedure InitializeForm(_SwisSBLKey : String;
_NoteNumber : Integer;
_EditMode : String);
end;
var
NotesEntryDialogForm: TNotesEntryDialogForm;
implementation
{$R *.DFM}
uses PASUtils, DataAccessUnit, GlblCnst, Utilitys, GlblVars, WinUtils;
const
TicklerNoteType = 'T';
{=========================================================================}
Procedure TNotesEntryDialogForm.Load;
begin
with MainQuery do
try
SQL.Clear;
SQL.Add('Select * from PNotesRec');
SQL.Add('where (SwisSBLKey = ' + FormatSQLString(SwisSBLKey) + ') and');
SQL.Add('(NoteNumber = ' + IntToStr(NoteNumber) + ')');
Open;
except
end;
DatasetLoadToForm(Self, MainQuery);
end; {Load}
{=========================================================================}
Function TNotesEntryDialogForm.MeetsRequirements : Boolean;
begin
Result := True;
If (_Compare(NoteTypeCode.Text, TicklerNoteType, coEqual) and
_Compare(UserResponsible.Text, coBlank))
then
begin
Result := False;
MessageDlg('Please enter the user responsible for this tickler note.', mtError, [mbOK], 0);
UserResponsible.SetFocus;
end;
end; {MeetsRequirements}
{=========================================================================}
Function TNotesEntryDialogForm.Save : Boolean;
begin
Result := False;
If (DataChanged and
MeetsRequirements)
then Result := SQLUpdateFromForm(Self, MainQuery, 'PNotesRec',
'(SwisSBLKey = ' + FormatSQLString(SwisSBLKey) + ') and ' +
'(NoteNumber = ' + IntToStr(NoteNumber) + ')');
DataChanged := False;
end; {Save}
{=========================================================================}
Procedure TNotesEntryDialogForm.EditChange(Sender: TObject);
begin
DataChanged := GetDataChangedStateForComponent(Sender);
If _Compare(TWinControl(Sender).Name, 'NoteTypeCode', coEqual)
then
begin
SetReadOnlyFields;
NoteOpen.Checked := _Compare(NoteTypeCode.Text, TicklerNoteType, coEqual);
end; {If ((Sender is TCustomEdit) and...}
end; {EditChange}
{=========================================================================}
Procedure TNotesEntryDialogForm.ButtonsStateTimerTimer(Sender: TObject);
var
Enabled : Boolean;
begin
Enabled := DataChanged;
SaveButton.Enabled := Enabled;
CancelButton.Enabled := Enabled;
SaveAndExitButton.Enabled := Enabled;
end; {ButtonsStateTimerTimer}
{=========================================================================}
Procedure TNotesEntryDialogForm.SetReadOnlyFields;
var
Enabled : Boolean;
begin
Enabled := _Compare(NoteTypeCode.Text, TicklerNoteType, coEqual);
UserResponsible.Enabled := Enabled;
end; {SetReadOnlyFields}
{=========================================================================}
Procedure TNotesEntryDialogForm.InitializeForm(_SwisSBLKey : String;
_NoteNumber : Integer;
_EditMode : String);
var
ReadOnlyStatus : Boolean;
begin
UnitName := 'PNotes_New_Subform';
NoteNumber := _NoteNumber;
SwisSBLKey := _SwisSBLKey;
Caption := 'Note #' + IntToStr(NoteNumber) +
' for parcel ' + ConvertSwisSBLToDashDot(SwisSBLKey);
_OpenTablesForForm(Self, NoProcessingType, []);
If _Compare(_EditMode, emInsert, coEqual)
then
with MainQuery do
try
SQL.Add('Insert into PNotesRec (SwisSBLKey, DateEntered, TimeEntered, NoteNumber, EnteredByUserID)');
SQL.Add('Values (' + '''' + SwisSBLKey + '''' + ',' +
'''' + DateToStr(Date) + '''' + ',' +
'''' + TimeToStr(Now) + '''' + ',' +
'''' + IntToStr(NoteNumber) + '''' + ',' +
'''' + GlblUserName + '''' + ')');
ExecSQL;
except
end;
Load;
{Don't automatically stop at the open on a new note.}
If _Compare(_EditMode, emInsert, coEqual)
then NoteOpen.TabStop := False;
ReadOnlyStatus := _Compare(_EditMode, emBrowse, coEqual);
{If they are not allowed to modify each others notes and they are not
the supervisor, person responsible, or the person who entered it,
they can't touch it.}
with MainQuery do
If (_Compare(_EditMode, emEdit, coEqual) and
(not GlblModifyOthersNotes) and
_Compare(GlblUserName, 'SUPERVISOR', coNotEqual) and
_Compare(FieldByName('EnteredByUserID').Text, GlblUserName, coNotEqual) and
_Compare(FieldByName('UserResponsible').Text, GlblUserName, coNotEqual))
then ReadOnlyStatus := True;
If ReadOnlyStatus
then SetComponentsToReadOnly(Self)
else SetReadOnlyFields;
{CHG04302003-1(2.07): Allow users to turn Open on and off even
if they are not allowed to modify each other's notes.}
If (_Compare(_EditMode, emEdit, coEqual) and
GlblAnyUserCanChangeOpenNoteStatus)
then NoteOpen.Enabled := True;
DataChanged := False;
ButtonsStateTimer.Enabled := True;
end; {InitializeForm}
{=========================================================================}
Procedure TNotesEntryDialogForm.FormKeyPress( Sender: TObject;
var Key: Char);
begin
If ((Key = #13) and
(not (ActiveControl is TMemo)))
then
begin
Perform(WM_NEXTDLGCTL, 0, 0);
Key := #0;
end;
end; {FormKeyPress}
{=========================================================================}
Procedure TNotesEntryDialogForm.DueDateExit(Sender: TObject);
begin
try
If (_Compare(DueDate.Text, BlankMaskDate, coNotEqual) and
_Compare(DueDate.Text, BlankMaskDateUnderscore, coNotEqual) and
_Compare(DueDate.Text, coNotBlank))
then StrToDate(DueDate.Text);
except
MessageDlg(DueDate.Text + ' is not a valid date.', mtError, [mbOK], 0);
DueDate.SetFocus;
end;
end; {DueDateExit}
{=========================================================================}
Procedure TNotesEntryDialogForm.SaveAndExitButtonClick(Sender: TObject);
begin
If Save
then Close;
end;
{=========================================================================}
Procedure TNotesEntryDialogForm.SaveButtonClick(Sender: TObject);
begin
Save;
end;
{=========================================================================}
Procedure TNotesEntryDialogForm.CancelButtonClick(Sender: TObject);
begin
If DataChanged
then
begin
If (MessageDlg('Do you want to cancel your changes?', mtConfirmation, [mbYes, mbNo], 0) = idYes)
then
begin
DataChanged := False;
ModalResult := mrCancel;
end;
end
else ModalResult := mrCancel;
end; {CancelButtonClick}
{=========================================================================}
Procedure TNotesEntryDialogForm.FormCloseQuery( Sender: TObject;
var CanClose: Boolean);
var
ReturnCode : Integer;
begin
If DataChanged
then
begin
ReturnCode := MessageDlg('Do you want to save your changes?', mtConfirmation, [mbYes, mbNo, mbCancel], 0);
case ReturnCode of
idYes : begin
Save;
ModalResult := mrOK;
end;
idNo : ModalResult := mrCancel;
idCancel : CanClose := False;
end; {case ReturnCode of}
end; {If DataChanged}
end; {FormCloseQuery}
end.
|
unit Form.AuditLogViewer;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Form.BaseForm, dxSkinsCore,
dxSkinMetropolis, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.Menus, cxCheckBox,
Vcl.StdCtrls, cxButtons, Vcl.ExtCtrls, cxTextEdit, cxMemo, System.ImageList,
Vcl.ImgList, cxClasses, dxSkinsForm, System.Generics.Collections,
Aurelius.Mapping.Explorer, Aurelius.Events.Manager;
type
TfrmAuditLogViewer = class(TfrmBase)
mmoLog: TcxMemo;
pnlButton: TPanel;
btnClear: TcxButton;
chkEnableMonitor: TcxCheckBox;
procedure btnClearClick(Sender: TObject);
procedure chkEnableMonitorClick(Sender: TObject);
private
class var
FInstance: TfrmAuditLogViewer;
private
FInsertedProc: TInsertedProc;
FDeletedProc: TDeletedProc;
FUpdatedProc: TUpdatedProc;
FCollectionItemAddedProc: TCollectionItemAddedProc;
FCollectionItemRemovedProc: TCollectionItemRemovedProc;
procedure InsertedHandler(Args: TInsertedArgs);
procedure DeletedHandler(Args: TDeletedArgs);
procedure UpdatedHandler(Args: TUpdatedArgs);
procedure CollectionItemAddedHandler(Args: TCollectionItemAddedArgs);
procedure CollectionItemRemovedHandler(Args: TCollectionItemRemovedArgs);
private
procedure Log(const S: string);
procedure BreakLine;
function EntityDesc(Entity: TObject; Manager: TObject): string;
procedure SubscribeListeners;
procedure UnsubscribeListeners;
public
class function GetInstance: TfrmAuditLogViewer;
constructor Create(AOwner: TComponent); override;
end;
var
frmAuditLogViewer: TfrmAuditLogViewer;
implementation
{$R *.dfm}
uses
Aurelius.Engine.ObjectManager, Aurelius.Global.Utils;
{ TfrmAuditLogViewer }
procedure TfrmAuditLogViewer.BreakLine;
begin
mmoLog.Lines.Add('================================================');
end;
procedure TfrmAuditLogViewer.btnClearClick(Sender: TObject);
begin
mmoLog.Clear;
end;
procedure TfrmAuditLogViewer.chkEnableMonitorClick(Sender: TObject);
begin
if chkEnableMonitor.Checked then
SubscribeListeners
else
UnsubscribeListeners;
end;
procedure TfrmAuditLogViewer.CollectionItemAddedHandler(
Args: TCollectionItemAddedArgs);
begin
Log(Format('Ёлемент коллекции %s добавлен к %s.%s',
[EntityDesc(Args.Item, Args.Manager),
EntityDesc(Args.Parent, Args.Manager),
Args.MemberName]));
end;
procedure TfrmAuditLogViewer.CollectionItemRemovedHandler(
Args: TCollectionItemRemovedArgs);
begin
Log(Format('Ёлемент коллекции %s удален из %s.%s',
[EntityDesc(Args.Item, Args.Manager),
EntityDesc(Args.Parent, Args.Manager),
Args.MemberName]));
end;
constructor TfrmAuditLogViewer.Create(AOwner: TComponent);
begin
inherited;
FInsertedProc := InsertedHandler;
FDeletedProc := DeletedHandler;
FUpdatedProc := UpdatedHandler;
FCollectionItemAddedProc := CollectionItemAddedHandler;
FCollectionItemRemovedProc := CollectionItemRemovedHandler;
SubscribeListeners;
end;
procedure TfrmAuditLogViewer.DeletedHandler(Args: TDeletedArgs);
begin
Log(Format('”даление: %s', [EntityDesc(Args.Entity, Args.Manager)]));
BreakLine;
end;
function TfrmAuditLogViewer.EntityDesc(Entity, Manager: TObject): string;
var
IdValue: Variant;
IdString: string;
begin
IdValue := TObjectManager(Manager).Explorer.GetIdValue(Entity);
IdString := TUtils.VariantToString(IdValue);
Result := Format('%s(%s)', [Entity.ClassName, IdString]);
end;
class function TfrmAuditLogViewer.GetInstance: TfrmAuditLogViewer;
begin
if FInstance = nil then
FInstance := TfrmAuditLogViewer.Create(Application);
Result := FInstance;
end;
procedure TfrmAuditLogViewer.InsertedHandler(Args: TInsertedArgs);
begin
Log(Format('¬ставка: %s', [EntityDesc(Args.Entity, Args.Manager)]));
BreakLine;
end;
procedure TfrmAuditLogViewer.Log(const S: string);
begin
mmoLog.Lines.Add(S);
end;
procedure TfrmAuditLogViewer.SubscribeListeners;
var
E: TManagerEvents;
begin
E := TMappingExplorer.Default.Events;
E.OnInserted.Subscribe(FInsertedProc);
E.OnUpdated.Subscribe(FUpdatedProc);
E.OnDeleted.Subscribe(FDeletedProc);
E.OnCollectionItemAdded.Subscribe(FCollectionItemAddedProc);
E.OnCollectionItemRemoved.Subscribe(FCollectionItemRemovedProc);
end;
procedure TfrmAuditLogViewer.UnsubscribeListeners;
var
E: TManagerEvents;
begin
E := TMappingExplorer.Default.Events;
E.OnInserted.Unsubscribe(FInsertedProc);
E.OnUpdated.Unsubscribe(FUpdatedProc);
E.OnDeleted.Unsubscribe(FDeletedProc);
E.OnCollectionItemAdded.Unsubscribe(FCollectionItemAddedProc);
E.OnCollectionItemRemoved.Unsubscribe(FCollectionItemRemovedProc);
end;
procedure TfrmAuditLogViewer.UpdatedHandler(Args: TUpdatedArgs);
var
Pair: TPair<string, Variant>;
OldValue: Variant;
begin
Log(Format('ќбновлено: %s', [EntityDesc(Args.Entity, Args.Manager)]));
for Pair in Args.NewColumnValues do
if not (Args.OldColumnValues.TryGetValue(Pair.Key, OldValue) and (OldValue = Pair.Value)) then
Log(Format(' %s Changed from "%s" to "%s"',
[Pair.Key, TUtils.VariantToString(OldValue), TUtils.VariantToString(Pair.Value)]));
BreakLine;
end;
end.
|
unit UFrmVisorPdf;
interface
uses
Windows,Messages, SysUtils, Variants, Classes,Graphics,
Controls, Forms, Dialogs, ExtCtrls,StdCtrls, AdvGroupBox,
cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, dxSkinsCore,
dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee,
dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle,
dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast,
dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky,
dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue,
dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver,
dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver,
dxSkinOffice2013White, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic,
dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust,
dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, cxButtons,
dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue,
DebenuPDFLibrary, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit,
cxDropDownEdit,UFunctionsGHH, dxSkinMetropolis, dxSkinMetropolisDark,
dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray;
type
TFrmVisorPdf = class(TForm)
AdvGroupBox1: TAdvGroupBox;
Panel1: TPanel;
PreviewScrollBox: TScrollBox;
imgPreview: TImage;
Panel2: TPanel;
CxBtnCargar: TcxButton;
CxBtnGuardar: TcxButton;
CxBtnLimpiar: TcxButton;
CxBtnAceptar: TcxButton;
CxBtnCancelar: TcxButton;
Archivo: TFileOpenDialog;
Panel3: TPanel;
cmbZoom: TcxComboBox;
btnViewPrintPrevPage: TcxButton;
btnViewPrintNextPage: TcxButton;
FGuardarArchivo: TFileSaveDialog;
procedure FormShow(Sender: TObject);
procedure CxBtnCargarClick(Sender: TObject);
procedure btnViewPrintPrevPageClick(Sender: TObject);
procedure btnViewPrintNextPageClick(Sender: TObject);
procedure cmbZoomPropertiesChange(Sender: TObject);
procedure CxBtnLimpiarClick(Sender: TObject);
procedure CxBtnAceptarClick(Sender: TObject);
procedure CxBtnGuardarClick(Sender: TObject);
procedure FGuardarArchivoTypeChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
ViewPrintQP: TDebenuPDFLibrary;
ViewPrintPageNum: Integer;
procedure RenderPage;
Procedure LoadFilePdf(sFile:TFilename;var ViewPrintParam:TDebenuPDFLibrary);
Procedure LoadFileJPEG(sFile:TFilename);
Procedure LoadFileJPEGPdf(sFile:TFilename;var ViewPrintParam:TDebenuPDFLibrary);
public
{ Public declarations }
Mode:vsMode;
TipoFile:smFile;
PDFStream:Tstream;
FileName:TFileName;
sNameFile:String;
end;
var
FrmVisorPdf: TFrmVisorPdf;
implementation
{$R *.dfm}
Procedure TFrmVisorPdf.LoadFileJPEGPdf(sFile:TFilename;var ViewPrintParam:TDebenuPDFLibrary);
var
Password: string;
R: Integer;
CanProceed: Boolean;
BlankBM: TBitmap;
lWidth :Integer;
lHeight:Integer;
begin
// ViewPrintParam.addi
CanProceed:=false;
if FileExists(sFile) then
begin
ViewPrintParam := TDebenuPDFLibrary.Create;
if ViewPrintParam.UnlockKey('jt3m77ty7ph97a6bp8t54f35y') = 1 then
begin
try
ViewPrintParam.AddImageFromFile(CompressImage(sFile,80),0);
lWidth := ViewPrintParam.ImageWidth();
lHeight := ViewPrintParam.ImageHeight();
ViewPrintParam.SetPageDimensions(lWidth, lHeight);
ViewPrintParam.DrawImage(0, lHeight, lWidth, lHeight);
CanProceed := True;
except
MessageDlg('El Archivo PDF no puede leerse.', mtError, [mbOK], 0);
end;
end
else
MessageDlg('La licencia es Incorrecta o a Expirado.', mtError, [mbOK], 0);
end;
if CanProceed then
begin
ViewPrintPageNum := 1;
RenderPage;
end
else
begin
BlankBM := TBitmap.Create;
try
imgPreview.Picture.Assign(BlankBM);
finally
BlankBM.Free;
end;
ViewPrintQP.Free;
ViewPrintQP := nil;
end;
end;
Procedure TFrmVisorPdf.LoadFilePdf(sFile:TFilename;var ViewPrintParam:TDebenuPDFLibrary);
var
Password: string;
R: Integer;
CanProceed: Boolean;
BlankBM: TBitmap;
begin
CanProceed:=false;
if FileExists(sFile) then
begin
ViewPrintParam := TDebenuPDFLibrary.Create;
if ViewPrintParam.UnlockKey('jt3m77ty7ph97a6bp8t54f35y') = 1 then
begin
if ViewPrintParam.LoadFromFile(sFile, '') = 1 then
begin
CanProceed := True;
end
else
MessageDlg('El Archivo PDF no puede leerse.', mtError, [mbOK], 0);
end
else
MessageDlg('La licencia es Incorrecta o a Expirado.', mtError, [mbOK], 0);
end;
if CanProceed then
begin
ViewPrintPageNum := 1;
RenderPage;
end
else
begin
BlankBM := TBitmap.Create;
try
imgPreview.Picture.Assign(BlankBM);
finally
BlankBM.Free;
end;
ViewPrintQP.Free;
ViewPrintQP := nil;
end;
end;
Procedure TFrmVisorPdf.LoadFileJPEG(sFile:TFilename);
var
Password: string;
R: Integer;
BlankBM: TBitmap;
begin
if FileExists(sFile) then
begin
try
imgPreview.Picture.LoadFromFile(CompressImage(sFile,80));
imgPreview.AutoSize:=true;
Except
MessageDlg('El Archivo JPEG no puede leerse.', mtError, [mbOK], 0);
end;
//ViewPrintQP.Free;
//ViewPrintQP := nil;
end
else
begin
BlankBM := TBitmap.Create;
try
imgPreview.Picture.Assign(BlankBM);
finally
BlankBM.Free;
end;
end;
end;
procedure TFrmVisorPdf.RenderPage;
var
BM: TBitmap;
MS: TMemoryStream;
DPI: Integer;
begin
BM := TBitmap.Create;
try
imgPreview.Picture.Assign(BM);
PreviewScrollBox.HorzScrollBar.Position := 0;
PreviewScrollBox.VertScrollBar.Position := 0;
imgPreview.Left := 0;
imgPreview.Top := 0;
finally
BM.Free;
end;
if Assigned(ViewPrintQP) then
begin
MS := TMemoryStream.Create;
try
DPI := ((cmbZoom.ItemIndex + 1) * 25 * 96) div 100;
ViewPrintQP.RenderPageToStream(DPI, ViewPrintPageNum, 0, MS);
MS.Seek(0, soFromBeginning);
BM := TBitmap.Create;
try
BM.LoadFromStream(MS);
imgPreview.AutoSize := True;
imgPreview.Picture.Assign(BM);
finally
BM.Free;
end;
finally
MS.Free;
end;
end;
end;
procedure TFrmVisorPdf.btnViewPrintNextPageClick(Sender: TObject);
begin
if Assigned(ViewPrintQP) then
begin
if ViewPrintPageNum < ViewPrintQP.PageCount then
begin
Inc(ViewPrintPageNum);
RenderPage;
end;
end;
end;
procedure TFrmVisorPdf.btnViewPrintPrevPageClick(Sender: TObject);
begin
if ViewPrintPageNum > 1 then
begin
Dec(ViewPrintPageNum);
RenderPage;
end;
end;
procedure TFrmVisorPdf.cmbZoomPropertiesChange(Sender: TObject);
begin
RenderPage;
end;
procedure TFrmVisorPdf.CxBtnAceptarClick(Sender: TObject);
begin
if ViewPrintQP<>nil then
begin
ViewPrintQP.SaveToStream(PDFStream);
end;
end;
procedure TFrmVisorPdf.CxBtnCargarClick(Sender: TObject);
var
BlankBM: TBitmap;
begin
if TipoFile=smPDF then
begin
if Assigned(ViewPrintQP) then
begin
ViewPrintQP.Free;
ViewPrintQP := nil;
end;
if Archivo.Execute then
begin
LoadFilePdf(Archivo.filename,ViewPrintQP);
FileName:=Archivo.filename;
end
else
begin
BlankBM := TBitmap.Create;
try
imgPreview.Picture.Assign(BlankBM);
finally
BlankBM.Free;
end;
ViewPrintQP.Free;
ViewPrintQP := nil;
end;
end;
if TipoFile=smJPEG then
begin
if Archivo.Execute then
begin
//LoadFileJPEG(Archivo.filename);
LoadFileJPEGPdf(Archivo.filename,ViewPrintQP);
FileName:=Archivo.filename;
end
else
begin
BlankBM := TBitmap.Create;
try
imgPreview.Picture.Assign(BlankBM);
finally
BlankBM.Free;
end;
// ViewPrintQP.Free;
// ViewPrintQP := nil;
end;
end;
end;
procedure TFrmVisorPdf.CxBtnGuardarClick(Sender: TObject);
begin
if sNameFile<>'' then
FGuardarArchivo.FileName:=sNameFile;
if FGuardarArchivo.Execute then
begin
if TipoFile=smPdf then
ViewPrintQP.SaveToFile(FGuardarArchivo.FileName);
if TipoFile=smJPeg then
ViewPrintQP.RenderDocumentToFile(72, 1, 1, 0,FGuardarArchivo.FileName);
// ViewPrintQP.SaveImageToFile(FGuardarArchivo.FileName);
end;
end;
procedure TFrmVisorPdf.CxBtnLimpiarClick(Sender: TObject);
var
BlankBM: TBitmap;
begin
BlankBM := TBitmap.Create;
try
imgPreview.Picture.Assign(BlankBM);
finally
BlankBM.Free;
end;
ViewPrintQP.Free;
ViewPrintQP := nil;
end;
procedure TFrmVisorPdf.FGuardarArchivoTypeChange(Sender: TObject);
begin
if TipoFile=smPdf then
begin
case FGuardarArchivo.FileTypeIndex of
1 : FGuardarArchivo.DefaultExtension := 'pdf';
else
FGuardarArchivo.DefaultExtension := '';
end;
end;
if TipoFile=smJPeg then
begin
case FGuardarArchivo.FileTypeIndex of
1 : FGuardarArchivo.DefaultExtension := 'jpg';
else
FGuardarArchivo.DefaultExtension := '';
end;
end;
end;
procedure TFrmVisorPdf.FormCreate(Sender: TObject);
begin
PDFStream:=TMemoryStream .Create;
end;
procedure TFrmVisorPdf.FormShow(Sender: TObject);
begin
cmbZoom.ItemIndex := 1;
Archivo.FileTypes.Clear;
FGuardarArchivo.FileTypes.clear;
if TipoFile=smPdf then
begin
with Archivo.FileTypes.Add do
begin
DisPlayName:='Archivo PDF';
FileMask:='*.PDF';
end;
with FGuardarArchivo.FileTypes.add do
begin
DisPlayName:='Archivo PDF';
FileMask:='*.PDF';
end;
end;
if TipoFile=smJPeg then
begin
with Archivo.FileTypes.Add do
begin
DisPlayName:='Archivo JPEG';
FileMask:='*.jpg';
end;
with FGuardarArchivo.FileTypes.add do
begin
DisPlayName:='Archivo JPEG';
FileMask:='*.jpg';
end;
end;
FGuardarArchivoTypeChange(Sender);
if (Mode=vsLectura) or (Mode=vsEdicion) then
begin
if (Mode=vsLectura) then
begin
Panel1.Visible:=false;
CxBtnCargar.Enabled:=false;
CxBtnLimpiar.Enabled:=false;
end;
if TipoFile=smPdf then
LoadFilePdf(FileName,ViewPrintQP);
if TipoFile=smJPeg then
begin
LoadFileJpegPdf(FileName,ViewPrintQP);
//ViewPrintQP
end;
end;
if Mode=vsInsercion then
begin
CxBtnGuardar.Enabled:=false;
CxBtnLimpiar.Enabled:=false;
end;
end;
end.
|
unit GrievanceAddDialogUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, wwdblook, Db, DBTables, ExtCtrls;
type
TGrievanceAddDialog = class(TForm)
OKButton: TBitBtn;
CancelButton: TBitBtn;
LawyerCodeTable: TTable;
RepresentativeGroupBox: TGroupBox;
Label2: TLabel;
LawyerCodeLookupCombo: TwwDBLookupCombo;
Label1: TLabel;
GrievanceNumberGroupBox: TGroupBox;
Label3: TLabel;
Label4: TLabel;
GrievanceTable: TTable;
EditGrievanceNumber: TEdit;
GrievanceYearGroupBox: TGroupBox;
Label5: TLabel;
Label6: TLabel;
EditGrievanceYear: TEdit;
NewLawyerButton: TBitBtn;
procedure OKButtonClick(Sender: TObject);
procedure LawyerCodeLookupComboNotInList(Sender: TObject;
LookupTable: TDataSet; NewValue: String; var Accept: Boolean);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure NewLawyerButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
LawyerCode : String;
AssessmentYear : String;
GrievanceNumber : LongInt;
end;
var
GrievanceAddDialog: TGrievanceAddDialog;
implementation
{$R *.DFM}
uses GrievanceDuplicatesDialogUnit, WinUtils, NewLawyerDialog;
{===============================================================}
Procedure TGrievanceAddDialog.FormShow(Sender: TObject);
begin
try
LawyerCodeTable.Open;
except
MessageDlg('Error opening lawyer code table.', mtError, [mbOK], 0);
end;
try
GrievanceTable.Open;
except
MessageDlg('Error opening grievance table.', mtError, [mbOK], 0);
end;
EditGrievanceNumber.Text := IntToStr(GrievanceNumber);
EditGrievanceYear.Text := AssessmentYear;
end; {FormShow}
{===============================================================}
Procedure TGrievanceAddDialog.OKButtonClick(Sender: TObject);
var
Continue : Boolean;
begin
Continue := True;
LawyerCode := LawyerCodeLookupCombo.Text;
AssessmentYear := EditGrievanceYear.Text;
try
GrievanceNumber := StrToInt(EditGrievanceNumber.Text);
except
Continue := False;
MessageDlg('Sorry, ' + EditGrievanceNumber.Text + ' is not a valid grievance number.' + #13 +
'Please correct it.', mtError, [mbOK], 0);
EditGrievanceNumber.SetFocus;
end;
{See if there are other parcels already with this grievance number.
If so, warn them, but let them continue.}
If Continue
then
begin
SetRangeOld(GrievanceTable, ['TaxRollYr', 'GrievanceNumber'],
[AssessmentYear, IntToStr(GrievanceNumber)],
[AssessmentYear, IntToStr(GrievanceNumber)]);
GrievanceTable.First;
If not GrievanceTable.EOF
then
try
GrievanceDuplicatesDialog := TGrievanceDuplicatesDialog.Create(nil);
GrievanceDuplicatesDialog.GrievanceNumber := GrievanceNumber;
GrievanceDuplicatesDialog.AssessmentYear := AssessmentYear;
GrievanceDuplicatesDialog.AskForConfirmation := True;
If (GrievanceDuplicatesDialog.ShowModal = idNo)
then Continue := False;
finally
GrievanceDuplicatesDialog.Free;
end;
end; {If Continue}
If Continue
then ModalResult := mrOK;
end; {OKButtonClick}
{===============================================================}
Procedure TGrievanceAddDialog.NewLawyerButtonClick(Sender: TObject);
{CHG01262004-1(2.07l1): Let them create a new representative right from the add screen.}
begin
try
NewLawyerForm := TNewLawyerForm.Create(nil);
NewLawyerForm.InitializeForm;
If (NewLawyerForm.ShowModal = idOK)
then
begin
LawyerCodeLookupCombo.Text := NewLawyerForm.LawyerSelected;
FindKeyOld(LawyerCodeTable, ['Code'], [NewLawyerForm.LawyerSelected]);
end;
finally
NewLawyerForm.Free;
end;
end; {NewLawyerButtonClick}
{===============================================================}
Procedure TGrievanceAddDialog.LawyerCodeLookupComboNotInList( Sender: TObject;
LookupTable: TDataSet;
NewValue: String;
var Accept: Boolean);
begin
If (NewValue = '')
then Accept := True;
end; {LawyerCodeLookupComboNotInList}
{======================================================}
Procedure TGrievanceAddDialog.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
GrievanceTable.Close;
Action := caFree;
end;
end.
|
unit uMulticastStreamAnalyzer;
interface
uses
System.Classes, IdBaseComponent, IdComponent, IdIPMCastBase, IdIPMCastClient,
System.SysUtils, System.IniFiles, System.Contnrs, Windows, System.SyncObjs,
IdGlobal, IdSocketHandle, USLogger;
const
MPEGTS_NULLPID = $1FFF;
type
TPacketInfo = record
PID: uint16;
Counter: uint8;
Microtime: int64;
isOnlyAdaptation: boolean;
hasError: boolean;
end;
TStreamInfo = class(TObject)
m_uPID: uint16;
m_bHaveError: boolean;
m_bCanHaveError: boolean;
m_rLastPacket: TPacketInfo;
m_uiPacketsCount: uint64;
m_uiErrorsCount: uint64;
public
constructor Create(PID: uint16);
end;
TMulticastStreamAnalyzer = class(TThread)
protected
m_sMulticastGroup: string;
m_uiMulticastPort: uint16;
m_sBindingIP: string;
m_uiPossibleErrors: uint8;
m_uiExtendedCounter: uint32;
m_iPerformanceFreq: int64;
m_oMulticastClient: TIdIPMCastClient;
procedure Execute; override;
procedure MulticastClientRead(Sender: TObject; const AData: TArray<System.Byte>; ABinding: TIdSocketHandle);
procedure MulticastClientStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string);
procedure Log(LogLevel: TLogLevel; Mess: string);
function ParseMPEGTSPacket(var Packet: TArray<System.Byte>): TPacketInfo;
procedure ProcessMPEGTSPacket(PacketInfo: TPacketInfo);
procedure UpdateMPEGTSStreamInfo(PacketInfo: TPacketInfo);
public
m_slStreamsInfo: TStringList;
m_oCriticalSection: TCriticalSection;
constructor Create(MulticastGroup: string; MulticastPort: uint16; BindingIP: string = '');
destructor Destroy; override;
end;
implementation
uses
uwMain;
{ StreamInfo }
function PrintPacketError(PID: uint16; Counter: uint8): string;
begin
Result := 'PID: #' + IntToHex(PID, 4) + '; Counter: ' + UIntToStr(Counter) + '.';
end;
constructor TStreamInfo.Create(PID: uint16);
begin
m_uPID := PID;
m_bHaveError := false;
m_bCanHaveError := false;
m_uiPacketsCount := 0;
m_uiErrorsCount := 0;
m_rLastPacket.PID := MPEGTS_NULLPID;
m_rLastPacket.Counter := 0;
m_rLastPacket.Microtime := 0;
end;
{ MulticastStreamAnalyzer }
constructor TMulticastStreamAnalyzer.Create(MulticastGroup: string; MulticastPort: uint16; BindingIP: string = '');
begin
inherited Create;
m_uiPossibleErrors := 0;
m_uiExtendedCounter := 0;
m_sMulticastGroup := MulticastGroup;
m_uiMulticastPort := MulticastPort;
m_sBindingIP := BindingIP;
if (not QueryPerformanceFrequency(m_iPerformanceFreq)) then
Log(llError, 'Error while getting frequency information, timing may be wrong');
m_slStreamsInfo := TStringList.Create;
m_slStreamsInfo.Duplicates := dupError;
m_slStreamsInfo.Sorted := true;
m_slStreamsInfo.OwnsObjects := true;
m_oCriticalSection := TCriticalSection.Create;
m_oMulticastClient := TIdIPMCastClient.Create(nil);
end;
destructor TMulticastStreamAnalyzer.Destroy;
begin
if (Assigned(m_oMulticastClient)) then begin
m_oMulticastClient.Active := false;
FreeAndNil(m_oMulticastClient);
end;
FreeAndNil(m_slStreamsInfo);
FreeAndNil(m_oCriticalSection);
Log(llDebug, 'Multicast Watcher stopped');
inherited Destroy;
end;
procedure TMulticastStreamAnalyzer.Execute;
begin
NameThreadForDebugging('MulticastStreamAnalyzer');
m_oMulticastClient.OnIPMCastRead := MulticastClientRead;
if m_sBindingIP <> '' then begin
with m_oMulticastClient.Bindings.Add do
IP := m_sBindingIP;
end;
m_oMulticastClient.MulticastGroup := m_sMulticastGroup;
m_oMulticastClient.DefaultPort := m_uiMulticastPort;
m_oMulticastClient.ReuseSocket := rsTrue;
m_oMulticastClient.ThreadedEvent := true;
m_oMulticastClient.BufferSize := 8196 * 4;
try
m_oMulticastClient.Active := true;
except
on E: Exception do
Log(llDebug, 'Socket Critical Error. ' + E.Message);
end;
Log(llDebug, 'Multicast Watcher for group ' + m_sMulticastGroup + ' started.');
end;
procedure TMulticastStreamAnalyzer.MulticastClientRead(Sender: TObject; const AData: TArray<System.Byte>; ABinding: TIdSocketHandle);
const
EXT_OFFSET = 188 * 7;
var
Packet: TArray<System.Byte>;
PacketInfo: TPacketInfo;
i, j: int32;
ExtendedCounter: UInt32;
begin
ExtendedCounter := 0;
if not WMain.cbExtendedMode.Checked and (Length(AData) <> 1316) then
Log(llDebug, 'Unknown network frame size: ' + UIntToStr(Length(AData)))
else if WMain.cbExtendedMode.Checked and (Length(AData) <> EXT_OFFSET + 4) then
Log(llDebug, 'Unknown network frame size (enabled extended mode): ' + UIntToStr(Length(AData)))
else if WMain.cbExtendedMode.Checked and (Length(AData) = EXT_OFFSET + 4) then begin
ExtendedCounter := AData[EXT_OFFSET+3] + (AData[EXT_OFFSET+2] shl 8) + (AData[EXT_OFFSET+1] shl 16) + (AData[EXT_OFFSET] shl 24);
if (m_uiExtendedCounter <> 0) then
if (m_uiExtendedCounter >= ExtendedCounter) then
Log(llDebug, 'Extended counter has been resetted')
else if (m_uiExtendedCounter + 1 <> ExtendedCounter) then
Log(llDebug, 'Error detected based on extended counter. Skipped frames: ' + IntToStr(ExtendedCounter - m_uiExtendedCounter - 1));
// TODO: show frame hash
m_uiExtendedCounter := ExtendedCounter
end;
i := 0;
j := i + 188;
while (j <= Length(AData)) do begin
Packet := Copy(AData, i, j + 1);
PacketInfo := ParseMPEGTSPacket(Packet);
if (PacketInfo.PID <> MPEGTS_NULLPID) then begin
ProcessMPEGTSPacket(PacketInfo);
UpdateMPEGTSStreamInfo(PacketInfo);
end;
i := j;
j := i + 188;
end;
end;
procedure TMulticastStreamAnalyzer.MulticastClientStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string);
begin
//
end;
procedure TMulticastStreamAnalyzer.Log(LogLevel: TLogLevel; Mess: string);
begin
Queue(
procedure
begin
WMain.Log(LogLevel, Mess);
end
);
end;
function TMulticastStreamAnalyzer.ParseMPEGTSPacket(var Packet: TArray<System.Byte>): TPacketInfo;
var
PacketInfo: TPacketInfo;
begin
// Default
PacketInfo.PID := MPEGTS_NULLPID;
PacketInfo.hasError := false;
PacketInfo.isOnlyAdaptation := false;
// Check for packet length
if (Length(Packet) < 188) then begin
//Log(llDebug, 'Packet has wrong length');
Exit;
end;
// Check for "MPEGTS" Mark
if (Packet[0] <> $47) then begin
//Log(llDebug, 'Packet has no MPEGTS mark');
Exit;
end;
// Check for "Transport Error Flag"
if ((Packet[1] and $80) <> 0) then begin
PacketInfo.hasError := true;
Log(llDebug, 'Transport error flag is set');
end;
// Check for "Payload Unit Start Indicator"
if ((Packet[1] and $40) <> 0) then begin
//Log(llDebug, 'payload_unit_start_indicator flag is set');
end;
// Check for "Transport Priority flag"
if ((Packet[1] and $20) <> 0) then begin
//Log(llDebug, 'transport priority flag is set');
end;
// Check for adaptation field
if (((Packet[3] and $30) shr 4) = $02) then begin
PacketInfo.isOnlyAdaptation := true;
//Log(llDebug, 'Packet with adaptation field: ' + IntToStr((Packet[3] and $30) shr 4));
end;
// PID
PacketInfo.PID := ((Packet[1] and $1F) shl 8) + Packet[2];
// Counter
PacketInfo.Counter := Packet[3] and $0F;
// Time
QueryPerformanceCounter(PacketInfo.Microtime);
Result := PacketInfo;
end;
procedure TMulticastStreamAnalyzer.ProcessMPEGTSPacket(PacketInfo: TPacketInfo);
begin
//
end;
procedure TMulticastStreamAnalyzer.UpdateMPEGTSStreamInfo(PacketInfo: TPacketInfo);
var
StreamInfo: TStreamInfo;
CanBeError: Boolean;
Index, I: Integer;
PresumablyErrorsCount: uint8;
begin
m_oCriticalSection.Enter;
Index := m_slStreamsInfo.IndexOf(IntToHex(PacketInfo.PID, 4));
if (Index = -1) then
Index := m_slStreamsInfo.AddObject(IntToHex(PacketInfo.PID, 4), TStreamInfo.Create(PacketInfo.PID));
StreamInfo := m_slStreamsInfo.Objects[Index] as TStreamInfo;
Inc(StreamInfo.m_uiPacketsCount);
if (PacketInfo.hasError) then begin
Inc(StreamInfo.m_uiErrorsCount);
Log(llWarning, 'Network Error. Packet with PID = #' + IntToHex(PacketInfo.PID, 4) + ' has error flag.');
end;
// Если пакет уже помечен, как имеющий ошибку - сбрасываем флаг и пропускаем его
if (StreamInfo.m_bHaveError) then begin
StreamInfo.m_bHaveError := false;
StreamInfo.m_bCanHaveError := false;
//Log(llDebug, '1: ' + PrintPacketError(PacketInfo.PID, PacketInfo.Counter));
end
else
// Обработка всех остальных пакетов
if ((StreamInfo.m_rLastPacket.PID <> MPEGTS_NULLPID) and (not PacketInfo.isOnlyAdaptation)) then begin
if not (((StreamInfo.m_rLastPacket.Counter + 1) = PacketInfo.Counter)
or (StreamInfo.m_rLastPacket.Counter = PacketInfo.Counter) // HACK! TODO: fix this for adopt-only packets
or (StreamInfo.m_rLastPacket.Counter = (PacketInfo.Counter + $0F))) then begin
// Находим предположительное количество ошибок от предыдущего пакета до текущего
if (StreamInfo.m_rLastPacket.Counter < PacketInfo.Counter) then
PresumablyErrorsCount := PacketInfo.Counter - (StreamInfo.m_rLastPacket.Counter + 1)
else
PresumablyErrorsCount := (PacketInfo.Counter + $0F) - StreamInfo.m_rLastPacket.Counter;
// Если ошибок более 7 - был потерян не один пакет. Точнее сказать невозможно.
if (PresumablyErrorsCount > 7) then
begin
// Считаем как 2 ошибки
Inc(StreamInfo.m_uiErrorsCount, 2);
// Маркируем все потоки для пропуска следующего пакета без ошибок
for I := 0 to m_slStreamsInfo.Count - 1 do
(m_slStreamsInfo.Objects[I] as TStreamInfo).m_bHaveError := true;
// Пишем в лог
Log(llWarning, 'Packet sequence error. More than one packet with PID = #' + IntToHex(PacketInfo.PID, 4) + ' has wrong counter: ' + UIntToStr(PacketInfo.Counter) + ', must be: ' + UIntToStr(StreamInfo.m_rLastPacket.Counter + 1));
end
else
// Если ошибок менее чем возможных ошибок потока - относим к уже обработанной ошибке
if (m_uiPossibleErrors >= PresumablyErrorsCount) then begin
// Уменьшаем количество возможных ошибок на количество предположительных ошибок
m_uiPossibleErrors := m_uiPossibleErrors - PresumablyErrorsCount;
// Помечаем данный поток как не имеющий ошибок
StreamInfo.m_bCanHaveError := false;
end
else
// Иначе - считаем необработанной ошибкой
begin
// Считаем ошибку
Inc(StreamInfo.m_uiErrorsCount);
// Выставляем количество возможных ошибок
m_uiPossibleErrors := 7 - PresumablyErrorsCount;
// Помечаем все потоки, кроме текущего, как возможно имеющие ошибки
for I := 0 to m_slStreamsInfo.Count - 1 do
if ((m_slStreamsInfo.Objects[I] as TStreamInfo).m_uPID <> PacketInfo.PID) then
(m_slStreamsInfo.Objects[I] as TStreamInfo).m_bCanHaveError := true;
// Пишем в лог
//Log(llDebug, 'Possible errors: ' + UIntToStr(m_uiPossibleErrors) + '; Pres. Errors: ' + UIntToStr(PresumablyErrorsCount));
Log(llWarning, 'Packet Error. Packet with PID = #' + IntToHex(PacketInfo.PID, 4) + ' has wrong counter: ' + UIntToStr(PacketInfo.Counter) + ', must be: ' + UIntToStr(StreamInfo.m_rLastPacket.Counter + 1));
end;
//Log(llDebug, 'Possible Errors Counter: ' + UIntToStr(m_uiPossibleErrors));
end
// Иначе - очищаем флаг возможных ошибок, пакет правильный
else
StreamInfo.m_bCanHaveError := false;
end;
// Если ни один поток не помечен, как возможно имеющий ошибку - очищаем счетчик возможных ошибок
if (m_uiPossibleErrors > 0) then begin
CanBeError := false;
for I := 0 to m_slStreamsInfo.Count - 1 do
if ((m_slStreamsInfo.Objects[I] as TStreamInfo).m_bCanHaveError) then begin
CanBeError := true;
//Log(llDebug, 'Stream with PID ' + IntToHex((m_slStreamsInfo.Objects[I] as TStreamInfo).m_uPID, 4) + ' can be with err');
end;
if (not CanBeError) then begin
m_uiPossibleErrors := 0;
//Log(llDebug, 'All streams clear');
end;
end
else
// Если мы уже нашли все возможные ошибки - очищаем флаги возможностей ошибок в потоках
if (m_uiPossibleErrors = 0) then begin
for I := 0 to m_slStreamsInfo.Count - 1 do
(m_slStreamsInfo.Objects[I] as TStreamInfo).m_bCanHaveError := false;
end;
StreamInfo.m_rLastPacket := PacketInfo;
m_oCriticalSection.Leave;
end;
end.
|
Unit WebPanel;
{$MODE objfpc}{$H+}
Interface
Uses
Classes, SysUtils, Controls, ComCtrls, FileUtil, Forms, LCLProc, Graphics, strutils, LazFileUtils,
cef3types, cef3lib, cef3intf, cef3own, cef3lcl,
FaviconGetter;
Type
TWebPanel = class(TTabSheet)
private
fChromium: TChromium;
fUrl: String;
fIconGetter: TFaviconGetter;
procedure ChromiumTitleChange(Sender: TObject; const Browser: ICefBrowser; const title: ustring);
procedure ChromiumAddressChange(Sender: TObject; const Browser: ICefBrowser;
const Frame: ICefFrame; const url: ustring);
procedure ChromiumFaviconUrlchange(Sender: TObject; const Browser: ICefBrowser; iconUrls: TStrings);
procedure ChromiumOpenUrlFromTab(Sender: TObject; browser: ICefBrowser; frame: ICefFrame;
const targetUrl: ustring; targetDisposition: TCefWindowOpenDisposition; useGesture: Boolean;
out Result: Boolean);
procedure ChromiumBeforePopup(Sender: TObject; const browser: ICefBrowser;
const frame: ICefFrame; const targetUrl, targetFrameName: ustring;
targetDisposition: TCefWindowOpenDisposition; userGesture: Boolean;
var popupFeatures: TCefPopupFeatures; var windowInfo: TCefWindowInfo; var client: ICefClient;
var settings: TCefBrowserSettings; var noJavascriptAccess: Boolean; out Result: Boolean);
procedure ChromiumBeforeContextMenu(Sender: TObject; const Browser: ICefBrowser;
const Frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel);
procedure ChromiumContextMenuCommand(Sender: TObject; const Browser: ICefBrowser;
const Frame: ICefFrame; const params: ICefContextMenuParams; commandId: Integer;
eventFlags: TCefEventFlags; out Result: Boolean);
procedure IconReady(const Success: Boolean; const Icon: TIcon);
protected
procedure DoHide; override;
procedure DoShow; override;
public
destructor Destroy; override;
procedure InitializeChromium;
procedure RequestClose;
procedure OpenUrl(AUrl: String);
procedure SetIcon(const Icon: TCustomIcon);
property Url: String read fUrl write fUrl;
end;
Implementation
Uses cef3ref, Main;
Type
TClientMenuIDs = (
CLIENT_ID_VISIT_COOKIES = Ord(MENU_ID_USER_FIRST),
CLIENT_ID_EXIT
);
TCefNewTabTask = class(TCefTaskOwn)
protected
fTargetUrl: ustring;
procedure Execute; override;
public
constructor Create(targetURL: ustring);
end;
Var Path: ustring;
function VisitCookies(const cookie: TCefCookie; count, total: Integer;
out deleteCookie: Boolean): Boolean;
Var
tmp: TCefString;
begin
Write(count, '/', total, ': ');
tmp := cookie.path;
Write(CefString(@tmp), ' ');
tmp := cookie.name;
Write(CefString(@tmp), ' ');
tmp := cookie.domain;
Write(CefString(@tmp), ' ');
WriteLn(DateTimeToStr(CefTimeToDateTime(cookie.expires)));
deleteCookie := False;
Result := True;
end;
{ TCefNewTabTask }
procedure TCefNewTabTask.Execute;
begin
Assert(CefCurrentlyOn(TID_UI));
FMain.NewTab(UTF8Encode(fTargetUrl));
end;
constructor TCefNewTabTask.Create(targetURL: ustring);
begin
inherited Create;
fTargetUrl := targetURL;
end;
{ TWebPanel }
procedure TWebPanel.ChromiumTitleChange(Sender: TObject; const Browser: ICefBrowser;
const title: ustring);
Var
NewTitle: String;
begin
NewTitle := UTF8Encode(title);
If UTF8Length(NewTitle) < 15 then Caption := NewTitle
Else Caption := UTF8Copy(NewTitle, 1, 12) + '...';
end;
procedure TWebPanel.ChromiumAddressChange(Sender: TObject; const Browser: ICefBrowser;
const Frame: ICefFrame; const url: ustring);
begin
Assert(CefCurrentlyOn(TID_UI));
If frame.IsMain then
begin
fUrl := UTF8Encode(Browser.MainFrame.Url);
If PageControl.ActivePage = Self then FMain.EUrl.Text := fUrl;
end;
end;
procedure TWebPanel.ChromiumFaviconUrlchange(Sender: TObject; const Browser: ICefBrowser;
iconUrls: TStrings);
Var
i: Integer;
begin
// For simplicity just use the first .ico image
For i := 0 to iconUrls.Count - 1 do
If AnsiEndsText('ico', iconUrls[i]) then
begin
// make sure there is only one
If Assigned(fIconGetter) then fIconGetter.Cancel;
fIconGetter := TFaviconGetter.Create(iconUrls[i], @IconReady);
Exit;
end;
// No suitabe icon found
SetIcon(nil);
end;
procedure TWebPanel.ChromiumBeforePopup(Sender: TObject; const browser: ICefBrowser;
const frame: ICefFrame; const targetUrl, targetFrameName: ustring;
targetDisposition: TCefWindowOpenDisposition; userGesture: Boolean;
var popupFeatures: TCefPopupFeatures; var windowInfo: TCefWindowInfo; var client: ICefClient;
var settings: TCefBrowserSettings; var noJavascriptAccess: Boolean; out Result: Boolean);
begin
// Called on IO thread, must be executed on the UI thread
CefPostTask(TID_UI, TCefNewTabTask.Create(targetUrl));
Result := True;
end;
procedure TWebPanel.ChromiumOpenUrlFromTab(Sender: TObject; browser: ICefBrowser; frame: ICefFrame;
const targetUrl: ustring; targetDisposition: TCefWindowOpenDisposition; useGesture: Boolean;
out Result: Boolean);
begin
Assert(CefCurrentlyOn(TID_UI));
FMain.NewTab(UTF8Encode(targetUrl));
Result := True;
end;
procedure TWebPanel.ChromiumBeforeContextMenu(Sender: TObject; const Browser: ICefBrowser;
const Frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel);
begin
Assert(CefCurrentlyOn(TID_UI));
If (params.GetTypeFlags in [CM_TYPEFLAG_PAGE, CM_TYPEFLAG_FRAME]) then
begin
// Add seperator if the menu already contains items
If model.GetCount > 0 then model.AddSeparator;
model.AddItem(Ord(CLIENT_ID_VISIT_COOKIES), '&Visit Cookies');
model.AddSeparator;
model.AddItem(Ord(CLIENT_ID_EXIT), 'Exit');
end;
end;
procedure TWebPanel.ChromiumContextMenuCommand(Sender: TObject; const Browser: ICefBrowser;
const Frame: ICefFrame; const params: ICefContextMenuParams; commandId: Integer;
eventFlags: TCefEventFlags; out Result: Boolean);
begin
Assert(CefCurrentlyOn(TID_UI));
Result := True;
Case commandId of
Ord(CLIENT_ID_VISIT_COOKIES): TCefCookieManagerRef.Global(nil).VisitAllCookiesProc(@VisitCookies);
Ord(CLIENT_ID_EXIT): Application.Terminate;
Else Result := False;
end;
end;
procedure TWebPanel.IconReady(const Success: Boolean; const Icon: TIcon);
begin
Assert(CefCurrentlyOn(TID_UI));
fIconGetter := nil;
If Success then SetIcon(Icon)
Else SetIcon(nil);
end;
procedure TWebPanel.DoHide;
begin
inherited DoHide;
If Assigned(fChromium) then fChromium.Hide;
end;
procedure TWebPanel.DoShow;
begin
inherited DoShow;
If Assigned(fChromium) then fChromium.Show;
end;
destructor TWebPanel.Destroy;
begin
// Cancel icon request
If Assigned(fIconGetter) then fIconGetter.Cancel;
inherited Destroy;
end;
procedure TWebPanel.InitializeChromium;
begin
If not Assigned(fChromium) then
begin
fChromium := TChromium.Create(Self);
fChromium.Parent := Self;
fChromium.AnchorAsAlign(alClient, 0);
// Register callbacks
fChromium.OnTitleChange := @ChromiumTitleChange;
fChromium.OnAddressChange := @ChromiumAddressChange;
fChromium.OnFaviconUrlchange := @ChromiumFaviconUrlchange;
fChromium.OnOpenUrlFromTab := @ChromiumOpenUrlFromTab;
fChromium.OnBeforePopup := @ChromiumBeforePopup;
fChromium.OnBeforeContextMenu := @ChromiumBeforeContextMenu;
fChromium.OnContextMenuCommand := @ChromiumContextMenuCommand;
end
Else raise Exception.Create('Chromium already initialized.');
end;
procedure TWebPanel.RequestClose;
begin
fChromium.Browser.Host.CloseBrowser(False);
end;
procedure TWebPanel.OpenUrl(AUrl: String);
begin
fChromium.Load(AUrl);
end;
// Change the icon of the tab
procedure TWebPanel.SetIcon(const Icon: TCustomIcon);
begin
If Assigned(Icon) then
begin
// Replace icon with new one
FMain.TabIcons.Delete(TabIndex);
FMain.TabIcons.InsertIcon(TabIndex, Icon);
ImageIndex := TabIndex;
end
Else If ImageIndex <> -1 then
begin
// Replace icon with dummy one
FMain.TabIcons.Delete(TabIndex);
FMain.TabIcons.InsertIcon(TabIndex, Application.Icon);
ImageIndex := -1;
end;
PageControl.Repaint;
end;
Initialization
Path := GetCurrentDirUTF8 + DirectorySeparator;
CefResourcesDirPath := Path + 'Resources';
CefLocalesDirPath := Path + 'Resources' + DirectorySeparator + 'locales';
//CefCachePath := Path + 'Cache';
//CefBrowserSubprocessPath := '.' + PathDelim + 'subprocess'{$IFDEF WINDOWS}+'.exe'{$ENDIF};
CefInitialize;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls,
OpenGL;
type
TfrmGL = class(TForm)
Timer1: TTimer;
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure Timer1Timer(Sender: TObject);
private
DC : HDC;
hrc : HGLRC;
left, up, right : GLfloat;
ctrlpoints : Array [0..16, 0..16, 0..2] of GLfloat ;
texpts : Array [0..1, 0..1, 0..1] of GLfloat;
procedure SetDCPixelFormat;
procedure init_surface;
procedure Init;
procedure PrepareImage (FileName : String);
public
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
var
frmGL: TfrmGL;
A : GLfloat = 0.0;
step : GLfloat = 0.05;
implementation
{$R *.DFM}
{=======================================================================
Инициализация контрольных точек поверхности}
procedure TfrmGL.init_surface;
var
x,y:integer;
begin
For x:=0 to 16 do
For y:=0 to 16 do begin
ctrlpoints [x][y][0] := (x-8)/3;
ctrlpoints [x][y][1] := (y-8)/3;
ctrlpoints [x][y][2] := cos(sqrt(sqr(x)+sqr(y)) - Pi / 8 * a);
end;
end;
{======================================================================
Подготовка текстуры}
procedure TfrmGL.PrepareImage (FileName : String);
type
PPixelArray = ^TPixelArray;
TPixelArray = array [0..0] of Byte;
var
Bitmap : TBitmap;
Data : PPixelArray;
BMInfo : TBitmapInfo;
I, ImageSize : Integer;
Temp : Byte;
MemDC : HDC;
begin
Bitmap := TBitmap.Create;
Bitmap.LoadFromFile (FileName);
with BMinfo.bmiHeader do begin
FillChar (BMInfo, SizeOf(BMInfo), 0);
biSize := sizeof (TBitmapInfoHeader);
biBitCount := 24;
biWidth := Bitmap.Width;
biHeight := Bitmap.Height;
ImageSize := biWidth * biHeight;
biPlanes := 1;
biCompression := BI_RGB;
MemDC := CreateCompatibleDC (0);
GetMem (Data, ImageSize * 3);
try
GetDIBits (MemDC, Bitmap.Handle, 0, biHeight, Data, BMInfo, DIB_RGB_COLORS);
For I := 0 to ImageSize - 1 do begin
Temp := Data [I * 3];
Data [I * 3] := Data [I * 3 + 2];
Data [I * 3 + 2] := Temp;
end;
glTexImage2d(GL_TEXTURE_2D, 0, 3, biWidth,
biHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, Data);
finally
FreeMem (Data);
DeleteDC (MemDC);
Bitmap.Free;
end;
end;
end;
{=======================================================================
Инициализация}
procedure TfrmGL.Init;
const
ambient : Array [0..3] of GLfloat = (1.0, 1.0, 1.0, 1.0);
position : Array [0..3] of GLfloat = (0.0, 0.0, -12.0, 1.0);
mat_diffuse : Array [0..3] of GLfloat = (1.0, 1.0, 1.0, 1.0);
mat_specular : Array [0..3] of GLfloat = (1.0, 1.0, 1.0, 1.0);
mat_shininess : GLfloat = 50.0;
begin
glEnable(GL_DEPTH_TEST);
glEnable(GL_AUTO_NORMAL);
glEnable(GL_NORMALIZE);
// источник света
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1);
glLightfv(GL_LIGHT0, GL_AMBIENT, @ambient);
glLightfv(GL_LIGHT0, GL_POSITION, @position);
glMaterialfv(GL_FRONT, GL_DIFFUSE, @mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, @mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, @mat_shininess);
glClearColor (0.0, 0.75, 1.0, 1.0);
init_surface;
PrepareImage ('..\earth.bmp');
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glEnable(GL_TEXTURE_2D);
glMap2f(GL_MAP2_TEXTURE_COORD_2, 0, 1, 2, 2, 0, 1, 4, 2, @texpts);
glEnable(GL_MAP2_TEXTURE_COORD_2);
glMap2f(GL_MAP2_VERTEX_3, 0, 1, 3, 17, 0, 1, 51, 17, @ctrlpoints);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20, 0.0, 1.0, 20, 0.0, 1.0);
end;
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
left := 0.0;
up := 0.0;
right := 0.0;
texpts [0][0][0] := 0.0;
texpts [0][0][1] := 0.0;
texpts [1][0][0] := 0.0;
texpts [1][0][1] := 1.0;
texpts [0][1][0] := 1.0;
texpts [0][1][1] := 0.0;
texpts [1][1][0] := 1.0;
texpts [1][1][1] := 1.0;
Init;
end;
{=======================================================================
Установка формата пикселей}
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or
PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport(0, 0, ClientWidth, ClientHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
If (ClientWidth <= ClientHeight)
then glOrtho(-4.0, 4.0, -4.0 * ClientHeight / ClientWidth, 4.0 * ClientHeight / ClientWidth, -4.0, 4.0)
else glOrtho(-4.0 * ClientWidth / ClientHeight, 4.0 * ClientWidth / ClientHeight, -4.0, 4.0, -4.0, 4.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Обработка сообщения WM_PAINT, рисование окна}
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
begin
BeginPaint(Handle, ps);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glPushMatrix;
glRotatef(left, 0.0, 1.0, 0.0);
glRotatef(up, 1.0, 0.0, 0.0);
glRotatef(right, 0.0, 0.0, 1.0);
glEvalMesh2(GL_FILL, 0, 20, 0, 20);
glPopMatrix;
SwapBuffers(DC);
EndPaint(Handle, ps);
end;
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglMakeCurrent (0, 0);
wglDeleteContext (hrc);
ReleaseDC (Handle, DC);
DeleteDC (DC);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
Case Key of
VK_ESCAPE : begin
Close;
Exit;
end;
VK_LEFT : left := left + 5;
VK_RIGHT: right := right + 5;
VK_UP : up := up + 5;
end;
end;
procedure TfrmGL.Timer1Timer(Sender: TObject);
begin
A := A + 0.5;
init_surface;
glMap2f(GL_MAP2_VERTEX_3, 0, 1, 3, 17, 0, 1, 51, 17, @ctrlpoints);
texpts [0][0][0] := texpts [0][0][0] - step;
texpts [0][0][1] := texpts [0][0][1] - step;
If (texpts [0][0][0] < -4.0) or (texpts [0][0][0] > 1.0)
then step := - step;
glMap2f(GL_MAP2_TEXTURE_COORD_2, 0, 1, 2, 2, 0, 1, 4, 2, @texpts);
InvalidateRect(Handle, nil, False);
end;
end.
|
unit PBATCH;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, StdCtrls, Grids, OnFocusButton, ExtCtrls, OnShapeLabel, Comobj, Db,
Func,
OnScheme;
type
TFM_Batch = class(TForm)
SF_Main: TOnSchemeForm;
OnSchemeForm1: TOnSchemeForm;
OnShapeLabel4: TOnShapeLabel;
Panel2: TPanel;
BT_Delete: TOnFocusButton;
BT_exit: TOnFocusButton;
BT_load: TOnFocusButton;
BT_Insert: TOnFocusButton;
Bt_Down: TOnFocusButton;
cbx_down: TComboBox;
StringGrid1: TStringGrid;
ErrorPanel: TPanel;
OnShapeLabel1: TOnShapeLabel;
Memo1: TMemo;
BT_ErrorClose: TOnFocusButton;
P_Help: TPanel;
Shape1: TShape;
Label1: TLabel;
Label2: TLabel;
OnShapeLabel2: TOnShapeLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
BT_HelpClose: TOnFocusButton;
OpenDialog1: TOpenDialog;
P_helpinfo: TStatusBar;
procedure BT_loadClick(Sender: TObject);
procedure Bt_DownClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure StringGrid_Clear;
end;
var
FM_Batch: TFM_Batch;
implementation
{$R *.DFM}
procedure TFM_Batch.StringGrid_Clear;
var
i : integer;
begin
StringGrid1.ColCount := 11;
StringGrid1.RowCount := 2;
StringGrid1.Cells[ 0,0] := '가족명';
StringGrid1.Cells[ 1,0] := '가족관계코드';
StringGrid1.Cells[ 2,0] := '가족주민번호';
StringGrid1.Cells[ 3,0] := '사업자번호';
StringGrid1.Cells[ 4,0] := '상호';
StringGrid1.Cells[ 5,0] := '지급일';
StringGrid1.Cells[ 6,0] := '치료내역';
StringGrid1.Cells[ 7,0] := '지급금액';
for i := 0 to 8 do
StringGrid1.Cells[i,1] := '';
end;
procedure TFM_Batch.BT_loadClick(Sender: TObject);
var
v : Variant ;
iRow, iCol : integer ;
CNT, Sg_RCnt, work : integer;
sEmpno, sImsiEmpno, sJobcode : String;
begin
P_Help.Visible := True;
Work := 0;
StringGrid_Clear;
BT_Insert.Enabled := False;
BT_Delete.Enabled := False;
Case MessageDlg('일괄등록할 데이터 업로드이면 Yes를 선택하세요.', mtConfirmation, [mbYes, mbCancel], 0) of
mrYes : Work := 1;
else
System.Exit;
end;
try
v:= CreateOleObject('Excel.application');
except
ShowMessage('Excel이 설치되어 있어야 합니다.');
Exit;
end;
if OpenDialog1.Execute then
begin
v.WorkBooks.open(OpenDialog1.FileName);
end
else Exit;
cnt := strToint(v.ActiveSheet.UsedRange.Rows.Count);
if Work = 1 then
begin
Memo1.Lines.Text := '';
StringGrid1.ColCount := 11;
StringGrid1.RowCount := cnt;
For iRow := 2 to cnt do
begin
For iCol := 1 to StringGrid1.ColCount - 1 do
begin
Case iCol of
1: begin
if not CheckComcode(UpperCase(v.cells[iRow, iCol])) then
Memo1.Lines.Add(inttoStr(iRow)+', '+
Trim(v.cells[iRow, 1]) +', '
Trim(v.cells[iRow, 2]) +', '
Trim(v.cells[iRow, 3]) +'- 등록 가능한 가족관계가 아닙니다.');
end;
2: begin
if Trim(v.cells[iRow, iCol]) = '' then
Memo1.Lines.Add(inttoStr(iRow)+', '+
Trim(v.cells[iRow, 1]) +', '
Trim(v.cells[iRow, 2]) +', '
Trim(v.cells[iRow, 3]) +' - 사업자번호가 없습니다.');
if Length(SearchAndReplace(Trim(v.cells[iRow, iCol]),'-','')) <> 10 then
Memo1.Lines.Add(inttoStr(iRow)+', '+
Trim(v.cells[iRow, 1]) +', '
Trim(v.cells[iRow, 2]) +', '
Trim(v.cells[iRow, 3]) +' - 사업자번호가 10자리의 숫자가 아닙니다.');
end;
3: begin
if Trim(v.cells[iRow, iCol]) = '' then
Memo1.Lines.Add(inttoStr(iRow)+', '+
Trim(v.cells[iRow, 1]) +', '
Trim(v.cells[iRow, 2]) +', '
Trim(v.cells[iRow, 3]) +' - 상호가 없습니다.' );
end;
4: begin
sJobcode := v.cells[iRow, iCol];
if sJobcode <> '' then
begin
if not CheckJobcode(UpperCase(v.cells[iRow, iCol])) then
Memo1.Lines.Add(inttoStr(iRow)+','+
Trim(v.cells[iRow, 1])+','+
Trim(v.cells[iRow, 2])+'-인력코드오류');
end;
end;
end;
if Memo1.Lines.text = '' then
begin
if (iCol = 1) then
begin
StringGrid1.Cells[iCol -1, iRow -1] := Uppercase(v.cells[iRow, iCol]) ;
end
else if (iCol = 2) or (iCol = 3) then
begin
StringGrid1.Cells[iCol, iRow -1] := v.cells[iRow, iCol];
end
else if (iCol = 4) then
begin
StringGrid1.Cells[iCol, iRow -1] := Uppercase(v.cells[iRow, iCol]);
end
else if (iCol = 5) then
begin
//StringGrid1.Cells[iCol, iRow -1] := FM_DRMMENU.gseOrgnum;
end
else if (iCol = 6) then
begin
// StringGrid1.Cells[iCol, iRow -1] := FM_DRMMENU.gseDeptCode;
end
else if (iCol = 7) or (iCol = 8) or (iCol = 9) or (iCol = 10) then
begin
StringGrid1.Cells[iCol , iRow -1] := v.cells[iRow, iCol - 2] ;
end;
end;
end;
end;
end
else
begin
Memo1.Lines.Text := '';
StringGrid1.ColCount := 3;
StringGrid1.RowCount := cnt;
For iRow := 2 to cnt do
begin
sImsiEmpno := v.cells[iRow, 2];
if length(sImsiEmpno) = 1 then sEmpno := '000' + sImsiEmpno
else if length(sImsiEmpno) = 2 then sEmpno := '00' + sImsiEmpno
else if length(sImsiEmpno) = 3 then sEmpno := '0' + sImsiEmpno
else if length(sImsiEmpno) = 4 then sEmpno := sImsiEmpno
else
begin
ShowMessage('사번을 정확히 입력하세요.');
Exit;
end;
{ if not CheckEmpno(Uppercase(v.cells[iRow, 1]),sEmpno) then
Memo1.Lines.Add(inttoStr(iRow)+','+
Trim(v.cells[iRow, 1])+','+
Trim(v.cells[iRow, 2])+','+
Trim(v.cells[iRow, 3])+'-이 사원은 없습니다.');
}
if Memo1.Lines.text = '' then
For iCol := 1 to StringGrid1.ColCount do
begin
if iCol = 2 then StringGrid1.Cells[iCol -1, iRow -1] := sEmpno
else StringGrid1.Cells[iCol -1, iRow -1] := UpperCase(v.cells[iRow, iCol]) ;
end;
end;
end;
v.WorkBooks.Close;
v.quit ;
v:=unassigned;
if Memo1.Lines.Text <> '' then
begin
Memo1.Lines.Add('==================================');
Memo1.Lines.Add('상기 오류 내역 수정후 재작업 요망.');
Memo1.Lines.Add('==================================');
Memo1.Lines.Add('중복된 주민번호 입력 오류사원에 경우 '); //kth 20090813 재직중이면서 주민가 동일하면 저장 안되게 체크
Memo1.Lines.Add('재직중인 동일 사원이 존재함으로 해당사원 검색후 ');
Memo1.Lines.Add('해당사번으로 사용해 주시기 바랍니다. ');
StringGrid_Clear;
ErrorPanel.Visible := True;
P_Help.Visible := True;
System.Exit;
end;
P_helpinfo.SimpleText := ('총 ' + IntTostr(Cnt -1) + ' 건의 엑셀파일 로드가 완료 되었습니다.');
if (Cnt - 1) <> 0 then
begin
if work = 1 then BT_Insert.Enabled := True
else BT_Delete.Enabled := True;
end
else
begin
BT_Insert.Enabled := False;
BT_Delete.Enabled := False;
end;
P_Help.Visible := False;
end;
procedure TFM_Batch.Bt_DownClick(Sender: TObject);
var
XL, XArr: Variant;
i,j,k: integer;
SavePlace: TBookmark;
begin
P_helpinfo.SimpleText := 'Excel이 설치되어 있는지 검색하고 있습니다.';
XArr := VarArrayCreate([1, 13], VarVariant);
try
XL := CreateOLEObject('Excel.Application');
except
MessageDlg('Excel이 설치되어 있지 않습니다.', MtWarning, [mbok], 0);
P_helpinfo.SimpleText := '';
Exit;
end;
XL.WorkBooks.Add; //새로운 페이지 생성
XL.Visible := false;
if cbx_down.ItemIndex = 0 then
begin
//컬럼명 지정_서브타이블 지정
XArr[1] := '본인사번';
XArr[2] := '가족명';
XArr[3] := '가족주민번호(''-''입력)';
XArr[4] := '사업자번호(''-''제외)';
XArr[5] := '상호명';
XArr[6] := '의료비지급일(ex. 20050105)';
XArr[7] := '치료내역';
XArr[8] := '지급금액';
XL.Range['A1', 'H1'].Value := XArr;
XL.Range['A1', 'H1'].Borders.LineStyle := 1; //테두리선을 만든다. 1은 실선
XL.Range['A1', 'H1'].Interior.Color:= $00CBF0B3;
end
else
begin
//컬럼명 지정_서브타이블 지정
XArr[1] := '본인사번';
XArr[2] := '가족명';
XArr[3] := '가족주민번호(''-''입력)';
XArr[4] := '사업자번호(''-''제외)';
XArr[5] := '의료비지급일(ex. 20050105)';
XArr[6] := '지급금액';
XL.Range['A1', 'F1'].Value := XArr;
XL.Range['A1', 'F1'].Borders.LineStyle := 1; //테두리선을 만든다. 1은 실선
XL.Range['A1', 'F1'].Interior.Color:= $00CBF0B3;
end;
XL.Visible := true; //엑셀자료 보여줌
P_helpinfo.SimpleText := '';
end;
end.
|
unit Module.DataSet.VigilanteBase;
interface
uses
System.Classes, System.Generics.Collections, Data.DB, FireDac.Comp.Client,
Vigilante.Aplicacao.SituacaoBuild, Vigilante.Aplicacao.ModelBase;
type
TVigilanteDataSetBase<T: IVigilanteModelBase> = class abstract(TFDMemTable)
private
FBuilding: TField;
FNome: TField;
FSituacao: TField;
FURL: TField;
FID: TField;
FAtualizar: TField;
FUltimaAtualizacao: TField;
FNotificar: TField;
function GetBuilding: boolean;
function GetNome: string;
function GetSituacao: TSituacaoBuild;
function GetURL: string;
procedure SetBuilding(const Value: boolean);
procedure SetNome(const Value: string);
procedure SetSituacao(const Value: TSituacaoBuild);
procedure SetURL(const Value: string);
function GetID: TGuid;
procedure SetID(const Value: TGuid);
function GetAtualizar: boolean;
function GetUltimaAtualizacao: TDateTime;
procedure SetAtualizar(const Value: boolean);
function GetNotificar: boolean;
procedure SetNotificar(const Value: boolean);
function EditOuInsert(const AModel: T): TDataSetState;
protected
procedure SetUltimaAtualizacao(const Value: TDateTime);
procedure ConfigurarCampos; virtual;
procedure MapearCampos; virtual;
procedure CriarCampos; virtual;
procedure DoAfterOpen; override;
procedure DoOnNewRecord; override;
procedure ImportarDetalhes(const AModel: T); virtual; abstract;
procedure CriarIndices; virtual;
public
constructor Create(AOwner: TComponent); override;
procedure ApenasAtualizaveis(const AFiltrar: boolean = true);
procedure CreateDataSet; override;
procedure Importar(const AModel: T);
function ExportarRegistro: T; virtual; abstract;
function LocalizarPorID(const AID: TGuid): boolean;
procedure DesativarNotificacao;
property ID: TGuid read GetID write SetID;
property Nome: string read GetNome write SetNome;
property URL: string read GetURL write SetURL;
property Situacao: TSituacaoBuild read GetSituacao write SetSituacao;
property Building: boolean read GetBuilding write SetBuilding;
property UltimaAtualizacao: TDateTime read GetUltimaAtualizacao;
property Atualizar: boolean read GetAtualizar write SetAtualizar;
property Notificar: boolean read GetNotificar write SetNotificar;
end;
implementation
uses
System.SysUtils, Module.DataSet.ConfigMemento,
Module.DataSet.ConfigMemento.ArmazenarConfiguracao;
constructor TVigilanteDataSetBase<T>.Create(AOwner: TComponent);
begin
inherited;
LogChanges := False;
CriarCampos;
end;
procedure TVigilanteDataSetBase<T>.CriarCampos;
begin
FieldDefs.Add('ID', ftGuid);
FieldDefs.Add('Nome', ftString, 255);
FieldDefs.Add('URL', ftString, 255);
FieldDefs.Add('Situacao', ftInteger);
FieldDefs.Add('Building', ftBoolean);
FieldDefs.Add('UltimaAtualizacao', ftDateTime);
FieldDefs.Add('Atualizar', ftBoolean);
FieldDefs.Add('Notificar', ftBoolean);
CriarIndices;
end;
procedure TVigilanteDataSetBase<T>.CriarIndices;
begin
with Indexes.Add do
begin
Name := 'IDX_ID';
Fields := 'ID';
Active := true;
end;
with Indexes.Add do
begin
Name := 'IDX_ID_SITUACAO';
Fields := 'ID;SITUACAO';
Active := true;
end;
end;
procedure TVigilanteDataSetBase<T>.CreateDataSet;
begin
inherited;
ConfigurarCampos;
LogChanges := False;
end;
procedure TVigilanteDataSetBase<T>.DesativarNotificacao;
begin
Edit;
Notificar := False;
Post;
end;
procedure TVigilanteDataSetBase<T>.DoAfterOpen;
begin
ConfigurarCampos;
inherited;
end;
procedure TVigilanteDataSetBase<T>.ConfigurarCampos;
begin
MapearCampos;
FID.Visible := False;
FNome.DisplayWidth := 25;
FURL.DisplayWidth := 50;
FBuilding.Visible := False;
end;
procedure TVigilanteDataSetBase<T>.MapearCampos;
begin
FID := FindField('ID');
FBuilding := FindField('Building');
FNome := FindField('Nome');
FSituacao := FindField('Situacao');
FURL := FindField('URL');
FAtualizar := FindField('Atualizar');
FUltimaAtualizacao := FindField('UltimaAtualizacao');
FNotificar := FindField('Notificar');
end;
procedure TVigilanteDataSetBase<T>.ApenasAtualizaveis(const AFiltrar: boolean);
begin
Filtered := AFiltrar;
Filter := 'Atualizar = True or Atualizar is null';
if not AFiltrar then
Filter := EmptyStr;
end;
procedure TVigilanteDataSetBase<T>.DoOnNewRecord;
begin
inherited;
ID := TGuid.NewGuid;
Nome := 'Informa��es indispon�veis';
Atualizar := true;
Building := False;
Situacao := sbUnknow;
Notificar := true;
end;
function TVigilanteDataSetBase<T>.GetAtualizar: boolean;
begin
Result := FAtualizar.AsBoolean;
end;
function TVigilanteDataSetBase<T>.GetBuilding: boolean;
begin
Result := FBuilding.AsBoolean;
end;
function TVigilanteDataSetBase<T>.GetID: TGuid;
begin
Result := FID.AsGuid;
end;
function TVigilanteDataSetBase<T>.GetNome: string;
begin
Result := FNome.AsString;
end;
function TVigilanteDataSetBase<T>.GetNotificar: boolean;
begin
Result := FNotificar.AsBoolean;
end;
function TVigilanteDataSetBase<T>.GetSituacao: TSituacaoBuild;
begin
Result := TSituacaoBuild.Parse(FSituacao.AsInteger);
end;
function TVigilanteDataSetBase<T>.GetUltimaAtualizacao: TDateTime;
begin
Result := FUltimaAtualizacao.AsDateTime;
end;
function TVigilanteDataSetBase<T>.GetURL: string;
begin
Result := FURL.AsString;
end;
procedure TVigilanteDataSetBase<T>.Importar(const AModel: T);
begin
if EditOuInsert(AModel) = dsInsert then
Insert
else
Edit;
Nome := AModel.Nome;
Building := AModel.Building;
SetUltimaAtualizacao(Now);
Situacao := AModel.Situacao;
if Building then
Situacao := sbProgresso;
ImportarDetalhes(AModel);
Post;
end;
function TVigilanteDataSetBase<T>.LocalizarPorID(const AID: TGuid): boolean;
var
_configMemento: IConfigMemento;
_state: TDataSetState;
begin
Result := False;
if IsEmpty then
Exit;
_configMemento := TConfigMemento.Create(Self, [acIndex]).GuardarConfig;
IndexName := 'IDX_ID';
IndexesActive := true;
Result := FindKey([AID.ToString]);
end;
function TVigilanteDataSetBase<T>.EditOuInsert(const AModel: T): TDataSetState;
var
_state: TDataSetState;
begin
Result := dsInactive;
if IsEmpty then
Exit(dsInsert);
_state := dsInsert;
if ID.ToString.Equals(AModel.ID.ToString) or LocalizarPorID(AModel.ID) then
_state := dsEdit;
Result := _state;
end;
procedure TVigilanteDataSetBase<T>.SetAtualizar(const Value: boolean);
begin
FAtualizar.AsBoolean := Value;
end;
procedure TVigilanteDataSetBase<T>.SetBuilding(const Value: boolean);
begin
FBuilding.AsBoolean := Value;
end;
procedure TVigilanteDataSetBase<T>.SetID(const Value: TGuid);
begin
FID.AsGuid := Value;
end;
procedure TVigilanteDataSetBase<T>.SetNome(const Value: string);
begin
FNome.AsString := Value;
end;
procedure TVigilanteDataSetBase<T>.SetNotificar(const Value: boolean);
begin
FNotificar.AsBoolean := Value;
end;
procedure TVigilanteDataSetBase<T>.SetSituacao(const Value: TSituacaoBuild);
begin
if FSituacao.AsInteger <> Value.AsInteger then
FNotificar.AsBoolean := true;
FSituacao.AsInteger := Value.AsInteger;
end;
procedure TVigilanteDataSetBase<T>.SetUltimaAtualizacao(const Value: TDateTime);
begin
FUltimaAtualizacao.AsDateTime := Value;
end;
procedure TVigilanteDataSetBase<T>.SetURL(const Value: string);
begin
FURL.AsString := Value;
end;
end.
|
unit IWCompEdit;
{PUBDIST}
interface
uses
{$IFDEF Linux}QGraphics,{$ELSE}Graphics,{$ENDIF}
Classes,
IWControl, IWTypes, IWScriptEvents, IWHTMLTag;
type
TIWCustomEdit = class(TIWControl)
protected
FBGColor: TIWColor;
FMaxLength: Integer;
FOnSubmit: TNotifyEvent;
FPasswordPrompt: Boolean;
FRequired: Boolean;
FReadOnly: Boolean;
FTagType: string;
//
procedure DoSubmit;
procedure HookEvents(AScriptEvents: TIWScriptEvents); override;
procedure SetValue(const AValue: string); override;
procedure Submit(const AValue: string); override;
procedure SetPasswordPrompt(const AValue: Boolean);
procedure SetBGColor(const Value: TIWColor);
public
constructor Create(AOwner: TComponent); override;
function RenderHTML: TIWHTMLTag; override;
function RenderStyle: string; override;
published
//@@ Specifies the background color for the edit field.
//
//Note: This has no effect in Netscape 4.
property BGColor: TIWColor read FBGColor write SetBGColor;
property DoSubmitValidation;
property Editable;
//@@ Browsers typically ignore some of the font attributes with edit controls, however
//all font attributes are usable when Editable = False.
//
//For more information on the font property, see TIWControl.Font.
//
//SeeAlso: TIWControl.Font
property Font;
property ExtraTagParams;
property FriendlyName;
//@@ This is the maximum length of text specified as a character count that the user will be
// permitted to enter.
property MaxLength: Integer read FMaxLength write FMaxLength;
//@@ Makes the edit control read only in the browser.
//Note: This has no effect in Netscape 4.
property ReadOnly: Boolean read FReadOnly write FReadOnly;
//@@ If required is true, the user will be required to enter a value in this field before
//they can submit the form.
property Required: Boolean read FRequired write FRequired;
property ScriptEvents;
property TabOrder;
//
//@@ OnSubmit will be fired if the user presses enter while in this field.
//Note: This does not work in Netscape 4.
property OnSubmit: TNotifyEvent read FOnSubmit write FOnSubmit;
end;
TIWEdit = class(TIWCustomEdit)
published
//@@ If True, this indicates that this field is to be used for password or other masked entry.
// When True, the field will not show the text the user is typing. Instead of the actual
// characters a single mask character such as * will be displayed. The actual character that is
// displayed is determined by the browser. This only affects display, and not the actual data
// that is available for use at run time.
//
// This is usually done to prevent people from obtaining a password simply by looking over the
// user's shoulder.
property PasswordPrompt: boolean read FPasswordPrompt write SetPasswordPrompt;
property Text;
end;
TReceivedFileEvent = procedure (ASender: TObject; const AFilename: string) of object;
TIWCustomFile = class(TIWCustomEdit)
protected
FContentType: string;
FFileName: string;
FFileData: TStream;
FOnReceivedFile: TReceivedFileEvent;
function GetContentType: string;
function GetFileName: string;
function GetFileData: TStream;
procedure DoReceivedFile(const AFileName:string);
public
constructor Create(AOwner: TComponent); override;
procedure SaveToFile(AFilename: string = '');
procedure SaveToStream(AStream: TStream);
property ContentType: string read GetContentType;
property Filename: string read GetFileName;
property FileData: TStream read GetFileData;
published
property OnReceivedFile: TReceivedFileEvent read FOnReceivedFile write FOnReceivedFile;
end;
TIWFile = class(TIWCustomFile)
end;
implementation
uses
IWAppForm, IWApplication, IWCompLabel, IWFileParser, IWResourceStrings,
SWSystem, SysUtils;
procedure TIWCustomEdit.SetValue(const AValue: string);
begin
Text := AValue;
Invalidate;
end;
function TIWCustomEdit.RenderHTML: TIWHTMLTag;
var
LLabel: TIWLabel;
LTag: TIWHTMLTag;
begin
result := nil;
if Editable then begin
Result := TIWHTMLTag.CreateTag('INPUT'); try
Result.AddStringParam('TYPE', FTagType);
Result.AddStringParam('NAME', HTMLName);
if MaxLength > 0 then begin
Result.AddIntegerParam('MAXLENGTH', MaxLength);
end;
Result.AddIntegerParam('SIZE', Width div 7);
Result.AddStringParam('VALUE', TextToHTML(Text));
Result.Add(iif(ReadOnly, 'READONLY'));
if Required then begin
TIWAppForm(Form).AddValidation('GSubmitter.' + HTMLName + '.value.length==0'
, Format(RSValidationRequeredField, [FriendlyName]));
end;
if AnsiSameText(FTagType, 'FILE') then begin
LTag := Result;
Result := TIWHTMLTag.CreateTag('SPAN'); try
Result.Contents.AddTagAsObject(LTag);
Result.AddStringParam('NAME', HTMLName + 'SPAN');
Result.ScriptedTag := LTag;
except FreeAndNil(LTag); raise; end;
end;
except FreeAndNil(Result); raise; end;
end else begin
LLabel := TIWLabel.Create(Self); try
LLabel.Name := Name;
LLabel.Caption := Text;
LLabel.Font.Assign(Font);
LLabel.Width := Width;
LLabel.Height := Height;
Result := LLabel.RenderHTML;
finally FreeAndNil(LLabel); end;
end;
end;
procedure TIWCustomEdit.DoSubmit;
begin
if Assigned(OnSubmit) then begin
OnSubmit(Self);
end;
end;
procedure TIWCustomEdit.Submit(const AValue: string);
begin
DoSubmit;
end;
function TIWCustomEdit.RenderStyle: string;
begin
Result := inherited RenderStyle
+ iif(Font.Color <> clNone, 'color:' + ColorToRGBString(Font.Color))
+ iif(BGColor <> clNone, 'background:' + ColorToRGBString(BGColor));
end;
procedure TIWCustomEdit.HookEvents(AScriptEvents: TIWScriptEvents);
begin
if Assigned(OnSubmit) then begin
AScriptEvents.HookEvent('OnKeyPress', 'CheckReturnKey(event.keyCode, ''' + HTMLName
+ ''', ' + iif(DoSubmitValidation, 'true', 'false') + ')');
end;
end;
constructor TIWCustomEdit.Create(AOwner: TComponent);
begin
inherited;
FBGColor := clNone;
FNeedsFormTag := True;
FSupportsInput := True;
FSupportsSubmit := True;
FSupportedScriptEvents := 'OnBlur,OnChange,OnFocus,OnKeyPress,OnSelect';
Height := 21;
Width := 121;
FTagType := 'TEXT';
end;
{ TIWCustomFile }
constructor TIWCustomFile.Create(AOwner: TComponent);
begin
inherited;
FTagType := 'FILE';
FControlEncode := ceMPFormData;
end;
procedure TIWCustomFile.DoReceivedFile(const AFileName: string);
begin
if Assigned(FOnReceivedFile) then begin
OnReceivedFile(Self, AFileName);
end;
end;
function TIWCustomFile.GetContentType: string;
begin
Result := THTTPFiles(WebApplication.FileList).GetContentType(Name);
end;
function TIWCustomFile.GetFileData: TStream;
begin
Result := THTTPFiles(WebApplication.FileList).GetFileData(Name);
end;
function TIWCustomFile.GetFileName: string;
begin
Result := THTTPFiles(WebApplication.FileList).GetFileName(Name);
if FFileName <> '' then begin
DoReceivedFile(FFilename);
end;
end;
procedure TIWCustomFile.SaveToFile(AFilename: string = '');
begin
if AFileName = '' then begin
AFileName := Filename;
end;
THTTPFiles(WebApplication.FileList).SaveToFile(Name, AFileName);
end;
procedure TIWCustomFile.SaveToStream(AStream: TStream);
begin
THTTPFiles(WebApplication.FileList).SaveToStream(Name, AStream);
end;
procedure TIWCustomEdit.SetPasswordPrompt(const AValue: Boolean);
begin
FTagType := IIF(AValue, 'PASSWORD', 'TEXT');
FPasswordPrompt := AValue;
end;
procedure TIWCustomEdit.SetBGColor(const Value: TIWColor);
begin
FBGColor := Value;
Invalidate;
end;
end.
|
unit SectionDrill;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Grids, ExtCtrls, Buttons;
type
TSectionDrillForm = class(TForm)
Panel1: TPanel;
Label2: TLabel;
sgSection: TStringGrid;
Panel2: TPanel;
lblAllDrills: TLabel;
Label1: TLabel;
sgDrills: TStringGrid;
sgSectionDrills: TStringGrid;
btnAdd: TButton;
btnEdit: TButton;
btnDelete: TButton;
btnDeleteAll: TButton;
btn_cancel: TBitBtn;
btnShouGong: TButton;
btnInsert: TButton;
procedure FormCreate(Sender: TObject);
procedure sgSectionSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure btn_cancelClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnAddClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure btnDeleteAllClick(Sender: TObject);
procedure btnEditClick(Sender: TObject);
procedure sgSectionDrillsDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure sgSectionDrillsExit(Sender: TObject);
procedure btnShouGongClick(Sender: TObject);
procedure btnInsertClick(Sender: TObject);
private
{ Private declarations }
procedure GetDrillsBySectionNo(aSectionNo: String);
procedure GetSectionByProjectNo(aProjectNo: String);
procedure GetAllDrillsByProjectNo(aProjectNo: String);
procedure UpdateKjj; //更新钻孔间距.
function GetInsertSQL: string;
function GetUpdateSQL: string;
function GetDeleteSQL: string;
function GetAfterDeleteUpdateSQL(aId:string): String;
function GetBeforeInsertUpdateSQL(aID:string): string;
function GetDeleteAllSQL: string;
function GetSectionScale(aSectionNo: String; aHeight: double; aWidth: double):TPoint;
public
{ Public declarations }
end;
var
SectionDrillForm: TSectionDrillForm;
m_sgSectionSelectedRow: integer;
implementation
uses MainDM, public_unit;
{$R *.dfm}
procedure TSectionDrillForm.FormCreate(Sender: TObject);
begin
self.Left := trunc((screen.Width -self.Width)/2);
self.Top := trunc((Screen.Height - self.Height)/2);
sgSection.RowCount :=2;
sgSection.ColCount :=2;
sgSection.Cells[1,0]:= '剖面编号';
sgSection.RowHeights[0]:= 16;
sgSection.ColWidths[0]:=10;
sgSection.ColWidths[1]:=60;
sgDrills.RowCount :=2;
sgDrills.ColCount := 2;
sgDrills.RowHeights[0] := 16;
sgDrills.Cells[1,0] := '孔号';
//sgDrills.Cells[2,0] := '孔口标高(m)';
//sgDrills.Cells[3,0] := '孔深(m)';
sgDrills.ColWidths[0]:=10;
sgDrills.ColWidths[1]:=130;
//sgDrills.ColWidths[2]:=100;
//sgDrills.ColWidths[2]:=100;
sgSectionDrills.RowCount := 2;
sgSectionDrills.ColCount := 3;
sgSectionDrills.Cells[0,0] := '序号';
sgSectionDrills.Cells[1,0] := '钻孔编号';
sgSectionDrills.Cells[2,0] := '下孔间距(m)';
sgSectionDrills.RowHeights[0] :=16;
sgSectionDrills.ColWidths[0] :=30;
sgSectionDrills.ColWidths[1] :=120;
sgSectionDrills.ColWidths[2] :=80;
m_sgSectionSelectedRow:= -1;
GetSectionByProjectNo(g_ProjectInfo.prj_no);
GetAllDrillsByProjectNo(g_ProjectInfo.prj_no);
sgSection.Row := 1;
if sgSection.Cells[1,1]<>'' then
begin
GetDrillsBySectionNo(sgSection.Cells[1,1]);
m_sgSectionSelectedRow:=1;
end;
end;
procedure TSectionDrillForm.GetDrillsBySectionNo(aSectionNo: String);
var
i: integer;
begin
sgSectionDrills.RowCount :=2;
DeleteStringGridRow(sgSectionDrills,1);
if aSectionNo = '' then exit;
with MainDataModule.qrySectionDrill do
begin
close;
sql.Clear;
sql.Add('SELECT prj_no,sec_no,id,drl_no,kjj FROM section_drill WHERE ');
sql.Add(' prj_no='+''''+g_ProjectInfo.prj_no_ForSQL+'''');
sql.Add(' AND sec_no='+''''+stringReplace(aSectionNo,'''','''''',[rfReplaceAll])+'''');
sql.Add(' ORDER BY id');
Open;
i:=0;
while not eof do
begin
i:=i+1;
sgSectionDrills.RowCount := i +2;
sgSectionDrills.RowCount := i +1;
sgSectionDrills.Cells[0,i] := inttostr(i);
sgSectionDrills.Cells[1,i] := FieldByName('drl_no').AsString;
sgSectionDrills.Cells[2,i] := FieldByName('kjj').AsString;
sgSectionDrills.Cells[3,i] := FieldByName('kjj').AsString;
Next ;
end;
close;
end;
end;
procedure TSectionDrillForm.GetSectionByProjectNo(aProjectNo:String);
var
i: integer;
begin
with MainDataModule.qrySection do
begin
close;
sql.Clear;
sql.Add('SELECT prj_no,sec_no FROM section WHERE ');
sql.Add('prj_no='+''''+stringReplace(aProjectNo,'''','''''',[rfReplaceAll])+'''');
Open;
i:=0;
sgSection.Tag :=1; //设置Tag是因为每次给StringGrid赋值都会触发它的SelectCell事件,为了避免这种情况,
//在SelectCell事件中当Tag=1时不执行在SelectCell事件中的操作.
while not eof do
begin
i:=i+1;
sgSection.RowCount := i +2;
sgSection.RowCount := i +1;
sgSection.Cells[1,i] := FieldByName('sec_no').AsString;
Next ;
end;
sgSection.Tag :=0;
close;
end;
end;
procedure TSectionDrillForm.sgSectionSelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
begin
if TStringGrid(Sender).Tag = 1 then exit; //设置Tag是因为每次给StringGrid赋值都会触发它的SelectCell事件,为了避免这种情况,
//在SelectCell事件中用Tag值来判断是否应该执行在SelectCell中的操作.
if (ARow <>0) and (ARow<>m_sgSectionSelectedRow) then
begin
GetDrillsBySectionNo(sgSection.Cells[1,ARow]);
end;
m_sgSectionSelectedRow:=ARow;
end;
procedure TSectionDrillForm.btn_cancelClick(Sender: TObject);
begin
self.Close;
end;
procedure TSectionDrillForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
UpdateKjj;
Action:= caFree;
end;
procedure TSectionDrillForm.GetAllDrillsByProjectNo(aProjectNo: String);
var
i: integer;
begin
with MainDataModule.qryDrills do
begin
close;
sql.Clear;
//sql.Add('select prj_no,prj_name,area_name,builder,begin_date,end_date,consigner from projects');
sql.Add('SELECT prj_no,drl_no,drl_elev,comp_depth');
sql.Add(' FROM drills ');
sql.Add(' WHERE prj_no='+''''+stringReplace(aProjectNo,'''','''''',[rfReplaceAll])+'''');
open;
i:=0;
while not Eof do
begin
i:=i+1;
sgDrills.RowCount := i +2;
sgDrills.RowCount := i +1;
sgDrills.Cells[1,i] := FieldByName('drl_no').AsString;
sgDrills.Cells[2,i] := FieldByName('drl_elev').AsString;
sgDrills.Cells[3,i] := FieldByName('comp_depth').AsString;
Next ;
end;
close;
end;
end;
procedure TSectionDrillForm.btnAddClick(Sender: TObject);
var
strSQL: String;
begin
if sgDrills.Cells[1,sgDrills.row]='' then exit;
if sgSection.Cells[1,sgSection.row]='' then exit;
if sgSectionDrills.Cells[1,1]='' then
begin
sgSectionDrills.Cells[0,1]:='1';
sgSectionDrills.Cells[1,1]:=sgDrills.Cells[1,sgDrills.row];
end
else
begin
sgSectionDrills.RowCount := sgSectionDrills.RowCount +2;
sgSectionDrills.RowCount := sgSectionDrills.RowCount -1;
sgSectionDrills.Cells[0,sgSectionDrills.RowCount-1]:=intToStr(sgSectionDrills.RowCount-1);
sgSectionDrills.Cells[1,sgSectionDrills.RowCount-1]:=sgDrills.Cells[1,sgDrills.row];
end;
strSQL:=getInsertSQL;
if not Insert_oneRecord(MainDataModule.qrySectionDrill,strSQL) then
begin
if sgSectionDrills.RowCount=2 then
DeleteStringGridRow(sgSectionDrills,1)
else
sgSectionDrills.RowCount := sgSectionDrills.RowCount -1;
end;
end;
function TSectionDrillForm.GetDeleteSQL: string;
begin
result :='DELETE FROM section_drill '
+' WHERE prj_no=' +''''+g_ProjectInfo.prj_no_ForSQL +''''
+' AND sec_no=' +''''+stringReplace(trim(sgSection.Cells[1,sgSection.row]),'''','''''',[rfReplaceAll])+''''
+' AND id=' +''''+sgSectionDrills.Cells[0,sgSectionDrills.Row]+'''';
end;
function TSectionDrillForm.GetInsertSQL: string;
begin
result := 'INSERT INTO section_drill (prj_no,sec_no,id,drl_no) VALUES('
+''''+g_ProjectInfo.prj_no_ForSQL +''''+','
+''''+stringReplace(trim(sgSection.Cells[1,sgSection.row]),'''','''''',[rfReplaceAll])+''''+','
+''''+stringReplace(trim(sgSectionDrills.Cells[0,sgSectionDrills.RowCount-1]),'''','''''',[rfReplaceAll])+''''+','
+''''+stringReplace(trim(sgSectionDrills.Cells[1,sgSectionDrills.RowCount-1]),'''','''''',[rfReplaceAll])+''''+')';
end;
function TSectionDrillForm.GetUpdateSQL: string;
var
strSQLWhere,strSQLSet:string;
begin
strSQLWhere:=' WHERE prj_no=' +''''+g_ProjectInfo.prj_no_ForSQL +''''
+' AND sec_no=' +''''+stringReplace(trim(sgSection.Cells[1,sgSection.row]),'''','''''',[rfReplaceAll])+''''
+' AND id=' +''''+sgSectionDrills.Cells[0,sgSectionDrills.Row]+'''';
strSQLSet:='UPDATE section_drill SET ';
strSQLSet := strSQLSet + 'drl_no' +'='+''''+stringReplace(sgDrills.Cells[1,sgDrills.row],'''','''''',[rfReplaceAll])+'''';
result := strSQLSet + strSQLWhere;
end;
procedure TSectionDrillForm.btnDeleteClick(Sender: TObject);
var
strSQL,strID: string;
i: integer;
begin
//if MessageBox(self.Handle,
// '您确定要删除吗?','警告', MB_YESNO+MB_ICONQUESTION)=IDNO then exit;
strID :='';
strID := sgSectionDrills.Cells[0,sgSectionDrills.Row];
if strID <> '' then
begin
strSQL := self.GetDeleteSQL;
if Delete_oneRecord(MainDataModule.qrySectionDrill,strSQL) then
begin
if (sgSectionDrills.Row <> sgSectionDrills.RowCount-1) then
begin
strSQL:=self.GetAfterDeleteUpdateSQL(strID);
DeleteStringGridRow(sgSectionDrills,sgSectionDrills.Row);
if update_oneRecord(MainDataModule.qrySectionDrill,strSQL) then
for i:=1 to sgSectionDrills.RowCount-1 do
sgSectionDrills.Cells[0,i]:= IntToStr(i);
end
else
DeleteStringGridRow(sgSectionDrills,sgSectionDrills.Row);
end;
end;
end;
function TSectionDrillForm.GetDeleteAllSQL: string;
begin
result :='DELETE FROM section_drill '
+' WHERE prj_no=' +''''+g_ProjectInfo.prj_no_ForSQL +''''
+' AND sec_no=' +''''+stringReplace(trim(sgSection.Cells[1,sgSection.row]),'''','''''',[rfReplaceAll])+'''';
end;
procedure TSectionDrillForm.btnDeleteAllClick(Sender: TObject);
var
strSQL,strID: string;
begin
//if MessageBox(self.Handle,
// '您确定要删除吗?','警告', MB_YESNO+MB_ICONQUESTION)=IDNO then exit;
strID :='';
strID := sgSectionDrills.Cells[0,sgSectionDrills.Row];
if strID <> '' then
begin
strSQL := self.GetDeleteAllSQL;
if Delete_oneRecord(MainDataModule.qrySectionDrill,strSQL) then
begin
sgSectionDrills.RowCount := 2;
DeleteStringGridRow(sgSectionDrills,1);
end;
end;
end;
procedure TSectionDrillForm.btnEditClick(Sender: TObject);
var
strSQL: string;
begin
if sgSectionDrills.Cells[1,sgSectionDrills.Row]='' then exit;
strSQL:='';
if sgDrills.Cells[1,sgDrills.row]='' then exit;
if sgSection.Cells[1,sgSection.row]='' then exit;
strSQL:= GetUpdateSQL;
if Update_oneRecord(MainDataModule.qryStratum,strSQL) then
sgSectionDrills.Cells[1,sgSectionDrills.Row]:=sgDrills.Cells[1,sgDrills.Row];
end;
procedure TSectionDrillForm.sgSectionDrillsDrawCell(Sender: TObject; ACol,
ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
if aRow<>0 then
if ACol=0 then
AlignGridCell(Sender,ACol,ARow,Rect,taCenter)
else if ACol=1 then
AlignGridCell(Sender,ACol,ARow,Rect,taLeftJustify)
else
AlignGridCell(Sender,ACol,ARow,Rect,taRightJustify);
end;
function TSectionDrillForm.GetAfterDeleteUpdateSQL(aId: string): String;
var
strSQLWhere,strSQLSet:string;
begin
strSQLWhere:=' WHERE prj_no=' +''''+g_ProjectInfo.prj_no_ForSQL+''''
+' AND sec_no=' +''''+stringReplace(trim(sgSection.Cells[1,sgSection.row]),'''','''''',[rfReplaceAll])+''''
+' AND id>' +aId;
strSQLSet:='UPDATE section_drill SET ';
strSQLSet := strSQLSet + 'id=id-1';
result := strSQLSet + strSQLWhere;
end;
//GetSectionScale 取得一个剖面图的横纵比例
// aSectionNo :剖面编号
// aHeight :任意剖面的钻孔在打印纸上实际占的范围的高度(单位是mm)
// aWidth :任意剖面的钻孔在打印纸上实际占的范围的宽度(单位是mm)
//返回值TPoint : TPoint.X 横比例 TPoint.Y 纵比例
function TSectionDrillForm.GetSectionScale(aSectionNo: String; aHeight: double; aWidth: double): TPoint;
const
M2MM = 1000; // 1m=1000mm
var
ScalePoint: TPoint;
i: integer;
bZuoBiao: boolean; //用这个来判断是否用孔的坐标来计算孔间距
totalZuoBiaoWidth, //用钻孔坐标来计算得到的剖面的宽度
totalKjjWidth, //用钻孔间距来计算得到的剖面的宽度
totalHeight, //剖面的高度
tempKjj, //临时变量,记录当前钻孔到下一钻孔的距离
maxTopElev,MinBottElev,//最大钻孔标高,最小钻孔底标高
preX,preY, //前一记录钻孔的坐标
nowX,nowY: double; //当前记录钻孔的坐标
begin
ScalePoint.X := 0;
ScalePoint.Y := 0;
if (aHeight<=0) or (aWidth<=0) then
begin
result:= ScalePoint;
exit;
end;
totalZuoBiaoWidth:=0;
totalKjjWidth:=0;
tempKjj:= 0;
totalHeight:=0;
maxTopElev:=0;
MinBottElev:=0;
preX:=0;
preY:=0;
nowX:=0;
nowY:=0;
i:=0;
bZuoBiao:= true;
with MainDataModule.qrySectionDrill do
begin
close;
sql.Clear;
sql.Add('SELECT s.prj_no,s.sec_no,s.id,s.drl_no,s.kjj,d.drl_elev,'
+'d.drl_elev-d.comp_depth drl_bott,d.drl_x,d.drl_y'
+' FROM section_drill s,drills d WHERE ');
sql.Add(' s.prj_no='+''''+g_ProjectInfo.prj_no_ForSQL+'''');
sql.Add(' AND s.sec_no='+''''+stringReplace(aSectionNo,'''','''''',[rfReplaceAll])+'''');
sql.Add(' AND s.prj_no = d.prj_no');
sql.Add(' ORDER BY s.id');
Open;
while not eof do
begin
tempKjj:= FieldByName('kjj').AsFloat;
totalKjjWidth := totalKjjWidth + tempKjj;
Inc(i);
if i=1 then
begin
preX:= FieldByName('drl_x').AsFloat;
preY:= FieldByName('drl_y').AsFloat;
maxTopElev:= FieldByName('drl_elev').AsFloat;
MinBottElev:=FieldByName('drl_bott').AsFloat;
end;
if i>1 then
begin
if maxTopElev < FieldByName('drl_elev').AsFloat then
maxTopElev:= FieldByName('drl_elev').AsFloat;
if MinBottElev>FieldByName('drl_bott').AsFloat then
MinBottElev:=FieldByName('drl_bott').AsFloat;
if (FieldByName('drl_x').AsString ='')
or (FieldByName('drl_y').AsString ='') then
bZuoBiao:= false;
if bZuoBiao then
begin
nowX:= FieldByName('drl_x').AsFloat;
nowY:= FieldByName('drl_y').AsFloat;
totalZuoBiaoWidth:= totalZuoBiaoWidth + sqrt(sqr(nowX-preX)+sqr(nowY-preY));
end;
end;
Next;
end;
close;
end;
totalKjjWidth := totalKjjWidth - tempKjj; //减去剖面中最后一个钻孔的孔间距离,在上面的循环中多加了。
if bZuoBiao then
scalePoint.X := round(totalZuoBiaoWidth * M2MM / aWidth)
else
scalePoint.X := round(totalKjjWidth * M2MM / aWidth);
if scalePoint.X <=100 then
scalePoint.X :=100
else if scalePoint.X<=1000 then
begin
if (scalePoint.X mod 100)<>0 then
scalePoint.X:= (scalePoint.X div 100) * 100 +100;
end
else if scalePoint.X<=10000 then
begin
if (scalePoint.X mod 500)<>0 then
scalePoint.X:= (scalePoint.X div 500) * 500 +500;
end
else
if (scalePoint.X mod 5000)<>0 then
scalePoint.X:= (scalePoint.X div 5000) * 5000 +5000;
scalePoint.Y := round((maxTopElev - minBottElev) * M2MM / aHeight);
if scalePoint.Y <=100 then
scalePoint.Y :=100
else if scalePoint.Y<=1000 then
begin
if (scalePoint.Y mod 100)<>0 then
scalePoint.Y:= (scalePoint.Y div 100) * 100 +100;
end
else if scalePoint.Y<=10000 then
begin
if (scalePoint.Y mod 500)<>0 then
scalePoint.Y:= (scalePoint.Y div 500) * 500 +500;
end
else
if (scalePoint.Y mod 5000)<>0 then
scalePoint.Y:= (scalePoint.Y div 5000) * 5000 +5000;
result := scalePoint;
end;
procedure TSectionDrillForm.sgSectionDrillsExit(Sender: TObject);
begin
UpdateKjj;
end;
procedure TSectionDrillForm.UpdateKjj;
var
strSQL,strAllSQL: string;
i: integer;
begin
strAllSQL := '';
for i:=1 to sgSectionDrills.RowCount -1 do
begin
if (sgSectionDrills.Cells[1,i]<>'')
and (sgSectionDrills.Cells[2,i]<>sgSectionDrills.Cells[3,i]) then
begin
strSQL:=' UPDATE section_drill SET kjj=';
if trim(sgSectionDrills.Cells[2,i])<>'' then
strSQL:= strSQL +''''+sgSectionDrills.Cells[2,i]+''''
else
strSQL:= strSQL + 'NULL';
strSQL:= strSQL
+' WHERE prj_no=' +''''+g_ProjectInfo.prj_no_ForSQL +''''
+' AND sec_no=' +''''+stringReplace(trim(sgSection.Cells[1,sgSection.row]),'''','''''',[rfReplaceAll])+''''
+' AND id=' +''''+sgSectionDrills.Cells[0,i]+'''';
strAllsql:= strallsql + strsql;
//if Update_oneRecord(MainDataModule.qryStratum,strSQL) then
sgSectionDrills.Cells[3,i]:= sgSectionDrills.Cells[2,i];
end;
end;
if strAllSQL<>'' then
Update_oneRecord(MainDataModule.qryStratum,strAllsql);
end;
procedure TSectionDrillForm.btnShouGongClick(Sender: TObject);
var
NewString, DrillNO, strSQL: string;
ClickedOK: Boolean;
DrillNoList: TStringList;
i,iRowID: Integer;
begin
NewString := '';
ClickedOK := InputQuery('输入框', '钻孔编号,格式为 C1 C2 C3 ', NewString);
if ClickedOK and (trim(NewString)<>'') then { NewString contains new input string }
begin
try
DrillNoList := TStringList.Create;
DivideString(trim(NewString),' ',DrillNoList);
if DrillNoList.Count >0 then
begin
for I := 0 to DrillNoList.Count - 1 do // Iterate
begin
DrillNo := DrillNoList.Strings[i];
if sgSectionDrills.Cells[1,1]='' then
begin
sgSectionDrills.Cells[0,1]:='1';
sgSectionDrills.Cells[1,1]:=sgDrills.Cells[1,sgDrills.row];
end
else
begin
sgSectionDrills.RowCount := sgSectionDrills.RowCount +2;
sgSectionDrills.RowCount := sgSectionDrills.RowCount -1;
sgSectionDrills.Cells[0,sgSectionDrills.RowCount-1]:=intToStr(sgSectionDrills.RowCount-1);
sgSectionDrills.Cells[1,sgSectionDrills.RowCount-1]:=DrillNo;
end;
strSQL := 'INSERT INTO section_drill (prj_no,sec_no,id,drl_no) VALUES('
+''''+g_ProjectInfo.prj_no_ForSQL +''''+','
+''''+stringReplace(trim(sgSection.Cells[1,sgSection.row]),'''','''''',[rfReplaceAll])+''''+','
+''''+intToStr(sgSectionDrills.RowCount-1)+''''+','
+''''+stringReplace(DrillNo,'''','''''',[rfReplaceAll])+''''+')';
if not Insert_oneRecord(MainDataModule.qrySectionDrill,strSQL) then
sgSectionDrills.RowCount := sgSectionDrills.RowCount -1;
end; // for
//GetDrillsBySectionNo(sgSection.Cells[1,m_sgSectionSelectedRow]);
end;
finally
DrillNoList.Free;
end;
end;
end;
function TSectionDrillForm.GetBeforeInsertUpdateSQL(aID: string): string;
var
strSQLWhere,strSQLSet:string;
begin
strSQLWhere:=' WHERE prj_no=' +''''+g_ProjectInfo.prj_no_ForSQL+''''
+' AND sec_no=' +''''+stringReplace(trim(sgSection.Cells[1,sgSection.row]),'''','''''',[rfReplaceAll])+''''
+' AND id>' +aId;
strSQLSet:='UPDATE section_drill SET ';
strSQLSet := strSQLSet + 'id=id+1';
result := strSQLSet + strSQLWhere;
end;
procedure TSectionDrillForm.btnInsertClick(Sender: TObject);
var
strSQL,drl_no,sec_No: String;
iRow,iRowCount : integer;
begin
if sgDrills.Cells[1,sgDrills.row]='' then exit;
if sgSection.Cells[1,sgSection.row]='' then exit;
iRow := sgSectionDrills.Row ;
sec_No := trim(sgSection.Cells[1,sgSection.row]);
drl_no := trim(sgDrills.Cells[1,sgDrills.row]);
if sgSectionDrills.Cells[1,1]='' then
begin
strSQL := 'INSERT INTO section_drill (prj_no,sec_no,id,drl_no) VALUES('
+''''+g_ProjectInfo.prj_no_ForSQL +''''+','
+''''+stringReplace(sec_No,'''','''''',[rfReplaceAll])+''''+','
+''''+inttostr(1)+''''+','
+''''+stringReplace(drl_no,'''','''''',[rfReplaceAll])+''''+')';
if Insert_oneRecord(MainDataModule.qrySectionDrill,strSQL) then
begin
sgSectionDrills.Cells[0,1]:='1';
sgSectionDrills.Cells[1,1]:=drl_no;
end;
end
else
begin
strSQL := 'UPDATE section_drill SET id=id+1 WHERE '
+' prj_no='+''''+g_ProjectInfo.prj_no_ForSQL +''''
+' AND sec_no= '+''''+stringReplace(sec_No,'''','''''',[rfReplaceAll])+''''
+' AND id>='+IntToStr(iRow);
if Update_oneRecord(MainDataModule.qrySectionDrill,strSQL) then
begin
strSQL := 'INSERT INTO section_drill (prj_no,sec_no,id,drl_no) VALUES('
+''''+g_ProjectInfo.prj_no_ForSQL +''''+','
+''''+stringReplace(sec_No,'''','''''',[rfReplaceAll])+''''+','
+''''+inttostr(iRow)+''''+','
+''''+stringReplace(drl_no,'''','''''',[rfReplaceAll])+''''+')';
if Insert_oneRecord(MainDataModule.qrySectionDrill,strSQL) then
begin
sgSectionDrills.RowCount := sgSectionDrills.RowCount+1;
for iRowCount := sgSectionDrills.RowCount -1 downto irow+1 do
begin
sgSectionDrills.Cells[0,iRowCount]:=InttoStr(iRowCount);
sgSectionDrills.Cells[1,iRowCount]:=sgSectionDrills.Cells[1,iRowCount-1];
sgSectionDrills.Cells[2,iRowCount]:=sgSectionDrills.Cells[2,iRowCount-1];
end;
sgSectionDrills.Cells[1,iRow]:=drl_no;
sgSectionDrills.Cells[2,iRow]:='';
end;
end;
end;
end;
end.
|
program GenericFunc(input,output);
const
hex = ['a'..'f', 'A'..'F'];
decimal= ['0'..'9'];
var
a, b, c, d:integer;
fresult:integer;
func: integer;
(* Here is a second version of the Pascal generic function that uses *)
(* the features of Turbo Pascal to simplify the program. *)
function ReadFunc:integer;
var ch:char;
i, val:integer;
begin
write('Enter function number (hexadecimal): ');
repeat
read(ch);
func := 0;
if not eoln then begin
if (ch in Hex) then
func := (func shl 4) + (ord(ch) and 15) + 9
else if (ch in Decimal) then
func := (func shl 4) + (ord(ch) and 15)
else write(chr(7));
end;
until eoln;
ReadFunc := func;
end;
(* Generic - Computes the generic logical function specified by *)
(* the function number "func" on the four input vars *)
(* a, b, c, and d. It does this by returning bit *)
(* d*8 + c*4 + b*2 + a from func. This version re- *)
(* lies on Turbo Pascal's shift right operator and *)
(* its ability to do bitwise operations on integers. *)
function Generic(func,a,b,c,d:integer):integer;
begin
Generic := (func shr (a + b*2 + c*4 + d*8)) and 1;
end;
begin (* main *)
repeat
fresult := ReadFunc;
if (fresult <> 0) then begin
write('Enter values for D, C, B, & A (0/1):');
readln(d, c, b, a);
writeln('The result is ',Generic(func,a,b,c,d));
end;
until fresult = 0;
end. |
unit uCfgStorage;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, IniFiles, Unix;
type
TCfgStorage = class
private
ini : TIniFile;
crit : TRTLCriticalSection;
public
constructor Create(IniFile : String);
destructor Destroy; override;
function ReadString(Section, Ident, Default: string): string;
function ReadInteger(Section, Ident: string; Default: Longint): Longint;
function ReadBool(Section, Ident: string; Default: Boolean): Boolean;
function ReadFloat(Section, Ident: string; Default: Double): Double;
procedure ReadSection(const Section: string; Strings: TStrings);
procedure ReadSectionRaw(const Section: string; Strings: TStrings);
procedure WriteString(const Section, Ident, Value: String);
procedure WriteInteger(const Section, Ident: string; Value: Longint);
procedure WriteBool(const Section, Ident: string; Value: Boolean);
procedure WriteFloat(const Section, Ident: string; Value: Double);
procedure DeleteKey(const Section, Ident: String);
procedure SaveToDisk;
function SectionExists(Section : String) : Boolean;
function ValueExists(const Section, Ident: string): Boolean;
end;
var
iniLocal : TCfgStorage;
iniGlobal : TCfgStorage;
implementation
constructor TcfgStorage.Create(IniFile : String);
begin
ini := TIniFile.Create(IniFile);
InitCriticalSection(crit)
end;
function TcfgStorage.ReadString(Section, Ident, Default: string): string;
begin
Result := Default;
EnterCriticalsection(crit);
try
Result := ini.ReadString(Section,Ident,Default)
finally
LeaveCriticalsection(crit)
end
end;
function TcfgStorage.ReadInteger(Section, Ident: string; Default: Longint): Longint;
begin
Result := Default;
EnterCriticalsection(crit);
try
Result := ini.ReadInteger(Section,Ident,Default)
finally
LeaveCriticalsection(crit)
end
end;
function TcfgStorage.ReadBool(Section, Ident: string; Default: Boolean): Boolean;
begin
Result := Default;
EnterCriticalsection(crit);
try
Result := ini.ReadBool(Section,Ident,Default)
finally
LeaveCriticalsection(crit)
end
end;
function TcfgStorage.ReadFloat(Section, Ident: string; Default: Double): Double;
begin
Result := Default;
EnterCriticalsection(crit);
try
Result := ini.ReadFloat(Section,Ident,Default)
finally
LeaveCriticalsection(crit)
end
end;
procedure TcfgStorage.ReadSection(const Section: string; Strings: TStrings);
begin
EnterCriticalsection(crit);
try
ini.ReadSection(Section,Strings)
finally
LeaveCriticalsection(crit)
end
end;
procedure TcfgStorage.ReadSectionRaw(const Section: string; Strings: TStrings);
begin
EnterCriticalsection(crit);
try
ini.ReadSectionRaw(Section,Strings)
finally
LeaveCriticalsection(crit)
end
end;
procedure TcfgStorage.WriteString(const Section, Ident, Value: String);
begin
EnterCriticalsection(crit);
try
ini.WriteString(Section,Ident,Value)
finally
LeaveCriticalsection(crit)
end
end;
procedure TcfgStorage.WriteInteger(const Section, Ident: string; Value: Longint);
begin
EnterCriticalsection(crit);
try
ini.WriteInteger(Section,Ident,Value)
finally
LeaveCriticalsection(crit)
end
end;
procedure TcfgStorage.WriteBool(const Section, Ident: string; Value: Boolean);
begin
EnterCriticalsection(crit);
try
ini.WriteBool(Section,Ident,Value)
finally
LeaveCriticalsection(crit)
end
end;
procedure TcfgStorage.WriteFloat(const Section, Ident: string; Value: Double);
begin
EnterCriticalsection(crit);
try
ini.WriteFloat(Section,Ident,Value)
finally
LeaveCriticalsection(crit)
end
end;
procedure TcfgStorage.DeleteKey(const Section, Ident: String);
begin
EnterCriticalsection(crit);
try
ini.DeleteKey(Section,Ident)
finally
LeaveCriticalsection(crit)
end
end;
procedure TcfgStorage.SaveToDisk;
begin
ini.UpdateFile
end;
function TcfgStorage.SectionExists(Section : String) : Boolean;
begin
Result := False;
EnterCriticalsection(crit);
try
Result := ini.SectionExists(Section)
finally
LeaveCriticalsection(crit)
end
end;
function TcfgStorage.ValueExists(const Section, Ident: string): Boolean;
begin
Result := False;
EnterCriticalsection(crit);
try
Result := ini.ValueExists(Section,Ident)
finally
LeaveCriticalsection(crit)
end
end;
destructor TcfgStorage.Destroy;
begin
FreeAndNil(ini);
DoneCriticalsection(crit)
end;
end.
|
{**********************************************}
{ TTeeGalleryForm - Alternate Gallery }
{ Copyright (c) 1996-2004 by David Berneda }
{**********************************************}
unit TeeGalleryAlternate;
{$I TeeDefs.inc}
interface
{ This unit implements a Form to display the TeeChart Gallery
in an alternate format.
Series types are located in the left-hand ListBox, while
sub-types are displayed using the normal Chart Gallery.
This form can be used for example embedded into another form
(see below).
}
uses
Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QExtCtrls, QStdCtrls, Qt,
{$ELSE}
Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls,
{$ENDIF}
TeeProcs, TeEngine, Chart, TeeGalleryPanel, TeeLisB, Series, TeCanvas;
type
TTeeGalleryForm = class(TForm)
ChartGalleryPanel1: TChartGalleryPanel;
ChartListBox1: TChartListBox;
Splitter1: TSplitter;
Panel1: TPanel;
CBPage: TComboFlat;
Label1: TLabel;
CB3D: TCheckBox;
CBSmooth: TCheckBox;
PanelBottom: TPanel;
Panel3: TPanel;
BOK: TButton;
BCancel: TButton;
procedure FormCreate(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ChartListBox1Click(Sender: TObject);
procedure CBPageChange(Sender: TObject);
procedure CB3DClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure CBSmoothClick(Sender: TObject);
procedure ChartGalleryPanel1SelectedChart(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
Chart : TChart;
OldClass : TChartSeriesClass;
Procedure CreateChartList(Const APage:String);
Procedure CreateGallery(AClass:TChartSeriesClass);
Procedure FillGalleryPages(AItems:TStrings);
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
{ Embedding this form inside another form can be done like this:
Uses TeeGalleryAlternate, TeePenDlg;
TMyForm = class(TForm)
procedure FormShow(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
Gallery : TTeeGalleryForm;
public
end;
procedure TMyForm.FormShow(Sender: TObject);
begin
Gallery:=TTeeGalleryForm.Create(Self);
Gallery.Align:=alClient;
Gallery.PanelBottom.Visible:=False;
AddFormTo(Gallery,Self,0);
end;
procedure TMyForm.FormDestroy(Sender: TObject);
begin
Gallery.Free;
end;
}
uses
TeeConst;
procedure TTeeGalleryForm.FormCreate(Sender: TObject);
begin
Chart:=TChart.Create(Self);
ChartListBox1.Chart:=Chart;
ChartListBox1.Sorted:=True;
FillGalleryPages(CBPage.Items);
CBPage.Items.Insert(0,TeeMsg_All);
CBPage.ItemIndex:=CBPage.Items.IndexOf(TeeMsg_GalleryStandard);
// Init checkbox using default "smooth" value from inifile or registry.
CBSmooth.Checked:=ChartGalleryPanel1.DefaultSmooth;
end;
type
TGalleryAccess=class(TChartGalleryPanel);
procedure TTeeGalleryForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
TGalleryAccess(ChartGalleryPanel1).KeyDown(Key,Shift);
end;
procedure TTeeGalleryForm.ChartListBox1Click(Sender: TObject);
var AClass : TChartSeriesClass;
begin
if Assigned(ChartListBox1.SelectedSeries) then
begin
AClass:=TChartSeriesClass(ChartListBox1.SelectedSeries.ClassType);
if OldClass<>AClass then
begin
CreateGallery(AClass);
OldClass:=AClass;
end;
end;
end;
procedure TTeeGalleryForm.CBPageChange(Sender: TObject);
begin
if CBPage.ItemIndex=0 then
CreateChartList('')
else
CreateChartList(CBPage.Items[CBPage.ItemIndex]);
end;
procedure TTeeGalleryForm.CB3DClick(Sender: TObject);
begin
ChartGalleryPanel1.View3D:=CB3D.Checked;
end;
Procedure TTeeGalleryForm.FillGalleryPages(AItems:TStrings);
var t : Integer;
s : String;
begin
With TeeSeriesTypes do
for t:=0 to Count-1 do
begin
s:=Items[t].GalleryPage{$IFNDEF CLR}^{$ENDIF};
if AItems.IndexOf(s)=-1 then
if Items[t].FunctionClass=nil then
AItems.Add(s);
end;
end;
Procedure TTeeGalleryForm.CreateChartList(Const APage:String);
var t : Integer;
begin
ChartListBox1.Items.BeginUpdate;
try
Chart.FreeAllSeries;
with TeeSeriesTypes do
for t:=0 to Count-1 do
with Items[t] do
if FunctionClass=nil then
if (APage='') or (GalleryPage{$IFNDEF CLR}^{$ENDIF}=APage) then
Chart.AddSeries(SeriesClass).Title:=
ReplaceChar(TeeSeriesTypes.Find(SeriesClass).Description{$IFNDEF CLR}^{$ENDIF},TeeLineSeparator,' ');
ChartListBox1Click(Self);
finally
ChartListBox1.Items.EndUpdate;
end;
end;
type
TSeriesAccess=class(TChartSeries);
Procedure TTeeGalleryForm.CreateGallery(AClass:TChartSeriesClass);
begin
With {$IFNDEF CLR}TGalleryAccess{$ENDIF}(ChartGalleryPanel1) do
begin
NumRows:=3;
DisplaySub:=False;
tmpG:=ChartGalleryPanel1;
tmpType:=TTeeSeriesType.Create;
try
tmpType.SeriesClass:=AClass;
tmpType.NumGallerySeries:=1;
tmpType.FunctionClass:=nil;
Charts.Clear;
SelectedChart:=nil;
tmpSeries:=tmpType.SeriesClass.Create(nil);
try
TSeriesAccess(tmpSeries).CreateSubGallery(TGalleryAccess(ChartGalleryPanel1).CreateSubChart);
{$IFNDEF CLR}TGalleryAccess{$ENDIF}(ChartGalleryPanel1).ShowSelectedChart;
finally
tmpSeries.Free;
end;
finally
tmpType.Free;
end;
end;
end;
procedure TTeeGalleryForm.FormDestroy(Sender: TObject);
begin
Chart.Free;
end;
procedure TTeeGalleryForm.CBSmoothClick(Sender: TObject);
begin
ChartGalleryPanel1.Smooth:=CBSmooth.Checked;
end;
procedure TTeeGalleryForm.ChartGalleryPanel1SelectedChart(Sender: TObject);
begin
ModalResult:=mrOk;
end;
procedure TTeeGalleryForm.FormShow(Sender: TObject);
begin
// Do this here, to not re-translate ChartListBox1...
CBPageChange(Self);
end;
end.
|
{ 25/05/2007 11:17:33 (GMT+1:00) > [Akadamia] checked in }
{ 25/05/2007 11:04:22 (GMT+1:00) > [Akadamia] checked out /}
{ 14/02/2007 08:40:09 (GMT+0:00) > [Akadamia] checked in }
{ 14/02/2007 08:39:53 (GMT+0:00) > [Akadamia] checked out /}
{ 12/02/2007 10:15:00 (GMT+0:00) > [Akadamia] checked in }
{-----------------------------------------------------------------------------
Unit Name: TCU
Author: ken.adam
Date: 15-Jan-2007
Purpose: Translation of Throttle Control example to Delphi
Press A to increase the throttle
Press Z to decrease the throttle
History:
-----------------------------------------------------------------------------}
unit TCU;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ImgList, ToolWin, ActnMan, ActnCtrls, XPStyleActnCtrls,
ActnList, ComCtrls, SimConnect, StdActns;
const
// Define a user message for message driven version of the example
WM_USER_SIMCONNECT = WM_USER + 2;
type
// Use enumerated types to create unique IDs as required
TGroupId = (GroupKeys);
TInputId = (InputKeys);
TEventID = (EventSimStart, EventA, EventZ);
TDataDefineId = (DefinitionThrottle, DefineAlti);
TDataRequestId = (RequestThrottle);
PThrottleControl = ^TThrottleControl;
TThrottleControl = record
ThrottlePercent: double;
end;
// The form
TThrottleControlForm = class(TForm)
StatusBar: TStatusBar;
ActionManager: TActionManager;
ActionToolBar: TActionToolBar;
Images: TImageList;
Memo: TMemo;
StartPoll: TAction;
FileExit: TFileExit;
StartEvent: TAction;
Button1: TButton;
procedure StartPollExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure SimConnectMessage(var Message: TMessage); message
WM_USER_SIMCONNECT;
procedure StartEventExecute(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
RxCount: integer; // Count of Rx messages
Quit: boolean; // True when signalled to quit
hSimConnect: THandle; // Handle for the SimConection
Tc: TThrottleControl;
public
{ Public declarations }
procedure DispatchHandler(pData: PSimConnectRecv; cbData: DWORD; pContext:
Pointer);
end;
var
ThrottleControlForm: TThrottleControlForm;
implementation
resourcestring
StrRx6d = 'Rx: %6d';
{$R *.dfm}
{-----------------------------------------------------------------------------
Procedure: MyDispatchProc
Wraps the call to the form method in a simple StdCall procedure
Author: ken.adam
Date: 11-Jan-2007
Arguments:
pData: PSimConnectRecv
cbData: DWORD
pContext: Pointer
-----------------------------------------------------------------------------}
procedure MyDispatchProc(pData: PSimConnectRecv; cbData: DWORD; pContext:
Pointer); stdcall;
begin
ThrottleControlForm.DispatchHandler(pData, cbData, pContext);
end;
{-----------------------------------------------------------------------------
Procedure: DispatchHandler
Handle the Dispatched callbacks in a method of the form. Note that this is
used by both methods of handling the interface.
The original C++ example is broken, in that it incorrectly uses
SIMCONNECT_RECV_ID_SIMOBJECT_DATA_BYTYPE
instead of
SIMCONNECT_RECV_ID_SIMOBJECT_DATA
(Thanks, Scott!)
Author: ken.adam
Date: 11-Jan-2007
Arguments:
pData: PSimConnectRecv
cbData: DWORD
pContext: Pointer
-----------------------------------------------------------------------------}
procedure TThrottleControlForm.Button1Click(Sender: TObject);
var
hr: HRESULT;
tmp: double;
begin
tmp := 1006;
// Tc.ThrottlePercent := 50;
// hr := SimConnect_SetDataOnSimObject(hSimConnect,
// Ord(DefinitionThrottle), SIMCONNECT_OBJECT_ID_USER, 0, 0,
// SizeOf(tc), @tc);
// Memo.Lines.Add(Format('Setting throttle = %2.1f',
// [Tc.throttlePercent]));
Tc.ThrottlePercent := 1006;
hr := SimConnect_SetDataOnSimObject(hSimConnect,
Ord(DefineAlti), SIMCONNECT_OBJECT_ID_USER, 0, 0,
SizeOf(tc), @tc);
Memo.Lines.Add(Format('Setting alti = %5.1f',
[Tc.ThrottlePercent]));
end;
procedure TThrottleControlForm.DispatchHandler(pData: PSimConnectRecv; cbData:
DWORD;
pContext: Pointer);
var
hr: HRESULT;
Evt: PSimconnectRecvEvent;
OpenData: PSimConnectRecvOpen;
pObjData: PSimConnectRecvSimObjectData;
pS: PThrottleControl;
begin
// Maintain a display of the message count
Inc(RxCount);
StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]);
// Only keep the last 200 lines in the Memo
while Memo.Lines.Count > 200 do
Memo.Lines.Delete(0);
// Handle the various types of message
case TSimConnectRecvId(pData^.dwID) of
SIMCONNECT_RECV_ID_OPEN:
begin
StatusBar.Panels[0].Text := 'Opened';
OpenData := PSimConnectRecvOpen(pData);
with OpenData^ do
begin
Memo.Lines.Add('');
Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', [szApplicationName,
dwApplicationVersionMajor, dwApplicationVersionMinor,
dwApplicationBuildMajor, dwApplicationBuildMinor]));
Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', ['SimConnect',
dwSimConnectVersionMajor, dwSimConnectVersionMinor,
dwSimConnectBuildMajor, dwSimConnectBuildMinor]));
Memo.Lines.Add('');
end;
end;
SIMCONNECT_RECV_ID_SIMOBJECT_DATA:
begin
pObjData := PSimConnectRecvSimObjectData(pData);
case TDataRequestId(pObjData^.dwRequestID) of
RequestThrottle:
begin
// Read and set the initial throttle control value
pS := PThrottleControl(@pObjData^.dwData);
tc.throttlePercent := pS^.throttlePercent;
Memo.Lines.Add(Format('REQUEST_USERID received, throttle = %2.1f',
[pS^.throttlePercent]));
// Now turn the input events on
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(InputKeys),
ord(SIMCONNECT_STATE_ON));
end;
end;
end;
SIMCONNECT_RECV_ID_EVENT:
begin
evt := PSimconnectRecvEvent(pData);
case TEventId(evt^.uEventID) of
EventSimStart:
begin
// Send this request to get the user aircraft id (or rather throttle?)
hr := SimConnect_RequestDataOnSimObject(hSimConnect,
Ord(RequestThrottle), Ord(DefinitionThrottle),
SIMCONNECT_OBJECT_ID_USER, SIMCONNECT_PERIOD_ONCE);
end;
EventA:
begin
// Increase the throttle
if Tc.ThrottlePercent <= 95.0 then
Tc.ThrottlePercent := Tc.ThrottlePercent + 5.0;
hr := SimConnect_SetDataOnSimObject(hSimConnect,
Ord(DefinitionThrottle), SIMCONNECT_OBJECT_ID_USER, 0, 0,
SizeOf(tc), @tc);
Memo.Lines.Add(Format('Setting throttle = %2.1f',
[Tc.throttlePercent]));
end;
EventZ:
begin
// Increase the throttle
if Tc.ThrottlePercent >= 5.0 then
Tc.ThrottlePercent := Tc.ThrottlePercent - 5.0;
hr := SimConnect_SetDataOnSimObject(hSimConnect,
Ord(DefinitionThrottle), SIMCONNECT_OBJECT_ID_USER, 0, 0,
SizeOf(tc), @tc);
Memo.Lines.Add(Format('Setting throttle = %2.1f',
[Tc.throttlePercent]));
end;
end;
end;
SIMCONNECT_RECV_ID_QUIT:
begin
Quit := True;
StatusBar.Panels[0].Text := 'FS X Quit';
end
else
Memo.Lines.Add(Format('Unknown dwID: %d', [pData.dwID]));
end;
end;
{-----------------------------------------------------------------------------
Procedure: FormCloseQuery
Ensure that we can signal "Quit" to the busy wait loop
Author: ken.adam
Date: 11-Jan-2007
Arguments: Sender: TObject var CanClose: Boolean
Result: None
-----------------------------------------------------------------------------}
procedure TThrottleControlForm.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
Quit := True;
CanClose := True;
end;
{-----------------------------------------------------------------------------
Procedure: FormCreate
We are using run-time dynamic loading of SimConnect.dll, so that the program
will execute and fail gracefully if the DLL does not exist.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
Result: None
-----------------------------------------------------------------------------}
procedure TThrottleControlForm.FormCreate(Sender: TObject);
begin
if InitSimConnect then
StatusBar.Panels[2].Text := 'SimConnect.dll Loaded'
else
begin
StatusBar.Panels[2].Text := 'SimConnect.dll NOT FOUND';
StartPoll.Enabled := False;
StartEvent.Enabled := False;
end;
Quit := False;
hSimConnect := 0;
StatusBar.Panels[0].Text := 'Not Connected';
RxCount := 0;
StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]);
end;
{-----------------------------------------------------------------------------
Procedure: SimConnectMessage
This uses CallDispatch, but could probably avoid the callback and use
SimConnect_GetNextDispatch instead.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
var Message: TMessage
-----------------------------------------------------------------------------}
procedure TThrottleControlForm.SimConnectMessage(var Message: TMessage);
begin
SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil);
end;
{-----------------------------------------------------------------------------
Procedure: StartEventExecute
Opens the connection for Event driven handling. If successful sets up the data
requests and hooks the system event "SimStart".
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
-----------------------------------------------------------------------------}
procedure TThrottleControlForm.StartEventExecute(Sender: TObject);
var
hr: HRESULT;
begin
if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Set Data', Handle,
WM_USER_SIMCONNECT, 0, 0))) then
begin
StatusBar.Panels[0].Text := 'Connected';
// Set up a data definition for the throttle control
hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionThrottle),
'GENERAL ENG THROTTLE LEVER POSITION:1', 'percent');
hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefineAlti),
'KOHLSMAN SETTING MB', 'Millibars');
// Request a simulation started event
hr := SimConnect_SubscribeToSystemEvent(hSimConnect, Ord(EventSimStart),
'SimStart');
// Create two private key events to control the throttle
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EventA));
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EventZ));
// Link the events to some keyboard keys
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(InputKeys), 'A',
Ord(EventA));
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(InputKeys), 'Z',
Ord(EventZ));
// Ensure the input events are off until the sim is up and running
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(InputKeys),
Ord(SIMCONNECT_STATE_OFF));
// Sign up for notifications
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GroupKeys),
Ord(EventA));
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GroupKeys),
Ord(EventZ));
StartEvent.Enabled := False;
StartPoll.Enabled := False;
end;
end;
{-----------------------------------------------------------------------------
Procedure: StartPollExecute
Opens the connection for Polled access. If successful sets up the data
requests and hooks the system event "SimStart", and then loops indefinitely
on CallDispatch.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
-----------------------------------------------------------------------------}
procedure TThrottleControlForm.StartPollExecute(Sender: TObject);
var
hr: HRESULT;
begin
if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Set Data', 0, 0, 0, 0))) then
begin
StatusBar.Panels[0].Text := 'Connected';
// Set up a data definition for the throttle control
hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionThrottle),
'GENERAL ENG THROTTLE LEVER POSITION:1', 'percent');
// Request a simulation started event
hr := SimConnect_SubscribeToSystemEvent(hSimConnect, Ord(EventSimStart),
'SimStart');
// Create two private key events to control the throttle
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EventA));
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EventZ));
// Link the events to some keyboard keys
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(InputKeys), 'A',
Ord(EventA));
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(InputKeys), 'Z',
Ord(EventZ));
// Ensure the input events are off until the sim is up and running
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(InputKeys),
Ord(SIMCONNECT_STATE_OFF));
// Sign up for notifications
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GroupKeys),
Ord(EventA));
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GroupKeys),
Ord(EventZ));
StartEvent.Enabled := False;
StartPoll.Enabled := False;
while not Quit do
begin
SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil);
Application.ProcessMessages;
Sleep(1);
end;
hr := SimConnect_Close(hSimConnect);
end;
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
SynHighlighterGeneral, SynHighlighterJScript, SynEditHighlighter,
SynHighlighterVBScript, SynEdit, ExtCtrls, SMScript, ComCtrls, Buttons,
StdCtrls, SynCompletionProposal, AngleLbl, TreeNT,
SMPanel, Menus;
type
TfrmPackage = class(TForm)
pnlToolbar: TPanel;
Editor: TSynEdit;
SynVBScriptSyn: TSynVBScriptSyn;
SynJScriptSyn: TSynJScriptSyn;
SynGeneralSyn: TSynGeneralSyn;
SMScriptExecutor: TSMScriptExecutor;
StatusBar: TStatusBar;
btnRunScript: TSpeedButton;
Splitter: TSplitter;
SynAutoComplete: TSynAutoComplete;
imgGutter: TImageList;
SynCompletionProposal: TSynCompletionProposal;
SplitterFunc: TSplitter;
imgScript: TImageList;
imgProcFunc: TImageList;
pnlErrors: TSMFramePanel;
lblErrors: TAngleLabel;
lbErrors: TListBox;
pnlTemplate: TSMFramePanel;
pcTemplates: TPageControl;
tsFunctions: TTabSheet;
lbScriptFuncs: TListBox;
pmEditor: TPopupMenu;
miUndo: TMenuItem;
miRedo: TMenuItem;
miSepar1: TMenuItem;
miCut: TMenuItem;
miCopy: TMenuItem;
miPaste: TMenuItem;
miSepar2: TMenuItem;
miSelectAll: TMenuItem;
miSepar3: TMenuItem;
miSaveAs: TMenuItem;
miLoad: TMenuItem;
miSepar4: TMenuItem;
miShowErrors: TMenuItem;
miShowTemplate: TMenuItem;
cbLanguage: TComboBox;
procedure EditorStatusChange(Sender: TObject;
Changes: TSynStatusChanges);
procedure btnRunScriptClick(Sender: TObject);
procedure EditorSpecialLineColors(Sender: TObject; Line: Integer;
var Special: Boolean; var FG, BG: TColor);
procedure FormShow(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormCreate(Sender: TObject);
procedure EditorChange(Sender: TObject);
function SynCompletionProposalPaintItem(AKey: String; ACanvas: TCanvas;
X, Y: Integer): Boolean;
procedure SynCompletionProposalCodeCompletion(var Value: String;
Shift: TShiftState);
procedure lbScriptFuncsDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure EditorDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure EditorDragDrop(Sender, Source: TObject; X, Y: Integer);
procedure lbScriptFuncsDblClick(Sender: TObject);
procedure miUndoClick(Sender: TObject);
procedure pmEditorPopup(Sender: TObject);
procedure cbLanguageChange(Sender: TObject);
procedure pnlToolbarResize(Sender: TObject);
private
{ Private declarations }
CodeIsParsed: Boolean;
procedure LoadScriptFuncs;
procedure DrawScriptFunc(IsSelected: Boolean; AKey: string; ACanvas: TCanvas; Obj, X, Y: Integer);
function GetScriptFunc(Value: string): string;
public
{ Public declarations }
end;
var
frmPackage: TfrmPackage;
implementation
{$R *.DFM}
procedure TfrmPackage.EditorStatusChange(Sender: TObject;
Changes: TSynStatusChanges);
var
ptCaret: TPoint;
begin
inherited;
ptCaret := Editor.CaretXY;
if (ptCaret.X > 0) and (ptCaret.Y > 0) then
StatusBar.Panels[0].Text := Format(' %6d:%3d ', [ptCaret.Y, ptCaret.X])
else
StatusBar.Panels[0].Text := '';
if Editor.Modified then
StatusBar.Panels[1].Text := 'Изменен'
else
StatusBar.Panels[1].Text := '';
if Editor.InsertMode then
StatusBar.Panels[2].Text := 'Вставка'
else
StatusBar.Panels[2].Text := 'Замена';
StatusBar.Panels[3].Text := SMScriptExecutor.LanguageStr
end;
procedure TfrmPackage.btnRunScriptClick(Sender: TObject);
var
err: TSMSEError;
strProcName: string;
IsCanceled: Boolean;
begin
btnRunScript.Enabled := False;
inherited;
lbErrors.Items.Clear;
Editor.InvalidateLine(SMScriptExecutor.LastError.Line);
try
if not CodeIsParsed then
begin
SMScriptExecutor.AddCode(Editor.Lines.Text);
SMScriptExecutor.Prepare;
SMScriptExecutor.ParseModules;
CodeIsParsed := True;
end;
if CodeIsParsed then
begin
strProcName := 'main';
IsCanceled := False;
if not IsCanceled then
SMScriptExecutor.Run(strProcName, NULL);//ExecuteStatement(Editor.Lines.Text);
end
except
on E: Exception do
begin
lbErrors.Items.Add(E.Message);
err := SMScriptExecutor.LastError;
if Assigned(err) then
begin
lbErrors.Items.Add('Error in line ' + IntToStr(err.Line) + ', col ' + intToStr(err.Column));
lbErrors.Items.Add(err.Number + ' ' + err.Source);
lbErrors.Items.Add('Description: ' + err.Description);
lbErrors.Items.Add('Message: ' + err.Text);
Editor.InvalidateLine(SMScriptExecutor.LastError.Line);
Editor.CaretXY := Point(err.Column+1, err.Line);
end
end;
end;
btnRunScript.Enabled := True;
end;
procedure TfrmPackage.EditorSpecialLineColors(Sender: TObject;
Line: Integer; var Special: Boolean; var FG, BG: TColor);
var
err: TSMSEError;
begin
inherited;
err := SMScriptExecutor.LastError;
if Assigned(err) then
if (err.Line = Line) then
begin
Special := True;
BG := clRed
end
end;
procedure TfrmPackage.FormShow(Sender: TObject);
begin
inherited;
case SMScriptExecutor.Language of
slVBScript: Editor.Highlighter := SynVBScriptSyn;
slJavaScript: Editor.Highlighter := SynJScriptSyn;
else
Editor.Highlighter := SynGeneralSyn;
end;
if (lbScriptFuncs.Items.Count = 0) then
LoadScriptFuncs;
// Editor.SetFocus
end;
procedure TfrmPackage.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if (Key = VK_F9) then
btnRunScript.Click
end;
procedure TfrmPackage.FormCreate(Sender: TObject);
begin
inherited;
CodeIsParsed := False;
end;
procedure TfrmPackage.EditorChange(Sender: TObject);
begin
inherited;
CodeIsParsed := False;
end;
procedure TfrmPackage.DrawScriptFunc(IsSelected: Boolean; AKey: string; ACanvas: TCanvas; Obj, X, Y: Integer);
var
i, j, intWidth: Integer;
s: string;
begin
{draw icon}
if (SMScriptExecutor.Language = slCustom) then
i := 3
else
i := Ord(SMScriptExecutor.Language);
imgScript.Draw(ACanvas, X, Y, i);
intWidth := imgScript.Width + 2;
if IsSelected then
ACanvas.Font.Color := clHighlightText
else
ACanvas.Font.Color := clBlack;
{draw a "function" word}
i := Pos(' ', AKey);
if (i > 0) then
begin
s := Copy(AKey, 1, i);
ACanvas.TextOut(X + intWidth, Y, s);
intWidth := intWidth + ACanvas.TextWidth(s);
AKey := Copy(AKey, i, Length(AKey));
end;
{draw a name of function}
ACanvas.Font.Style := ACanvas.Font.Style + [fsBold];
i := Pos('(', AKey);
j := Pos(#9, AKey);
if (j <= 0) then
j := Length(AKey)+1;
if (i <= 0) then
i := j;
s := Copy(AKey, 1, i-1);
ACanvas.TextOut(X + intWidth, Y, s);
Inc(intWidth, ACanvas.TextWidth(s));
ACanvas.Font.Style := ACanvas.Font.Style - [fsBold];
{draw function parameters}
s := Copy(AKey, i, j-i);
ACanvas.TextOut(X + intWidth, Y, s);
Inc(intWidth, ACanvas.TextWidth(s));
{draw function help string}
if IsSelected then
ACanvas.Font.Color := clYellow
else
ACanvas.Font.Color := clBlue;
ACanvas.Font.Style := ACanvas.Font.Style + [fsItalic];
ACanvas.TextOut(X + intWidth + 10, Y, Copy(AKey, j+1, Length(AKey)-j));
ACanvas.Font.Style := ACanvas.Font.Style - [fsItalic];
end;
function TfrmPackage.SynCompletionProposalPaintItem(AKey: String;
ACanvas: TCanvas; X, Y: Integer): Boolean;
var
i: Integer;
begin
inherited;
with SynCompletionProposal do
begin
i := ItemList.IndexOf(AKey);
DrawScriptFunc((Position = i), AKey, ACanvas, LongInt(lbScriptFuncs.Items.Objects[i]), X, Y);
end;
Result := True;
end;
function TfrmPackage.GetScriptFunc(Value: string): string;
var
i: Integer;
begin
i := Pos(' ', Value);
if (i <= 0) then
i := 0;
Result := Copy(Value, i+1, Length(Value));
i := Pos('(', Result);
if (i <= 0) then
i := Length(Result)+1;
Result := Copy(Result, 1, i-1);
end;
procedure TfrmPackage.SynCompletionProposalCodeCompletion(
var Value: String; Shift: TShiftState);
begin
inherited;
Value := GetScriptFunc(Value);
end;
procedure TfrmPackage.LoadScriptFuncs;
var
i: Integer;
strDescr: string;
begin
inherited;
if (SMScriptExecutor.LanguageStr = 'JAVASCRIPT') then
strDescr := 'JScript'
else
if (SMScriptExecutor.LanguageStr = 'RSLSCRIPT') then
strDescr := 'RSLSrvt'
else
strDescr := SMScriptExecutor.LanguageStr;
SMScriptExecutor.LoadScriptFunctions(strDescr + '.dll', lbScriptFuncs.Items, True);
for i := 0 to lbScriptFuncs.Items.Count-1 do
lbScriptFuncs.Items[i] := 'function ' + lbScriptFuncs.Items[i];
SynCompletionProposal.ItemList.Clear;
SynCompletionProposal.ItemList.AddStrings(lbScriptFuncs.Items);
end;
procedure TfrmPackage.lbScriptFuncsDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
begin
inherited;
lbScriptFuncs.Canvas.FillRect(Rect);
DrawScriptFunc((odSelected in State),
lbScriptFuncs.Items[Index],
lbScriptFuncs.Canvas,
LongInt(lbScriptFuncs.Items.Objects[Index]),
Rect.Left,
Rect.Top);
end;
procedure TfrmPackage.EditorDragOver(Sender, Source: TObject; X,
Y: Integer; State: TDragState; var Accept: Boolean);
begin
inherited;
Accept := (not Editor.ReadOnly) and
(Source = lbScriptFuncs)
end;
procedure TfrmPackage.EditorDragDrop(Sender, Source: TObject; X,
Y: Integer);
begin
inherited;
Editor.CaretXY := Editor.PixelsToRowColumn(Point(X, Y));
lbScriptFuncsDblClick(Source);
end;
procedure TfrmPackage.lbScriptFuncsDblClick(Sender: TObject);
begin
inherited;
if (Sender = lbScriptFuncs) then
Editor.SelText := GetScriptFunc(lbScriptFuncs.Items[lbScriptFuncs.ItemIndex])
end;
procedure TfrmPackage.miUndoClick(Sender: TObject);
const
strAllWildCard = 'All files (*.*)|*.*';
begin
inherited;
case TMenuItem(Sender).Tag of
1: Editor.Undo;
2: Editor.Redo;
3: Editor.CutToClipboard;
4: Editor.CopyToClipboard;
5: Editor.PasteFromClipboard;
6: Editor.Lines.Clear;
7: Editor.SelectAll;
8: begin
with TSaveDialog.Create(Application) do
try
Filter := strAllWildCard;
if Execute then
Editor.Lines.SaveToFile(FileName);
finally
Free
end;
end;
9: begin
with TOpenDialog.Create(Application) do
try
Filter := strAllWildCard;
if Execute then
begin
Editor.Lines.LoadFromFile(FileName);
Editor.Modified := True;
end
finally
Free
end
end;
10: pnlErrors.Visible := (Sender as TMenuItem).Checked;
11: pnlTemplate.Visible := (Sender as TMenuItem).Checked;
end;
end;
procedure TfrmPackage.pmEditorPopup(Sender: TObject);
begin
inherited;
miShowErrors.Checked := pnlErrors.Visible;
miShowTemplate.Checked := pnlTemplate.Visible;
end;
procedure TfrmPackage.cbLanguageChange(Sender: TObject);
begin
SMScriptExecutor.LanguageStr := UpperCase(cbLanguage.Text);
lbScriptFuncs.Items.Clear;
FormShow(Sender);
end;
procedure TfrmPackage.pnlToolbarResize(Sender: TObject);
begin
btnRunScript.Left := pnlToolbar.ClientRect.Right - btnRunScript.Width - 10
end;
end.
|
unit fDXClusterList;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, DBGrids,
ExtCtrls, Buttons, StdCtrls, inifiles, lcltype, db;
type
{ TfrmDXClusterList }
TfrmDXClusterList = class(TForm)
btnNew: TButton;
btnEdit: TButton;
btnDelete: TButton;
btnCancel: TButton;
btnApply: TButton;
dbgrdDXClusterList: TDBGrid;
Panel1: TPanel;
procedure dbgrdDXClusterListDblClick(Sender : TObject);
procedure FormShow(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure btnEditClick(Sender: TObject);
procedure btnNewClick(Sender: TObject);
private
procedure ShowFields;
procedure RefreshData(const id:Integer=0);
public
OldDesc : String;
end;
var
frmDXClusterList: TfrmDXClusterList;
implementation
{ TfrmDXClusterList }
uses dData, dUtils, fNewDXCluster;
procedure TfrmDXClusterList.RefreshData(const id:Integer=0);
begin
dmData.qDXClusters.DisableControls;
try
dmData.qDXClusters.Close;
if dmData.trDXClusters.Active then dmData.trDXClusters.Rollback;
dmData.trDXClusters.StartTransaction;
dmData.qDXClusters.SQL.Text := 'select * from cqrtest_common.dxclusters order by description';
dmData.qDXClusters.Open;
if id > 0 then
dmData.QueryLocate(dmData.qDXClusters,'id_dxclusters',id,False)
finally
dmData.qDXClusters.EnableControls;
ShowFields
end
end;
procedure TfrmDXClusterList.ShowFields;
begin
dbgrdDXClusterList.Columns[dbgrdDXClusterList.Columns.Count-1].Visible := False;
dbgrdDXClusterList.Columns[dbgrdDXClusterList.Columns.Count-2].Visible := False;
dbgrdDXClusterList.Columns[0].Visible := False;
dbgrdDXClusterList.Columns[1].Width := 100;
dbgrdDXClusterList.Columns[2].Width := 150;
dbgrdDXClusterList.Columns[3].Width := 50
end;
procedure TfrmDXClusterList.FormShow(Sender: TObject);
begin
dbgrdDXClusterList.DataSource := dmData.dsrDXCluster;
RefreshData();
if OldDesc <> '' then
dmData.QueryLocate(dmData.qDXClusters,'DESCRIPTION',OldDesc,True)
end;
procedure TfrmDXClusterList.dbgrdDXClusterListDblClick(Sender : TObject);
begin
if dmData.qDXClusters.RecordCount > 0 then
btnEdit.Click
end;
procedure TfrmDXClusterList.btnDeleteClick(Sender: TObject);
var
id : Integer;
begin
if Application.MessageBox('Do you realy want to delete this dxcluster?',
'Question ...', MB_ICONQUESTION + MB_YESNO) = idNo then
exit;
id := dmData.qDXClusters.FieldByName('id_dxclusters').AsInteger;
dmData.qDXClusters.Close;
if dmData.trDXClusters.Active then dmData.trDXClusters.Rollback;
dmData.qDXClusters.SQL.Text := 'delete from cqrtest_common.dxclusters where id_dxclusters = ' + IntToStr(id);
dmUtils.DebugMsg(dmData.qDXClusters.SQL.Text);
dmData.trDXClusters.StartTransaction;
dmData.qDXClusters.ExecSQL;
dmData.trDXClusters.Commit;
RefreshData()
end;
procedure TfrmDXClusterList.btnEditClick(Sender: TObject);
var
id : Integer=0;
begin
with TfrmNewDXCluster.Create(self) do
try
id := dmData.qDXClusters.Fields[0].AsInteger;
edtDescription.Text := dmData.qDXClusters.Fields[1].AsString;
edtAddress.Text := dmData.qDXClusters.Fields[2].AsString;
edtPort.Text := dmData.qDXClusters.Fields[3].AsString;
edtUserName.Text := dmData.qDXClusters.Fields[4].AsString;
edtPassword.Text := dmData.qDXClusters.Fields[5].AsString;
ShowModal;
if ModalResult = mrOK then
begin
dmData.qDXClusters.Close;
dmData.qDXClusters.SQL.Text := 'UPDATE cqrtest_common.dxclusters SET description='+QuotedStr(edtDescription.Text)+
',address='+QuotedStr(edtAddress.Text)+
',port='+QuotedStr(edtPort.Text)+
',dxcuser='+QuotedStr(edtUserName.Text)+
',dxcpass='+QuotedStr(edtPassword.Text)+
' WHERE id_dxclusters = '+IntToStr(id);
dmUtils.DebugMsg(dmData.qDXClusters.SQL.Text);
dmData.trDXClusters.Rollback;
dmData.trDXClusters.StartTransaction;
dmData.qDXClusters.ExecSQL;
dmData.trDXClusters.Commit
end
finally
Free;
RefreshData(id)
end
end;
procedure TfrmDXClusterList.btnNewClick(Sender: TObject);
begin
with TfrmNewDXCluster.Create(self) do
try
ShowModal;
if ModalResult = mrOK then
begin
dmData.qDXClusters.Close;
dmData.qDXClusters.SQL.Text := 'INSERT INTO cqrtest_common.dxclusters (description,address,port,dxcuser,dxcpass) ' +
'values ('+QuotedStr(edtDescription.Text) + ',' + QuotedStr(edtAddress.Text) +
','+QuotedStr(edtPort.Text)+','+QuotedStr(edtUserName.Text)+
','+QuotedStr(edtPassword.Text)+')';
dmUtils.DebugMsg(dmData.qDXClusters.SQL.Text);
dmData.trDXClusters.Rollback;
dmData.trDXClusters.StartTransaction;
dmData.qDXClusters.ExecSQL;
dmData.trDXClusters.Commit;
RefreshData()
end
finally
Free
end
end;
initialization
{$I fDXClusterList.lrs}
end.
|
unit PZO20106;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, OnFocusButton, ComCtrls, OnEditBaseCtrl,
OnEditStdCtrl, OnEditBtnCtrl, OnShapeLabel, Db, MemDS, DBAccess, Ora, Datelib,
Grids, Comobj, OnScheme, Tmax_DataSetText, func;
type
TFM_Batch = class(TForm)
OpenDialog1: TOpenDialog;
P_helpinfo: TStatusBar;
Panel2: TPanel;
BT_Delete: TOnFocusButton;
BT_exit: TOnFocusButton;
BT_Upload: TOnFocusButton;
BT_Insert: TOnFocusButton;
Bt_Down: TOnFocusButton;
cbx_down: TComboBox;
StringGrid1: TStringGrid;
ErrorPanel: TPanel;
OnShapeLabel1: TOnShapeLabel;
Memo1: TMemo;
BT_ErrorClose: TOnFocusButton;
SF_Main: TOnSchemeForm;
TDS1: TTMaxDataSet;
P_Help: TPanel;
Shape1: TShape;
OnShapeLabel2: TOnShapeLabel;
BT_HelpClose: TOnFocusButton;
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;
BT_help: TOnFocusButton;
Label15: TLabel;
Label16: TLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BT_exitClick(Sender: TObject);
procedure BT_UploadClick(Sender: TObject);
procedure BT_InsertClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure BT_ErrorCloseClick(Sender: TObject);
procedure BT_HelpCloseClick(Sender: TObject);
procedure Bt_DownClick(Sender: TObject);
procedure BT_helpClick(Sender: TObject);
procedure StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
private
LastEmpno : String;
{ Private declarations }
gsJuminMsg : String;
public
{ Public declarations }
procedure StringGrid_Clear;
end;
var
FM_Batch: TFM_Batch;
implementation
uses PZO20101;
{$R *.DFM}
procedure TFM_Batch.StringGrid_Clear;
var
i : integer;
begin
StringGrid1.ColCount := 13;
StringGrid1.RowCount := 2;
StringGrid1.Cells[ 0,0] := '성명' ;
StringGrid1.Cells[ 1,0] := '소속회사코드' ;
StringGrid1.Cells[ 2,0] := '생년월일' ;
StringGrid1.Cells[ 3,0] := '성별' ;
StringGrid1.Cells[ 4,0] := '관리부서코드' ;
StringGrid1.Cells[ 5,0] := '담당매니저사번';
StringGrid1.Cells[ 6,0] := '일반전화' ;
StringGrid1.Cells[ 7,0] := '핸드폰' ;
StringGrid1.Cells[ 8,0] := '이메일' ;
StringGrid1.Cells[ 9,0] := '근무지명' ;
StringGrid1.Cells[10,0] := '투입시작일' ;
StringGrid1.Cells[11,0] := '투입종료일' ;
StringGrid1.Cells[12,0] := '현장대리인여부';
for i := 0 to 12 do
StringGrid1.Cells[i,1] := '';
end;
procedure TFM_Batch.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FM_Main.FL_OPstate := 0;
Action := CaFree;
end;
procedure TFM_Batch.BT_exitClick(Sender: TObject);
begin
Close;
end;
procedure TFM_Batch.BT_UploadClick(Sender: TObject);
var
v : Variant ;
iRow, iCol : integer ;
CNT, Sg_RCnt, work : integer;
tmp_korname, tmp_birthdate, tmp_sex : String;
begin
Work := 0;
Memo1.Clear;
StringGrid_Clear;
BT_Insert.Enabled := False;
BT_Delete.Enabled := False;
LastEmpno := '0000';
Case MessageDlg('일괄등록할 데이터 업로드이면 Yes를 선택하세요.', mtConfirmation, [mbYes, mbCancel], 0) of
mrYes : Work := 1;
else
System.Exit;
end;
try
v:= CreateOleObject('Excel.application');
except
ShowMessage('Excel이 설치되어 있어야 합니다.');
Exit;
end;
if OpenDialog1.Execute then
begin
v.WorkBooks.open(OpenDialog1.FileName);
end
else Exit;
cnt := strToint(v.ActiveSheet.UsedRange.Rows.Count);
if Work = 1 then
begin
Memo1.Lines.Text := '';
StringGrid1.ColCount := 13;
StringGrid1.RowCount := cnt;
For iRow := 2 to cnt do
begin
tmp_korname := '';
tmp_birthdate := '';
tmp_sex := '';
For iCol := 1 to StringGrid1.ColCount do
begin
Case iCol of
1: begin
if Trim(v.cells[iRow, iCol]) = '' then
Memo1.Lines.Add(inttoStr(iRow)+', '+
Trim(v.cells[iRow, 1])+', '+
Trim(v.cells[iRow, 2])+' - 사원성명없음')
else tmp_korname := Trim(v.cells[iRow, iCol]);
end;
2: begin
if not FM_Main.IsValidComCode(UpperCase(v.cells[iRow, iCol])) then
Memo1.Lines.Add(inttoStr(iRow)+', '+
Trim(v.cells[iRow, 1])+', '+
Trim(v.cells[iRow, 2])+' - 동일회사코드없음');
end;
3: begin
if not DateCheck(v.cells[iRow, iCol]) then
Memo1.Lines.Add(inttoStr(iRow)+', '+
Trim(v.cells[iRow, 1])+', '+
Trim(v.cells[iRow, 2])+' - 생년월일오류')
else tmp_birthdate := trim(v.cells[iRow, iCol]);
end;
4: begin
if not FM_Main.IsValidSex(v.cells[iRow, iCol]) then
Memo1.Lines.Add(inttoStr(iRow)+', '+
Trim(v.cells[iRow, 1])+', '+
Trim(v.cells[iRow, 2])+' - 성별오류')
else tmp_sex := trim(v.cells[iRow, iCol]);
if(tmp_korname<>'') and (tmp_birthdate<>'') and (tmp_sex<>'') then
begin
if FM_Main.CheckEmpnoDup(tmp_korname,tmp_birthdate,tmp_sex) then
begin
Memo1.Lines.Add(inttoStr(iRow)+', '+
Trim(v.cells[iRow, 1])+', '+
Trim(v.cells[iRow, 3])+', '+
Trim(v.cells[iRow, 4])+' - 성명,생년월일,성별 중복오류')
end;
end;
end;
5: begin
if not FM_Main.IsValidDeptCode(UpperCase(v.cells[iRow, iCol])) then
Memo1.Lines.Add(inttoStr(iRow)+', '+
Trim(v.cells[iRow, 1])+', '+
Trim(v.cells[iRow, 2])+' - 관리부서코드오류');
end;
6: begin
if not FM_Main.IsValidEmpno(UpperCase(v.cells[iRow, iCol])) then
Memo1.Lines.Add(inttoStr(iRow)+', '+
Trim(v.cells[iRow, 1])+', '+
Trim(v.cells[iRow, 2])+' - 담당매니저사번오류');
end;
7: begin
if not FM_Main.IsValidPhoneNo(v.cells[iRow, iCol]) then
Memo1.Lines.Add(inttoStr(iRow)+', '+
Trim(v.cells[iRow, 1])+', '+
Trim(v.cells[iRow, 2])+' - 일반전화오류');
end;
8: begin
if not FM_Main.IsValidPhoneNo(v.cells[iRow, iCol]) then
Memo1.Lines.Add(inttoStr(iRow)+', '+
Trim(v.cells[iRow, 1])+', '+
Trim(v.cells[iRow, 2])+' - 핸드폰오류');
end;
9: begin
if not FM_Main.IsValidEmail(v.cells[iRow, iCol]) then
Memo1.Lines.Add(inttoStr(iRow)+', '+
Trim(v.cells[iRow, 1])+', '+
Trim(v.cells[iRow, 2])+' - 이메일오류');
end;
10: begin
if not FM_Main.IsValidJobplace(Trim(v.cells[iRow, iCol])) then
Memo1.Lines.Add(inttoStr(iRow)+', '+
Trim(v.cells[iRow, 1])+', '+
Trim(v.cells[iRow, 2])+' - 근무지명오류');
end;
11: begin
if not FM_Main.IsValidStartDate(FM_Main.RemoveSpecialChar(v.cells[iRow, iCol])) then
Memo1.Lines.Add(inttoStr(iRow)+', '+
Trim(v.cells[iRow, 1])+', '+
Trim(v.cells[iRow, 2])+' - 투입시작일오류');
end;
12: begin
if not FM_Main.IsValidEndDate(v.cells[iRow, iCol-1],v.cells[iRow, iCol]) then
Memo1.Lines.Add(inttoStr(iRow)+', '+
Trim(v.cells[iRow, 1])+', '+
Trim(v.cells[iRow, 2])+' - 투입종료일오류');
end;
13: begin
if Trim(v.cells[iRow, iCol]) = '' then
Memo1.Lines.Add(inttoStr(iRow)+', '+
Trim(v.cells[iRow, 1])+', '+
Trim(v.cells[iRow, 2])+' - 현장대리인여부없음');
end;
end;
if Memo1.Lines.text = '' then
begin
StringGrid1.Cells[iCol-1, iRow -1] := v.cells[iRow, iCol];
end;
end; //For iCol := 1 to StringGrid1.ColCount - 1 do
end; //For iRow := 2 to cnt do
end;
v.WorkBooks.Close;
v.quit ;
v:=unassigned;
if Memo1.Lines.Text <> '' then
begin
Memo1.Lines.Add('================================== ');
Memo1.Lines.Add('상기 오류 내역 수정후 재작업 요망. ');
Memo1.Lines.Add('================================== ');
Memo1.Lines.Add('중복된 성명, 생년월일, 성별에 대해 ');
Memo1.Lines.Add('재직중인 동일 사원이 존재할 경우 해당 사원 검색후 ');
Memo1.Lines.Add('해당 사번으로 사용해 주시기 바라며, ');
Memo1.Lines.Add('중복 등록이 불가피 할 경우 ');
Memo1.Lines.Add(' IT기획보안팀 윤진석M로 문의바랍니다. ');
StringGrid_Clear;
ErrorPanel.Visible := True;
P_Help.Visible := True;
System.Exit;
end;
ErrorPanel.Visible := false;
P_helpinfo.SimpleText := ('총 ' + IntTostr(Cnt -1) + ' 건의 엑셀파일 로드가 완료 되었습니다.');
if (Cnt - 1) <> 0 then
begin
if work = 1 then BT_Insert.Enabled := True
else BT_Delete.Enabled := True;
end
else
begin
BT_Insert.Enabled := False;
BT_Delete.Enabled := False;
end;
end;
procedure TFM_Batch.BT_InsertClick(Sender: TObject);
var
MRow, Cnt : integer ;
ret_val : boolean;
begin
Cnt := 0;
if MessageDlg('일괄등록작업을 진행하시겠습니까?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
Memo1.Clear;
For MRow := 1 to StringGrid1.RowCount -1 do
begin
with fm_main do
begin
p_empno := AutoEmpno;
p_korname := trim(StringGrid1.Cells[ 0, MRow]);
p_comcode := trim(UpperCase (StringGrid1.Cells[ 1, MRow]));
p_birthdate := trim(removechar(StringGrid1.Cells[ 2, MRow],'-'));
p_sex := trim(StringGrid1.Cells[ 3, MRow]);
p_orgnum := GSorgnum;
p_deptcode := trim(UpperCase(StringGrid1.Cells[ 4, MRow]));
p_managerid := trim(UpperCase(StringGrid1.Cells[ 5, MRow]));
p_telno := removechar(StringGrid1.Cells[ 6, MRow],' ');
p_cellno := removechar(StringGrid1.Cells[ 7, MRow],' ');
p_email := trim(StringGrid1.Cells[ 8, MRow]);
p_jobplacenm := trim(RemoveSpecialChar(StringGrid1.Cells[ 9, MRow]));
//p_jobplacenm := trim(StringGrid1.Cells[ 9, MRow]);
p_regman := GSempno;
p_regdate := Copy(FG_Date,1,8);
p_startdate := trim(removechar(StringGrid1.Cells[10, MRow],'-'));
p_enddate := trim(removechar(StringGrid1.Cells[11, MRow],'-'));
p_fieldrepyn := trim(StringGrid1.Cells[12, MRow]);
p_stateyn := 'Y';
p_writeman := GSempno;
if(trim(p_empno)='') then
begin
self.Memo1.Lines.Add(IntToStr(MRow)+','+
Trim(p_korname)+','+
Trim(p_comcode)+','+
Trim(p_birthdate)+'-사번 생성 오류');
end
else
begin
ret_val := InsertPzmoutmas;
if(ret_val) then Cnt := Cnt + 1
else
begin
self.Memo1.Lines.Add(IntToStr(MRow)+','+
Trim(p_korname)+','+
Trim(p_comcode)+','+
Trim(p_birthdate)+'-저장 오류');
end;
end;
end;
end; //Row For End
if Memo1.Lines.Text <> '' then
begin
Memo1.Lines.Add('==================================');
Memo1.Lines.Add('상기 오류 대상자에 대해 수정후 재작업 요망.');
StringGrid_Clear;
ErrorPanel.Visible := True;
P_Help.Visible := True;
end;
StringGrid1.ColCount := 3;
BT_Insert.Enabled := False;
MessageDlg('총 ' + IntTostr(Cnt) + '건의 데이터 저장완료.', mtInformation,[mbOK],0);
end;
end;
procedure TFM_Batch.FormShow(Sender: TObject);
begin
StringGrid_Clear;
cbx_down.ItemIndex := 0;
fm_main.FL_OPstate := 1;
end;
procedure TFM_Batch.BT_ErrorCloseClick(Sender: TObject);
begin
ErrorPanel.Visible := False;
end;
procedure TFM_Batch.BT_HelpCloseClick(Sender: TObject);
begin
P_Help.Visible := False;
end;
procedure TFM_Batch.Bt_DownClick(Sender: TObject);
var
XL, XArr: Variant;
i,j,k: integer;
SavePlace: TBookmark;
begin
P_helpinfo.SimpleText := 'Excel이 설치되어 있는지 검색하고 있습니다.';
XArr := VarArrayCreate([1, 13], VarVariant);
try
XL := CreateOLEObject('Excel.Application');
except
MessageDlg('Excel이 설치되어 있지 않습니다.', MtWarning, [mbok], 0);
P_helpinfo.SimpleText := '';
Exit;
end;
XL.WorkBooks.Add; //새로운 페이지 생성
XL.Visible := false;
if cbx_down.ItemIndex = 0 then
begin
//컬럼명 지정_서브타이블 지정
XArr[ 1] := '성명' ;
XArr[ 2] := '소속회사코드' ;
XArr[ 3] := '생년월일(ex.19880808)' ;
XArr[ 4] := '성별(남/여)' ;
XArr[ 5] := '관리부서코드' ;
XArr[ 6] := '담당매니저사번';
XArr[ 7] := '일반전화(ex.02-1234-1234)' ;
XArr[ 8] := '핸드폰(ex.010-1234-1234)' ;
XArr[ 9] := '이메일(ex.ab12@abc.com)' ;
XArr[10] := '근무지명(ex.저동)' ;
XArr[11] := '투입시작일(ex.20150105)' ;
XArr[12] := '투입종료일(ex.20160104)' ;
XArr[13] := '현장대리인여부(N/Y)';
XL.Range['A1', 'M1'].Value := XArr;
XL.Range['A1', 'M1'].Borders.LineStyle := 1; //테두리선을 만든다. 1은 실선
XL.Range['A1', 'M1'].Interior.Color:= $00CBF0B3;
end
else
begin
//컬럼명 지정_서브타이블 지정
XArr[1] := '사원번호';
XArr[2] := '사원성명';
//XArr[1] := '회사코드';
XL.Range['A1', 'B1'].Value := XArr;
XL.Range['A1', 'B1'].Borders.LineStyle := 1; //테두리선을 만든다. 1은 실선
XL.Range['A1', 'B1'].Interior.Color:= $00CBF0B3;
end;
XL.Visible := true; //엑셀자료 보여줌
P_helpinfo.SimpleText := '';
end;
procedure TFM_Batch.BT_helpClick(Sender: TObject);
begin
P_Help.Visible := true;
end;
procedure TFM_Batch.StringGrid1DrawCell(Sender: TObject; ACol,
ARow: Integer; Rect: TRect; State: TGridDrawState);
var
TW , TH : Integer;
begin
StringGrid1.canvas.fillRect(rect);
StringGrid1.canvas.TextRect(Rect, Rect.Left + 3, Rect.Top + 3, StringGrid1.cells[acol, arow]);
if (ACol >= 0) then
begin
with StringGrid1.Canvas do
begin
FillRect(Rect);
TW := TextWidth(StringGrid1.Cells[ACol , ARow]);
TH := TextHeight(StringGrid1.Cells[ACol , ARow]);
TextOut((Rect.Left + Rect.Right - TW) div 2, (Rect.Top + Rect.Bottom - TH) div 2 , StringGrid1.Cells[ ACol , ARow] );
Exit;
end;
end;
end;
end.
|
unit Employer;
interface
uses
SysUtils, Group;
type
TEmployer = class(TObject)
protected
FId: string;
FName: string;
FGroup: TGroup;
FAddress: string;
public
property Id: string read FId write FId;
property Name: string read FName write FName;
property Group: TGroup read FGroup write FGroup;
property Address: string read FAddress write FAddress;
constructor Create; overload;
constructor Create(const id, name, addr: string; const gp: TGroup); overload;
destructor Destroy; override;
end;
var
emp: TEmployer;
implementation
constructor TEmployer.Create;
begin
if emp = nil then
emp := self;
end;
constructor TEmployer.Create(const id, name, addr: string; const gp: TGroup);
begin
FId := id;
FName := name;
FGroup := gp;
FAddress := addr;
end;
destructor TEmployer.Destroy;
begin
if emp = self then
emp := nil;
inherited;
end;
end.
|
unit xClientType;
interface
uses System.Classes, System.SysUtils;
type
/// <summary>
/// 考生状态
/// </summary>
TClientState = (esDisconn, // 未连接
esConned, // 已经连接
esLogin, // 已登录
esWorkReady, // 准备好考试
esWorking, // 正在考试
esWorkFinished, // 交卷
esPractise, // 正在练习
esTrain // 正在培训
);
/// <summary>
/// 状态转换成字符串
/// </summary>
function ClientStateStr(AState : TClientState) : string;
type
/// <summary>
/// 客户端连接状态
/// </summary>
TClientConnState = (ccsDisConn, // 未连接
ccsConned // 已连接
);
function ClientConnStateStr(AState : TClientConnState) : string;
type
/// <summary>
/// 登录状态
/// </summary>
TLoginState = (lsLogin, // 已登录
lsLogOut // 未登录
);
function LoginStateStr(AState : TLoginState) : string;
type
/// <summary>
/// 客户端登录状态
/// </summary>
TClientWorkState = (cwsNot, // 未定义
cwsTrain, // 正在培训
cwsPractise, // 正在练习
cwsExamReady, // 准备好考试
cwsExamDoing, // 正在答卷
cwsExamFinished // 考试完成
);
function ClientWorkStateStr(AState : TClientWorkState) : string;
/// <summary>
/// 组包
/// </summary>
function BuildData(aData: TBytes): TBytes;
/// <summary>
/// 解析软件
/// </summary>
function AnalysisRevData(aRevData : TBytes) : TBytes;
implementation
function ClientWorkStateStr(AState : TClientWorkState) : string;
begin
case AState of
cwsTrain : Result := '正在培训';
cwsPractise: Result := '正在练习';
cwsExamReady: Result := '准备好考试';
cwsExamDoing: Result := '正在答题';
cwsExamFinished: Result := '已交卷';
else
Result := '未定义';
end;
end;
function LoginStateStr(AState : TLoginState) : string;
begin
case AState of
lsLogin : Result := '已登录';
lsLogOut: Result := '未登录';
else
Result := '未定义';
end;
end;
function ClientConnStateStr(AState : TClientConnState) : string;
begin
case AState of
ccsDisConn : Result := '未连接';
ccsConned : Result := '已连接';
else
Result := '未定义';
end;
end;
function BuildData(aData: TBytes): TBytes;
var
nByte, nCode1, nCode2 : Byte;
i : Integer;
nFixCodeCount, nIndex : Integer; // 转译字符个数
function IsFixCode(nCode : Integer) : Boolean;
begin
Result := nCode in [$7F, $7E];
if Result then
begin
Inc(nFixCodeCount);
nCode1 := $7F;
if nCode = $7E then
nCode2 := $01
else
nCode2 := $02;
end;
end;
begin
nByte := 0;
nFixCodeCount := 0;
for i := 0 to Length(aData) - 1 do
begin
IsFixCode(aData[i]); // 计算转译字符个数
nByte := (nByte + aData[i])and $FF; // 计算校验码
end;
IsFixCode(nByte); // 判断校验码是否是转译字符
SetLength(Result, Length(aData) + nFixCodeCount + 3);
Result[0] := $7E;
Result[Length(Result)-1] := $7E;
Result[Length(Result)-2] := nByte;
nIndex := 1;
for i := 0 to Length(aData) - 1 do
begin
if IsFixCode(aData[i]) then
begin
Result[nIndex] := nCode1;
Result[nIndex+1] := nCode2;
Inc(nIndex, 2);
end
else
begin
Result[nIndex] := aData[i];
Inc(nIndex);
end;
end;
end;
function AnalysisRevData(aRevData : TBytes) : TBytes;
var
aBuf : TBytes;
i : Integer;
nCS : Byte;
procedure AddByte(nByte : Byte);
var
nLen : Integer;
begin
nLen := Length(aBuf);
SetLength(aBuf, nLen + 1);
aBuf[nLen] := nByte;
end;
begin
Result := nil;
// 处理转译字符
for i := 0 to Length(aRevData) - 1 do
begin
if (aRevData[i] = $7F) and (aRevData[i+1] = $01) then
begin
AddByte($7E);
end
else if (aRevData[i] = $7F) and (aRevData[i+1] = $02) then
begin
AddByte($7F);
end
else
begin
AddByte(aRevData[i]);
end;
end;
// 检验校验和
nCS := 0;
for i := 1 to Length(aBuf) - 3 do
begin
nCS := (nCS + aBuf[i]) and $FF;
end;
if nCS = aBuf[Length(aBuf)-2] then
begin
Result := aBuf;
end;
end;
function ClientStateStr(AState : TClientState) : string;
begin
case AState of
esDisconn : Result := '未连接';
esConned : Result := '已经连接';
esLogin : Result := '已登录';
esWorkReady : Result := '准备好考试';
esWorking : Result := '正在考试';
esWorkFinished : Result := '交卷';
esPractise : Result := '正在练习';
esTrain : Result := '正在培训';
else
Result := '未定义';
end;
end;
end.
|
unit SIP_QueueManager;
interface
uses SyncObjs, Classes, SIP_RingList, Contnrs, SIP_Env, SIP_Event;
type
TProcessingKind =(pkSIP,pkSMS,pkMail);
TSIPQueueManager=class(TCriticalSection)
private
FList:TObjectList;
FCurrent:Integer;
FEvent:TEvent;
FQuitEvent:TEvent;
Handles:array [1..2] of THandle;
FSIPApp:TObject;
FID:Integer;
FCounter:Integer;
procedure Status(S:String);inline;
procedure ShowStatus;
public
constructor Create(App:TObject;ID:Integer);
destructor Destroy;override;
procedure Add(ScriptID:Integer;Addresses:TSIPRingList; Count:Integer; SIPEnv:ISIPEnv; SIPEvent:TSIPEvent; var StartID:Integer; var Counter:PInteger;var Report:String);
procedure Next(out ScriptID:Integer;out Address:TSIPAddress;out QueueID:Cardinal;out Env:ISIPEnv; out Event:TSIPEvent; out StartID:Integer);
procedure Retry(Address:TSIPAddress;Delay,QueueID:Cardinal);
procedure Fail(Address:TSIPAddress;QueueID:Cardinal;ProcessingKind:TProcessingKind);
procedure Succeed(Address:TSIPAddress;QueueID:Cardinal;ProcessingKind:TProcessingKind);
procedure StartMail(Address:TSIPAddress;QueueID:Cardinal);
procedure StartSMS(Address:TSIPAddress;QueueID:Cardinal);
function QueueStatus(ID:Integer):String;
procedure Stop(EventID:Integer);
function Mode(EventID:Integer):Integer;
procedure Close;
function IsEmpty:Boolean;
end;
implementation
uses Windows,SysUtils,SIP_App,Util,SIP_Monitor;
type
TSIPQueueItem=class(TObject)
ScriptID:Integer;
Addresses:TSIPRingList;
AddressesRetry:TSIPRingList;
AddressesSuccess:TSIPRingList;
AddressesFailure:TSIPRingList;
AddressesProcessing:TSIPRingList;
EMails:TSIPRingList;
SMSes:TSIPRingList;
AddressCount:PInteger;
AddressCounter:Integer;
Count:Integer;
Current:Integer;
Retry:Boolean;
Env:ISIPEnv;
Event:TSIPEvent;
QueueID:Cardinal;
Stop:Boolean;
StartID:Integer;
ID:Integer;
destructor Destroy;override;
function Status(Journal:Boolean):String;
end;
{ TSIPQueueManager }
var
EventCounter:Integer=0;
ItemCounter:Integer=0;
procedure TSIPQueueManager.Add(ScriptID: Integer; Addresses: TSIPRingList; Count:Integer; SIPEnv:ISIPEnv; SIPEvent:TSIPEvent; var StartID:Integer; var Counter:PInteger;var Report:String);
var Item:TSIPQueueItem;
AddressCount:String;
ScriptName:String;
IsFirst:Boolean;
begin
Acquire;
try
Inc(FCounter);
Item:=TSIPQueueItem.Create;
Item.ID:=3*InterlockedIncrement(ItemCounter);
if StartID>0 then
begin
IsFirst:=False;
Item.StartID:=StartID;
Item.AddressCount:=Counter;
end
else
begin
IsFirst:=True;
Item.StartID:=InterlockedIncrement(EventCounter);
Item.AddressCount:=@Item.AddressCounter;
Counter:=Item.AddressCount;
StartID:=Item.StartID;
end;
Item.QueueID:=FCounter;
Item.ScriptID:=ScriptID;
Item.Addresses:=Addresses;
Item.AddressesRetry:=TSIPRingList.Create;
Item.AddressesFailure:=TSIPRingList.Create;
Item.AddressesSuccess:=TSIPRingList.Create;
Item.AddressesProcessing:=TSIPRingList.Create;
Item.EMails:=TSIPRingList.Create;
Item.SMSes:=TSIPRingList.Create;
if Item.Addresses<>nil then
Item.AddressCount^:=Item.AddressCount^+Item.Addresses.Count
else
Item.AddressCount^:=Item.AddressCount^+1;
Item.Current:=0;
Item.Count:=Count;
Item.Retry:=False;
Item.Env:=SIPEnv;
Item.Event:=SIPEvent;
Item.Event.BeginItem;
ScriptName:=SIPEnv.SIPLibrary.ScriptName[ScriptID];
if ScriptName<>'' then
ScriptName:=' => Оповестяване по сценарий "'+ScriptName+'"';
if Addresses=nil then
AddressCount:=', индивидуално'
else
if Addresses.Count=1 then
AddressCount:=' на 1 обект'
else
if Addresses.Count>0 then
AddressCount:=' на '+IntToStr(Addresses.Count)+' обекта'
else
AddressCount:='';
if ScriptName<>'' then Report:=Report+ScriptName+AddressCount+#13#10;
FList.Add(Item);
ShowStatus;
if FList.Count=1 then FEvent.SetEvent;
finally
Release;
end;
end;
procedure TSIPQueueManager.Close;
begin
FQuitEvent.SetEvent;
end;
constructor TSIPQueueManager.Create;
begin
inherited Create;
FID:=ID;
FSIPApp:=app;
FEvent:=TEvent.Create(nil,False,False,'',False);
FQuitEvent:=TEvent.Create;
Handles[1]:=FQuitEvent.Handle;
Handles[2]:=FEvent.Handle;
FList:=TObjectList.Create;
FList.OwnsObjects:=True;
FCurrent:=0;
end;
destructor TSIPQueueManager.Destroy;
begin
FreeAndNil(FQuitEvent);
FreeAndNil(FEvent);
FreeAndNil(FList);
inherited;
end;
procedure TSIPQueueManager.Fail(Address: TSIPAddress; QueueID: Cardinal;ProcessingKind:TProcessingKind);
var
Q:TSIPQueueItem;
I,J: Integer;
begin
Acquire;
try
for I := 0 to FList.Count - 1 do
begin
Q:=TSIPQueueItem(FList[I]);
if Q.QueueID=QueueID then
begin
try
J:=Q.AddressesSuccess.LockList.IndexOf(Address);
finally
Q.AddressesSuccess.UnlockList;
end;
case ProcessingKind of
pkSIP: begin
Q.AddressesProcessing.Remove(Address);
Address.ResultSIP:='fail';
end;
pkSMS: begin
Q.SMSes.Remove(Address);
Address.ResultSMS:='fail';
end;
pkMail: begin
Q.EMails.Remove(Address);
Address.ResultMail:='fail';
end;
end;
if J<0 then
try
J:=Q.SMSes.LockList.IndexOf(Address);
finally
Q.SMSes.UnlockList;
end;
if J<0 then
try
J:=Q.EMails.LockList.IndexOf(Address);
finally
Q.EMails.UnlockList;
end;
if J<0 then
Q.AddressesFailure.AddAddress(Address,0);
if ((Q.Addresses=nil) or (Q.Addresses.Count<=0)) and (Q.AddressesRetry.Count<=0) and (Q.AddressesProcessing.Count<=0) and (Q.EMails.Count<=0) and (Q.SMSes.Count<=0) then
Q.Event.EndItem;
Break;
end;
end;
finally
Release;
end;
end;
function TSIPQueueManager.IsEmpty: Boolean;
begin
Acquire;
try
Result:=FList.Count<=0;
finally
Release;
end;
end;
function TSIPQueueManager.Mode(EventID: Integer): Integer;
var
Q:TSIPQueueItem;
I: Integer;
begin
Result:=0;
Acquire;
try
for I := FList.Count - 1 downto 0 do
begin
Q:=TSIPQueueItem(FList[I]);
if Q.StartID=EventID then
begin
Result:=Q.Env.DatabaseID;
Break;
end;
end;
finally
Release;
end;
end;
procedure TSIPQueueManager.Next(out ScriptID:Integer;out Address:TSIPAddress;out QueueID:Cardinal;out Env:ISIPEnv; out Event:TSIPEvent; out StartID:Integer);
var newAddress:TSIPAddress;
Q:TSIPQueueItem;
W:DWORD;
Finished:Boolean;
Stop:Integer;
DoSleep:Boolean;
begin
W:=WaitForMultipleObjects(2,@Handles[1],False,INFINITE);
if W<>WAIT_OBJECT_0+1 then
begin
ScriptID:=-1;
Address:=nil;
Exit;
end;
DoSleep:=False;
Acquire;
try
try
ScriptID:=0;
Address:=nil;
Env:=nil;
Event:=nil;
StartID:=0;
if FList.Count>0 then
begin
Stop:=FCurrent;
repeat
Q:=TSIPQueueItem(FList[FCurrent]);
if Q.Addresses=nil then
begin
newAddress:=nil;
Address:=nil;
QueueID:=0;
ScriptID:=Q.ScriptID;
Env:=Q.Env;
Event:=Q.Event;
StartID:=Q.StartID;
if Q.Event<>nil then
Q.Event.UpdateWait(MaxAnnounce);
FList.Delete(FCurrent);
if FCurrent>=FList.Count then FCurrent:=0;
if Stop>=FList.Count then Stop:=Flist.Count-1;
end
else
begin
newAddress:=nil;
if Q.Stop then
begin
Finished:=Q.Event.Finished
end else
if Q.Count<=0 then
Finished:=True
else
begin
if Q.Retry then
begin
newAddress:=Q.AddressesRetry.Get();
Q.Retry:=Q.Addresses.Count<=0;
end else
newAddress:=nil;
if newAddress=nil then
begin
Q.Retry:=True;
newAddress:=Q.Addresses.Get;
end;
if newAddress<>nil then
begin
Q.Event.UpdateWait(MaxAnnounce);
Q.AddressesProcessing.AddAddress(newAddress,0);
Q.Event.AddReport(FormatDateTime('yyyy-mm-dd hh:nn:ss ',Now)+'Оповестяване на '+newAddress.ObjectName+' (опит '+IntToStr(newAddress.TryCount)+')'#13#10,'');
end;
//Finished:=Q.Event.Finished;
Finished:=Q.Event.Finished and ((Q.Addresses=nil) or (Q.Addresses.Count<=0)) and (Q.AddressesRetry.Count<=0) and (Q.AddressesProcessing.Count<=0) and (Q.EMails.Count<=0) and (Q.SMSes.Count<=0);
end;
if Finished then
begin
FList.Delete(FCurrent);
if FCurrent>=FList.Count then FCurrent:=0;
if Stop>=FList.Count then Stop:=Flist.Count-1;
end else
if newAddress=nil then
begin
Q.Current:=0;
FCurrent:=(FCurrent+1) mod FList.Count;
if FCurrent=Stop then
begin
DoSleep:=True;
Break;
end;
end else
begin
Address:=newAddress;
QueueID:=Q.QueueID;
ScriptID:=Q.ScriptID;
Env:=Q.Env;
Event:=Q.Event;
StartID:=Q.StartID;
Q.Current:=(Q.Current+1) mod Q.Count;
if Q.Current=0 then
FCurrent:=(FCurrent+1) mod FList.Count;
end;
end;
until (newAddress<>nil) or (FList.Count<=0);
end;
ShowStatus;
finally
if FList.Count>0 then FEvent.SetEvent;
end;
finally
Release;
end;
if DoSleep then Sleep(200);
end;
procedure TSIPQueueManager.Retry(Address:TSIPAddress;Delay,QueueID:Cardinal);
var
Q:TSIPQueueItem;
I: Integer;
begin
Acquire;
try
Inc(Address.TryCount);
for I := 0 to FList.Count - 1 do
begin
Q:=TSIPQueueItem(FList[I]);
if Q.QueueID=QueueID then
begin
Q.AddressesProcessing.Remove(Address);
Q.AddressesRetry.AddAddress(Address,Delay);
Q.Event.UpdateWait(MaxAnnounce);
Break;
end;
end;
finally
Release;
end;
end;
procedure TSIPQueueManager.ShowStatus;
var
I:Integer;
S:String;
Q:TSIPQueueItem;
Cnt:Integer;
begin
S:='';
for I := 0 to FList.Count - 1 do
begin
Q:=TSIPQueueItem(FList[I]);
if Q.Addresses=nil then
Cnt:=1
else
Cnt:=Q.Addresses.Count;
S:=S+IntToStr(Q.ScriptID)+'('+IntToStr(Cnt)+','+IntToStr(Q.AddressesRetry.Count)+') ';
end;
Status(S);
end;
function TSIPQueueManager.QueueStatus(ID:Integer): String;
var
I: Integer;
Item:TSIPQueueItem;
Queues:String;
IDList:TList;
procedure Add(const S:String);
begin
if Result='' then Result:=S else
if S<>'' then Result:=Result+','+S;
end;
begin
Acquire;
try
Result:='';
Queues:='';
IDList:=TList.Create;
try
for I := 0 to FList.Count - 1 do
begin
Item:=TSIPQueueItem(FList[I]);
if (ID<=0) or (Item.StartID=ID) then
begin
Add(Item.Status(False));
end;
if IDList.IndexOf(Pointer(Item.StartID))<0 then
begin
IDList.Add(Pointer(Item.StartID));
if Queues<>'' then Queues:=Queues+',';
Queues:=Queues+Format('{queueid:%d,name:%s,time:%s,stopped:%d,count:%d}',[Item.StartID,StrEscape(Item.Event.Name),StrEscape(FormatDateTime('mm-dd hh:nn:ss',Item.Event.DateTime)),Ord(Item.Stop),Item.AddressCount^]);
end;
end;
if IDList.Count>1 then
begin
if Queues<>'' then Queues:=','+Queues;
Queues:='{queueid:0,name:''Всички'',time:null,stopped:0}'+Queues;
end;
finally
IDList.Free;
end;
Result:=Format('"queues":[%s],"queuerows":[%s]',[Queues,Result]);
finally
Release;
end;
end;
procedure TSIPQueueManager.StartMail(Address: TSIPAddress; QueueID: Cardinal);
var
Q:TSIPQueueItem;
I: Integer;
begin
Acquire;
try
for I := 0 to FList.Count - 1 do
begin
Q:=TSIPQueueItem(FList[I]);
if Q.QueueID=QueueID then
begin
Q.EMails.AddAddress(Address,0);
Break;
end;
end;
finally
Release;
end;
end;
procedure TSIPQueueManager.StartSMS(Address: TSIPAddress; QueueID: Cardinal);
var
Q:TSIPQueueItem;
I: Integer;
begin
Acquire;
try
for I := 0 to FList.Count - 1 do
begin
Q:=TSIPQueueItem(FList[I]);
if Q.QueueID=QueueID then
begin
Q.SMSes.AddAddress(Address,0);
Break;
end;
end;
finally
Release;
end;
end;
procedure TSIPQueueManager.Status(S: String);
begin
//if TSIPApp(FSIPApp).SIPStatus<>nil then TSIPApp(FSIPApp).SIPStatus.Status(FID,S);
end;
procedure TSIPQueueManager.Stop(EventID: Integer);
var
Q:TSIPQueueItem;
I: Integer;
begin
Acquire;
try
for I := FList.Count - 1 downto 0 do
begin
Q:=TSIPQueueItem(FList[I]);
if Q.StartID=EventID then
begin
Q.Event.UpdateWait(MaxRing);
Q.Stop:=True;
end;
end;
finally
Release;
end;
end;
procedure TSIPQueueManager.Succeed(Address: TSIPAddress; QueueID: Cardinal;ProcessingKind:TProcessingKind);
var
Q:TSIPQueueItem;
I: Integer;
begin
Acquire;
try
for I := 0 to FList.Count - 1 do
begin
Q:=TSIPQueueItem(FList[I]);
if Q.QueueID=QueueID then
begin
case ProcessingKind of
pkSIP: begin
Q.AddressesProcessing.Remove(Address);
Address.ResultSIP:=Address.SucceedMethod;
end;
pkSMS: begin
Q.SMSes.Remove(Address);
//Address.Status:='SMS';
Address.ResultSMS:='succeed';
end;
pkMail: begin
Q.EMails.Remove(Address);
//Address.Status:='Email';
Address.ResultMail:='succeed';
end;
end;
Q.AddressesSuccess.AddAddress(Address,0);
Q.AddressesFailure.Remove(Address);
if ((Q.Addresses=nil) or (Q.Addresses.Count<=0)) and (Q.AddressesRetry.Count<=0) and (Q.AddressesProcessing.Count<=0) and (Q.EMails.Count<=0) and (Q.SMSes.Count<=0) then
Q.Event.EndItem;
Break;
end;
end;
finally
Release;
end;
end;
{ TSIPQueueItem }
destructor TSIPQueueItem.Destroy;
begin
if Event<>nil then
begin
Event.AddReport(FormatDateTime('yyyy-mm-dd hh:nn:ss ',Now)+'Край на оповестяване'#13#10,'');
Event.AddReport(Status(True),'queue');
end;
FreeAndNil(Addresses);
FreeAndNil(AddressesRetry);
FreeAndNil(AddressesFailure);
FreeAndNil(AddressesSuccess);
FreeAndNil(AddressesProcessing);
EMails.Clear;
SMSes.Clear;
FreeAndNil(EMails);
FreeAndNil(SMSes);
inherited;
end;
function TSIPQueueItem.Status(Journal:Boolean): String;
procedure Add(const S:String);
begin
if Result='' then Result:=S else
if S<>'' then Result:=Result+','+S;
end;
begin
Result:='';
if Addresses=nil then Exit;
Add(Addresses.Status('"queueid":'+IntToStr(StartID)+',"state":"чакащи",',IntToStr(ID)+'-1-',Journal,False));
Add(AddressesRetry.Status('"queueid":'+IntToStr(StartID)+',"state":"за повторение",',IntToStr(ID)+'-2-',Journal,False));
Add(AddressesSuccess.Status('"queueid":'+IntToStr(StartID),IntToStr(ID)+'-',Journal,True));
Add(AddressesFailure.Status('"queueid":'+IntToStr(StartID)+',"state":"неуспешно оповестени",',IntToStr(ID)+'-3-',Journal,False));
Add(AddressesProcessing.Status('"queueid":'+IntToStr(StartID)+',"state":"оповестяване",',IntToStr(ID)+'-4-',Journal,False));
Add(EMails.Status('"queueid":'+IntToStr(StartID)+',"state":"изпращане на EMail",',IntToStr(ID+1)+'-5-',Journal,False));
Add(SMSes.Status('"queueid":'+IntToStr(StartID)+',"state":"изпращане на SMS",',IntToStr(ID+2)+'-6-',Journal,False));
end;
end.
|
unit classe.Period;
interface
uses System.SysUtils;
type
TPeriod = class
private
{ private declarations }
FMonth : String;
FYear : String;
procedure SetMonth(const Value: String);
procedure SetYear(const Value: String);
public
{ public declarations }
property Month : String read FMonth write SetMonth;
property Year : String read FYear write SetYear;
procedure SaveInDatabase;
procedure SearchPeriod(valSearch, valPeriod: String);
end;
implementation
{ TPeriod }
uses untDM;
procedure TPeriod.SaveInDatabase;
begin
untDM.frmDM.qrCategory.Open;
untDM.frmDM.qrPeriod.Insert;
untDM.frmDM.qrPeriodMONTH.AsString := Month;
untDM.frmDM.qrPeriodYEAR.AsString := Year;
untDM.frmDM.qrPeriod.Post;
end;
procedure TPeriod.SearchPeriod(valSearch, valPeriod: String);
var
Line : String;
begin
untDM.frmDM.qrSearchPeriod.Close;
Line := 'SELECT * FROM period WHERE period.":Search" like %:Time%';
untDM.frmDM.qrSearchPeriod.SQL.Text := Line;
untDM.frmDM.qrSearchPeriod.ParamByName('Search').Text := valSearch;
untDM.frmDM.qrSearchPeriod.ParamByName('Time').Text := valPeriod;
untDM.frmDM.qrSearchPeriod.Open;
end;
procedure TPeriod.SetMonth(const Value: String);
begin
FMonth := Value;
end;
procedure TPeriod.SetYear(const Value: String);
begin
FYear := Value;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit RSConfig.DataFrame;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Layouts, FMX.EditBox, FMX.SpinBox, FMX.Edit, FMX.Controls.Presentation,
System.Rtti, System.Bindings.Outputs, FMX.Bind.Editors, Data.Bind.EngExt,
FMX.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope;
type
TDataFrame = class(TFrame)
Layout10: TLayout;
UserNameEdit: TEdit;
Layout11: TLayout;
DatabaseEdit: TEdit;
LocateDBButton: TButton;
Layout5: TLayout;
PooledMaxHelpButton: TButton;
Layout6: TLayout;
InstanceNameEdit: TEdit;
InstanceNameHelpButton: TButton;
Layout7: TLayout;
PooledHelpButton: TButton;
Layout8: TLayout;
SEPasswordEdit: TEdit;
SEPasswordHelpButton: TButton;
Layout9: TLayout;
PasswordEdit: TEdit;
VertScrollBox1: TVertScrollBox;
BindSourceDBData: TBindSourceDB;
BindingsList1: TBindingsList;
LinkControlToField1: TLinkControlToField;
LinkControlToField2: TLinkControlToField;
LinkControlToField3: TLinkControlToField;
LinkControlToField5: TLinkControlToField;
OpenDialog: TOpenDialog;
PooledMaxSB: TSpinBox;
LinkControlToField6: TLinkControlToField;
LinkControlToField7: TLinkControlToField;
InstanceNameCB: TCheckBox;
DatabaseCB: TCheckBox;
UsernameCB: TCheckBox;
PasswordCB: TCheckBox;
SEPasswordCB: TCheckBox;
PooledCB: TCheckBox;
PooledMaxCB: TCheckBox;
Layout4: TLayout;
Label2: TLabel;
Label3: TLabel;
PooledSwitch: TSwitch;
LinkControlToField4: TLinkControlToField;
BindSourceDB1: TBindSourceDB;
LinkControlToField8: TLinkControlToField;
LinkControlToField9: TLinkControlToField;
LinkControlToField10: TLinkControlToField;
LinkControlToField11: TLinkControlToField;
LinkControlToField12: TLinkControlToField;
LinkControlToField13: TLinkControlToField;
LinkControlToField14: TLinkControlToField;
procedure LocateDBButtonClick(Sender: TObject);
procedure HelpButtonClick(Sender: TObject);
procedure PooledMaxSBChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
procedure LoadSection;
procedure SaveSection;
end;
implementation
{$R *.fmx}
uses
RSConfig.ConfigDM, RSConfig.Consts;
constructor TDataFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
InstanceNameHelpButton.Hint := strInstanceNameHelp;
SEPasswordHelpButton.Hint := strSEPasswordHelp;
PooledHelpButton.Hint := strPooledHelp;
PooledMaxHelpButton.Hint := strPooledMax;
end;
procedure TDataFrame.HelpButtonClick(Sender: TObject);
begin
ConfigDM.ShowHelp(Sender);
end;
procedure TDataFrame.LoadSection;
begin
ConfigDM.LoadSection(strData, ConfigDM.DataMT, ConfigDM.DataStatusMT);
end;
procedure TDataFrame.SaveSection;
begin
ConfigDM.SaveSection(strData, ConfigDM.DataMT, ConfigDM.DataStatusMT);
end;
procedure TDataFrame.LocateDBButtonClick(Sender: TObject);
begin
ConfigDM.OpenDialogForEdit(DatabaseEdit, OpenDialog);
end;
procedure TDataFrame.PooledMaxSBChange(Sender: TObject);
begin
TLinkObservers.ControlChanged(TSpinBox(Sender));
end;
end.
|
{***************************************************************
*
* Project : SSLTunnel
* Unit Name: main
* Purpose : Demonstrates setting up an SSL tunnell
* Version : 1.0
* Date : Wed 25 Apr 2001 - 01:33:51
* Author : <unknown>
* History :
* Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com>
*
****************************************************************}
unit main;
interface
uses
{$IFDEF Linux}
QGraphics, QControls, QForms, QDialogs, QStdCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls,
{$ENDIF}
windows, messages, SysUtils, Classes, IdBaseComponent, IdComponent,
IdTCPServer, IdMappedPortTCP, IdIntercept, IdSSLIntercept, IdSSLOpenSSL,
IdTCPClient;
type
TformMain = class(TForm)
MappedPort: TIdMappedPortTCP;
lablLocal: TLabel;
Label2: TLabel;
lablHost: TLabel;
Label1: TLabel;
Label3: TLabel;
procedure FormCreate(Sender: TObject);
procedure MappedPortBeforeClientConnect(ASender: TComponent;
AThread: TIdPeerThread; AClient: TIdTCPClient);
procedure SSLInterceptGetPassword(var Password: string);
private
public
end;
var
formMain: TformMain;
implementation
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
procedure TformMain.FormCreate(Sender: TObject);
begin
if ParamCount = 3 then
begin
with MappedPort do
begin
DefaultPort := StrToInt(ParamStr(1));
MappedHost := ParamStr(2);
MappedPort := StrToInt(ParamStr(3));
//
Active := True;
//
lablLocal.Caption := 'Local Port: ' + IntToStr(DefaultPort);
lablHost.Caption := 'Host: ' + MappedHost + ':' + IntToStr(MappedPort);
end;
lablLocal.Visible := True;
lablHost.Visible := True;
end;
end;
procedure TformMain.MappedPortBeforeClientConnect(ASender: TComponent;
AThread: TIdPeerThread; AClient: TIdTCPClient);
var
LIntercept: TIdConnectionInterceptOpenSSL;
begin
LIntercept := TIdConnectionInterceptOpenSSL.Create(AClient);
AClient.Intercept := LIntercept;
with LIntercept do
begin
SSLOptions.Method := sslvSSLv2;
SSLOptions.Mode := sslmClient;
SSLOptions.VerifyMode := [];
SSLOptions.VerifyDepth := 0;
OnGetPassword := SSLInterceptGetPassword;
end;
end;
procedure TformMain.SSLInterceptGetPassword(var Password: string);
begin
Password := 'aaaa';
end;
end.
|
unit FC.StockChart.UnitTask.MBB.CalculateProfitDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Contnrs,
Dialogs, BaseUtils,SystemService, ufmDialogClose_B, ufmDialog_B, ActnList, StdCtrls, ExtendControls, ExtCtrls, Spin,
StockChart.Definitions,StockChart.Definitions.Units, FC.Definitions, DB, Grids, DBGrids, MultiSelectDBGrid,
ColumnSortDBGrid, EditDBGrid, MemoryDS, ComCtrls;
type
TfmMBBCalculateProfitDialog = class(TfmDialogClose_B)
buCalculate: TButton;
taReport: TMemoryDataSet;
DataSource1: TDataSource;
grReport: TEditDBGrid;
taReportNumber: TIntegerField;
Label1: TLabel;
laBestValue: TLabel;
Label2: TLabel;
pbProgress: TProgressBar;
taReportOpenTime: TDateTimeField;
taReportOpenPrice: TCurrencyField;
taReportCloseTime: TDateTimeField;
taReportClosePrice: TCurrencyField;
taReportProfitPt: TIntegerField;
procedure buCalculateClick(Sender: TObject);
private
FIndicator: ISCIndicatorMBB;
procedure Calculate;
public
class procedure Run(const aIndicator: ISCIndicatorMBB);
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
uses Math;
type
TDirection = (dNone,dUp,dDown);
{$R *.dfm}
{ TfmCalculateWidthDialog }
type
TOrderState = (osNone,osBuy,osSell);
procedure TfmMBBCalculateProfitDialog.Calculate;
var
i,j: Integer;
aTotalProfit: integer;
aInputData: ISCInputDataCollection;
aCurProgress: integer;
aOrderState : TOrderState;
aValue : integer;
aOpenPrice: TStockRealNumber;
aOpenDate: TDateTime;
aClosePrice: TStockRealNumber;
aProfit: integer;
aNumber: integer;
begin
TWaitCursor.SetUntilIdle;
aInputData:=FIndicator.GetInputData;
aTotalProfit:=0;
// taReport.DisableControls;
try
taReport.EmptyTable;
taReport.Open;
pbProgress.Max:=100;
pbProgress.Position:=0;
pbProgress.Visible:=true;
aCurProgress:=0;
aOrderState:=osNone;
aOpenPrice:=0;
aOpenDate:=0;
aNumber:=1;
for i:=FIndicator.GetFirstValidValueIndex to aInputData.Count-1 do
begin
aValue:=FIndicator.GetCrosses(i);
if aValue<>0 then
begin
aClosePrice:=0;
aProfit:=0;
case aOrderState of
osBuy: begin
if aValue=1 then
begin
aClosePrice:=FIndicator.GetTopLine(i);
aProfit:=aInputData.PriceToPoint(aClosePrice-aOpenPrice);
end;
end;
osSell: begin
if aValue=-1 then
begin
aClosePrice:=FIndicator.GetBottomLine(i);
aProfit:=aInputData.PriceToPoint(aOpenPrice-aClosePrice);
end;
end;
end;
if aClosePrice<>0 then
begin
taReport.Append;
taReportNumber.Value:=aNumber;
inc(aNumber);
taReportOpenTime.Value:=aOpenDate;
taReportOpenPrice.Value:=aOpenPrice;
taReportCloseTime.Value:=aInputData.DirectGetItem_DataDateTime(i);
taReportClosePrice.Value:=aClosePrice;
taReportProfitPt.Value:=aProfit;
taReport.Post;
aTotalProfit:=aTotalProfit+aProfit;
end;
if aValue=1 then
begin
aOrderState:=osSell;
aOpenPrice:=FIndicator.GetTopLine(i);
aOpenDate:=aInputData.DirectGetItem_DataDateTime(i);
end
else if aValue=-1 then
begin
aOrderState:=osBuy;
aOpenPrice:=FIndicator.GetBottomLine(i);
aOpenDate:=aInputData.DirectGetItem_DataDateTime(i);
end;
end;
j:=(i div aInputData.Count)*100;
if j<>aCurProgress then
begin
pbProgress.Position:=j;
aCurProgress:=j;
Application.ProcessMessages;
end;
end;
finally
grReport.RefreshSort;
pbProgress.Visible:=false;
//taReport.EnableControls;
end;
laBestValue.Caption:=IntToStr(aTotalProfit)+' pt';
end;
procedure TfmMBBCalculateProfitDialog.buCalculateClick(Sender: TObject);
begin
inherited;
Calculate;
end;
constructor TfmMBBCalculateProfitDialog.Create(aOwner: TComponent);
begin
inherited;
end;
destructor TfmMBBCalculateProfitDialog.Destroy;
begin
inherited;
end;
class procedure TfmMBBCalculateProfitDialog.Run(const aIndicator: ISCIndicatorMBB);
begin
with TfmMBBCalculateProfitDialog.Create(nil) do
try
FIndicator:=aIndicator;
Caption:=IndicatorFactory.GetIndicatorInfo(FIndicator.GetIID).Name+': '+Caption;
ShowModal;
finally
Free;
end;
end;
end.
|
unit frm_ZonasGeograficas;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, frm_connection, global, ComCtrls, ToolWin,
StdCtrls, ExtCtrls, DBCtrls, Mask, frm_barra, adodb, db, Menus, OleCtrls,
frxClass, frxDBSet, ZAbstractRODataset, ZAbstractDataset, ZDataset,
udbgrid, unitexcepciones, unittbotonespermisos, UnitValidaTexto,
unitactivapop;
type
TfrmZonasGeograficas = class(TForm)
gridZonasGeo: TDBGrid;
Label2: TLabel;
Label9: TLabel;
frmBarra1: TfrmBarra;
txtZona: TDBEdit;
txtSalMin: TDBEdit;
PopupPrincipal: TPopupMenu;
Insertar1: TMenuItem;
Editar1: TMenuItem;
N1: TMenuItem;
Registrar1: TMenuItem;
Can1: TMenuItem;
N2: TMenuItem;
Eliminar1: TMenuItem;
Refresh1: TMenuItem;
N4: TMenuItem;
Cut1: TMenuItem;
Copy1: TMenuItem;
N3: TMenuItem;
Salir1: TMenuItem;
qryZonasGeo: TZQuery;
dsZonasGeo: TDataSource;
qryZonasGeoiId: TIntegerField;
qryZonasGeosZona: TStringField;
qryZonasGeodSalarioMinimo: TFloatField;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure gridZonasGeoCellClick(Column: TColumn);
procedure frmBarra1btnAddClick(Sender: TObject);
procedure frmBarra1btnEditClick(Sender: TObject);
procedure frmBarra1btnPostClick(Sender: TObject);
procedure frmBarra1btnCancelClick(Sender: TObject);
procedure frmBarra1btnDeleteClick(Sender: TObject);
procedure frmBarra1btnRefreshClick(Sender: TObject);
procedure frmBarra1btnExitClick(Sender: TObject);
procedure Insertar1Click(Sender: TObject);
procedure Editar1Click(Sender: TObject);
procedure Registrar1Click(Sender: TObject);
procedure Can1Click(Sender: TObject);
procedure Eliminar1Click(Sender: TObject);
procedure Refresh1Click(Sender: TObject);
procedure Salir1Click(Sender: TObject);
procedure gridZonasGeoEnter(Sender: TObject);
procedure gridZonasGeoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure gridZonasGeoKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure txtZonaEnter(Sender: TObject);
procedure txtZonaExit(Sender: TObject);
procedure txtZonaKeyPress(Sender: TObject; var Key: Char);
procedure txtSalMinEnter(Sender: TObject);
procedure txtSalMinExit(Sender: TObject);
procedure txtSalMinKeyPress(Sender: TObject; var Key: Char);
procedure gridZonasGeoMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure gridZonasGeoMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure gridZonasGeoTitleClick(Column: TColumn);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmZonasGeograficas : TfrmZonasGeograficas;
utgrid : ticdbgrid;
sOldId : string;
botonpermiso : tbotonespermisos;
sOpcion : string;
implementation
uses
frm_inteligent;
{$R *.dfm}
procedure TfrmZonasGeograficas.FormClose(Sender: TObject; var Action: TCloseAction);
begin
utgrid.Destroy;
action := cafree ;
botonpermiso.Free;
end;
procedure TfrmZonasGeograficas.FormShow(Sender: TObject);
begin
UtGrid:=TicdbGrid.create(gridZonasGeo);
BotonPermiso := TBotonesPermisos.Create(Self, connection.zConnection, global_grupo, 'MnuMarcaSubF', PopupPrincipal);
frmbarra1.btnCancel.Click ;
qryZonasGeo.Active := False;
qryZonasGeo.Open ;
BotonPermiso.permisosBotones(frmBarra1);
frmbarra1.btnPrinter.Enabled := False;
end;
procedure TfrmZonasGeograficas.gridZonasGeoCellClick(Column: TColumn);
begin
If frmbarra1.btnCancel.Enabled = True then
frmBarra1.btnCancel.Click ;
end;
procedure TfrmZonasGeograficas.frmBarra1btnAddClick(Sender: TObject);
begin
BotonPermiso.permisosBotones(frmBarra1);
txtZona.SetFocus;
frmBarra1.btnAddClick(Sender);
qryZonasGeo.Append;
end;
procedure TfrmZonasGeograficas.frmBarra1btnEditClick(Sender: TObject);
begin
If qryZonasGeo.RecordCount > 0 Then
Begin
try
qryZonasGeo.Edit ;
txtZona.SetFocus;
except
on e : exception do begin
UnitExcepciones.manejarExcep(E.Message, E.ClassName, 'Catálogo de Zonas Geográficas', 'Al Actualizar el registro', 0);
end;
end;
End;
BotonPermiso.permisosBotones(frmBarra1);
frmBarra1.btnEditClick(Sender);
end;
procedure TfrmZonasGeograficas.frmBarra1btnPostClick(Sender: TObject);
var
nombres, cadenas : TStringList;
begin
{Validaciones de campos}
nombres:=TStringList.Create;cadenas:=TStringList.Create;
nombres.Add('Descripción'); cadenas.Add(txtZona.Text);
nombres.Add('Salario Mínimo'); cadenas.Add(txtSalMin.Text);
if not validaTexto(nombres, cadenas, '',txtZona.Text) then
begin
MessageDlg(UnitValidaTexto.errorValidaTexto, mtInformation, [mbOk], 0);
exit;
end;
Try
qryZonasGeo.Post ;
frmBarra1.btnPostClick(Sender);
except
on e : exception do begin
UnitExcepciones.manejarExcep(E.Message, E.ClassName, 'Catálogo de Zonas Geográficas', 'Al salvar registro', 0);
frmBarra1.btnCancel.Click;
qryZonasGeo.Cancel;
end;
end;
BotonPermiso.permisosBotones(frmBarra1);
end;
procedure TfrmZonasGeograficas.frmBarra1btnCancelClick(Sender: TObject);
begin
qryZonasGeo.Cancel ;
BotonPermiso.permisosBotones(frmBarra1);
frmBarra1.btnCancelClick(Sender);
end;
procedure TfrmZonasGeograficas.frmBarra1btnDeleteClick(Sender: TObject);
begin
If qryZonasGeo.RecordCount > 0 then
if MessageDlg('Desea eliminar el Registro Activo?',
mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
try
qryZonasGeo.Delete ;
except
on e : exception do begin
MessageDlg('No se puede Eliminar el Registro, por que éste Existe en otras Tablas',mtError,[mbOk],0);
end;
end
end
end;
procedure TfrmZonasGeograficas.frmBarra1btnRefreshClick(Sender: TObject);
begin
qryZonasGeo.refresh ;
end;
procedure TfrmZonasGeograficas.frmBarra1btnExitClick(Sender: TObject);
begin
frmBarra1.btnExitClick(Sender);
Close;
end;
procedure TfrmZonasGeograficas.Insertar1Click(Sender: TObject);
begin
frmBarra1.btnAdd.Click
end;
procedure TfrmZonasGeograficas.Editar1Click(Sender: TObject);
begin
frmBarra1.btnEdit.Click
end;
procedure TfrmZonasGeograficas.Registrar1Click(Sender: TObject);
begin
frmBarra1.btnPost.Click
end;
procedure TfrmZonasGeograficas.Can1Click(Sender: TObject);
begin
frmBarra1.btnCancel.Click
end;
procedure TfrmZonasGeograficas.Eliminar1Click(Sender: TObject);
begin
frmBarra1.btnDelete.Click
end;
procedure TfrmZonasGeograficas.Refresh1Click(Sender: TObject);
begin
frmBarra1.btnRefresh.Click
end;
procedure TfrmZonasGeograficas.Salir1Click(Sender: TObject);
begin
frmBarra1.btnExit.Click
end;
procedure TfrmZonasGeograficas.gridZonasGeoEnter(Sender: TObject);
begin
If frmbarra1.btnCancel.Enabled = True then
frmBarra1.btnCancel.Click ;
end;
procedure TfrmZonasGeograficas.gridZonasGeoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If frmbarra1.btnCancel.Enabled = True then
frmBarra1.btnCancel.Click ;
end;
procedure TfrmZonasGeograficas.gridZonasGeoKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If frmbarra1.btnCancel.Enabled = True then
frmBarra1.btnCancel.Click ;
end;
procedure TfrmZonasGeograficas.gridZonasGeoMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
UtGrid.dbGridMouseMoveCoord(x,y);
end;
procedure TfrmZonasGeograficas.gridZonasGeoMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
UtGrid.DbGridMouseUp(Sender,Button,Shift,X, Y);
end;
procedure TfrmZonasGeograficas.gridZonasGeoTitleClick(Column: TColumn);
begin
UtGrid.DbGridTitleClick(Column);
end;
procedure TfrmZonasGeograficas.txtZonaEnter(Sender: TObject);
begin
txtZona.Color := global_color_entrada
end;
procedure TfrmZonasGeograficas.txtZonaExit(Sender: TObject);
begin
txtZona.Color := global_color_salida
end;
procedure TfrmZonasGeograficas.txtZonaKeyPress(Sender: TObject;
var Key: Char);
begin
If Key = #13 Then
txtSalMin.SetFocus
end;
procedure TfrmZonasGeograficas.txtSalMinEnter(Sender: TObject);
begin
txtSalMin.Color := global_color_entrada
end;
procedure TfrmZonasGeograficas.txtSalMinExit(Sender: TObject);
begin
txtSalMin.Color := global_color_salida
end;
procedure TfrmZonasGeograficas.txtSalMinKeyPress(Sender: TObject;
var Key: Char);
begin
If Key = #13 then
txtZona.SetFocus
end;
end.
|
unit GameDevDialog;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ExtCtrls, KbdMacro;
type
TGameForm = class(TForm)
OKBtn: TButton;
CancelBtn: TButton;
Label1: TLabel;
GameComboBox: TComboBox;
GroupBox1: TGroupBox;
ScrollBox1: TScrollBox;
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
fLastIndex: Integer;
fLastDirection: TMacroDirection;
public
{ Public declarations }
TXTdown: String;
TXTup: String;
procedure SetMacroAttribs(pMacro: TKeyboardMacro);
procedure InitByMacro(pMacro: TKeyboardMacro);
end;
implementation
{$R *.dfm}
uses Dialogs, uGameDevices;
procedure TGameForm.FormClose(Sender: TObject; var Action: TCloseAction);
var I:Integer;
tmpC: TControl;
begin
// free all childs of ScrollBox1
for I := ScrollBox1.ControlCount - 1 downto 0 do
begin
tmpC := ScrollBox1.Controls[I];
if Copy(tmpC.Name, 1, 6) = 'Button' then
if (tmpC is TRadioButton) then
if (tmpC as TRadioButton).Checked then
begin
fLastIndex := tmpC.Tag;
if tmpC.Name = 'Button'+IntToStr(fLastIndex)+'Up' then
fLastDirection := mdUp
else
fLastDirection := mdDown;
end;
tmpC.Free;
end;
end;
procedure TGameForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if (GameComboBox.ItemIndex = -1) and (ModalResult = mrOK) then
begin
MessageDlg('Select game device or cancel dialog.', mtError, [mbOK], 0);
CanClose := False;
end
end;
procedure TGameForm.FormCreate(Sender: TObject);
begin
TXTdown := 'down';
TXTup := 'up';
end;
procedure TGameForm.InitByMacro(pMacro: TKeyboardMacro);
var
I: Integer;
tmpRB: TRadioButton;
tmpLabel: TLabel;
begin
if pMacro = nil then
exit;
GameComboBox.Items.Clear;
GameComboBox.Items.Add(pMacro.Keyboard.Name);
GameComboBox.ItemIndex := 0;
GameComboBox.Enabled := False;
for I := 0 to (pMacro.Keyboard as THIDJoystick).ButtonsCount - 1 do
begin
tmpLabel := TLabel.Create(self);
with tmpLabel do
begin
Parent := ScrollBox1;
Name := 'LabelButton'+IntToStr(I);
Left := 10;
Top := I*25+5;
Caption := 'Button ' +IntToStr(I+1);
Visible := True;
end;
tmpRB := TRadioButton.Create(self);
tmpRB.Parent := ScrollBox1;
tmpRB.Name := 'Button'+IntToStr(I)+'Down';
tmpRB.Left := 90;
tmpRB.Top := I*25+5;
tmpRB.Tag := I;
tmpRB.Caption := TXTdown;
tmpRB.Checked := (pMacro.ButtonIndex = I) and (pMacro.Direction = mdDown);
tmpRB.Visible := True;
tmpRB := TRadioButton.Create(self);
tmpRB.Parent := ScrollBox1;
tmpRB.Name := 'Button'+IntToStr(I)+'Up';
tmpRB.Left := 160;
tmpRB.Top := I*25+5;
tmpRB.Tag := I;
tmpRB.Caption := TXTup;
tmpRB.Checked := (pMacro.ButtonIndex = I) and (pMacro.Direction = mdUp);
tmpRB.Visible := True;
end;
end;
procedure TGameForm.SetMacroAttribs(pMacro: TKeyboardMacro);
var
I: Integer;
begin
if pMacro = nil then
exit;
if fLastIndex < (pMacro.Keyboard as THIDJoystick).ButtonsCount then
begin
pMacro.ButtonIndex := fLastIndex;
pMacro.Direction := fLastDirection;
end;
end;
end.
|
{******************************************}
{ TeeChart VCL Library }
{ Copyright (c) 1995-2004 by David Berneda }
{ All Rights Reserved }
{******************************************}
unit TeeChartGrid;
{$I TeeDefs.inc}
interface
Uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
{$IFDEF CLX}
QControls, QGrids, QGraphics, QExtCtrls, Qt, Types,
{$ELSE}
Controls, Grids, Graphics, ExtCtrls,
{$ENDIF}
Classes, Chart, TeEngine, TeeProcs, TeCanvas, TeeNavigator;
type
TChartGridNavigator=class;
TChartGridShow=(cgsAuto,cgsNo,cgsYes);
TCustomChartGrid=class;
TEditingCellEvent=procedure (Sender: TCustomChartGrid; ACol, ARow: Integer;
var Allow:Boolean) of object;
TCustomChartGrid=class(TCustomGrid,ITeeEventListener)
private
FChart : TCustomChart;
FColors : Boolean;
FGrid3DMode : Boolean;
FLabels : Boolean;
FXValues : TChartGridShow;
FOldValue : String;
FOnChangeColor : TNotifyEvent;
FOnEditing : TEditingCellEvent;
FOnSetCell : TSetEditEvent;
FShowFields : Boolean;
FWasNull : Boolean;
IHasNo : Array[0..1000] of Boolean;
INavigator : TChartGridNavigator;
FSeries : TChartSeries;
ISeriesChart : TCustomAxisPanel;
Procedure AddListener(AChart:TCustomAxisPanel); // 5.03
Function FirstRowNum:Integer;
Function ColorsColumn:Integer;
Function LabelsColumn:Integer;
procedure NotifyChange;
procedure Regenerate;
Procedure RemoveListener(AChart:TCustomAxisPanel); // 5.03
Procedure SetBooleanProperty(Var Variable:Boolean; Value:Boolean);
Procedure SetChart(AChart:TCustomChart);
Procedure SetGrid3DMode(Value:Boolean);
Procedure SetManualData(ASeries:TChartSeries);
Procedure SetNavigator(ANavigator:TChartGridNavigator);
Procedure SetShowColors(Value:Boolean);
Procedure SetShowFields(Value:Boolean);
Procedure SetShowLabels(Value:Boolean);
Procedure SetShowXValues(Value:TChartGridShow);
procedure SetSeries(const Value: TChartSeries);
protected
FActiveChanged : TNotifyEvent;
FSelectedChanged : TSelectCellEvent;
function CanEditModify: Boolean; override;
function CanEditShow: Boolean; override;
procedure DblClick; override;
procedure DrawCell(ACol, ARow: Integer; ARect: TRect;
AState: TGridDrawState); override;
function GetEditText(ACol, ARow: Integer): {$IFDEF CLX}WideString{$ELSE}String{$ENDIF}; override;
Function GetSeriesColor(var AColor:TColor):TChartSeries;
Function HasPoints:Boolean;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure Notification( AComponent: TComponent;
Operation: TOperation); override;
Procedure Loaded; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
function SelectCell(ACol, ARow: Integer): Boolean; override;
procedure SetEditText(ACol, ARow: Integer;
const Value: {$IFDEF CLX}WideString{$ELSE}String{$ENDIF}); override;
procedure TeeEvent(Event: TTeeEvent);
public
{ Allow changing cells even if Series.DataSource is assigned }
AllowChanges : Boolean; { 5.02 }
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
Procedure AppendRow;
Procedure ChangeColor; overload;
Procedure ChangeColor(AColor:TColor); overload;
Procedure ChangeColor(ASeries:TChartSeries; AColor:TColor); overload;
Procedure Delete;
Function FindXYZIndex(ASeries:TChartSeries; ARow,ACol:Integer):Integer;
Function GetSeries(ACol:Integer; Var AList:TChartValueList):TChartSeries;
Function GetXYZSeries:TChartSeries;
Procedure Insert;
Procedure RecalcDimensions;
{$IFDEF TEEOCX}
procedure SetFocus; override;
{$ENDIF}
Procedure StartEditing;
Procedure StopEditing(Cancel:Boolean);
property Chart:TCustomChart read FChart write SetChart;
property Series:TChartSeries read FSeries write SetSeries;
property ShowColors:Boolean read FColors write SetShowColors default False;
property ShowFields:Boolean read FShowFields write SetShowFields default True;
property ShowLabels:Boolean read FLabels write SetShowLabels default True;
property ShowXValues:TChartGridShow read FXValues write SetShowXValues default cgsAuto;
property FixedCols default 1;
property DefaultRowHeight default {$IFDEF LINUX}20{$ELSE}16{$ENDIF};
property Grid3DMode:Boolean read FGrid3DMode write
SetGrid3DMode default False; // for XYZ series, set x by z grid mode
property GridLineWidth default 1;
{$IFDEF CLR}
property Col;
property EditorMode;
property Options;
property Row;
property RowCount;
{$ENDIF}
{ events }
property OnChangeColor:TNotifyEvent read FOnChangeColor write FOnChangeColor; { 5.02 }
property OnEditingCell:TEditingCellEvent read FOnEditing write FOnEditing; // 7.0
property OnSetEditText:TSetEditEvent read FOnSetCell write FOnSetCell; { 5.02 }
end;
TChartGrid=class(TCustomChartGrid)
public
property Col;
property ColCount;
{$IFNDEF CLR}
property ColWidths;
{$ENDIF}
property EditorMode;
property GridHeight;
property GridWidth;
property LeftCol;
property Selection;
property Row;
property RowCount;
{$IFNDEF CLR}
property RowHeights;
property TabStops;
{$ENDIF}
property TopRow;
published
property Align;
property Anchors;
{$IFNDEF CLX}
property BiDiMode;
{$ENDIF}
property BorderStyle;
property Color;
property Constraints;
{$IFNDEF CLX}
property Ctl3D;
{$ENDIF}
property DefaultColWidth;
property DefaultRowHeight;
property DefaultDrawing;
property DragMode;
{$IFNDEF CLX}
property DragCursor;
property DragKind;
{$ENDIF}
property Enabled;
property FixedColor;
property Font;
property GridLineWidth;
property Options;
{$IFNDEF CLX}
property ParentBiDiMode;
{$ENDIF}
property ParentColor;
{$IFNDEF CLX}
property ParentCtl3D;
{$ENDIF}
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ScrollBars;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
{ events }
property OnClick;
{$IFDEF D5}
property OnContextPopup;
{$ENDIF}
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnStartDrag;
{$IFNDEF CLX}
property OnEndDock;
{$ENDIF}
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheelDown;
property OnMouseWheelUp;
{$IFNDEF CLX}
property OnStartDock;
{$ENDIF}
property Chart;
property Series;
property ShowColors; { 5.02 }
property ShowLabels;
property ShowXValues; { 5.02 }
{ event }
property OnChangeColor; // 7.0
property OnEditingCell; // 7.0
property OnSetEditText;
end;
TChartGridNavigator=class(TCustomTeeNavigator)
private
FGrid : TCustomChartGrid;
procedure ActiveChanged(Sender:TObject);
procedure EnableButtonsColRow(ACol,ARow:Integer);
procedure SelectedChanged(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure SetGrid(Value:TCustomChartGrid);
protected
procedure BtnClick(Index: TTeeNavigateBtn); override;
procedure Notification( AComponent: TComponent;
Operation: TOperation); override;
public
procedure EnableButtons; override;
published
property Grid:TCustomChartGrid read FGrid write SetGrid;
end;
implementation
Uses Math, SysUtils, TeeConst, TeePenDlg;
{ TChartGridNavigator }
procedure TChartGridNavigator.Notification( AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation=opRemove) and Assigned(Grid) and (AComponent=Grid) then
Grid:=nil;
end;
procedure TChartGridNavigator.SetGrid(Value:TCustomChartGrid);
begin
if FGrid<>Value then
begin
{$IFDEF D5}
if Assigned(FGrid) then
FGrid.RemoveFreeNotification(Self);
{$ENDIF}
FGrid:=Value;
if Assigned(FGrid) then
begin
FGrid.FreeNotification(Self);
FGrid.FActiveChanged:=ActiveChanged;
FGrid.FSelectedChanged:=SelectedChanged;
FGrid.SetNavigator(Self);
end;
EnableButtons;
end;
end;
procedure TChartGridNavigator.ActiveChanged(Sender:TObject);
begin
EnableButtons;
end;
procedure TChartGridNavigator.BtnClick(Index: TTeeNavigateBtn);
begin
if Assigned(FGrid) then
with FGrid do
begin
case Index of
nbPrior : if Row>FirstRowNum then Row:=Row-1;
nbNext : if Row<RowCount-1 then Row:=Row+1;
nbFirst : if Row>FirstRowNum then Row:=FirstRowNum;
nbLast : if Row<RowCount-1 then Row:=RowCount-1;
nbInsert: Insert;
nbEdit : begin
SetFocus;
StartEditing;
end;
nbCancel: StopEditing(True);
nbPost : StopEditing(False);
nbDelete: Delete;
end;
end;
inherited;
end;
procedure TChartGridNavigator.EnableButtons;
begin
inherited;
if Assigned(FGrid) then EnableButtonsColRow(FGrid.Col,FGrid.Row);
end;
procedure TChartGridNavigator.EnableButtonsColRow(ACol,ARow:Integer);
var UpEnable : Boolean;
DnEnable : Boolean;
begin
UpEnable := ARow>FGrid.FirstRowNum;
DnEnable := ARow<FGrid.RowCount-1;
Buttons[nbFirst].Enabled := UpEnable;
Buttons[nbPrior].Enabled := UpEnable;
Buttons[nbNext].Enabled := DnEnable;
Buttons[nbLast].Enabled := DnEnable;
Buttons[nbInsert].Enabled := (goEditing in FGrid.Options) and
(not FGrid.EditorMode) and
(Assigned(FGrid.Chart) and (FGrid.Chart.SeriesCount>0)) or
Assigned(FGrid.Series);
Buttons[nbDelete].Enabled := (FGrid.RowCount>1) and
Buttons[nbInsert].Enabled and
FGrid.HasPoints;
Buttons[nbPost].Enabled := FGrid.EditorMode;
Buttons[nbEdit].Enabled := Buttons[nbInsert].Enabled;
Buttons[nbCancel].Enabled := FGrid.EditorMode;
end;
procedure TChartGridNavigator.SelectedChanged(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
begin
EnableButtonsColRow(ACol,ARow);
end;
{ TCustomChartGrid }
Constructor TCustomChartGrid.Create(AOwner:TComponent);
begin
inherited;
FSaveCellExtents:=False;
FColors:=False;
FLabels:=True;
FXValues:=cgsAuto;
FShowFields:=True;
FWasNull:=False;
GridLineWidth:=1;
ColWidths[0]:=30;
DefaultRowHeight:={$IFDEF LINUX}20{$ELSE}16{$ENDIF};
FixedCols:=1;
RowHeights[0]:=20;
Options:=[ goHorzLine,
goVertLine,
goRangeSelect,
goDrawFocusSelected,
goRowSizing,
goColSizing,
goEditing,
goTabs,
goThumbTracking
];
RecalcDimensions;
end;
Destructor TCustomChartGrid.Destroy;
begin
Series:=nil; // 5.03
Chart:=nil;
inherited;
end;
Procedure TCustomChartGrid.Loaded;
begin
inherited;
RowHeights[0]:=20;
end;
Function TCustomChartGrid.HasPoints:Boolean;
var t: Integer;
begin
result:=False;
if Assigned(FSeries) then { single series }
result:=FSeries.Count>0
else
if Assigned(Chart) then { all series in chart }
With Chart do
for t:=0 to SeriesCount-1 do
if Series[t].Count>0 then
begin
result:=True;
Exit;
end;
end;
Function TCustomChartGrid.FirstRowNum:Integer;
begin
if ShowFields then result:=2 else result:=1;
end;
function TCustomChartGrid.SelectCell(ACol, ARow: Integer): Boolean;
begin
result:=inherited SelectCell(ACol,ARow) and (ACol>0) and (ARow>=FirstRowNum);
// Call event
if result and Assigned(FSelectedChanged) then
FSelectedChanged(Self,ACol,ARow,result);
end;
function TCustomChartGrid.CanEditModify: Boolean;
begin
result:=inherited CanEditModify;
if result then
if Assigned(INavigator) then INavigator.ActiveChanged(Self);
end;
procedure TCustomChartGrid.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
Procedure SelectColumn;
var tmpCoord : TGridCoord;
tmpSelection : TGridRect;
begin
tmpCoord:=MouseCoord(x,y);
if (tmpCoord.X>FixedCols) and (tmpCoord.Y<FixedRows) then
begin
with tmpSelection do
begin
Left:=tmpCoord.X;
Right:=Left;
Top:=FixedRows;
Bottom:=RowCount-1;
end;
Selection:=tmpSelection;
end;
end;
begin
inherited;
if FGridState=gsNormal then SelectColumn;
if Assigned(INavigator) then INavigator.ActiveChanged(Self);
end;
Procedure TCustomChartGrid.StopEditing(Cancel:Boolean);
begin
if EditorMode then
begin
if Cancel then InplaceEditor.Text:=''; // 5.02
HideEditor;
if Cancel and (not FWasNull) then SetEditText(Col,Row,FOldValue);
NotifyChange;
end;
end;
{$IFDEF TEEOCX}
procedure TCustomChartGrid.SetFocus; // 6.02
begin
if GetParentForm(Self)<>nil then inherited
else Windows.SetFocus(Handle);
end;
{$ENDIF}
Procedure TCustomChartGrid.StartEditing;
var tmpList : TChartValueList;
tmpSeries : TChartSeries;
begin
if (goEditing in Options) and (not EditorMode) then
begin
if Col>0 then
begin
tmpSeries:=GetSeries(Col,tmpList);
if Assigned(tmpSeries) then
With tmpSeries do
if (DataSource=nil) or Self.AllowChanges then { 5.02 }
begin
if Grid3DMode then
FWasNull:=Row>tmpSeries.MaxZValue
else
FWasNull:=(Row>Count) or (IsNull(Row-1));
if FWasNull then FOldValue:=''
else FOldValue:=GetEditText(Col,Row);
EditorMode:=True;
NotifyChange;
end;
end;
end;
end;
procedure TCustomChartGrid.KeyDown(var Key: Word; Shift: TShiftState);
var tmpList : TChartValueList;
tmpSeries : TChartSeries;
tmpCol : Integer;
tmpRow : Integer;
begin
if (not (ssCtrl in Shift)) then
begin
Case Key of
TeeKey_Escape : StopEditing(True);
TeeKey_F2 : if FColors and (Col=ColorsColumn) then
ChangeColor
else
StartEditing;
TeeKey_Up :
if (Row=RowCount-1) then // last row
begin
if FColors and (Col=ColorsColumn) then tmpCol:=Succ(Col)
else tmpCol:=Col;
tmpSeries:=GetSeries(tmpCol,tmpList);
tmpRow:=Row-FirstRowNum;
if Assigned(tmpSeries) and
(tmpSeries.Count>tmpRow) and { 5.01 }
tmpSeries.IsNull(tmpRow) and
(tmpSeries.Labels[tmpRow]='') then
begin
RowCount:=RowCount-1;
tmpSeries.Delete(Row-FirstRowNum+1);
end
else inherited; { 5.01 }
end
else inherited;
TeeKey_Down :
begin
if Row=RowCount-1 then AppendRow
else inherited;
end;
TeeKey_Insert : Insert;
TeeKey_Delete : if ssCtrl in Shift then Delete
else
begin
if not EditorMode then EditorMode:=True;
inherited;
end;
TeeKey_Return,
TeeKey_Space : if FColors and (Col=ColorsColumn) then
ChangeColor
else
inherited;
else inherited;
end;
end
else inherited;
end;
Procedure TCustomChartGrid.AppendRow;
var tmpCol : Integer;
tmpSeries : TChartSeries;
tmpList : TChartValueList;
begin
if (goEditing in Options) and (not Grid3DMode) then // 7.0
begin
if FColors and (Col=ColorsColumn) then tmpCol:=Succ(Col)
else tmpCol:=Col;
tmpSeries:=GetSeries(tmpCol,tmpList);
if Assigned(tmpSeries) then
begin
tmpSeries.AddNull;
RowCount:=RowCount+1;
Row:=RowCount-1;
end;
end
end;
Function TCustomChartGrid.FindXYZIndex(ASeries:TChartSeries;
ARow,ACol:Integer):Integer;
var tmpList : TChartValueList;
t : Integer;
begin
result:=-1;
tmpList:=ASeries.GetYValueList('Z');
for t:=0 to ASeries.Count-1 do
if (tmpList.Value[t]=ARow+1) and
(ASeries.NotMandatoryValueList.Value[t]=ACol) then
begin
result:=t;
break;
end;
end;
function TCustomChartGrid.GetEditText(ACol,ARow: Integer): {$IFDEF CLX}WideString{$ELSE}String{$ENDIF};
Function GetALabel(Index:Integer):String;
var t : Integer;
begin
result:='';
if Assigned(FSeries) then result:=FSeries.Labels[Index]
else
// return first Label found
for t:=0 to FChart.SeriesCount-1 do
With FChart.Series[t] do
if Labels.Count>Index then { 5.01 }
begin
result:=Labels[Index];
break;
end;
end;
var tmpSeries : TChartSeries;
tmpList : TChartValueList;
Procedure FindHeaderText;
begin
if FLabels and (ACol=LabelsColumn) then { 5.02 }
result:=TeeMsg_Text
else
if FColors and (ACol=ColorsColumn) then
result:=TeeMsg_Colors
else
if ShowFields and (ACol>LabelsColumn) then
begin
tmpSeries:=GetSeries(ACol,tmpList);
if Assigned(tmpSeries) then
if Grid3DMode then
result:=IntToStr(Round(tmpSeries.MinXValue)+ACol-1)
else
if Assigned(tmpList) then result:=tmpList.Name;
end;
end;
Function GetAValue:String;
var tmpValue : TDateTime;
begin
tmpSeries:=GetSeries(ACol,tmpList);
if Assigned(tmpSeries) and (tmpSeries.Count>ARow) then
if tmpList.DateTime then
begin
tmpValue:=tmpList.Value[ARow];
if tmpValue<1 then result:=TimeToStr(tmpValue)
else result:=DateTimeToStr(tmpValue);
end
else
result:=FormatFloat(tmpSeries.ValueFormat,tmpList.Value[ARow])
else
result:='';
end;
var t : Integer;
begin
result:='';
if ACol=0 then // First column
begin
if ARow>=FirstRowNum then
if Grid3DMode then
begin
tmpSeries:=GetXYZSeries;
result:=IntToStr(Round(tmpSeries.MinZValue)+ARow-FirstRowNum);
end
else
Str(ARow-FirstRowNum,Result)
else
if (not ShowFields) or (ARow=1) then
result:='#';
end
else
begin
if ((not ShowFields) and (ARow=0)) or
(ShowFields and (ARow=1)) then FindHeaderText // Header
else // Values
if ARow>=FirstRowNum then
begin
Dec(ARow,FirstRowNum);
if Grid3DMode then
begin
tmpSeries:=GetXYZSeries;
t:=FindXYZIndex(tmpSeries,ARow,ACol);
if t<>-1 then
result:=FormatFloat(tmpSeries.ValueFormat,
tmpSeries.MandatoryValueList.Value[t]);
end
else
if FLabels and (ACol=LabelsColumn) then
result:=GetALabel(ARow)
else
if FColors and (ACol=ColorsColumn) then
else
result:=GetAValue;
end;
end;
end;
Procedure TCustomChartGrid.SetGrid3DMode(Value:Boolean);
begin
FGrid3DMode:=Value;
Regenerate;
Repaint;
end;
type TSeriesAccess=class(TChartSeries);
Procedure TCustomChartGrid.SetManualData(ASeries:TChartSeries);
begin
TSeriesAccess(ASeries).ManualData:=True;
end;
procedure TCustomChartGrid.SetEditText(ACol, ARow: Integer;
const Value: {$IFDEF CLX}WideString{$ELSE}string{$ENDIF});
Procedure SetALabel(Index:Integer; Const AValue:String);
Procedure SetLabelSeries(ASeries:TChartSeries);
begin
While Index>=ASeries.Count do ASeries.AddNull('');
ASeries.Labels[Index]:=AValue;
end;
var t : Integer;
begin
if Assigned(Series) then SetLabelSeries(Series)
else
for t:=0 to Chart.SeriesCount-1 do SetLabelSeries(Chart[t]);
end;
Procedure SetAllManualData;
var t : Integer;
begin
if Assigned(Series) then SetManualData(Series)
else
for t:=0 to Chart.SeriesCount-1 do SetManualData(Chart[t]);
end;
var tmpSeries : TChartSeries;
tmpList : TChartValueList;
tmpRow : Integer;
begin
inherited;
if Assigned(FSeries) or (Assigned(FChart) and (FChart.SeriesCount>0)) then
try
SetAllManualData;
Dec(ARow,FirstRowNum);
if FLabels and (ACol=LabelsColumn) then // Labels
SetALabel(ARow,Value)
else
if FColors and (ACol=ColorsColumn) then // Colors
else
begin // Values
tmpSeries:=GetSeries(ACol,tmpList);
if Assigned(tmpSeries) then
begin
if Grid3DMode then
begin
tmpRow:=FindXYZIndex(tmpSeries,ARow,ACol);
tmpList:=tmpSeries.MandatoryValueList;
end
else
begin
While ARow>=tmpSeries.Count do tmpSeries.AddNull;
tmpRow:=ARow;
end;
if Trim(Value)='' then // 5.03
begin
if not EditorMode then
begin
tmpSeries.ValueColor[tmpRow]:=clNone;
Invalidate;
end;
end
else
begin
if tmpList.DateTime then
tmpList.Value[tmpRow]:=StrToDateTime(Value)
else
tmpList.Value[tmpRow]:=StrToFloat(Value);
tmpList.Modified:=True;
if tmpSeries.IsNull(tmpRow) then
begin
tmpSeries.ValueColor[tmpRow]:=clTeeColor;
if FColors then Self.Repaint; // 5.02
end;
end;
tmpSeries.RefreshSeries;
end;
{ Repaint Series and / or Chart }
if Assigned(FSeries) then FSeries.Repaint
else FChart.Repaint;
end;
{ call event }
if Assigned(FOnSetCell) then
FOnSetCell(Self,ACol,ARow+FirstRowNum,Value);
except { hide exception }
on EConvertError do ;
end;
end;
Function TCustomChartGrid.GetXYZSeries:TChartSeries;
var t : Integer;
begin
result:=nil;
if Assigned(FChart) then
begin
for t:=0 to FChart.SeriesCount-1 do
if FChart[t].HasZValues then
begin
result:=FChart[t];
break;
end;
end
else
if Assigned(FSeries) and FSeries.HasZValues then
result:=FSeries;
end;
// Returns series and series valuelist for the ACol column parameter
Function TCustomChartGrid.GetSeries(ACol:Integer; Var AList:TChartValueList):TChartSeries;
var tmp : Integer;
t : Integer;
begin
AList:=nil;
if Grid3DMode then result:=GetXYZSeries
else
begin
if FLabels then Dec(ACol);
if FColors then Dec(ACol);
if ACol>=0 then
begin
if Assigned(FSeries) then
begin
tmp:=FSeries.ValuesList.Count;
if not IHasNo[0] then Dec(tmp);
if (tmp>=ACol) then
begin
result:=FSeries;
if IHasNo[0] then
AList:=result.ValuesList[ACol-1]
else
if result.YMandatory then
AList:=result.ValuesList[ACol]
else
AList:=result.ValuesList[ACol-1];
exit;
end;
end
else
if Assigned(FChart) then
for t:=0 to FChart.SeriesCount-1 do
begin
tmp:=FChart.Series[t].ValuesList.Count;
if not IHasNo[t] then Dec(tmp);
if (tmp>=ACol) then
begin
result:=FChart.Series[t];
if IHasNo[t] then
AList:=result.ValuesList[ACol-1]
else
if result.YMandatory then
AList:=result.ValuesList[ACol]
else
AList:=result.ValuesList[ACol-1];
exit;
end;
Dec(ACol,tmp);
end;
end;
result:=nil;
end;
end;
procedure TCustomChartGrid.DrawCell(ACol, ARow: Integer; ARect: TRect;
AState: TGridDrawState);
Function GetSeriesCol(ACol:Integer):TChartSeries;
var tmp : Integer;
t : Integer;
begin
if FLabels then tmp:=LabelsColumn else
if FColors then tmp:=ColorsColumn else tmp:=0;
if Assigned(FSeries) then
begin
result:=FSeries;
exit;
end
else
for t:=0 to FChart.SeriesCount-1 do
begin
Inc(tmp);
if tmp=ACol then
begin
result:=FChart.Series[t];
exit;
end;
Inc(tmp,FChart.Series[t].ValuesList.Count-2);
if IHasNo[t] then Inc(tmp);
end;
result:=nil;
end;
Procedure FillWithColor(AColor:TColor);
begin
Canvas.Brush.Color:=AColor;
Canvas.Brush.Style:=bsSolid;
Canvas.FillRect(ARect);
end;
var tmp : Integer;
tmpSeries : TChartSeries;
AList : TChartValueList;
tmpSt : String;
tmpColor : TColor;
begin
if Assigned(FChart) or Assigned(FSeries) then
begin
tmp:=0;
if FLabels then Inc(tmp);
if FColors then Inc(tmp);
if (ARow=0) and (ACol>tmp) then // Series first Header
begin
tmpSeries:=GetSeriesCol(ACol);
if Assigned(FSeries) and (not ShowFields) then // 5.03
begin
GetSeries(ACol,AList);
Canvas.TextRect(ARect, ARect.Left+18, ARect.Top+4,AList.Name);
end
else
if Assigned(tmpSeries) then
if (not Grid3DMode) or ((ACol-tmp)=1) then // only once for 3D mode
begin
With ARect do
PaintSeriesLegend(tmpSeries,Canvas,TeeRect(Left+4,Top+4,Left+16,Top+16));
{$IFDEF CLX}
QPainter_setBackgroundMode(Canvas.Handle,BGMode_TransparentMode);
{$ENDIF}
Canvas.Brush.Style:=bsClear;
Canvas.Pen.Style:=psSolid;
Canvas.Font.Color:=Self.Font.Color;
Canvas.TextRect(ARect, ARect.Left+18, ARect.Top+4,
SeriesTitleOrName(tmpSeries));
end;
end
else
begin
if (ACol=0) or (ShowFields and (ARow=1)) then // Point number (#) column
FillWithColor(FixedColor);
if FColors and (ACol=ColorsColumn) then // Colors
begin
if ARow=FirstRowNum-1 then
Canvas.TextRect(ARect, ARect.Left+2, ARect.Top+2,
TeeMsg_Colors)
else
if ARow>=FirstRowNum then
begin
tmpSeries:=GetSeries(ACol+1,AList);
if Assigned(tmpSeries) and (tmpSeries.Count>(ARow-FirstRowNum)) then
begin
tmpColor:=tmpSeries.ValueColor[ARow-FirstRowNum];
if tmpColor=clNone then tmpColor:=Self.Color;
end
else tmpColor:=Self.Color;
FillWithColor(tmpColor);
end;
end
else
if FLabels and (ACol=LabelsColumn) then // Labels
Canvas.TextRect(ARect, ARect.Left+2, ARect.Top+2, GetEditText(ACol, ARow))
else
begin
// Values
{$IFNDEF CLX}
{$IFNDEF CLR}Windows.{$ENDIF}SetTextAlign(Canvas.Handle,TA_RIGHT);
{$ENDIF}
{$IFDEF CLX}
QPainter_setBackgroundMode(Canvas.Handle,BGMode_TransparentMode);
{$ENDIF}
tmpSt:=GetEditText(ACol, ARow);
{$IFDEF CLX}
Dec(ARect.Right,3);
{$ENDIF}
Canvas.TextRect(ARect,
{$IFDEF CLX}ARect.Left{$ELSE}ARect.Right-2{$ENDIF},
ARect.Top+2, tmpSt
{$IFDEF CLX},Integer(AlignmentFlags_AlignRight){$ENDIF});
{$IFNDEF CLX}
{$IFNDEF CLR}Windows.{$ENDIF}SetTextAlign(Canvas.Handle,TA_LEFT);
{$ENDIF}
end;
end;
end;
end;
procedure TCustomChartGrid.Notification( AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if Operation=opRemove then
begin
if Assigned(FChart) and (AComponent=FChart) then
Chart:=nil
else
if Assigned(INavigator) and (AComponent=INavigator) then
INavigator:=nil
else
if Assigned(FSeries) and (AComponent=FSeries) then
Series:=nil
end;
end;
// Deletes current row, also deletes series points
Procedure TCustomChartGrid.Delete;
Procedure TryDelete(ASeries:TChartSeries; AIndex:Integer);
begin
With ASeries do
if (Row-FirstRowNum)<Count then
begin
Delete(Row-FirstRowNum);
if not IHasNo[AIndex] then NotMandatoryValueList.FillSequence;
end;
end;
var t : Integer;
begin
if goEditing in Options then // 7.0
begin
if Assigned(FSeries) then
TryDelete(FSeries,0)
else
With FChart do
for t:=0 to SeriesCount-1 do
TryDelete(Series[t],t);
if RowCount>(1+FirstRowNum) then RowCount:=RowCount-1
else
begin
Repaint;
NotifyChange;
end;
end;
end;
// Inserts a new row to the end (appends),
// also inserts (appends) new series points
Procedure TCustomChartGrid.Insert;
var tmpInc : Boolean;
Procedure TryInsert(ASeries:TChartSeries);
begin
With ASeries do
begin
tmpInc:=Count>0;
AddNullXY(Count,0);
end;
end;
Var t : Integer;
begin
if goEditing in Options then // 7.0
begin
tmpInc:=False;
if Assigned(FSeries) then
TryInsert(FSeries)
else
With FChart do
for t:=0 to SeriesCount-1 do
TryInsert(Series[t]);
if tmpInc then RowCount:=RowCount+1;
Row:=RowCount-1; // Go to last row
end;
end;
{$IFNDEF CLR}
type
TTeePanelAccess=class(TCustomAxisPanel);
{$ENDIF}
Procedure TCustomChartGrid.AddListener(AChart:TCustomAxisPanel); // 5.03
begin
if Assigned(AChart) then
begin
AChart.FreeNotification(Self);
{$IFNDEF CLR}TTeePanelAccess{$ENDIF}(AChart).Listeners.Add(Self);
end;
end;
Procedure TCustomChartGrid.RemoveListener(AChart:TCustomAxisPanel); // 5.03
begin
if Assigned(AChart) and (not (csDestroying in AChart.ComponentState)) then
begin
{$IFDEF D5}
AChart.RemoveFreeNotification(Self);
{$ENDIF}
{$IFNDEF CLR}TTeePanelAccess{$ENDIF}(AChart).RemoveListener(Self);
end;
end;
Procedure TCustomChartGrid.SetChart(AChart:TCustomChart);
begin
if FChart<>AChart then
begin
RemoveListener(FChart);
FChart:=AChart;
AddListener(FChart);
end;
Regenerate;
Repaint; { 5.01 }
end;
Procedure TCustomChartGrid.SetNavigator(ANavigator:TChartGridNavigator);
begin
INavigator:=ANavigator;
if Assigned(INavigator) then INavigator.FreeNotification(Self);
end;
// Main procedure to calculate how many rows and columns should the grid have
Procedure TCustomChartGrid.RecalcDimensions;
Function MaxNumPoints:Integer;
var t : Integer;
begin
result:=0;
if Assigned(FSeries) then result:=FSeries.Count
else
for t:=0 to FChart.SeriesCount-1 do
With FChart.Series[t] do
if (t=0) or (Count>result) then result:=Count;
end;
var tmpCol : Integer;
Procedure CalcParams(ASeries:TChartSeries; AIndex:Integer);
begin
if not (csDestroying in ASeries.ComponentState) then
begin
Inc(tmpCol);
if FXValues=cgsAuto then
IHasNo[AIndex]:=HasNoMandatoryValues(ASeries)
else
IHasNo[AIndex]:=FXValues=cgsYes;
if IHasNo[AIndex] then Inc(tmpCol);
Inc(tmpCol,ASeries.ValuesList.Count-2);
end;
end;
Procedure SetXYZDimensions;
var Values : Array of TChartValue;
Function Find(Const Value:TChartValue):Boolean;
var t : Integer;
begin
result:=False;
for t:=0 to Length(Values)-1 do
if Values[t]=Value then
begin
result:=True;
exit;
end;
end;
var tmpSeries : TChartSeries;
t : Integer;
tmp : Double;
begin
tmpSeries:=GetXYZSeries;
if Assigned(tmpSeries) then
begin
for t:=0 to tmpSeries.Count-1 do
begin
tmp:=tmpSeries.ValuesList[2].Value[t];
if not Find(tmp) then
begin
SetLength(Values,Length(Values)+1);
Values[Length(Values)-1]:=tmp;
end;
end;
ColCount:=1+Length(Values);
Values:=nil;
//1+Round(tmpSeries.MaxZValue-tmpSeries.MinZValue+1);
for t:=0 to tmpSeries.Count-1 do
begin
tmp:=tmpSeries.NotMandatoryValueList.Value[t];
if not Find(tmp) then
begin
SetLength(Values,Length(Values)+1);
Values[Length(Values)-1]:=tmp;
end;
end;
RowCount:=2+Length(Values);
// with tmpSeries.NotMandatoryValueList do
// RowCount:=2+Round(MaxValue-MinValue+1);
end;
FLabels:=False;
FColors:=False;
FixedRows:=2;
end;
var t : Integer;
begin
if Grid3DMode then SetXYZDimensions
else
begin
tmpCol:=1;
if Assigned(FChart) or Assigned(FSeries) then
begin
if Assigned(FSeries) then CalcParams(FSeries,0)
else
for t:=0 to FChart.SeriesCount-1 do CalcParams(FChart[t],t);
if FLabels then Inc(tmpCol);
if FColors then Inc(tmpCol);
RowCount:=Math.Max(1+FirstRowNum,MaxNumPoints+FirstRowNum);
end
else RowCount:=1+FirstRowNum;
ColCount:=tmpCol;
ColWidths[0]:=30;
if FColors and (ColCount>1) then
ColWidths[1]:=40; { 5.02 }
if ShowFields then FixedRows:=2
else FixedRows:=1;
end;
if (Col=0) and (ColCount>1) then Col:=1; // 5.02
NotifyChange;
end;
procedure TCustomChartGrid.NotifyChange;
begin
if Assigned(FActiveChanged) then FActiveChanged(Self);
end;
Procedure TCustomChartGrid.SetBooleanProperty(Var Variable:Boolean; Value:Boolean);
begin
if Variable<>Value then
begin
Variable:=Value;
RecalcDimensions;
Repaint;
end;
end;
Procedure TCustomChartGrid.SetShowFields(Value:Boolean);
begin
SetBooleanProperty(FShowFields,Value);
if Row<FirstRowNum then Row:=FirstRowNum;
end;
procedure TCustomChartGrid.SetShowLabels(Value: Boolean);
begin
SetBooleanProperty(FLabels,Value);
end;
Procedure TCustomChartGrid.SetShowColors(Value:Boolean);
begin
SetBooleanProperty(FColors,Value);
end;
Procedure TCustomChartGrid.SetShowXValues(Value:TChartGridShow);
begin
FXValues:=Value;
RecalcDimensions;
Repaint;
end;
procedure TCustomChartGrid.TeeEvent(Event: TTeeEvent);
begin
if not (csDestroying in ComponentState) then
if Event is TTeeSeriesEvent then
Case TTeeSeriesEvent(Event).Event of
seChangeTitle,
seChangeColor,
seChangeActive: Repaint
else RecalcDimensions;
end;
end;
Function TCustomChartGrid.GetSeriesColor(var AColor:TColor):TChartSeries;
var tmpList : TChartValueList;
begin
if FColors and (Col=ColorsColumn) and (Row>=FirstRowNum) then
begin
result:=GetSeries(Col+1,tmpList);
if result.Count>(Row-FirstRowNum) then
AColor:=result.ValueColor[Row-FirstRowNum]
else
result:=nil;
end
else
result:=nil;
end;
Procedure TCustomChartGrid.ChangeColor(AColor:TColor);
var tmpColor : TColor;
tmpSeries : TChartSeries;
begin
tmpSeries:=GetSeriesColor(tmpColor);
if Assigned(tmpSeries) then
ChangeColor(tmpSeries,AColor);
end;
Procedure TCustomChartGrid.ChangeColor(ASeries:TChartSeries; AColor:TColor);
begin
ASeries.ValueColor[Row-FirstRowNum]:=AColor;
SetManualData(ASeries);
DrawCell(Col,Row,CellRect(Col,Row),[gdSelected,gdFocused]);
if Assigned(FOnChangeColor) then FOnChangeColor(Self);
end;
Procedure TCustomChartGrid.ChangeColor;
var tmpSeries : TChartSeries;
tmpColor : TColor;
begin
tmpSeries:=GetSeriesColor(tmpColor);
if Assigned(tmpSeries) then
if EditColorDialog(Self,tmpColor) then
ChangeColor(tmpSeries,tmpColor);
end;
// Use double-click mouse event to show the color editor dialog
// to change a series point color
procedure TCustomChartGrid.DblClick;
begin
if FColors and (Col=ColorsColumn) and (goEditing in Options) then
ChangeColor
else
inherited;
end;
function TCustomChartGrid.CanEditShow: Boolean;
begin
result:=inherited CanEditShow;
if result then
begin
if Assigned(FOnEditing) then // 7.0
FOnEditing(Self,Col,Row,result);
if result then
if FColors and (Col=ColorsColumn) then
result:=False
else
FOldValue:=GetEditText(Col,Row);
end;
end;
procedure TCustomChartGrid.Regenerate;
begin
if not (csDestroying in ComponentState) then
begin
RecalcDimensions;
MoveColRow(Math.Min(ColCount-1,1), FirstRowNum, True, True);
end;
end;
procedure TCustomChartGrid.SetSeries(const Value: TChartSeries);
begin
if FSeries<>Value then
begin
if Assigned(FSeries) then
begin
{$IFDEF D5}
FSeries.RemoveFreeNotification(Self);
{$ENDIF}
if Assigned(FSeries.ParentChart) then
RemoveListener(FSeries.ParentChart)
else
RemoveListener(ISeriesChart); // 6.02
end;
FSeries:=Value;
if Assigned(FSeries) then
begin
FSeries.FreeNotification(Self);
Chart:=nil;
ISeriesChart:=FSeries.ParentChart; // 6.02
AddListener(ISeriesChart);
end;
end;
Regenerate;
Repaint;
end;
// Returns column number for series "Labels"
Function TCustomChartGrid.LabelsColumn:Integer;
begin
if FLabels then
begin
if FColors then result:=2
else result:=1;
end
else result:=-1;
end;
// Returns column number for series "Colors"
Function TCustomChartGrid.ColorsColumn:Integer;
begin
if FColors then result:=1 else result:=-1;
end;
end. |
unit fyDBGrid;
{******************************************************************************}
{ }
{ Enhanced Database Grid V0.5 }
{ }
{ By : Amir Mahfoozi }
{ }
{ email : mahfoozi@gmail.com }
{ }
{******************************************************************************}
interface
uses
messages,
inifiles, imgList,
Winapi.Windows, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls,
Data.DB, System.StrUtils,
Vcl.Grids,
Vcl.DBGrids,
System.UITypes,
FireDAC.Comp.Client,
Math, Vcl.Menus, System.Types,
FireDAC.Comp.DataSet, Vcl.AppEvnts, Vcl.StdCtrls, Vcl.Samples.Spin;
const
bmArrow = 'DBGARROW2';
bmEdit = 'DBEDIT2';
bmInsert = 'DBINSERT2';
bmMultiDot = 'DBMULTIDOT2';
bmMultiArrow = 'DBMULTIARROW2';
type
TSortType = (stNone, stAsc, stDesc);
TActiveChangedEvent = procedure(Sender: TObject; dataset: TDataSet) of object;
TFilterEvent = procedure(Sender: TObject; searchCol: TColumn;
searchStr:String; var filterStr: string) of object;
TOnPopupCommandEvent = procedure(Sender: TObject; commandID, rowNo: integer ) of object;
TRowInfo = record
recNo,
top,
bottom: integer;
end;
TfyDBGrid = class(TCustomDBGrid)
protected
myIndicators:TImageList;
procedure DblClick; override;
procedure TitleClick(Column: TColumn); override;
procedure DrawCell(ACol, ARow: integer; ARect: TRect;
AState: TGridDrawState); override;
procedure DrawColumnCell(const Rect: TRect; DataCol: integer;
Column: TColumn; State: TGridDrawState); override;
procedure MouseMove(Shift: TShiftState; X, Y: integer); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: integer); override;
procedure WndProc(var Message: TMessage); override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure Paint; override;
procedure Resize; override;
procedure edtSearchCriteriaWindowProc(var Message: TMessage);
procedure ColWidthsChanged; override;
procedure RowHeightsChanged; override;
procedure Scroll(Distance: integer); override;
procedure CalcSizingState(X: integer; Y: integer; var State: TGridState;
var Index: integer; var SizingPos: integer; var SizingOfs: integer;
var FixedInfo: TGridDrawInfo); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Integer;
Y: Integer); override;
procedure onPopupMenuItemClick(Sender : TObject);
private
tempFont:TFont;
bmpClipped,
bmpDrawText:TBitmap;
pmCommands:TPopupMenu;
originalRowHeight,
lastRowHeight: integer;
lastResizedRow: integer;
myLeftCol: integer; // grid left column
lastMouseX, lastMouseY: integer;
sndEsc, sndSort, sndDblClick, sndHover: TResourceStream;
resized: boolean;
searchVisible, filtering: boolean;
searchFieldName: string;
lastSearchStr: string;
lastSearchColumn: TColumn;
lastEditboxWndProc: TWndMethod;
edtSearchCriteria: TEdit;
ri: array of TRowInfo;
lastRowCount: integer;
dblClicked: boolean;
lastSortColumn: TColumn;
lastSortType: TSortType;
FAltRowColor1Finish: TColor;
FAltRowColor1Start: TColor;
FAltRowColor2Finish: TColor;
FAltRowColor2Start: TColor;
FSelectedColorFinish: TColor;
FSelectedColorStart: TColor;
grBmpTitle: TBitmap;
grBmpActive: TBitmap;
grBmpSelected: TBitmap;
grBmpAlt1: TBitmap;
grBmpAlt2: TBitmap;
FAltRowColor2Steps: integer;
FAltRowColor1Steps: integer;
FSelectedColorSteps: integer;
FAutoFocus: boolean;
FHotTrack: boolean;
FAltRowColor1CenterPosition: integer;
FAltRowColor2CenterPosition: integer;
FAltRowColor1Center: TColor;
FAltRowColor2Center: TColor;
FSelectedColorCenterPosition: integer;
FSelectedColorCenter: TColor;
FTitleColorCenterPosition: integer;
FTitleColorSteps: integer;
FTitleColorFinish: TColor;
FTitleColorStart: TColor;
FTitleColorCenter: TColor;
FAutoWidthMin: integer;
FAutoWidthMax: integer;
FMoveSoundEnabled: boolean;
FSortArrowColor: TColor;
FAutoWidthAllColor: TColor;
FDblClickSoundEnabled: boolean;
FSortSoundEnabled: boolean;
FEscSoundEnabled: boolean;
FAllowFilter: boolean;
FOnBeforeFilter: TFilterEvent;
FAllowRowResize: boolean;
FAllowSort: boolean;
FActiveColorCenterPosition: integer;
FActiveColorSteps: integer;
FActiveColorStart: TColor;
FActiveColorFinish: TColor;
FActiveColorCenter: TColor;
FPopupMenuCommands: TStrings;
FOnPopupCommand: TOnPopupCommandEvent;
FActiveCellFontColor: TColor;
FSelectedCellFontColor: TColor;
procedure PopupMenuCommandsChanged(Sender: TObject);
procedure toggleTransparentColor;
procedure myDrawText(s:string; outputCanvas: Tcanvas; drawRect: TRect;
drawAlignment:TAlignment ; drawFont:TFont);
function rowVisible(rw: integer): boolean;
function rowFullVisible(rw: integer): boolean;
function isMultiSelectedRow: Boolean;
procedure playSoundInMemory(cnd: boolean; m: TResourceStream; name: string);
function getColumnRightEdgePos(cl: TColumn): integer;
procedure extractRGB(cl: TColor; var red, green, blue: byte);
procedure drawVerticalGradient(var grBmp: TBitmap; gHeight: integer;
color1, color2, color3: TColor; centerPosition: integer = 50);
procedure produceTitleGradient;
procedure produceActiveGradient;
procedure produceSelectedGradient;
procedure produceAltRow1Gradient;
procedure produceAltRow2Gradient;
procedure autoFitColumn(ix: integer; canDisableControls:boolean);
procedure drawTriangleInRect(r: TRect; st: TSortType; al: TAlignment);
procedure drawCircleInRect(r: TRect);
procedure SetAltRowColor1Start(const Value: TColor);
procedure SetAltRowColor2Start(const Value: TColor);
procedure SetSelectedColorStart(const Value: TColor);
procedure SetAltRowColor1Finish(const Value: TColor);
procedure SetAltRowColor2Finish(const Value: TColor);
procedure SetSelectedColorFinish(const Value: TColor);
function checkDBPrerequisites: boolean;
procedure SetAltRowColor1Steps(const Value: integer);
procedure SetAltRowColor2Steps(const Value: integer);
procedure SetSelectedColorSteps(const Value: integer);
procedure SetAutoFocus(const Value: boolean);
procedure SetHotTrack(const Value: boolean);
function pointInRect(p: TPoint; r: TRect): boolean;
procedure ClearFilter;
procedure ClearSort;
function isVisibleColumn(cl: TColumn): boolean;
procedure SetAltRowColor1Center(const Value: TColor);
procedure SetAltRowColor1CenterPosition(const Value: integer);
procedure SetAltRowColor2Center(const Value: TColor);
procedure SetAltRowColor2CenterPosition(const Value: integer);
procedure SetSelectedColorCenter(const Value: TColor);
procedure SetSelectedColorCenterPosition(const Value: integer);
procedure SetTitleColorCenter(const Value: TColor);
procedure SetTitleColorCenterPosition(const Value: integer);
procedure SetTitleColorFinish(const Value: TColor);
procedure SetTitleColorStart(const Value: TColor);
procedure SetTitleColorSteps(const Value: integer);
procedure SetAutoWidthMax(const Value: integer);
procedure SetAutoWidthMin(const Value: integer);
procedure SetAutoWidthAllColor(const Value: TColor);
procedure SetMoveSoundEnabled(const Value: boolean);
procedure SetSortArrowColor(const Value: TColor);
procedure incLeftCol;
procedure decLeftCol;
function cellWidth(ACol, ARow: integer): integer;
function cellHeight(ACol, ARow: integer): integer;
procedure SetDblClickSoundEnabled(const Value: boolean);
procedure SetSortSoundEnabled(const Value: boolean);
procedure SetEscSoundEnabled(const Value: boolean);
procedure SetAllowFilter(const Value: boolean);
procedure SetOnBeforeFilter(const Value: TFilterEvent);
procedure SetAllowRowResize(const Value: boolean);
procedure SetAllowSort(const Value: boolean);
procedure SetActiveColorCenter(const Value: TColor);
procedure SetActiveColorCenterPosition(const Value: integer);
procedure SetActiveColorFinish(const Value: TColor);
procedure SetActiveColorStart(const Value: TColor);
procedure SetActiveColorSteps(const Value: integer);
procedure SetPopupMenuCommands(const Value: TStrings);
procedure SetOnPopupCommand(const Value: TOnPopupCommandEvent);
procedure buildPopUpMenu;
procedure SetActiveCellFontColor(const Value: TColor);
procedure SetSelectedCellFontColor(const Value: TColor);
public
constructor create(owner: TComponent); override;
destructor destroy; override;
procedure autoFitAll;
procedure saveConfig(fn: String);
procedure loadConfig(fn: String);
property Canvas;
property SelectedRows;
published
property TitleColorStart: TColor read FTitleColorStart
write SetTitleColorStart default clGray;
property TitleColorCenter: TColor read FTitleColorCenter
write SetTitleColorCenter default clWhite;
property TitleColorCenterPosition: integer read FTitleColorCenterPosition
write SetTitleColorCenterPosition default 50;
property TitleColorFinish: TColor read FTitleColorFinish
write SetTitleColorFinish default clGray;
property TitleColorSteps: integer read FTitleColorSteps
write SetTitleColorSteps default 50;
property ActiveColorStart: TColor read FActiveColorStart write SetActiveColorStart default $00FFD7EB;
property ActiveColorCenter: TColor read FActiveColorCenter write SetActiveColorCenter default $00FF0080;
property ActiveColorCenterPosition: integer read FActiveColorCenterPosition write SetActiveColorCenterPosition default 50;
property ActiveColorFinish: TColor read FActiveColorFinish write SetActiveColorFinish default $00FFD7EB;
property ActiveColorSteps: integer read FActiveColorSteps write SetActiveColorSteps default 50;
property SelectedColorStart: TColor read FSelectedColorStart
write SetSelectedColorStart default $00EDB6B6;
property SelectedColorCenter: TColor read FSelectedColorCenter
write SetSelectedColorCenter default $00F31212;
property SelectedColorCenterPosition: integer
read FSelectedColorCenterPosition write SetSelectedColorCenterPosition
default 50;
property SelectedColorFinish: TColor read FSelectedColorFinish
write SetSelectedColorFinish default $00EDB6B6;
property SelectedColorSteps: integer read FSelectedColorSteps
write SetSelectedColorSteps default 50;
property AltRowColor1Start: TColor read FAltRowColor1Start
write SetAltRowColor1Start default $00DAFEFC;
property AltRowColor1Center: TColor read FAltRowColor1Center
write SetAltRowColor1Center default $000EFAEE;
property AltRowColor1CenterPosition: integer
read FAltRowColor1CenterPosition write SetAltRowColor1CenterPosition
default 50;
property AltRowColor1Finish: TColor read FAltRowColor1Finish
write SetAltRowColor1Finish default $00DAFEFC;
property AltRowColor1Steps: integer read FAltRowColor1Steps
write SetAltRowColor1Steps default 50;
property AltRowColor2Start: TColor read FAltRowColor2Start
write SetAltRowColor2Start default $00ECD9FF;
property AltRowColor2Center: TColor read FAltRowColor2Center
write SetAltRowColor2Center default $00B164FF;
property AltRowColor2CenterPosition: integer
read FAltRowColor2CenterPosition write SetAltRowColor2CenterPosition
default 50;
property AltRowColor2Finish: TColor read FAltRowColor2Finish
write SetAltRowColor2Finish default $00ECD9FF;
property AltRowColor2Steps: integer read FAltRowColor2Steps
write SetAltRowColor2Steps default 50;
property AutoFocus: boolean read FAutoFocus write SetAutoFocus
default false;
property HotTrack: boolean read FHotTrack write SetHotTrack default false;
property AutoWidthMax: integer read FAutoWidthMax write SetAutoWidthMax
default 0;
property AutoWidthMin: integer read FAutoWidthMin write SetAutoWidthMin
default 0;
property EscSoundEnabled: boolean read FEscSoundEnabled
write SetEscSoundEnabled default false;
property SortSoundEnabled: boolean read FSortSoundEnabled
write SetSortSoundEnabled default false;
property DblClickSoundEnabled: boolean read FDblClickSoundEnabled
write SetDblClickSoundEnabled default false;
property MoveSoundEnabled: boolean read FMoveSoundEnabled
write SetMoveSoundEnabled default false;
property SortArrowColor: TColor read FSortArrowColor write SetSortArrowColor
default clRed;
property AutoWidthAllColor: TColor read FAutoWidthAllColor
write SetAutoWidthAllColor default clBlue;
property AllowFilter: boolean read FAllowFilter write SetAllowFilter
default true;
property AllowSort: boolean read FAllowSort write SetAllowSort default true ;
property OnBeforeFilter: TFilterEvent read FOnBeforeFilter
write SetOnBeforeFilter;
property AllowRowResize: boolean read FAllowRowResize
write SetAllowRowResize default false;
property PopupMenuCommands:TStrings read FPopupMenuCommands write SetPopupMenuCommands;
property OnPopupCommand:TOnPopupCommandEvent read FOnPopupCommand write SetOnPopupCommand;
property ActiveCellFontColor:TColor read FActiveCellFontColor write SetActiveCellFontColor default clWhite;
property SelectedCellFontColor:TColor read FSelectedCellFontColor write SetSelectedCellFontColor default clWhite;
property Align;
property Anchors;
property BiDiMode;
property BorderStyle;
property Color;
property Columns stored False;
property Constraints;
property Ctl3D;
property DataSource;
property DefaultDrawing;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property FixedColor;
property Font;
property ImeMode;
property ImeName;
property Options;
property ParentBiDiMode;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ReadOnly;
property ShowHint;
property TabOrder;
property TabStop;
property TitleFont;
property Visible;
property OnCellClick;
property OnColEnter;
property OnColExit;
property OnColumnMoved;
property OnDrawDataCell; { obsolete }
property OnDrawColumnCell;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEditButtonClick;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDock;
property OnStartDrag;
property OnTitleClick;
property DataLink;
end;
procedure Register;
{$R 'TEnhDBGrid.dcr'}
{$R data.res}
implementation
uses DateUtils, TypInfo;
{ TEnhDBGrid }
function TfyDBGrid.checkDBPrerequisites: boolean;
begin
Result := false;
if not Assigned(DataSource) then
Exit;
if not Assigned(DataSource.DataSet) then
Exit;
if not DataSource.DataSet.Active then
Exit;
Result := true;
end;
constructor TfyDBGrid.create(owner: TComponent);
var
bmp:TBitmap;
begin
inherited;
bmpDrawText:=TBitmap.Create;
bmpDrawText.Transparent:=true;
bmpDrawText.TransparentMode:=tmFixed;
bmpDrawText.TransparentColor:=clWhite;
bmpDrawText.Canvas.Brush.Color:=clWhite;
bmpClipped:=TBitmap.Create;
bmpClipped.Transparent:=true;
bmpClipped.TransparentMode:=tmFixed;
bmpClipped.TransparentColor:=clWhite;
bmpClipped.Canvas.Brush.Color:=clWhite;
Bmp := TBitmap.Create;
try
Bmp.LoadFromResourceName(HInstance, bmArrow);
myIndicators := TImageList.CreateSize(Bmp.Width, Bmp.Height);
myIndicators.AddMasked(Bmp, clWhite);
Bmp.LoadFromResourceName(HInstance, bmEdit);
myIndicators.AddMasked(Bmp, clWhite);
Bmp.LoadFromResourceName(HInstance, bmInsert);
myIndicators.AddMasked(Bmp, clWhite);
Bmp.LoadFromResourceName(HInstance, bmMultiDot);
myIndicators.AddMasked(Bmp, clWhite);
Bmp.LoadFromResourceName(HInstance, bmMultiArrow);
myIndicators.AddMasked(Bmp, clWhite);
finally
Bmp.Free;
end;
try
sndHover := TResourceStream.create(HInstance, 'hover', RT_RCDATA);
sndDblClick := TResourceStream.create(HInstance, 'dblclick', RT_RCDATA);
sndSort := TResourceStream.create(HInstance, 'click', RT_RCDATA);
sndEsc := TResourceStream.create(HInstance, 'esc', RT_RCDATA);
except
OutputDebugString('Error in loading sounds from resources');
end;
originalRowHeight:=0;
FOnBeforeFilter:=nil;
FMoveSoundEnabled := false;
FDblClickSoundEnabled := false;
FSortSoundEnabled := false;
FAllowFilter := true;
FAllowSort := true;
FAllowRowResize := false;
myLeftCol := leftCol;
grBmpSelected := nil;
grBmpAlt1 := nil;
grBmpAlt2 := nil;
resized := false;
FAutoFocus := false;
FHotTrack := false;
lastSortColumn := nil;
lastSortType := stNone;
dblClicked := false;
FAutoWidthMax := 0;
FAutoWidthMin := 0;
lastRowCount := 0;
edtSearchCriteria := TEdit.create(Self);
edtSearchCriteria.Width := 0;
edtSearchCriteria.Height := 0;
edtSearchCriteria.Parent := Self;
edtSearchCriteria.Visible := false;
searchVisible := false;
lastEditboxWndProc := edtSearchCriteria.WindowProc;
edtSearchCriteria.WindowProc := edtSearchCriteriaWindowProc;
filtering := false;
FTitleColorStart := clGreen;
FTitleColorCenter := clGreen;
FTitleColorCenterPosition := 50;
FTitleColorFinish := $00BBFFBB;
FTitleColorSteps := 50;
FActiveColorStart := $00FFD7EB;
FActiveColorCenter := $00FF0080;
FActiveColorCenterPosition := 50;
FActiveColorFinish := $00FFD7EB;
FActiveColorSteps := 50;
FSelectedColorStart := $00EDB6B6;
FSelectedColorCenter := $00F31212;
FSelectedColorCenterPosition := 50;
FSelectedColorFinish := $00EDB6B6;
FSelectedColorSteps := 50;
FAltRowColor1Start := $00DAFEFC;
FAltRowColor1Center := $000EFAEE;
FAltRowColor1CenterPosition := 50;
FAltRowColor1Finish := $00DAFEFC;
FAltRowColor1Steps := 50;
FAltRowColor2Start := $00ECD9FF;
FAltRowColor2Center := $00B164FF;
FAltRowColor2CenterPosition := 50;
FAltRowColor2Finish := $00ECD9FF;
FAltRowColor2Steps := 50;
FMoveSoundEnabled := false;
FSortArrowColor := clRed;
FAutoWidthAllColor := clBlue;
produceTitleGradient;
produceActiveGradient;
produceSelectedGradient;
produceAltRow1Gradient;
produceAltRow2Gradient;
tempFont:=TFont.Create;
FActiveCellFontColor:=Font.Color;
FSelectedCellFontColor:=Font.Color;
FPopupMenuCommands:=TStringList.Create;
TStringList(FPopupMenuCommands).OnChange:=PopupMenuCommandsChanged;
buildPopUpMenu;
end;
procedure TfyDBGrid.DblClick;
var
plc, // previous left column
i: integer;
p: TPoint;
r: TRect;
begin
inherited;
if not checkDBPrerequisites then
Exit;
playSoundInMemory(FDblClickSoundEnabled, sndDblClick, 'DblClick');
plc := leftCol;
p := CalcCursorPos;
// if cell is the corner one then autofit all columns
if pointInRect(p, CellRect(0, 0)) then
begin
autoFitAll;
Exit;
end;
// find the column that should be auto widthed
for i := 0 to Columns.Count - 1 do
begin
r := CellRect(i + 1, 0);
// if you want just title DblClicks uncomment this line
// if (p.Y>=r.Top) and (p.Y<=r.Bottom) then
begin
if (UseRightToLeftAlignment and (abs(p.X - r.Left) < 5)) or
((not UseRightToLeftAlignment) and (abs(p.X - r.Right) < 5)) then
begin
autoFitColumn(i, true);
leftCol := plc;
// don't allow an extra click event
dblClicked := true;
break;
end
end;
end;
end;
function TfyDBGrid.isMultiSelectedRow: Boolean;
var
Index: Integer;
begin
Result := (dgMultiSelect in Options) and
SelectedRows.Find(Datalink.Datasource.Dataset.Bookmark, Index);
end;
procedure TfyDBGrid.DrawCell(ACol, ARow: integer; ARect: TRect;
AState: TGridDrawState);
var
ar: TRect;
MultiSelected: Boolean;
myLeft, indicIndex, prevousActive: integer;
begin
try
if not checkDBPrerequisites then
Exit;
if ARow > 0 then //draw contents
begin
if ACol = 0 then // draw indicators
begin
dec(ARow);
Canvas.StretchDraw(ARect, grBmpTitle);
// shape borders like a button
DrawEdge(Canvas.Handle, ARect, BDR_RAISEDOUTER, BF_RECT);
if (gdFixed in AState) then
begin
if Assigned(DataLink) and DataLink.Active then
begin
MultiSelected := False;
if ARow >= 0 then
begin
prevousActive := DataLink.ActiveRecord;
try
Datalink.ActiveRecord := ARow;
MultiSelected := isMultiSelectedRow;
finally
Datalink.ActiveRecord := prevousActive;
end;
end;
if (ARow = DataLink.ActiveRecord) or MultiSelected then
begin
indicIndex := 0;
if DataLink.DataSet <> nil then
case DataLink.DataSet.State of
dsEdit: indicIndex := 1;
dsInsert: indicIndex := 2;
dsBrowse:
if MultiSelected then
if (ARow <> Datalink.ActiveRecord) then
indicIndex := 3
else
indicIndex := 4; // multiselected and current row
end;
myIndicators.BkColor := FixedColor;
myLeft := ARect.Right - myIndicators.Width - 1;
if Canvas.CanvasOrientation = coRightToLeft then Inc(myLeft);
myIndicators.Draw(Canvas, myLeft,
(ARect.Top + ARect.Bottom - myIndicators.Height) shr 1, indicIndex, dsTransparent, itImage,True);
end;
end;
end;
inc(ARow);
end
else // draw grid content
inherited;
end
else // draw titles
begin
Canvas.StretchDraw(ARect, grBmpTitle);
ar:=ARect;
// shape borders like a button
DrawEdge(Canvas.Handle, AR, BDR_RAISEDOUTER, BF_RECT);
// write title
if ACol > 0 then
myDrawText(Columns[ACol - 1].Title.Caption, Canvas, AR, Columns[ACol - 1].Title.Alignment , Columns[ACol - 1].Title.Font)
end;
// make search editbox visible if it is necessary
if lastSearchColumn <> nil then
if (ACol > 0) and (ARow = 0) then
begin
if searchVisible then
begin
edtSearchCriteria.Visible :=isVisibleColumn(lastSearchColumn);
// reposition edit box
if (Columns[ACol - 1].FieldName = searchFieldName) then
begin
// adjust search edit box position
ar := CellRect(ACol, 0);
if edtSearchCriteria.Visible then
begin
if UseRightToLeftAlignment then
edtSearchCriteria.Left := ClientWidth - ARect.Right
else
edtSearchCriteria.Left := ARect.Left;
edtSearchCriteria.Width := ARect.Right - ARect.Left;
end;
end;
end
end;
if (ARow = 0) and (ACol = 0) then
drawCircleInRect(ARect);
// draw an arrow in sorted columns
if (lastSortColumn <> nil) then
begin
if (lastSortColumn.Index + 1 = ACol) and (ARow = 0) then
drawTriangleInRect(ARect, lastSortType,
Columns[ACol - 1].Title.Alignment);
end;
except
OutputDebugString(pchar(format('Error in DrawCell c = %d r = %d' , [ACol,ARow])));
end;
end;
procedure TfyDBGrid.DrawColumnCell(const Rect: TRect; DataCol: integer;
Column: TColumn; State: TGridDrawState);
var
row, i: integer;
r:trect;
begin
try
inherited;
if not checkDBPrerequisites then
Exit;
row := DataSource.DataSet.recNo;
// if number of rows have been changed then reallocate memory for their info
if RowCount <> lastRowCount then
begin
SetLength(ri, RowCount);
lastRowCount := RowCount;
// reset all records
for i := 0 to RowCount - 1 do
begin
ri[i].recNo := -1;
ri[i].top := 0;
ri[i].bottom := 0;
end;
end;
// find first empty rowInfo element or same row position
// and store this row info
for i := 0 to RowCount - 1 do
if (ri[i].recNo = -1) or
((ri[i].top = Rect.top) and (ri[i].bottom = Rect.bottom)) then
begin
ri[i].recNo := row;
ri[i].top := Rect.top;
ri[i].bottom := Rect.bottom;
break;
end;
//save previous column font
tempFont.Assign(Column.Font);
if (gdSelected in State) then
begin
// draw gradient background
Canvas.StretchDraw(Rect, grBmpActive);
tempFont.Color:=FActiveCellFontColor;
end
else if isMultiSelectedRow then
begin
Canvas.StretchDraw(Rect, grBmpSelected);
tempFont.Color:=FSelectedCellFontColor;
end
else if Odd(row) then
begin
Canvas.StretchDraw(Rect, grBmpAlt1);
end
else
begin
Canvas.StretchDraw(Rect, grBmpAlt2);
end;
if Column.Field<>nil then
myDrawText(Column.Field.DisplayText, Canvas, Rect, Column.alignment, tempFont);
//draw border
r:=rect;
Canvas.Brush.Style := bsClear;
Canvas.Pen.Color:=clGray;
InflateRect(r, 1,1);
Canvas.Rectangle(r);
except
OutputDebugString(PChar(format('Error in DCC : %d %d',
[Rect.top, Rect.Left])));
end;
end;
procedure TfyDBGrid.drawTriangleInRect(r: TRect; st: TSortType; al: TAlignment);
const
OFFSET=2;
var
goLeft: integer;
begin
//if IsRightToLeft then
begin
if al = taLeftJustify then
goLeft := 0
else
goLeft := r.Right - r.Left - 17;
end;
// draw shadow
Canvas.Brush.Color := clGray;
Canvas.Pen.Color := clGray;
if st = stAsc then
Canvas.Polygon([point(r.Right - 2 - OFFSET - goLeft, r.top + 10 + OFFSET),
point(r.Right - 7 - OFFSET - goLeft, r.top + 5 + OFFSET),
point(r.Right - 12 - OFFSET - goLeft, r.top + 10 + OFFSET)])
else if st = stDesc then
Canvas.Polygon([point(r.Right - 2 - OFFSET - goLeft, r.top + 5 + OFFSET),
point(r.Right - 7 - OFFSET - goLeft, r.top + 10 + OFFSET),
point(r.Right - 12 - OFFSET - goLeft, r.top + 5 + OFFSET)]);
// draw triangle
Canvas.Brush.Color := FSortArrowColor;
Canvas.Pen.Color := FSortArrowColor;
if st = stAsc then
Canvas.Polygon([point(r.Right - 2 - goLeft, r.top + 10),
point(r.Right - 7 - goLeft, r.top + 5), point(r.Right - 12 - goLeft,
r.top + 10)])
else if st = stDesc then
Canvas.Polygon([point(r.Right - 2 - goLeft, r.top + 5),
point(r.Right - 7 - goLeft, r.top + 10), point(r.Right - 12 - goLeft,
r.top + 5)]);
end;
procedure TfyDBGrid.KeyDown(var Key: Word; Shift: TShiftState);
var
p1: pointer;
p: TArray<System.Byte>;
begin
inherited;
if not checkDBPrerequisites then
Exit;
// clear filters and search criteria if users presses escape
if Key = VK_ESCAPE then
begin
playSoundInMemory(FEscSoundEnabled, sndEsc, 'Escape');
p := DataSource.DataSet.GetBookmark;
ClearFilter;
ClearSort;
if DataSource.DataSet.BookmarkValid(p) then
begin
DataSource.DataSet.GotoBookmark(p);
DataSource.DataSet.FreeBookmark(p);
end;
invalidate;
end;
end;
procedure TfyDBGrid.MouseMove(Shift: TShiftState; X, Y: integer);
var
i: integer;
gc: TGridCoord;
gr: TGridRect;
begin
inherited;
if not checkDBPrerequisites then
Exit;
// if need auto focus then take focus to this control
// if (not searchVisible) and FAutoFocus and (not Focused) then
// SetFocus(Handle);
if FHotTrack then
if DataSource.DataSet.State = dsBrowse then //do not bother user actions
begin
// prevent repetitive mouse move events
if (lastMouseX = X) and (lastMouseY = Y) then
Exit
else
begin
lastMouseX := X;
lastMouseY := Y;
end;
// move to the suitable row
// ri was filled in CellDraw
for i := 0 to high(ri) do
if (Y >= ri[i].top) and (Y <= ri[i].bottom) then
begin
if ri[i].recNo < 1 then
continue;
// movebackward or forward to reach to the pointer
// you could set RecNo exactly to the desired no to
// see the disastrous results
if ri[i].recNo > DataSource.DataSet.recNo then
begin
while ri[i].recNo > DataSource.DataSet.recNo do
DataSource.DataSet.Next;
break;
end
else if ri[i].recNo < DataSource.DataSet.recNo then
begin
while ri[i].recNo < DataSource.DataSet.recNo do
DataSource.DataSet.Prior;
break;
end
end;
// if row select is not enabled
if not(dgRowSelect in Options) then
begin
// move to cell under mouse pointer
gc := MouseCoord(X, Y);
if (gc.X > 0) and (gc.Y > 0) then
begin
gr.Left := gc.X;
gr.Right := gc.X;
gr.top := gc.Y;
gr.bottom := gc.Y;
Selection := gr;
end;
end;
// update indicator column
InvalidateCol(0);
end;
end;
// gets a column index and finds the minimum with ofits content
procedure TfyDBGrid.autoFitColumn(ix: integer; canDisableControls:boolean);
var
mw, cw: integer;
p1: pointer;
p: TArray<System.Byte>;
begin
if not checkDBPrerequisites then
Exit;
mw := 0;
with DataSource.DataSet do
begin
if canDisableControls then
begin
p := GetBookmark;
DisableControls;
end;
First;
while not Eof do
begin
cw := Canvas.TextWidth(FieldByName(Columns[ix].FieldName).AsString);
if cw > mw then
mw := cw;
Next;
end;
if canDisableControls then
begin
EnableControls;
if BookmarkValid(p) then
begin
GotoBookmark(p);
FreeBookmark(p);
end;
end;
end;
mw := mw + 5; // put a margin aside
if (FAutoWidthMin <> 0) then
mw := Max(FAutoWidthMin, mw);
if (FAutoWidthMax <> 0) then
mw := Min(FAutoWidthMax, mw);
Columns[ix].Width := mw;
end;
procedure TfyDBGrid.SetAltRowColor1Start(const Value: TColor);
begin
FAltRowColor1Start := Value;
produceAltRow1Gradient;
invalidate;
end;
procedure TfyDBGrid.SetAltRowColor2Start(const Value: TColor);
begin
FAltRowColor2Start := Value;
produceAltRow2Gradient;
invalidate;
end;
procedure TfyDBGrid.SetSelectedColorStart(const Value: TColor);
begin
FSelectedColorStart := Value;
produceSelectedGradient;
invalidate;
end;
procedure TfyDBGrid.SetAltRowColor1Finish(const Value: TColor);
begin
FAltRowColor1Finish := Value;
produceAltRow1Gradient;
invalidate;
end;
procedure TfyDBGrid.SetAltRowColor2Finish(const Value: TColor);
begin
FAltRowColor2Finish := Value;
produceAltRow2Gradient;
invalidate;
end;
procedure TfyDBGrid.SetSelectedColorFinish(const Value: TColor);
begin
FSelectedColorFinish := Value;
produceSelectedGradient;
invalidate;
end;
procedure TfyDBGrid.TitleClick(Column: TColumn);
var
p1: pointer;
p: TArray<System.Byte>;
plc: integer; // previous left column
begin
inherited;
if dblClicked then
begin
// ignore DblClicks
dblClicked := false;
Exit;
end;
if not FAllowSort then
Exit;
if not checkDBPrerequisites then
Exit;
if not(DataSource.DataSet is TFDQuery) then
Exit;
playSoundInMemory(FSortSoundEnabled, sndSort, 'Sort');
plc := leftCol;
p := DataSource.DataSet.GetBookmark;
try
if lastSortColumn <> Column then
begin
// new column to sort
lastSortColumn := Column;
lastSortType := stAsc;
TFDQuery(DataSource.DataSet).IndexFieldNames := Column.FieldName + ':A';
end
else
begin
// reverse sort order
if lastSortType = stAsc then
begin
lastSortType := stDesc;
TFDQuery(DataSource.DataSet).IndexFieldNames := Column.FieldName + ':D';
end
else
begin
lastSortType := stAsc;
TFDQuery(DataSource.DataSet).IndexFieldNames := Column.FieldName + ':A';
end;
end;
except
showmessage('Error in sorting !');
end;
if DataSource.DataSet.BookmarkValid(p) then
begin
DataSource.DataSet.GotoBookmark(p);
DataSource.DataSet.FreeBookmark(p);
end;
leftCol := plc;
end;
procedure Register;
begin
RegisterComponents('fyControls', [TfyDBGrid]);
end;
procedure TfyDBGrid.WndProc(var Message: TMessage);
var
di: TGridDrawInfo;
ctrlPressed: boolean;
begin
// disable unwanted scrolls
if (Message.Msg <> WM_MOUSEWHEEL) then
inherited;
// leftCol is not stable for our job so we had to have an internal myLeftCol
if Message.Msg = WM_HSCROLL then
begin
CalcDrawInfo(di);
myLeftCol := di.Horz.FirstGridCell;
end;
// the control should have focus to receive this message
if Message.Msg = WM_MOUSEWHEEL then
begin
ctrlPressed := ((Message.WParam and $FFFF) and (MK_CONTROL)) > 0;
if Message.WParam < 0 then
begin
if not checkDBPrerequisites then
Exit;
if ctrlPressed then
begin
// horizontal scroll
incLeftCol;
end
else
begin
// vertical scroll
if not DataSource.DataSet.Eof then
begin
DataSource.DataSet.Next;
InvalidateCol(0);
end;
end;
end
else
begin
if not checkDBPrerequisites then
Exit;
if ctrlPressed then
// horizontal scroll
decLeftCol
else
begin
// vertical scroll
if not DataSource.DataSet.Bof then
begin
DataSource.DataSet.Prior;
InvalidateCol(0);
end;
end;
end;
end;
end;
procedure TfyDBGrid.extractRGB(cl: TColor; var red, green, blue: byte);
begin
red := getRValue(cl);
green := getGValue(cl);
blue := getBValue(cl);
end;
procedure TfyDBGrid.SetAltRowColor1Steps(const Value: integer);
begin
if (Value < 1) or (Value > 50) then
begin
ShowMessage('Value should be between 1 and 50');
Exit;
end;
FAltRowColor1Steps := Value;
produceAltRow1Gradient;
invalidate;
end;
procedure TfyDBGrid.SetAltRowColor2Steps(const Value: integer);
begin
if (Value < 1) or (Value > 50) then
begin
ShowMessage('Value should be between 1 and 50');
Exit;
end;
FAltRowColor2Steps := Value;
produceAltRow2Gradient;
invalidate;
end;
procedure TfyDBGrid.SetSelectedColorSteps(const Value: integer);
begin
if (Value < 1) or (Value > 50) then
begin
ShowMessage('Value should be between 1 and 50');
Exit;
end;
FSelectedColorSteps := Value;
produceSelectedGradient;
invalidate;
end;
procedure TfyDBGrid.SetAutoFocus(const Value: boolean);
begin
FAutoFocus := Value;
end;
procedure TfyDBGrid.SetHotTrack(const Value: boolean);
begin
FHotTrack := Value;
if FHotTrack then
Cursor := crHandPoint
else
Cursor := crDefault;
end;
procedure TfyDBGrid.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: integer);
var
i: integer;
r: TRect;
mp: TPoint;
begin
inherited;
if not checkDBPrerequisites then
Exit;
//remember last rows height and restore it to
//previous state after column resizing
if RowCount>0 then
lastRowHeight:=RowHeights[0];
//remember an original row height and
//restore it in case of rows were oversized by user.
//in autoWidthAll it will be restored
if originalRowHeight=0 then
originalRowHeight:=DefaultRowHeight;
// if user clicked out of editbox then make it invisible
if edtSearchCriteria.Visible then
begin
mp:= CalcCursorPos;
if not pointInRect(mp, edtSearchCriteria.ClientRect) then
begin
edtSearchCriteria.Visible := false;
searchVisible := false;
edtSearchCriteria.invalidate;
end;
end;
//right click on content
if cellHeight(0,0)<y then
begin
if (Button = mbRight) and Assigned(pmCommands) then
pmCommands.Popup(ClientToScreen(point(x,y) ).X,ClientToScreen(point(x,y) ).Y);
end
else if (Button = mbRight) and FAllowFilter then //right click on title
begin
for i := 0 to Columns.Count - 1 do
begin
r := CellRect(i + 1, 0);
mp := CalcCursorPos;
// if mouse in column title
if pointInRect(mp, r) then
begin
if (Columns[i].Field.DataType = ftString) or
(Columns[i].Field.DataType = ftWideString) then
begin
if not(filtering and (lastSearchColumn = Columns[i])) then
ClearFilter;
lastSearchColumn := Columns[i];
edtSearchCriteria.Visible := true;
searchVisible := true;
if searchFieldName <> Columns[i].FieldName then
searchFieldName := Columns[i].FieldName
else
edtSearchCriteria.Text := lastSearchStr;
edtSearchCriteria.Font := Columns[i].Title.Font;
edtSearchCriteria.Color := clWindow;
edtSearchCriteria.Font.Color := clWindowText;
// alignEditToRect(edtSearchCriteria, r);
edtSearchCriteria.Left := r.Left;
edtSearchCriteria.top := r.top;
edtSearchCriteria.Width := r.Right - r.Left;
edtSearchCriteria.Height := r.bottom - r.top;
filtering := true;
LeftCol:=myLeftCol;
//SetFocus(edtSearchCriteria.Handle);
break;
end;
end;
end;
end;
end;
procedure TfyDBGrid.edtSearchCriteriaWindowProc(var Message: TMessage);
var
plc, psp: integer;
Msg: tagMSG;
critStr: string;
begin
// windowproc for search criteria edit box
// edtbox doesn't know what to do whith WM_MOUSEWHEEL so we have diverted it
if Message.Msg = WM_MOUSEWHEEL then
PostMessage(Handle, Message.Msg, Message.WParam, Message.LParam)
else
lastEditboxWndProc(Message);
if not(( Message.Msg = WM_KEYDOWN ) or ( Message.Msg = WM_CHAR )) then
exit;
if Message.Msg = WM_KEYDOWN then
begin
if Message.WParam = VK_ESCAPE then
begin
playSoundInMemory(FEscSoundEnabled, sndEsc, 'Escape');
// first escape disappears the search box
// second escape disables searchs and sortings
if searchVisible then
begin
// there are some remaining messages that cause windows to play an
// exclamation sound because editbox is not visible after this.
// by removing remaining messages we prevent that unwanted sounds
while (GetQueueStatus(QS_ALLINPUT)) > 0 do
PeekMessage(Msg, 0, 0, 0, PM_REMOVE);
edtSearchCriteria.Visible := false;
searchVisible := false;
edtSearchCriteria.invalidate;
end
else
ClearFilter;
end
else if (Message.WParam = VK_DOWN) then
begin
// if user presses down arrow it means that he/she needs to go forward
// in records
DataSource.DataSet.Next;
//SetFocus(Handle);
end
else if (Message.WParam = VK_UP) then
begin
DataSource.DataSet.Prior;
//SetFocus(Handle);
end;
end;
// there was a change in search criteria
if lastSearchStr<>edtSearchCriteria.Text then
begin
if filtering then
begin
plc := leftCol;
lastSearchStr := edtSearchCriteria.Text;
psp:=edtSearchCriteria.SelStart;
if lastSearchStr <> '' then
begin
DataSource.DataSet.Filtered := false;
critStr := '[' + searchFieldName + '] LIKE ''%' + lastSearchStr + '%''';
//critStr := '[' + searchFieldName + '] = ''' + lastSearchStr + '*''';
if Assigned(FOnBeforeFilter) then
FOnBeforeFilter(Self, lastSearchColumn, lastSearchStr, critStr);
DataSource.DataSet.Filter := critStr;
try
DataSource.DataSet.Filtered := true;
except
ShowMessage('Couldn''t filter data.');
end;
end
else
begin
DataSource.DataSet.Filtered := false;
end;
leftCol := plc;
if not edtSearchCriteria.Focused then
begin
//SetFocus(edtSearchCriteria.Handle);
edtSearchCriteria.SelStart:=psp;
end;
end;
end;
end;
function TfyDBGrid.pointInRect(p: TPoint; r: TRect): boolean;
begin
Result := (p.X >= r.Left) and (p.X <= r.Right) and (p.Y >= r.top) and
(p.Y <= r.bottom);
end;
procedure TfyDBGrid.ClearFilter;
var
lrh, llc: integer;
begin
try
if not checkDBPrerequisites then
Exit;
if DataSource.DataSet.Filtered then
begin
llc := leftCol;
lrh := DefaultRowHeight;
DataSource.DataSet.Filtered := false;
DataSource.DataSet.Filter := '';
lastSearchStr := '';
searchFieldName := '';
lastSearchColumn := nil;
edtSearchCriteria.Text := '';
edtSearchCriteria.Visible := false;
searchVisible := false;
leftCol := llc;
filtering := false;
DefaultRowHeight := lrh;
invalidate;
end;
except
ShowMessage('Error in clearing filter !')
end;
end;
procedure TfyDBGrid.Paint;
var
B: TBitmap;
begin
if checkDBPrerequisites then
begin
inherited
end
else
begin
// draw a gradient and write NO DATA whenthere is no data connection
B := nil;
drawVerticalGradient(B, Height, clRed, clWhite, clBlue);
Canvas.StretchDraw(ClientRect, B);
B.Free;
Canvas.Brush.Style := bsClear;
Canvas.Font.Name := 'Tahoma';
Canvas.Font.Size := 20;
Canvas.TextRect(ClientRect, 10, 10, 'No Data !');
// detect resizes
if resized then
begin
invalidate;
resized := false;
end;
end;
end;
procedure TfyDBGrid.autoFitAll;
var
i: integer;
begin
if not checkDBPrerequisites then
Exit;
//just one disablecontrols makes autofitcolumn faster but
//it makes a longtime to respond to user in huge datasets
//no application.processmessages to prevent application confusion
DataSource.DataSet.DisableControls;
for i := 0 to Columns.Count - 1 do
autoFitColumn(Columns[i].Index, false);
DataSource.DataSet.EnableControls;
DefaultRowHeight:=originalRowHeight;
end;
function TfyDBGrid.isVisibleColumn(cl: TColumn): boolean;
var
tw, i: integer;
di: TGridDrawInfo;
begin
Result := (cellWidth(cl.Index + 1, 0) > 0);
Exit;
if myLeftCol > (cl.Index + 1) then
begin
Result := false;
Exit;
end
else if myLeftCol = (cl.Index + 1) then
begin
Result := true;
Exit;
end;
CalcDrawInfo(di);
tw := 0;
for i := 0 to di.Horz.FixedCellCount - 1 do
tw := cellWidth(i, 0) + di.Vert.EffectiveLineWidth;
// iterate through data columns up to one before this column
for i := myLeftCol - 1 to cl.Index - 1 do
tw := tw + Columns[i].Width + di.Vert.EffectiveLineWidth;
Result := (tw > 0) and (tw <= ClientWidth);
end;
procedure TfyDBGrid.SetAltRowColor1Center(const Value: TColor);
begin
FAltRowColor1Center := Value;
produceAltRow1Gradient;
invalidate;
end;
procedure TfyDBGrid.SetAltRowColor1CenterPosition(const Value: integer);
begin
if (Value < 0) or (Value > 100) then
begin
ShowMessage('Value should be between 0 and 100');
Exit;
end;
FAltRowColor1CenterPosition := Value;
produceAltRow1Gradient;
invalidate;
end;
procedure TfyDBGrid.SetAltRowColor2Center(const Value: TColor);
begin
FAltRowColor2Center := Value;
produceAltRow2Gradient;
invalidate;
end;
procedure TfyDBGrid.SetAltRowColor2CenterPosition(const Value: integer);
begin
if (Value < 0) or (Value > 100) then
begin
ShowMessage('Value should be between 0 and 100');
Exit;
end;
FAltRowColor2CenterPosition := Value;
produceAltRow2Gradient;
invalidate;
end;
procedure TfyDBGrid.SetSelectedColorCenter(const Value: TColor);
begin
FSelectedColorCenter := Value;
produceSelectedGradient;
invalidate;
end;
procedure TfyDBGrid.SetSelectedColorCenterPosition(const Value: integer);
begin
if (Value < 0) or (Value > 100) then
begin
ShowMessage('Value should be between 0 and 100');
Exit;
end;
FSelectedColorCenterPosition := Value;
produceSelectedGradient;
invalidate;
end;
procedure TfyDBGrid.produceSelectedGradient;
begin
drawVerticalGradient(grBmpSelected, FSelectedColorSteps, FSelectedColorStart,
FSelectedColorCenter, FSelectedColorFinish, FSelectedColorCenterPosition);
end;
procedure TfyDBGrid.produceAltRow1Gradient;
begin
drawVerticalGradient(grBmpAlt1, FAltRowColor1Steps, FAltRowColor1Start,
FAltRowColor1Center, FAltRowColor1Finish, FAltRowColor1CenterPosition);
end;
procedure TfyDBGrid.produceAltRow2Gradient;
begin
drawVerticalGradient(grBmpAlt2, FAltRowColor2Steps, FAltRowColor2Start,
FAltRowColor2Center, FAltRowColor2Finish, FAltRowColor2CenterPosition);
end;
procedure TfyDBGrid.drawVerticalGradient(var grBmp: TBitmap; gHeight: integer;
color1, color2, color3: TColor; centerPosition: integer);
var
graphics: TGraphic;
//linGrBrush: TGPLinearGradientBrush;
r1, g1, b1, r2, g2, b2, r3, g3, b3: byte;
colors: array [0 .. 2] of TColor;
blendPoints: array [0 .. 2] of single;
begin
{ try
if Assigned(grBmp) then
grBmp.Free;
grBmp := TBitmap.create;
grBmp.Width := 1;
grBmp.Height := gHeight;
extractRGB(color1, r1, g1, b1);
extractRGB(color2, r2, g2, b2);
extractRGB(color3, r3, g3, b3);
//graphics := TGraphic.Create(grBmp.Canvas.Handle);
//linGrBrush := TGPLinearGradientBrush.create(MakePoint(0, 0),
// MakePoint(0, gHeight), MakeColor(255, 255, 255, 255),
// MakeColor(255, 255, 255, 255));
colors[0] := RGB(r1, g1, b1);
blendPoints[0] := 0;
colors[1] := RGB(r2, g2, b2);
blendPoints[1] := centerPosition / 100;
colors[2] := RGB(r3, g3, b3);
blendPoints[2] := 1;
//linGrBrush.SetInterpolationColors(@colors, @blendPoints, 3);
//graphics.FillRectangle(linGrBrush, 0, 0, 1, gHeight);
//linGrBrush.Free;
graphics.Free;
except
OutputDebugString('Error in creating gradient.');
end;}
end;
procedure TfyDBGrid.drawCircleInRect(r: TRect);
begin
Canvas.Lock;
Canvas.Brush.Color := clGray;
Canvas.Pen.Color := clGray;
Canvas.Ellipse(1, 4, 7, 10);
Canvas.Brush.Color := FAutoWidthAllColor;
Canvas.Pen.Color := FAutoWidthAllColor;
Canvas.Ellipse(3, 3, 9, 9);
Canvas.Unlock;
end;
procedure TfyDBGrid.SetTitleColorCenter(const Value: TColor);
begin
FTitleColorCenter := Value;
produceTitleGradient;
InvalidateTitles;
end;
procedure TfyDBGrid.SetTitleColorCenterPosition(const Value: integer);
begin
if (Value < 0) or (Value > 100) then
begin
ShowMessage('Value should be between 1 and 50');
Exit;
end;
FTitleColorCenterPosition := Value;
produceTitleGradient;
InvalidateTitles;
end;
procedure TfyDBGrid.SetTitleColorFinish(const Value: TColor);
begin
FTitleColorFinish := Value;
produceTitleGradient;
InvalidateTitles;
end;
procedure TfyDBGrid.SetTitleColorStart(const Value: TColor);
begin
FTitleColorStart := Value;
produceTitleGradient;
InvalidateTitles;
end;
procedure TfyDBGrid.SetTitleColorSteps(const Value: integer);
begin
if (Value < 1) or (Value > 50) then
begin
ShowMessage('Value should be between 1 and 50');
Exit;
end;
FTitleColorSteps := Value;
produceTitleGradient;
InvalidateTitles;
end;
procedure TfyDBGrid.produceTitleGradient;
begin
drawVerticalGradient(grBmpTitle, FTitleColorSteps, FTitleColorStart,
FTitleColorCenter, FTitleColorFinish, FTitleColorCenterPosition);
end;
procedure TfyDBGrid.SetAutoWidthMax(const Value: integer);
begin
if (Value < 0) then
begin
ShowMessage('Value should be greater equal to zero.');
Exit;
end;
if (Value <> 0) and (Value < FAutoWidthMin) then
begin
ShowMessage('Value should be greater than auto with min value.');
Exit;
end;
FAutoWidthMax := Value;
end;
procedure TfyDBGrid.SetAutoWidthMin(const Value: integer);
begin
if (Value < 0) then
begin
ShowMessage('Value should be greater equal to zero.');
Exit;
end;
if (Value <> 0) and (FAutoWidthMax <> 0) and (Value > FAutoWidthMax) then
begin
ShowMessage('Value should be less than auto with max value.');
Exit;
end;
FAutoWidthMin := Value;
end;
procedure TfyDBGrid.Resize;
begin
inherited;
// notify PAINT method of a resize event
resized := true;
end;
procedure TfyDBGrid.ClearSort;
begin
lastSortColumn := nil;
lastSortType := stNone;
if DataSource.DataSet is TFDQuery then
TFDQuery(DataSource.DataSet).IndexFieldNames := '';
end;
procedure TfyDBGrid.ColWidthsChanged;
begin
myLeftCol := leftCol;
inherited;
// update internal myLeftCol value
leftCol:=myLeftCol;
//restore resized row heights
if lastRowHeight>0 then
DefaultRowHeight:=lastRowHeight;
end;
procedure TfyDBGrid.Scroll(Distance: integer);
begin
inherited;
playSoundInMemory(FMoveSoundEnabled, sndHover, 'hover');
if row > TopRow then
begin
while not rowVisible(row) do
TopRow := TopRow + 1;
end
else if row < TopRow then
begin
while not rowVisible(row) do
TopRow := TopRow - 1;
end
end;
procedure TfyDBGrid.SetAutoWidthAllColor(const Value: TColor);
begin
FAutoWidthAllColor := Value;
InvalidateCell(0, 0);
end;
procedure TfyDBGrid.SetMoveSoundEnabled(const Value: boolean);
begin
FMoveSoundEnabled := Value;
end;
procedure TfyDBGrid.SetSortArrowColor(const Value: TColor);
begin
FSortArrowColor := Value;
InvalidateTitles;
end;
procedure TfyDBGrid.decLeftCol;
begin
if leftCol > 1 then
begin
leftCol := leftCol - 1;
myLeftCol := leftCol;
invalidate;
end;
end;
procedure TfyDBGrid.incLeftCol;
begin
if leftCol < (Columns.Count) then
begin
leftCol := leftCol + 1;
myLeftCol := leftCol;
invalidate;
end;
end;
function TfyDBGrid.cellWidth(ACol, ARow: integer): integer;
var
r: TRect;
begin
r := CellRect(ACol, ARow);
Result := r.Right - r.Left;
end;
procedure TfyDBGrid.CalcSizingState(X, Y: integer; var State: TGridState;
var Index, SizingPos, SizingOfs: integer; var FixedInfo: TGridDrawInfo);
var
i: integer;
begin
inherited;
if MouseCoord(x,y).X=-1 then
exit;
for i := myLeftCol - 1 to Columns.Count - 1 do
if abs(getColumnRightEdgePos(Columns[i]) - X) < 5 then
begin
State := gsColSizing;
Index := i + 1;
if IsRightToLeft then
SizingPos := ClientWidth - X
else
SizingPos := X;
SizingOfs := 0;
end;
if FAllowRowResize then
if State <> gsColSizing then
for i := 0 to high(ri) do
begin //search rows bottom line positions
if (abs(ri[i].bottom - Y) < 3) and (ri[i].bottom>0) then
begin
State := gsRowSizing;
Index := i + 1;
SizingPos := Y;
SizingOfs := 0;
lastResizedRow := Index;
Break;
end;
end;
end;
function TfyDBGrid.getColumnRightEdgePos(cl: TColumn): integer;
var
tw, i: integer;
di: TGridDrawInfo;
begin
if myLeftCol > (cl.Index + 1) then
begin
Result := 0;
Exit;
end;
CalcDrawInfo(di);
// add fixed cells width and lines between them
tw := 0;
for i := 0 to di.Horz.FixedCellCount - 1 do
tw := cellWidth(i, 0) + di.Vert.EffectiveLineWidth;
// iterate through data columns up to this column
for i := myLeftCol - 1 to cl.Index do
tw := tw + cellWidth(i + di.Horz.FixedCellCount, 0) +
di.Vert.EffectiveLineWidth;
if IsRightToLeft then
Result := Min(abs(ClientWidth - tw), ClientWidth)
else
Result := Min(tw, ClientWidth);
end;
procedure TfyDBGrid.SetDblClickSoundEnabled(const Value: boolean);
begin
FDblClickSoundEnabled := Value;
end;
procedure TfyDBGrid.SetSortSoundEnabled(const Value: boolean);
begin
FSortSoundEnabled := Value;
end;
procedure TfyDBGrid.SetEscSoundEnabled(const Value: boolean);
begin
FEscSoundEnabled := Value;
end;
procedure TfyDBGrid.playSoundInMemory(cnd: boolean; m: TResourceStream;
name: string);
begin
try
// if cnd then
// sndPlaySound(m.Memory, SND_MEMORY or SND_ASYNC);
except
OutputDebugString(PChar('Error in playing ' + name + ' sound !'));
end;
end;
procedure TfyDBGrid.SetAllowFilter(const Value: boolean);
begin
if not Value then
ClearFilter;
FAllowFilter := Value;
end;
procedure TfyDBGrid.SetAllowRowResize(const Value: boolean);
begin
FAllowRowResize := Value;
end;
procedure TfyDBGrid.SetOnBeforeFilter(const Value: TFilterEvent);
begin
FOnBeforeFilter := Value;
end;
procedure TfyDBGrid.loadConfig(fn: String);
var
cf: TIniFile;
begin
try
cf := TIniFile.create(fn);
TitleColorStart := cf.ReadInteger('config', 'TCS', clWhite);
TitleColorCenter := cf.ReadInteger('config', 'TCC', clWhite);
TitleColorCenterPosition := cf.ReadInteger('config', 'TCCP', 50);
TitleColorFinish := cf.ReadInteger('config', 'TCF', clWhite);
TitleColorSteps := cf.ReadInteger('config', 'TCSTP', 50);
ActiveColorStart := cf.ReadInteger('config', 'ACS', clWhite);
ActiveColorCenter := cf.ReadInteger('config', 'ACC', clNavy);
ActiveColorCenterPosition := cf.ReadInteger('config', 'ACCP', 50);
ActiveColorFinish := cf.ReadInteger('config', 'ACF', clWhite);
ActiveColorSteps := cf.ReadInteger('config', 'ACSTP', 50);
ActiveCellFontColor := cf.ReadInteger('config', 'ACFC', clBlack);
SelectedColorStart := cf.ReadInteger('config', 'SCS', clWhite);
SelectedColorCenter := cf.ReadInteger('config', 'SCC', clWhite);
SelectedColorCenterPosition := cf.ReadInteger('config', 'SCCP', 50);
SelectedColorFinish := cf.ReadInteger('config', 'SCF', clWhite);
SelectedColorSteps := cf.ReadInteger('config', 'SCSTP', 50);
SelectedCellFontColor := cf.ReadInteger('config', 'SCFC', clBlack);
AltRowColor1Start := cf.ReadInteger('config', 'A1CS', clWhite);
AltRowColor1Center := cf.ReadInteger('config', 'A1CC', clWhite);
AltRowColor1CenterPosition := cf.ReadInteger('config', 'A1CCP', 50);
AltRowColor1Finish := cf.ReadInteger('config', 'A1CF', clWhite);
AltRowColor1Steps := cf.ReadInteger('config', 'A1CSTP', 50);
AltRowColor2Start := cf.ReadInteger('config', 'A2CS', clWhite);
AltRowColor2Center := cf.ReadInteger('config', 'A2CC', clWhite);
AltRowColor2CenterPosition := cf.ReadInteger('config', 'A2CCP', 50);
AltRowColor2Finish := cf.ReadInteger('config', 'A2CF', clWhite);
AltRowColor2Steps := cf.ReadInteger('config', 'A2CSTP', 50);
SortArrowColor := cf.ReadInteger('config', 'SortArrowColor', clYellow);
AutoWidthAllColor := cf.ReadInteger('config', 'AutoWidthAllColor',
clYellow);
AutoWidthMin := cf.ReadInteger('config', 'AutoWidthMin', 0);
AutoWidthMax := cf.ReadInteger('config', 'AutoWidthMax', 0);
AllowSort := cf.ReadBool('config', 'AllowSort', false);
AllowRowResize := cf.ReadBool('config', 'AllowRowResize', false);
AllowFilter := cf.ReadBool('config', 'AllowFilter', false);
MoveSoundEnabled := cf.ReadBool('config', 'MoveSoundEnabled', false);
SortSoundEnabled := cf.ReadBool('config', 'SortSoundEnabled', false);
DblClickSoundEnabled := cf.ReadBool('config',
'DblClickSoundEnabled', false);
EscSoundEnabled := cf.ReadBool('config', 'EscSoundEnabled', false);
HotTrack := cf.ReadBool('config', 'HotTrack', false);
AutoFocus := cf.ReadBool('config', 'AutoFocus', false);
// *********************************************************************
Font.Name := cf.ReadString('config', 'FN', 'Tahoma');
Font.Size := cf.ReadInteger('config', 'FS', 8);
Font.Color := cf.ReadInteger('config', 'FC', clBlack);
SetSetProp(Font, 'Style', cf.ReadString('config', 'FSTL', ''));
Color := cf.ReadInteger('config', 'Color', clWhite);
FixedColor := cf.ReadInteger('config', 'FixColor', clBtnFace);
TitleFont.Name := cf.ReadString('config', 'TFN', 'Tahoma');
TitleFont.Color := cf.ReadInteger('config', 'TFC', clBlack);
TitleFont.Size := cf.ReadInteger('config', 'TFS', 8);
SetSetProp(TitleFont, 'Style', cf.ReadString('config', 'TFSTL', ''));
SetSetProp(Self, 'Options', cf.ReadString('config', 'OPT',
'dgEditing,dgTitles,dgIndicator,dgColumnResize,dgColLines,dgRowLines,dgTabs,dgConfirmDelete,dgCancelOnExit')
);
finally
cf.Free;
end;
end;
procedure TfyDBGrid.saveConfig(fn: String);
var
cf: TIniFile;
begin
try
cf := TIniFile.create(fn);
cf.WriteInteger('config', 'TCS', TitleColorStart);
cf.WriteInteger('config', 'TCC', TitleColorCenter);
cf.WriteInteger('config', 'TCCP', TitleColorCenterPosition);
cf.WriteInteger('config', 'TCF', TitleColorFinish);
cf.WriteInteger('config', 'TCSTP', TitleColorSteps);
cf.WriteInteger('config', 'ACS', ActiveColorStart);
cf.WriteInteger('config', 'ACC', ActiveColorCenter);
cf.WriteInteger('config', 'ACCP', ActiveColorCenterPosition);
cf.WriteInteger('config', 'ACF', ActiveColorFinish);
cf.WriteInteger('config', 'ACSTP', ActiveColorSteps);
cf.WriteInteger('config', 'ACFC', ActiveCellFontColor);
cf.WriteInteger('config', 'SCS', SelectedColorStart);
cf.WriteInteger('config', 'SCC', SelectedColorCenter);
cf.WriteInteger('config', 'SCCP', SelectedColorCenterPosition);
cf.WriteInteger('config', 'SCF', SelectedColorFinish);
cf.WriteInteger('config', 'SCSTP', SelectedColorSteps);
cf.WriteInteger('config', 'SCFC', SelectedCellFontColor);
cf.WriteInteger('config', 'A1CS', AltRowColor1Start);
cf.WriteInteger('config', 'A1CC', AltRowColor1Center);
cf.WriteInteger('config', 'A1CCP', AltRowColor1CenterPosition);
cf.WriteInteger('config', 'A1CF', AltRowColor1Finish);
cf.WriteInteger('config', 'A1CSTP', AltRowColor1Steps);
cf.WriteInteger('config', 'A2CS', AltRowColor2Start);
cf.WriteInteger('config', 'A2CC', AltRowColor2Center);
cf.WriteInteger('config', 'A2CCP', AltRowColor2CenterPosition);
cf.WriteInteger('config', 'A2CF', AltRowColor2Finish);
cf.WriteInteger('config', 'A2CSTP', AltRowColor2Steps);
cf.WriteInteger('config', 'SortArrowColor', SortArrowColor);
cf.WriteInteger('config', 'AutoWidthAllColor', AutoWidthAllColor);
cf.WriteInteger('config', 'AutoWidthMin', AutoWidthMin);
cf.WriteInteger('config', 'AutoWidthMax', AutoWidthMax);
cf.WriteBool('config', 'AllowFilter', AllowFilter);
cf.WriteBool('config', 'AllowSort', AllowSort);
cf.WriteBool('config', 'AllowRowResize', AllowRowResize);
cf.WriteBool('config', 'MoveSoundEnabled', MoveSoundEnabled);
cf.WriteBool('config', 'SortSoundEnabled', SortSoundEnabled);
cf.WriteBool('config', 'DblClickSoundEnabled', DblClickSoundEnabled);
cf.WriteBool('config', 'EscSoundEnabled', EscSoundEnabled);
cf.WriteBool('config', 'HotTrack', HotTrack);
cf.WriteBool('config', 'AutoFocus', AutoFocus);
// ************************************************************************
cf.WriteString('config', 'FN', Font.Name);
cf.WriteInteger('config', 'FS', Font.Size);
cf.WriteInteger('config', 'FC', Font.Color);
cf.WriteString('config', 'FSTL', SetToString(GetPropInfo(Font, 'Style'),
GetOrdProp(Font, 'Style')));
cf.WriteInteger('config', 'Color', Color);
cf.WriteInteger('config', 'FixColor', FixedColor);
cf.WriteString('config', 'TFN', TitleFont.Name);
cf.WriteInteger('config', 'TFC', TitleFont.Color);
cf.WriteInteger('config', 'TFS', TitleFont.Size);
cf.WriteString('config', 'TFSTL',
SetToString(GetPropInfo(TitleFont, 'Style'), GetOrdProp(TitleFont,
'Style')));
cf.WriteString('config', 'OPT', SetToString(GetPropInfo(Self, 'Options'),
GetOrdProp(Self, 'options')));
finally
cf.Free;
end;
end;
procedure TfyDBGrid.RowHeightsChanged;
var
t: integer;
begin
inherited;
//resize all rows to the resized row height
t := RowHeights[lastResizedRow];
if DefaultRowHeight <> t then
DefaultRowHeight := t;
// force recalculating row Infos
lastRowCount := 0;
// force recalculate number of visible rows
SendMessage(Handle, WM_SIZE, 0,0);
invalidate;
end;
function TfyDBGrid.cellHeight(ACol, ARow: integer): integer;
var
r: TRect;
begin
r := CellRect(ACol, ARow);
Result := r.bottom - r.top;
end;
function TfyDBGrid.rowVisible(rw: integer): boolean;
begin
Result := not(cellHeight(0, rw) = 0);
end;
function TfyDBGrid.rowFullVisible(rw: integer): boolean;
begin
Result := (cellHeight(0, rw) = RowHeights[rw]);
Exit;
end;
destructor TfyDBGrid.destroy;
begin
try
grBmpTitle.Free;
grBmpSelected.Free;
grBmpAlt1.Free;
grBmpAlt2.Free;
sndEsc.Free;
sndSort.Free;
sndDblClick.Free;
sndHover.Free;
bmpDrawText.Free;
bmpClipped.Free;
finally
inherited;
end;
end;
procedure TfyDBGrid.SetAllowSort(const Value: boolean);
begin
FAllowSort := Value;
end;
procedure TfyDBGrid.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
myLeftCol:= LeftCol;
inherited;
LeftCol:=myLeftCol;
end;
procedure TfyDBGrid.SetActiveColorCenter(const Value: TColor);
begin
FActiveColorCenter := Value;
produceActiveGradient;
invalidate;
end;
procedure TfyDBGrid.SetActiveColorCenterPosition(const Value: integer);
begin
FActiveColorCenterPosition := Value;
produceActiveGradient;
invalidate;
end;
procedure TfyDBGrid.SetActiveColorFinish(const Value: TColor);
begin
FActiveColorFinish := Value;
produceActiveGradient;
invalidate;
end;
procedure TfyDBGrid.SetActiveColorStart(const Value: TColor);
begin
FActiveColorStart := Value;
produceActiveGradient;
invalidate;
end;
procedure TfyDBGrid.SetActiveColorSteps(const Value: integer);
begin
FActiveColorSteps := Value;
produceActiveGradient;
invalidate;
end;
procedure TfyDBGrid.produceActiveGradient;
begin
drawVerticalGradient(grBmpActive, FActiveColorSteps, FActiveColorStart,
FActiveColorCenter, FActiveColorFinish, FActiveColorCenterPosition);
end;
procedure TfyDBGrid.myDrawText(s:string; outputCanvas: Tcanvas; drawRect: TRect;
drawAlignment:TAlignment ; drawFont:TFont);
const
drawFlags : array [TAlignment] of Integer =
(DT_WORDBREAK or DT_LEFT or DT_NOPREFIX,
DT_WORDBREAK or DT_RIGHT or DT_NOPREFIX,
DT_WORDBREAK or DT_CENTER or DT_NOPREFIX );
var
r:trect;
bw, bh, cw, ch:integer;
begin
if s='' then
exit;
if UseRightToLeftAlignment then
case drawAlignment of
taLeftJustify: drawAlignment := taRightJustify;
taRightJustify: drawAlignment := taLeftJustify;
end;
r:= drawRect;
cw:=ClientWidth;
ch:=ClientHeight;
//set dimentions for output
bmpDrawText.Width:=( r.Right - r.Left);
bmpDrawText.Height:=r.Bottom- r.Top;
bw:=bmpDrawText.Width;
bh:=bmpDrawText.Height;
//set drawing area in output bmp
drawRect.Left:=0;
drawRect.Top:=0;
drawRect.Right:=bw;
drawRect.Bottom:=bh;
// if the drawing font color is same as transparent color
//change transparent color
if ColorToRGB( drawFont.Color )=(ColorToRGB( bmpDrawText.TransparentColor) and $ffffff) then
toggleTransparentColor;
//to make entire surface of canvas transparent
bmpDrawText.Canvas.FillRect(drawRect);
//shrink the rectangle
InflateRect(drawRect, -2,-2);
//Canvas.Font.Color:=clRed;
bmpDrawText.Canvas.Font:= drawFont;
DrawText(bmpDrawText.Canvas.Handle,
pchar(s), length(s), drawRect,
drawFlags[drawAlignment]
);
if UseRightToLeftAlignment then
begin
if r.Right > ClientWidth then
begin
bmpClipped.Width:=cw-r.Left;
bmpClipped.Height:=bh;
bmpClipped.Canvas.CopyRect(bmpClipped.Canvas.ClipRect, bmpDrawText.Canvas, Rect(bw, 0, bw-( cw - r.Left ), bh) );
outputCanvas.StretchDraw(rect(r.Left , r.Top, cw, r.Bottom), bmpClipped);
end
else
outputCanvas.StretchDraw(Rect(r.Right, r.Top, r.Left, r.Bottom), bmpDrawText);
end
else
outputCanvas.Draw(r.Left, r.top, bmpDrawText);
end;
procedure TfyDBGrid.SetPopupMenuCommands(const Value: TStrings);
begin
FPopupMenuCommands.Assign(Value);
end;
procedure TfyDBGrid.onPopupMenuItemClick(Sender: TObject);
begin
if checkDBPrerequisites then
if Assigned(fonpopupcommand) then
FOnPopupCommand(sender, tmenuitem(sender).Tag, DataSource.DataSet.RecNo);
end;
procedure TfyDBGrid.SetOnPopupCommand(const Value: TOnPopupCommandEvent);
begin
FOnPopupCommand := Value;
end;
procedure TfyDBGrid.buildPopUpMenu;
var
mi:TMenuItem;
i, j, t:integer;
begin
if not assigned(pmCommands) then
begin
pmCommands:= tpopupmenu.Create(Parent);
pmCommands.AutoPopup:=false;
end;
pmCommands.Items.Clear;
for i:= 0 to FPopupMenuCommands.Count-1 do
begin
j:=pos(',', FPopupMenuCommands[i]);
if j>0 then
if TryStrToInt(midstr(FPopupMenuCommands[i], j+1, length(FPopupMenuCommands[i])), t) then
begin
mi:=TMenuItem.Create(pmCommands);
mi.Caption:=midstr(FPopupMenuCommands[i], 0 , j-1);
mi.Tag:=t;
mi.OnClick:=onPopupMenuItemClick;
pmCommands.Items.Add(mi);
end;
end;
PopupMenu:=pmCommands;
end;
procedure TfyDBGrid.toggleTransparentColor;
begin
if (not Assigned(bmpClipped)) or (not Assigned(bmpDrawText)) then
Exit;
try
if (bmpDrawText.TransparentColor and $ffffff)=clWhite then
begin
bmpDrawText.TransparentColor:=clBlack;
bmpDrawText.Canvas.Brush.Color:=clBlack;
bmpClipped.TransparentColor:=clBlack;
bmpClipped.Canvas.Brush.Color:=clBlack;
end
else
begin
bmpDrawText.TransparentColor:=clWhite;
bmpDrawText.Canvas.Brush.Color:=clWhite;
bmpClipped.TransparentColor:=clWhite;
bmpClipped.Canvas.Brush.Color:=clWhite;
end;
except
OutputDebugString('Error in toggling transparent color.');
end;
end;
procedure TfyDBGrid.PopupMenuCommandsChanged(Sender: TObject);
begin
buildPopUpMenu;
end;
procedure TfyDBGrid.SetActiveCellFontColor(const Value: TColor);
begin
FActiveCellFontColor := Value;
InvalidateGrid;
end;
procedure TfyDBGrid.SetSelectedCellFontColor(const Value: TColor);
begin
FSelectedCellFontColor := Value;
InvalidateGrid;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ File: oledlg.h }
{ Copyright (c) Microsoft Corporation }
{ All Rights Reserved. }
{ }
{ Translator: Embarcadero Technologies, Inc. }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
{*******************************************************}
{ OLE dialogs interface unit }
{*******************************************************}
unit Winapi.OleDlg;
{$WEAKPACKAGEUNIT}
{$ALIGN 8}
{$MINENUMSIZE 4}
interface
(*$HPPEMIT '' *)
(*$HPPEMIT '#include <oledlg.h>' *)
(*$HPPEMIT '' *)
uses Winapi.Windows, Winapi.CommCtrl, Winapi.ActiveX;
const
{ Help Button Identifier }
{$EXTERNALSYM IDC_OLEUIHELP}
IDC_OLEUIHELP = 99;
{ Insert Object Dialog identifiers }
{$EXTERNALSYM IDC_IO_CREATENEW}
IDC_IO_CREATENEW = 2100;
{$EXTERNALSYM IDC_IO_CREATEFROMFILE}
IDC_IO_CREATEFROMFILE = 2101;
{$EXTERNALSYM IDC_IO_LINKFILE}
IDC_IO_LINKFILE = 2102;
{$EXTERNALSYM IDC_IO_OBJECTTYPELIST}
IDC_IO_OBJECTTYPELIST = 2103;
{$EXTERNALSYM IDC_IO_DISPLAYASICON}
IDC_IO_DISPLAYASICON = 2104;
{$EXTERNALSYM IDC_IO_CHANGEICON}
IDC_IO_CHANGEICON = 2105;
{$EXTERNALSYM IDC_IO_FILE}
IDC_IO_FILE = 2106;
{$EXTERNALSYM IDC_IO_FILEDISPLAY}
IDC_IO_FILEDISPLAY = 2107;
{$EXTERNALSYM IDC_IO_RESULTIMAGE}
IDC_IO_RESULTIMAGE = 2108;
{$EXTERNALSYM IDC_IO_RESULTTEXT}
IDC_IO_RESULTTEXT = 2109;
{$EXTERNALSYM IDC_IO_ICONDISPLAY}
IDC_IO_ICONDISPLAY = 2110;
{$EXTERNALSYM IDC_IO_OBJECTTYPETEXT}
IDC_IO_OBJECTTYPETEXT = 2111;
{$EXTERNALSYM IDC_IO_FILETEXT}
IDC_IO_FILETEXT = 2112;
{$EXTERNALSYM IDC_IO_FILETYPE}
IDC_IO_FILETYPE = 2113;
{$EXTERNALSYM IDC_IO_INSERTCONTROL}
IDC_IO_INSERTCONTROL = 2114;
{$EXTERNALSYM IDC_IO_ADDCONTROL}
IDC_IO_ADDCONTROL = 2115;
{$EXTERNALSYM IDC_IO_CONTROLTYPELIST}
IDC_IO_CONTROLTYPELIST = 2116;
{ Paste Special Dialog identifiers }
{$EXTERNALSYM IDC_PS_PASTE}
IDC_PS_PASTE = 500;
{$EXTERNALSYM IDC_PS_PASTELINK}
IDC_PS_PASTELINK = 501;
{$EXTERNALSYM IDC_PS_SOURCETEXT}
IDC_PS_SOURCETEXT = 502;
{$EXTERNALSYM IDC_PS_PASTELIST}
IDC_PS_PASTELIST = 503;
{$EXTERNALSYM IDC_PS_PASTELINKLIST}
IDC_PS_PASTELINKLIST = 504;
{$EXTERNALSYM IDC_PS_DISPLAYLIST}
IDC_PS_DISPLAYLIST = 505;
{$EXTERNALSYM IDC_PS_DISPLAYASICON}
IDC_PS_DISPLAYASICON = 506;
{$EXTERNALSYM IDC_PS_ICONDISPLAY}
IDC_PS_ICONDISPLAY = 507;
{$EXTERNALSYM IDC_PS_CHANGEICON}
IDC_PS_CHANGEICON = 508;
{$EXTERNALSYM IDC_PS_RESULTIMAGE}
IDC_PS_RESULTIMAGE = 509;
{$EXTERNALSYM IDC_PS_RESULTTEXT}
IDC_PS_RESULTTEXT = 510;
{ Change Icon Dialog identifiers }
{$EXTERNALSYM IDC_CI_GROUP}
IDC_CI_GROUP = 120;
{$EXTERNALSYM IDC_CI_CURRENT}
IDC_CI_CURRENT = 121;
{$EXTERNALSYM IDC_CI_CURRENTICON}
IDC_CI_CURRENTICON = 122;
{$EXTERNALSYM IDC_CI_DEFAULT}
IDC_CI_DEFAULT = 123;
{$EXTERNALSYM IDC_CI_DEFAULTICON}
IDC_CI_DEFAULTICON = 124;
{$EXTERNALSYM IDC_CI_FROMFILE}
IDC_CI_FROMFILE = 125;
{$EXTERNALSYM IDC_CI_FROMFILEEDIT}
IDC_CI_FROMFILEEDIT = 126;
{$EXTERNALSYM IDC_CI_ICONLIST}
IDC_CI_ICONLIST = 127;
{$EXTERNALSYM IDC_CI_LABEL}
IDC_CI_LABEL = 128;
{$EXTERNALSYM IDC_CI_LABELEDIT}
IDC_CI_LABELEDIT = 129;
{$EXTERNALSYM IDC_CI_BROWSE}
IDC_CI_BROWSE = 130;
{$EXTERNALSYM IDC_CI_ICONDISPLAY}
IDC_CI_ICONDISPLAY = 131;
{ Convert Dialog identifiers }
{$EXTERNALSYM IDC_CV_OBJECTTYPE}
IDC_CV_OBJECTTYPE = 150;
{$EXTERNALSYM IDC_CV_DISPLAYASICON}
IDC_CV_DISPLAYASICON = 152;
{$EXTERNALSYM IDC_CV_CHANGEICON}
IDC_CV_CHANGEICON = 153;
{$EXTERNALSYM IDC_CV_ACTIVATELIST}
IDC_CV_ACTIVATELIST = 154;
{$EXTERNALSYM IDC_CV_CONVERTTO}
IDC_CV_CONVERTTO = 155;
{$EXTERNALSYM IDC_CV_ACTIVATEAS}
IDC_CV_ACTIVATEAS = 156;
{$EXTERNALSYM IDC_CV_RESULTTEXT}
IDC_CV_RESULTTEXT = 157;
{$EXTERNALSYM IDC_CV_CONVERTLIST}
IDC_CV_CONVERTLIST = 158;
{$EXTERNALSYM IDC_CV_ICONDISPLAY}
IDC_CV_ICONDISPLAY = 165;
{ Edit Links Dialog identifiers }
{$EXTERNALSYM IDC_EL_CHANGESOURCE}
IDC_EL_CHANGESOURCE = 201;
{$EXTERNALSYM IDC_EL_AUTOMATIC}
IDC_EL_AUTOMATIC = 202;
{$EXTERNALSYM IDC_EL_CANCELLINK}
IDC_EL_CANCELLINK = 209;
{$EXTERNALSYM IDC_EL_UPDATENOW}
IDC_EL_UPDATENOW = 210;
{$EXTERNALSYM IDC_EL_OPENSOURCE}
IDC_EL_OPENSOURCE = 211;
{$EXTERNALSYM IDC_EL_MANUAL}
IDC_EL_MANUAL = 212;
{$EXTERNALSYM IDC_EL_LINKSOURCE}
IDC_EL_LINKSOURCE = 216;
{$EXTERNALSYM IDC_EL_LINKTYPE}
IDC_EL_LINKTYPE = 217;
{$EXTERNALSYM IDC_EL_LINKSLISTBOX}
IDC_EL_LINKSLISTBOX = 206;
{$EXTERNALSYM IDC_EL_COL1}
IDC_EL_COL1 = 220;
{$EXTERNALSYM IDC_EL_COL2}
IDC_EL_COL2 = 221;
{$EXTERNALSYM IDC_EL_COL3}
IDC_EL_COL3 = 222;
{ Busy dialog identifiers }
{$EXTERNALSYM IDC_BZ_RETRY}
IDC_BZ_RETRY = 600;
{$EXTERNALSYM IDC_BZ_ICON}
IDC_BZ_ICON = 601;
{$EXTERNALSYM IDC_BZ_MESSAGE1}
IDC_BZ_MESSAGE1 = 602;
{$EXTERNALSYM IDC_BZ_SWITCHTO}
IDC_BZ_SWITCHTO = 604;
{ Update Links dialog identifiers }
{$EXTERNALSYM IDC_UL_METER}
IDC_UL_METER = 1029;
{$EXTERNALSYM IDC_UL_STOP}
IDC_UL_STOP = 1030;
{$EXTERNALSYM IDC_UL_PERCENT}
IDC_UL_PERCENT = 1031;
{$EXTERNALSYM IDC_UL_PROGRESS}
IDC_UL_PROGRESS = 1032;
{ User Prompt dialog identifiers }
{$EXTERNALSYM IDC_PU_LINKS}
IDC_PU_LINKS = 900;
{$EXTERNALSYM IDC_PU_TEXT}
IDC_PU_TEXT = 901;
{$EXTERNALSYM IDC_PU_CONVERT}
IDC_PU_CONVERT = 902;
{$EXTERNALSYM IDC_PU_ICON}
IDC_PU_ICON = 908;
{ General Properties identifiers }
{$EXTERNALSYM IDC_GP_OBJECTNAME}
IDC_GP_OBJECTNAME = 1009;
{$EXTERNALSYM IDC_GP_OBJECTTYPE}
IDC_GP_OBJECTTYPE = 1010;
{$EXTERNALSYM IDC_GP_OBJECTSIZE}
IDC_GP_OBJECTSIZE = 1011;
{$EXTERNALSYM IDC_GP_CONVERT}
IDC_GP_CONVERT = 1013;
{$EXTERNALSYM IDC_GP_OBJECTICON}
IDC_GP_OBJECTICON = 1014;
{$EXTERNALSYM IDC_GP_OBJECTLOCATION}
IDC_GP_OBJECTLOCATION = 1022;
{ View Properties identifiers }
{$EXTERNALSYM IDC_VP_PERCENT}
IDC_VP_PERCENT = 1000;
{$EXTERNALSYM IDC_VP_CHANGEICON}
IDC_VP_CHANGEICON = 1001;
{$EXTERNALSYM IDC_VP_EDITABLE}
IDC_VP_EDITABLE = 1002;
{$EXTERNALSYM IDC_VP_ASICON}
IDC_VP_ASICON = 1003;
{$EXTERNALSYM IDC_VP_RELATIVE}
IDC_VP_RELATIVE = 1005;
{$EXTERNALSYM IDC_VP_SPIN}
IDC_VP_SPIN = 1006;
{$EXTERNALSYM IDC_VP_SCALETXT}
IDC_VP_SCALETXT = 1034;
{$EXTERNALSYM IDC_VP_ICONDISPLAY}
IDC_VP_ICONDISPLAY = 1021;
{$EXTERNALSYM IDC_VP_RESULTIMAGE}
IDC_VP_RESULTIMAGE = 1033;
{ Link Properties identifiers }
{$EXTERNALSYM IDC_LP_OPENSOURCE}
IDC_LP_OPENSOURCE = 1006;
{$EXTERNALSYM IDC_LP_UPDATENOW}
IDC_LP_UPDATENOW = 1007;
{$EXTERNALSYM IDC_LP_BREAKLINK}
IDC_LP_BREAKLINK = 1008;
{$EXTERNALSYM IDC_LP_LINKSOURCE}
IDC_LP_LINKSOURCE = 1012;
{$EXTERNALSYM IDC_LP_CHANGESOURCE}
IDC_LP_CHANGESOURCE = 1015;
{$EXTERNALSYM IDC_LP_AUTOMATIC}
IDC_LP_AUTOMATIC = 1016;
{$EXTERNALSYM IDC_LP_MANUAL}
IDC_LP_MANUAL = 1017;
{$EXTERNALSYM IDC_LP_DATE}
IDC_LP_DATE = 1018;
{$EXTERNALSYM IDC_LP_TIME}
IDC_LP_TIME = 1019;
{ Dialog Identifiers as passed in Help messages to identify the source }
{$EXTERNALSYM IDD_INSERTOBJECT}
IDD_INSERTOBJECT = 1000;
{$EXTERNALSYM IDD_CHANGEICON}
IDD_CHANGEICON = 1001;
{$EXTERNALSYM IDD_CONVERT}
IDD_CONVERT = 1002;
{$EXTERNALSYM IDD_PASTESPECIAL}
IDD_PASTESPECIAL = 1003;
{$EXTERNALSYM IDD_EDITLINKS}
IDD_EDITLINKS = 1004;
{$EXTERNALSYM IDD_BUSY}
IDD_BUSY = 1006;
{$EXTERNALSYM IDD_UPDATELINKS}
IDD_UPDATELINKS = 1007;
{$EXTERNALSYM IDD_CHANGESOURCE}
IDD_CHANGESOURCE = 1009;
{$EXTERNALSYM IDD_INSERTFILEBROWSE}
IDD_INSERTFILEBROWSE = 1010;
{$EXTERNALSYM IDD_CHANGEICONBROWSE}
IDD_CHANGEICONBROWSE = 1011;
{$EXTERNALSYM IDD_CONVERTONLY}
IDD_CONVERTONLY = 1012;
{$EXTERNALSYM IDD_CHANGESOURCE4}
IDD_CHANGESOURCE4 = 1013;
{$EXTERNALSYM IDD_GNRLPROPS}
IDD_GNRLPROPS = 1100;
{$EXTERNALSYM IDD_VIEWPROPS}
IDD_VIEWPROPS = 1101;
{$EXTERNALSYM IDD_LINKPROPS}
IDD_LINKPROPS = 1102;
{ The following Dialogs are message dialogs used by OleUIPromptUser API }
{$EXTERNALSYM IDD_CANNOTUPDATELINK}
IDD_CANNOTUPDATELINK = 1008;
{$EXTERNALSYM IDD_LINKSOURCEUNAVAILABLE}
IDD_LINKSOURCEUNAVAILABLE = 1020;
{$EXTERNALSYM IDD_SERVERNOTFOUND}
IDD_SERVERNOTFOUND = 1023;
{$EXTERNALSYM IDD_OUTOFMEMORY}
IDD_OUTOFMEMORY = 1024;
{$EXTERNALSYM IDD_SERVERNOTREG}
IDD_SERVERNOTREG = 1021;
{$EXTERNALSYM IDD_LINKTYPECHANGED}
IDD_LINKTYPECHANGED = 1022;
{ Delimeter used to separate ItemMoniker pieces of a composite moniker }
{$EXTERNALSYM OLESTDDELIM}
OLESTDDELIM = '\';
{ Strings for registered messages }
{$EXTERNALSYM SZOLEUI_MSG_HELP}
SZOLEUI_MSG_HELP = 'OLEUI_MSG_HELP';
{$EXTERNALSYM SZOLEUI_MSG_ENDDIALOG}
SZOLEUI_MSG_ENDDIALOG = 'OLEUI_MSG_ENDDIALOG';
{$EXTERNALSYM SZOLEUI_MSG_BROWSE}
SZOLEUI_MSG_BROWSE = 'OLEUI_MSG_BROWSE';
{$EXTERNALSYM SZOLEUI_MSG_CHANGEICON}
SZOLEUI_MSG_CHANGEICON = 'OLEUI_MSG_CHANGEICON';
{$EXTERNALSYM SZOLEUI_MSG_CLOSEBUSYDIALOG}
SZOLEUI_MSG_CLOSEBUSYDIALOG = 'OLEUI_MSG_CLOSEBUSYDIALOG';
{$EXTERNALSYM SZOLEUI_MSG_CONVERT}
SZOLEUI_MSG_CONVERT = 'OLEUI_MSG_CONVERT';
{$EXTERNALSYM SZOLEUI_MSG_CHANGESOURCE}
SZOLEUI_MSG_CHANGESOURCE = 'OLEUI_MSG_CHANGESOURCE';
{$EXTERNALSYM SZOLEUI_MSG_ADDCONTROL}
SZOLEUI_MSG_ADDCONTROL = 'OLEUI_MSG_ADDCONTROL';
{$EXTERNALSYM SZOLEUI_MSG_BROWSE_OFN}
SZOLEUI_MSG_BROWSE_OFN = 'OLEUI_MSG_BROWSE_OFN';
{ Identifiers for SZOLEUI_MSG_BROWSE_OFN (in wParam) }
{$EXTERNALSYM ID_BROWSE_CHANGEICON}
ID_BROWSE_CHANGEICON = 1;
{$EXTERNALSYM ID_BROWSE_INSERTFILE}
ID_BROWSE_INSERTFILE = 2;
{$EXTERNALSYM ID_BROWSE_ADDCONTROL}
ID_BROWSE_ADDCONTROL = 3;
{$EXTERNALSYM ID_BROWSE_CHANGESOURCE}
ID_BROWSE_CHANGESOURCE = 4;
{ Standard success/error definitions }
{$EXTERNALSYM OLEUI_FALSE}
OLEUI_FALSE = 0;
{$EXTERNALSYM OLEUI_SUCCESS}
OLEUI_SUCCESS = 1; { No error, same as OLEUI_OK }
{$EXTERNALSYM OLEUI_OK}
OLEUI_OK = 1; { OK button pressed }
{$EXTERNALSYM OLEUI_CANCEL}
OLEUI_CANCEL = 2; { Cancel button pressed }
{$EXTERNALSYM OLEUI_ERR_STANDARDMIN}
OLEUI_ERR_STANDARDMIN = 100;
{$EXTERNALSYM OLEUI_ERR_OLEMEMALLOC}
OLEUI_ERR_OLEMEMALLOC = 100;
{$EXTERNALSYM OLEUI_ERR_STRUCTURENULL}
OLEUI_ERR_STRUCTURENULL = 101; { Standard field validation }
{$EXTERNALSYM OLEUI_ERR_STRUCTUREINVALID}
OLEUI_ERR_STRUCTUREINVALID = 102;
{$EXTERNALSYM OLEUI_ERR_CBSTRUCTINCORRECT}
OLEUI_ERR_CBSTRUCTINCORRECT = 103;
{$EXTERNALSYM OLEUI_ERR_HWNDOWNERINVALID}
OLEUI_ERR_HWNDOWNERINVALID = 104;
{$EXTERNALSYM OLEUI_ERR_LPSZCAPTIONINVALID}
OLEUI_ERR_LPSZCAPTIONINVALID = 105;
{$EXTERNALSYM OLEUI_ERR_LPFNHOOKINVALID}
OLEUI_ERR_LPFNHOOKINVALID = 106;
{$EXTERNALSYM OLEUI_ERR_HINSTANCEINVALID}
OLEUI_ERR_HINSTANCEINVALID = 107;
{$EXTERNALSYM OLEUI_ERR_LPSZTEMPLATEINVALID}
OLEUI_ERR_LPSZTEMPLATEINVALID = 108;
{$EXTERNALSYM OLEUI_ERR_HRESOURCEINVALID}
OLEUI_ERR_HRESOURCEINVALID = 109;
{$EXTERNALSYM OLEUI_ERR_FINDTEMPLATEFAILURE}
OLEUI_ERR_FINDTEMPLATEFAILURE = 110; { Initialization errors }
{$EXTERNALSYM OLEUI_ERR_LOADTEMPLATEFAILURE}
OLEUI_ERR_LOADTEMPLATEFAILURE = 111;
{$EXTERNALSYM OLEUI_ERR_DIALOGFAILURE}
OLEUI_ERR_DIALOGFAILURE = 112;
{$EXTERNALSYM OLEUI_ERR_LOCALMEMALLOC}
OLEUI_ERR_LOCALMEMALLOC = 113;
{$EXTERNALSYM OLEUI_ERR_GLOBALMEMALLOC}
OLEUI_ERR_GLOBALMEMALLOC = 114;
{$EXTERNALSYM OLEUI_ERR_LOADSTRING}
OLEUI_ERR_LOADSTRING = 115;
{$EXTERNALSYM OLEUI_ERR_STANDARDMAX}
OLEUI_ERR_STANDARDMAX = 116; { Start here for specific errors }
{ Hook type used in all structures }
type
TFNOleUIHook = function(Wnd: HWnd; Msg, WParam, LParam: Longint): Longint stdcall;
{ Miscellaneous utility functions }
function OleUIAddVerbMenu(oleObj: IOleObject; pszShortType: PWideChar;
menu: HMenu; uPos: Integer; uIDVerbMin: Integer; uIDVerbMax: Integer;
bAddConvert: BOOL; idConvert: Integer; var outMenu: HMenu): BOOL; stdcall;
{$EXTERNALSYM OleUIAddVerbMenu}
function OleUIAddVerbMenuA(oleObj: IOleObject; pszShortType: PAnsiChar;
menu: HMenu; uPos: Integer; uIDVerbMin: Integer; uIDVerbMax: Integer;
bAddConvert: BOOL; idConvert: Integer; var outMenu: HMenu): BOOL; stdcall;
{$EXTERNALSYM OleUIAddVerbMenuA}
function OleUIAddVerbMenuW(oleObj: IOleObject; pszShortType: PWideChar;
menu: HMenu; uPos: Integer; uIDVerbMin: Integer; uIDVerbMax: Integer;
bAddConvert: BOOL; idConvert: Integer; var outMenu: HMenu): BOOL; stdcall;
{$EXTERNALSYM OleUIAddVerbMenuW}
{ **** Insert Object dialog **** }
{ Insert object dialog structure }
type
POleUIInsertObjectA = ^TOleUIInsertObjectA;
POleUIInsertObjectW = ^TOleUIInsertObjectW;
POleUIInsertObject = POleUIInsertObjectW;
tagOLEUIINSERTOBJECTA = record
cbStruct: DWORD; { Structure Size }
dwFlags: DWORD; { IN-OUT: Flags }
hWndOwner: HWnd; { Owning window }
lpszCaption: PAnsiChar; { Dialog caption bar contents }
lpfnHook: TFNOleUIHook; { Hook callback }
lCustData: LPARAM; { Custom data to pass to hook }
hInstance: THandle; { Instance for customized template name }
lpszTemplate: PAnsiChar; { Customized template name }
hResource: HRsrc; { Customized template handle }
clsid: TCLSID; { OUT: Return space for class ID }
lpszFile: PAnsiChar; { IN-OUT: Filename for inserts or links }
cchFile: UINT; { IN: Size of lpszFile buffer: MAX_PATH }
cClsidExclude: UINT; { IN: CLSIDs in lpClsidExclude }
lpClsidExclude: PCLSID; { IN: List of CLSIDs to exclude from listing }
iid: TIID; { IN: Requested interface on creation }
oleRender: DWORD; { IN: Rendering option }
lpFormatEtc: PFormatEtc; { IN: Desired format }
lpIOleClientSite: IOleClientSite; { IN: Site to be use for the object }
lpIStorage: IStorage; { IN: Storage used for the object }
ppvObj: Pointer; { OUT: Where the object is returned }
sc: HResult; { OUT: Result of creation calls }
hMetaPict: HGlobal; { OUT: metafile aspect (METAFILEPICT) }
end;
{$EXTERNALSYM tagOLEUIINSERTOBJECTA}
tagOLEUIINSERTOBJECTW = record
cbStruct: DWORD; { Structure Size }
dwFlags: DWORD; { IN-OUT: Flags }
hWndOwner: HWnd; { Owning window }
lpszCaption: PWideChar; { Dialog caption bar contents }
lpfnHook: TFNOleUIHook; { Hook callback }
lCustData: LPARAM; { Custom data to pass to hook }
hInstance: THandle; { Instance for customized template name }
lpszTemplate: PWideChar; { Customized template name }
hResource: HRsrc; { Customized template handle }
clsid: TCLSID; { OUT: Return space for class ID }
lpszFile: PWideChar; { IN-OUT: Filename for inserts or links }
cchFile: UINT; { IN: Size of lpszFile buffer: MAX_PATH }
cClsidExclude: UINT; { IN: CLSIDs in lpClsidExclude }
lpClsidExclude: PCLSID; { IN: List of CLSIDs to exclude from listing }
iid: TIID; { IN: Requested interface on creation }
oleRender: DWORD; { IN: Rendering option }
lpFormatEtc: PFormatEtc; { IN: Desired format }
lpIOleClientSite: IOleClientSite; { IN: Site to be use for the object }
lpIStorage: IStorage; { IN: Storage used for the object }
ppvObj: Pointer; { OUT: Where the object is returned }
sc: HResult; { OUT: Result of creation calls }
hMetaPict: HGlobal; { OUT: metafile aspect (METAFILEPICT) }
end;
{$EXTERNALSYM tagOLEUIINSERTOBJECTW}
tagOLEUIINSERTOBJECT = tagOLEUIINSERTOBJECTW;
TOleUIInsertObjectA = tagOLEUIINSERTOBJECTA;
TOleUIInsertObjectW = tagOLEUIINSERTOBJECTW;
TOleUIInsertObject = TOleUIInsertObjectW;
{ Insert object dialog function }
function OleUIInsertObject(var Info: TOleUIInsertObject): Integer; stdcall;
{$EXTERNALSYM OleUIInsertObject}
function OleUIInsertObjectA(var Info: TOleUIInsertObjectA): Integer; stdcall;
{$EXTERNALSYM OleUIInsertObjectA}
function OleUIInsertObjectW(var Info: TOleUIInsertObjectW): Integer; stdcall;
{$EXTERNALSYM OleUIInsertObjectW}
{ Insert Object flags }
const
{$EXTERNALSYM IOF_SHOWHELP}
IOF_SHOWHELP = $00000001;
{$EXTERNALSYM IOF_SELECTCREATENEW}
IOF_SELECTCREATENEW = $00000002;
{$EXTERNALSYM IOF_SELECTCREATEFROMFILE}
IOF_SELECTCREATEFROMFILE = $00000004;
{$EXTERNALSYM IOF_CHECKLINK}
IOF_CHECKLINK = $00000008;
{$EXTERNALSYM IOF_CHECKDISPLAYASICON}
IOF_CHECKDISPLAYASICON = $00000010;
{$EXTERNALSYM IOF_CREATENEWOBJECT}
IOF_CREATENEWOBJECT = $00000020;
{$EXTERNALSYM IOF_CREATEFILEOBJECT}
IOF_CREATEFILEOBJECT = $00000040;
{$EXTERNALSYM IOF_CREATELINKOBJECT}
IOF_CREATELINKOBJECT = $00000080;
{$EXTERNALSYM IOF_DISABLELINK}
IOF_DISABLELINK = $00000100;
{$EXTERNALSYM IOF_VERIFYSERVERSEXIST}
IOF_VERIFYSERVERSEXIST = $00000200;
{$EXTERNALSYM IOF_DISABLEDISPLAYASICON}
IOF_DISABLEDISPLAYASICON = $00000400;
{$EXTERNALSYM IOF_HIDECHANGEICON}
IOF_HIDECHANGEICON = $00000800;
{$EXTERNALSYM IOF_SHOWINSERTCONTROL}
IOF_SHOWINSERTCONTROL = $00001000;
{$EXTERNALSYM IOF_SELECTCREATECONTROL}
IOF_SELECTCREATECONTROL = $00002000;
{ Insert Object specific error codes }
const
{$EXTERNALSYM OLEUI_IOERR_LPSZFILEINVALID}
OLEUI_IOERR_LPSZFILEINVALID = OLEUI_ERR_STANDARDMAX + 0;
{$EXTERNALSYM OLEUI_IOERR_LPSZLABELINVALID}
OLEUI_IOERR_LPSZLABELINVALID = OLEUI_ERR_STANDARDMAX + 1;
{$EXTERNALSYM OLEUI_IOERR_HICONINVALID}
OLEUI_IOERR_HICONINVALID = OLEUI_ERR_STANDARDMAX + 2;
{$EXTERNALSYM OLEUI_IOERR_LPFORMATETCINVALID}
OLEUI_IOERR_LPFORMATETCINVALID = OLEUI_ERR_STANDARDMAX + 3;
{$EXTERNALSYM OLEUI_IOERR_PPVOBJINVALID}
OLEUI_IOERR_PPVOBJINVALID = OLEUI_ERR_STANDARDMAX + 4;
{$EXTERNALSYM OLEUI_IOERR_LPIOLECLIENTSITEINVALID}
OLEUI_IOERR_LPIOLECLIENTSITEINVALID = OLEUI_ERR_STANDARDMAX + 5;
{$EXTERNALSYM OLEUI_IOERR_LPISTORAGEINVALID}
OLEUI_IOERR_LPISTORAGEINVALID = OLEUI_ERR_STANDARDMAX + 6;
{$EXTERNALSYM OLEUI_IOERR_SCODEHASERROR}
OLEUI_IOERR_SCODEHASERROR = OLEUI_ERR_STANDARDMAX + 7;
{$EXTERNALSYM OLEUI_IOERR_LPCLSIDEXCLUDEINVALID}
OLEUI_IOERR_LPCLSIDEXCLUDEINVALID = OLEUI_ERR_STANDARDMAX + 8;
{$EXTERNALSYM OLEUI_IOERR_CCHFILEINVALID}
OLEUI_IOERR_CCHFILEINVALID = OLEUI_ERR_STANDARDMAX + 9;
{ **** Paste Special dialog **** }
{ The OLEUIPASTE_xxx values are used by the TOleUIPasteEntry structure.
OLEUIPASTE_ENABLEICON: If the container does not specify this flag for
the entry in the TOleUIPasteEntry array passed as input to
OleUIPasteSpecial, the DisplayAsIcon button will be unchecked and
disabled when the the user selects the format that corresponds to
the entry.
OLEUIPASTE_PASTEONLY: Indicates that the entry in the TOleUIPasteEntry
array is valid for pasting only.
OLEUIPASTE_PASTE: Indicates that the entry in the TOleUIPasteEntry array
is valid for pasting. It may also be valid for linking if any of
the following linking flags are specified.
If the entry in the TOleUIPasteEntry array is valid for linking, the
following flags indicate which link types are acceptable by OR'ing
together the appropriate OLEUIPASTE_LINKTYPE<#> values.
These values correspond as follows to the array of link types passed to
OleUIPasteSpecial:
OLEUIPASTE_LINKTYPE1 = arrLinkTypes[0]
OLEUIPASTE_LINKTYPE2 = arrLinkTypes[1]
OLEUIPASTE_LINKTYPE3 = arrLinkTypes[2]
OLEUIPASTE_LINKTYPE4 = arrLinkTypes[3]
OLEUIPASTE_LINKTYPE5 = arrLinkTypes[4]
OLEUIPASTE_LINKTYPE6 = arrLinkTypes[5]
OLEUIPASTE_LINKTYPE7 = arrLinkTypes[6]
OLEUIPASTE_LINKTYPE8 = arrLinkTypes[7]
where,
UINT arrLinkTypes[8] is an array of registered clipboard formats for
linking. A maximium of 8 link types are allowed. }
const
{$EXTERNALSYM OLEUIPASTE_ENABLEICON}
OLEUIPASTE_ENABLEICON = 2048; { enable display as icon }
{$EXTERNALSYM OLEUIPASTE_PASTEONLY}
OLEUIPASTE_PASTEONLY = 0;
{$EXTERNALSYM OLEUIPASTE_PASTE}
OLEUIPASTE_PASTE = 512;
{$EXTERNALSYM OLEUIPASTE_LINKANYTYPE}
OLEUIPASTE_LINKANYTYPE = 1024;
{$EXTERNALSYM OLEUIPASTE_LINKTYPE1}
OLEUIPASTE_LINKTYPE1 = 1;
{$EXTERNALSYM OLEUIPASTE_LINKTYPE2}
OLEUIPASTE_LINKTYPE2 = 2;
{$EXTERNALSYM OLEUIPASTE_LINKTYPE3}
OLEUIPASTE_LINKTYPE3 = 4;
{$EXTERNALSYM OLEUIPASTE_LINKTYPE4}
OLEUIPASTE_LINKTYPE4 = 8;
{$EXTERNALSYM OLEUIPASTE_LINKTYPE5}
OLEUIPASTE_LINKTYPE5 = 16;
{$EXTERNALSYM OLEUIPASTE_LINKTYPE6}
OLEUIPASTE_LINKTYPE6 = 32;
{$EXTERNALSYM OLEUIPASTE_LINKTYPE7}
OLEUIPASTE_LINKTYPE7 = 64;
{$EXTERNALSYM OLEUIPASTE_LINKTYPE8}
OLEUIPASTE_LINKTYPE8 = 128;
{ TOleUIPasteEntry structure
An array of TOleUIPasteEntry entries is specified for the PasteSpecial
dialog box. Each entry includes a TFormatEtc which specifies the
formats that are acceptable, a string that is to represent the format
in the dialog's list box, a string to customize the result text of the
dialog and a set of flags from the OLEUIPASTE_xxx constants. The
flags indicate if the entry is valid for pasting only, linking only or
both pasting and linking. }
type
POleUIPasteEntryA = ^TOleUIPasteEntryA;
POleUIPasteEntryW = ^TOleUIPasteEntryW;
POleUIPasteEntry = POleUIPasteEntryW;
tagOLEUIPASTEENTRYA = record
fmtetc: TFormatEtc; { Format that is acceptable }
lpstrFormatName: PAnsiChar; { AnsiString that represents the format
to the user. %s is replaced by the
full user type name of the object }
lpstrResultText: PAnsiChar; { AnsiString to customize the result text
of the dialog when the user
selects the format correspoding to
this entry. Any %s in this AnsiString
is replaced by the the application
name or FullUserTypeName of the
object on the clipboard }
dwFlags: DWORD; { Values from OLEUIPASTE_xxx set }
dwScratchSpace: DWORD; { Scratch space used internally }
end;
{$EXTERNALSYM tagOLEUIPASTEENTRYA}
tagOLEUIPASTEENTRYW = record
fmtetc: TFormatEtc; { Format that is acceptable }
lpstrFormatName: PWideChar; { UnicodeString that represents the format
to the user. %s is replaced by the
full user type name of the object }
lpstrResultText: PWideChar; { UnicodeString to customize the result text
of the dialog when the user
selects the format correspoding to
this entry. Any %s in this UnicodeString
is replaced by the the application
name or FullUserTypeName of the
object on the clipboard }
dwFlags: DWORD; { Values from OLEUIPASTE_xxx set }
dwScratchSpace: DWORD; { Scratch space used internally }
end;
{$EXTERNALSYM tagOLEUIPASTEENTRYW}
tagOLEUIPASTEENTRY = tagOLEUIPASTEENTRYW;
TOleUIPasteEntryA = tagOLEUIPASTEENTRYA;
TOleUIPasteEntryW = tagOLEUIPASTEENTRYW;
TOleUIPasteEntry = TOleUIPasteEntryW;
OLEUIPASTEENTRYA = tagOLEUIPASTEENTRYA;
{$EXTERNALSYM OLEUIPASTEENTRYA}
OLEUIPASTEENTRYW = tagOLEUIPASTEENTRYW;
{$EXTERNALSYM OLEUIPASTEENTRYW}
OLEUIPASTEENTRY = OLEUIPASTEENTRYW;
{ Maximum number of link types }
const
{$EXTERNALSYM PS_MAXLINKTYPES}
PS_MAXLINKTYPES = 8;
type
POleUIPasteSpecialA = ^TOleUIPasteSpecialA;
POleUIPasteSpecialW = ^TOleUIPasteSpecialW;
POleUIPasteSpecial = POleUIPasteSpecialW;
tagOLEUIPASTESPECIALA = record
cbStruct: DWORD; { Structure Size }
dwFlags: DWORD; { IN-OUT: Flags }
hWndOwner: HWnd; { Owning window }
lpszCaption: PAnsiChar; { Dialog caption bar contents }
lpfnHook: TFNOleUIHook; { Hook callback }
lCustData: LPARAM; { Custom data to pass to hook }
hInstance: HINST; { Instance for customized template name }
lpszTemplate: PAnsiChar; { Customized template name }
hResource: HRsrc; { Customized template handle }
lpSrcDataObj: IDataObject; { IN-OUT: Source IDataObject on the clipboard }
arrPasteEntries: POleUIPasteEntryA; { IN: Array of acceptable formats }
cPasteEntries: Integer; { IN: No. of TOleUIPasteEntry array entries }
arrLinkTypes: PLongint; { IN: List of acceptable link types }
cLinkTypes: Integer; { IN: Number of link types }
cClsidExclude: UINT; { IN: Number of CLSIDs in lpClsidExclude }
lpClsidExclude: PCLSID; { IN: List of CLSIDs to exclude from list }
nSelectedIndex: Integer; { OUT: Index that the user selected }
fLink: BOOL; { OUT: Indicates if Paste or PasteLink }
hMetaPict: HGlobal; { OUT: Handle to Metafile containing icon }
sizel: TSize; { OUT: size of object/link in its source
may be 0,0 if different display
aspect is chosen }
end;
{$EXTERNALSYM tagOLEUIPASTESPECIALA}
tagOLEUIPASTESPECIALW = record
cbStruct: DWORD; { Structure Size }
dwFlags: DWORD; { IN-OUT: Flags }
hWndOwner: HWnd; { Owning window }
lpszCaption: PWideChar; { Dialog caption bar contents }
lpfnHook: TFNOleUIHook; { Hook callback }
lCustData: LPARAM; { Custom data to pass to hook }
hInstance: HINST; { Instance for customized template name }
lpszTemplate: PWideChar; { Customized template name }
hResource: HRsrc; { Customized template handle }
lpSrcDataObj: IDataObject; { IN-OUT: Source IDataObject on the clipboard }
arrPasteEntries: POleUIPasteEntryW; { IN: Array of acceptable formats }
cPasteEntries: Integer; { IN: No. of TOleUIPasteEntry array entries }
arrLinkTypes: PLongint; { IN: List of acceptable link types }
cLinkTypes: Integer; { IN: Number of link types }
cClsidExclude: UINT; { IN: Number of CLSIDs in lpClsidExclude }
lpClsidExclude: PCLSID; { IN: List of CLSIDs to exclude from list }
nSelectedIndex: Integer; { OUT: Index that the user selected }
fLink: BOOL; { OUT: Indicates if Paste or PasteLink }
hMetaPict: HGlobal; { OUT: Handle to Metafile containing icon }
sizel: TSize; { OUT: size of object/link in its source
may be 0,0 if different display
aspect is chosen }
end;
{$EXTERNALSYM tagOLEUIPASTESPECIALW}
tagOLEUIPASTESPECIAL = tagOLEUIPASTESPECIALW;
TOleUIPasteSpecialA = tagOLEUIPASTESPECIALA;
TOleUIPasteSpecialW = tagOLEUIPASTESPECIALW;
TOleUIPasteSpecial = TOleUIPasteSpecialW;
function OleUIPasteSpecial(var Info: TOleUIPasteSpecial): Integer; stdcall;
{$EXTERNALSYM OleUIPasteSpecial}
function OleUIPasteSpecialA(var Info: TOleUIPasteSpecialA): Integer; stdcall;
{$EXTERNALSYM OleUIPasteSpecialA}
function OleUIPasteSpecialW(var Info: TOleUIPasteSpecialW): Integer; stdcall;
{$EXTERNALSYM OleUIPasteSpecialW}
{ Paste Special specific flags }
const
{$EXTERNALSYM PSF_SHOWHELP}
PSF_SHOWHELP = $00000001;
{$EXTERNALSYM PSF_SELECTPASTE}
PSF_SELECTPASTE = $00000002;
{$EXTERNALSYM PSF_SELECTPASTELINK}
PSF_SELECTPASTELINK = $00000004;
{$EXTERNALSYM PSF_CHECKDISPLAYASICON}
PSF_CHECKDISPLAYASICON = $00000008;
{$EXTERNALSYM PSF_DISABLEDISPLAYASICON}
PSF_DISABLEDISPLAYASICON = $00000010;
{$EXTERNALSYM PSF_HIDECHANGEICON}
PSF_HIDECHANGEICON = $00000020;
{$EXTERNALSYM PSF_STAYONCLIPBOARDCHANGE}
PSF_STAYONCLIPBOARDCHANGE = $00000040;
{$EXTERNALSYM PSF_NOREFRESHDATAOBJECT}
PSF_NOREFRESHDATAOBJECT = $00000080;
{ Paste Special specific error codes }
const
{$EXTERNALSYM OLEUI_IOERR_SRCDATAOBJECTINVALID}
OLEUI_IOERR_SRCDATAOBJECTINVALID = OLEUI_ERR_STANDARDMAX + 0;
{$EXTERNALSYM OLEUI_IOERR_ARRPASTEENTRIESINVALID}
OLEUI_IOERR_ARRPASTEENTRIESINVALID = OLEUI_ERR_STANDARDMAX + 1;
{$EXTERNALSYM OLEUI_IOERR_ARRLINKTYPESINVALID}
OLEUI_IOERR_ARRLINKTYPESINVALID = OLEUI_ERR_STANDARDMAX + 2;
{$EXTERNALSYM OLEUI_PSERR_CLIPBOARDCHANGED}
OLEUI_PSERR_CLIPBOARDCHANGED = OLEUI_ERR_STANDARDMAX + 3;
{$EXTERNALSYM OLEUI_PSERR_GETCLIPBOARDFAILED}
OLEUI_PSERR_GETCLIPBOARDFAILED = OLEUI_ERR_STANDARDMAX + 4;
{ **** Edit Links dialog **** }
{ IOleUILinkContainer interface
This interface must be implemented by container applications that
want to use the EditLinks dialog. the EditLinks dialog calls back
to the container app to perform the OLE functions to manipulate
the links within the container. }
type
IOleUILinkContainer = interface(IUnknown)
['{00000000-0000-0000-0000-000000000000}'] //!!!
function GetNextLink(dwLink: Longint): Longint; stdcall;
function SetLinkUpdateOptions(dwLink: Longint; dwUpdateOpt: Longint): HResult; stdcall;
function GetLinkUpdateOptions(dwLink: Longint;
var dwUpdateOpt: Longint): HResult; stdcall;
function SetLinkSource(dwLink: Longint; pszDisplayName: PChar;
lenFileName: Longint; var chEaten: Longint;
fValidateSource: BOOL): HResult; stdcall;
function GetLinkSource(dwLink: Longint; var pszDisplayName: PChar;
var lenFileName: Longint; var pszFullLinkType: PChar;
var pszShortLinkType: PChar; var fSourceAvailable: BOOL;
var fIsSelected: BOOL): HResult; stdcall;
function OpenLinkSource(dwLink: Longint): HResult; stdcall;
function UpdateLink(dwLink: Longint; fErrorMessage: BOOL;
fErrorAction: BOOL): HResult; stdcall;
function CancelLink(dwLink: Longint): HResult; stdcall;
end;
{$EXTERNALSYM IOleUILinkContainer}
{ TOleIUEditLinks structure }
type
POleUIEditLinksA = ^TOleUIEditLinksA;
POleUIEditLinksW = ^TOleUIEditLinksW;
POleUIEditLinks = POleUIEditLinksW;
tagOLEUIEDITLINKSA = record
cbStruct: DWORD; { Structure Size }
dwFlags: DWORD; { IN-OUT: Flags }
hWndOwner: HWnd; { Owning window }
lpszCaption: PAnsiChar; { Dialog caption bar contents }
lpfnHook: TFNOleUIHook; { Hook callback }
lCustData: LPARAM; { Custom data to pass to hook }
hInstance: HINST; { Instance for customized template name }
lpszTemplate: PAnsiChar; { Customized template name }
hResource: HRsrc; { Customized template handle }
OleUILinkContainer: IOleUILinkContainer; { IN: Interface to manipulate
links in the container }
end;
{$EXTERNALSYM tagOLEUIEDITLINKSA}
tagOLEUIEDITLINKSW = record
cbStruct: DWORD; { Structure Size }
dwFlags: DWORD; { IN-OUT: Flags }
hWndOwner: HWnd; { Owning window }
lpszCaption: PWideChar; { Dialog caption bar contents }
lpfnHook: TFNOleUIHook; { Hook callback }
lCustData: LPARAM; { Custom data to pass to hook }
hInstance: HINST; { Instance for customized template name }
lpszTemplate: PWideChar; { Customized template name }
hResource: HRsrc; { Customized template handle }
OleUILinkContainer: IOleUILinkContainer; { IN: Interface to manipulate
links in the container }
end;
{$EXTERNALSYM tagOLEUIEDITLINKSW}
tagOLEUIEDITLINKS = tagOLEUIEDITLINKSW;
TOleUIEditLinksA = tagOLEUIEDITLINKSA;
TOleUIEditLinksW = tagOLEUIEDITLINKSW;
TOleUIEditLinks = TOleUIEditLinksW;
const
{$EXTERNALSYM OLEUI_ELERR_LINKCNTRNULL}
OLEUI_ELERR_LINKCNTRNULL = OLEUI_ERR_STANDARDMAX + 0;
{$EXTERNALSYM OLEUI_ELERR_LINKCNTRINVALID}
OLEUI_ELERR_LINKCNTRINVALID = OLEUI_ERR_STANDARDMAX + 1;
function OleUIEditLinks(var Info: TOleUIEditLinks): Integer; stdcall;
{$EXTERNALSYM OleUIEditLinks}
function OleUIEditLinksA(var Info: TOleUIEditLinksA): Integer; stdcall;
{$EXTERNALSYM OleUIEditLinksA}
function OleUIEditLinksW(var Info: TOleUIEditLinksW): Integer; stdcall;
{$EXTERNALSYM OleUIEditLinksW}
{ Edit Links flags }
const
{$EXTERNALSYM ELF_SHOWHELP}
ELF_SHOWHELP = $00000001;
{$EXTERNALSYM ELF_DISABLEUPDATENOW}
ELF_DISABLEUPDATENOW = $00000002;
{$EXTERNALSYM ELF_DISABLEOPENSOURCE}
ELF_DISABLEOPENSOURCE = $00000004;
{$EXTERNALSYM ELF_DISABLECHANGESOURCE}
ELF_DISABLECHANGESOURCE = $00000008;
{$EXTERNALSYM ELF_DISABLECANCELLINK}
ELF_DISABLECANCELLINK = $00000010;
{ **** Change Icon dialog **** }
type
POleUIChangeIconA = ^TOleUIChangeIconA;
POleUIChangeIconW = ^TOleUIChangeIconW;
POleUIChangeIcon = POleUIChangeIconW;
tagOLEUICHANGEICONA = record
cbStruct: DWORD; { Structure Size }
dwFlags: DWORD; { IN-OUT: Flags }
hWndOwner: HWnd; { Owning window }
lpszCaption: PAnsiChar; { Dialog caption bar contents }
lpfnHook: TFNOleUIHook; { Hook callback }
lCustData: LPARAM; { Custom data to pass to hook }
hInstance: HInst; { Instance for customized template name }
lpszTemplate: PAnsiChar; { Customized template name }
hResource: HRsrc; { Customized template handle }
hMetaPict: HGlobal; { IN-OUT: Current and final image.
Source of the icon is embedded in
the metafile itself }
clsid: TCLSID; { IN: class used to get Default icon }
szIconExe: array[0..MAX_PATH - 1] of AnsiChar; { IN: exlicit icon source path }
cchIconExe: Integer; { IN: number of characters in szIconExe }
end;
{$EXTERNALSYM tagOLEUICHANGEICONA}
tagOLEUICHANGEICONW = record
cbStruct: DWORD; { Structure Size }
dwFlags: DWORD; { IN-OUT: Flags }
hWndOwner: HWnd; { Owning window }
lpszCaption: PWideChar; { Dialog caption bar contents }
lpfnHook: TFNOleUIHook; { Hook callback }
lCustData: LPARAM; { Custom data to pass to hook }
hInstance: HInst; { Instance for customized template name }
lpszTemplate: PWideChar; { Customized template name }
hResource: HRsrc; { Customized template handle }
hMetaPict: HGlobal; { IN-OUT: Current and final image.
Source of the icon is embedded in
the metafile itself }
clsid: TCLSID; { IN: class used to get Default icon }
szIconExe: array[0..MAX_PATH - 1] of WideChar; { IN: exlicit icon source path }
cchIconExe: Integer; { IN: number of characters in szIconExe }
end;
{$EXTERNALSYM tagOLEUICHANGEICONW}
tagOLEUICHANGEICON = tagOLEUICHANGEICONW;
TOleUIChangeIconA = tagOLEUICHANGEICONA;
TOleUIChangeIconW = tagOLEUICHANGEICONW;
TOleUIChangeIcon = TOleUIChangeIconW;
function OleUIChangeIcon(var Info: TOleUIChangeIcon): Integer; stdcall;
{$EXTERNALSYM OleUIChangeIcon}
function OleUIChangeIconA(var Info: TOleUIChangeIconA): Integer; stdcall;
{$EXTERNALSYM OleUIChangeIconA}
function OleUIChangeIconW(var Info: TOleUIChangeIconW): Integer; stdcall;
{$EXTERNALSYM OleUIChangeIconW}
{ Change Icon flags }
const
{$EXTERNALSYM CIF_SHOWHELP}
CIF_SHOWHELP = $00000001;
{$EXTERNALSYM CIF_SELECTCURRENT}
CIF_SELECTCURRENT = $00000002;
{$EXTERNALSYM CIF_SELECTDEFAULT}
CIF_SELECTDEFAULT = $00000004;
{$EXTERNALSYM CIF_SELECTFROMFILE}
CIF_SELECTFROMFILE = $00000008;
{$EXTERNALSYM CIF_USEICONEXE}
CIF_USEICONEXE = $00000010;
{ Change Icon specific error codes }
const
{$EXTERNALSYM OLEUI_CIERR_MUSTHAVECLSID}
OLEUI_CIERR_MUSTHAVECLSID = OLEUI_ERR_STANDARDMAX + 0;
{$EXTERNALSYM OLEUI_CIERR_MUSTHAVECURRENTMETAFILE}
OLEUI_CIERR_MUSTHAVECURRENTMETAFILE = OLEUI_ERR_STANDARDMAX + 1;
{$EXTERNALSYM OLEUI_CIERR_SZICONEXEINVALID}
OLEUI_CIERR_SZICONEXEINVALID = OLEUI_ERR_STANDARDMAX + 2;
{ Property used by ChangeIcon dialog to give its parent window access to
its hDlg. The PasteSpecial dialog may need to force the ChgIcon dialog
down if the clipboard contents change underneath it. If so it will send
a IDCANCEL command to the ChangeIcon dialog. }
const
{$EXTERNALSYM PROP_HWND_CHGICONDLG}
PROP_HWND_CHGICONDLG = 'HWND_CIDLG';
{ **** Convert dialog **** }
type
POleUIConvertA = ^TOleUIConvertA;
POleUIConvertW = ^TOleUIConvertW;
POleUIConvert = POleUIConvertW;
tagOLEUICONVERTA = record
cbStruct: DWORD; { Structure Size }
dwFlags: DWORD; { IN-OUT: Flags }
hWndOwner: HWnd; { Owning window }
lpszCaption: PAnsiChar; { Dialog caption bar contents }
lpfnHook: TFNOleUIHook; { Hook callback }
lCustData: LPARAM; { Custom data to pass to hook }
hInstance: HInst; { Instance for customized template name }
lpszTemplate: PAnsiChar; { Customized template name }
hResource: HRsrc; { Customized template handle }
clsid: TCLSID; { IN: Class ID sent in to dialog: IN only }
clsidConvertDefault: TCLSID; { IN: use as convert default: IN only }
clsidActivateDefault: TCLSID; { IN: use as activate default: IN only }
clsidNew: TCLSID; { OUT: Selected Class ID }
dvAspect: DWORD; { IN-OUT: either DVASPECT_CONTENT or
DVASPECT_ICON }
wFormat: Word; { IN" Original data format }
fIsLinkedObject: BOOL; { IN: true if object is linked }
hMetaPict: HGlobal; { IN-OUT: metafile icon image }
lpszUserType: PAnsiChar; { IN-OUT: user type name of original class.
We'll do lookup if NULL. This gets freed
on exit }
fObjectsIconChanged: BOOL; { OUT: TRUE == ChangeIcon was called }
lpszDefLabel: PAnsiChar; { IN-OUT: default label to use for icon.
if NULL, the short user type name
will be used. if the object is a
link, the caller should pass the
DisplayName of the link source
This gets freed on exit }
cClsidExclude: UINT; { IN: No. of CLSIDs in lpClsidExclude }
lpClsidExclude: PCLSID; { IN: List of CLSIDs to exclude from list }
end;
{$EXTERNALSYM tagOLEUICONVERTA}
tagOLEUICONVERTW = record
cbStruct: DWORD; { Structure Size }
dwFlags: DWORD; { IN-OUT: Flags }
hWndOwner: HWnd; { Owning window }
lpszCaption: PWideChar; { Dialog caption bar contents }
lpfnHook: TFNOleUIHook; { Hook callback }
lCustData: LPARAM; { Custom data to pass to hook }
hInstance: HInst; { Instance for customized template name }
lpszTemplate: PWideChar; { Customized template name }
hResource: HRsrc; { Customized template handle }
clsid: TCLSID; { IN: Class ID sent in to dialog: IN only }
clsidConvertDefault: TCLSID; { IN: use as convert default: IN only }
clsidActivateDefault: TCLSID; { IN: use as activate default: IN only }
clsidNew: TCLSID; { OUT: Selected Class ID }
dvAspect: DWORD; { IN-OUT: either DVASPECT_CONTENT or
DVASPECT_ICON }
wFormat: Word; { IN" Original data format }
fIsLinkedObject: BOOL; { IN: true if object is linked }
hMetaPict: HGlobal; { IN-OUT: metafile icon image }
lpszUserType: PWideChar; { IN-OUT: user type name of original class.
We'll do lookup if NULL. This gets freed
on exit }
fObjectsIconChanged: BOOL; { OUT: TRUE == ChangeIcon was called }
lpszDefLabel: PWideChar; { IN-OUT: default label to use for icon.
if NULL, the short user type name
will be used. if the object is a
link, the caller should pass the
DisplayName of the link source
This gets freed on exit }
cClsidExclude: UINT; { IN: No. of CLSIDs in lpClsidExclude }
lpClsidExclude: PCLSID; { IN: List of CLSIDs to exclude from list }
end;
{$EXTERNALSYM tagOLEUICONVERTW}
tagOLEUICONVERT = tagOLEUICONVERTW;
TOleUIConvertA = tagOLEUICONVERTA;
TOleUIConvertW = tagOLEUICONVERTW;
TOleUIConvert = TOleUIConvertW;
function OleUIConvert(var Info: TOleUIConvert): Integer; stdcall;
{$EXTERNALSYM OleUIConvert}
function OleUIConvertA(var Info: TOleUIConvertA): Integer; stdcall;
{$EXTERNALSYM OleUIConvertA}
function OleUIConvertW(var Info: TOleUIConvertW): Integer; stdcall;
{$EXTERNALSYM OleUIConvertW}
{ Determine if there is at least one class that can Convert or ActivateAs
the given clsid }
function OleUICanConvertOrActivateAs(const clsid: TCLSID;
fIsLinkedObject: BOOL; wFormat: Word): BOOL; stdcall;
{$EXTERNALSYM OleUICanConvertOrActivateAs}
{ Convert Dialog flags }
const
{$EXTERNALSYM CF_SHOWHELPBUTTON}
CF_SHOWHELPBUTTON = $00000001;
{$EXTERNALSYM CF_SETCONVERTDEFAULT}
CF_SETCONVERTDEFAULT = $00000002;
{$EXTERNALSYM CF_SETACTIVATEDEFAULT}
CF_SETACTIVATEDEFAULT = $00000004;
{$EXTERNALSYM CF_SELECTCONVERTTO}
CF_SELECTCONVERTTO = $00000008;
{$EXTERNALSYM CF_SELECTACTIVATEAS}
CF_SELECTACTIVATEAS = $00000010;
{$EXTERNALSYM CF_DISABLEDISPLAYASICON}
CF_DISABLEDISPLAYASICON = $00000020;
{$EXTERNALSYM CF_DISABLEACTIVATEAS}
CF_DISABLEACTIVATEAS = $00000040;
{$EXTERNALSYM CF_HIDECHANGEICON}
CF_HIDECHANGEICON = $00000080;
{$EXTERNALSYM CF_CONVERTONLY}
CF_CONVERTONLY = $00000100;
{ Convert specific error codes }
const
{$EXTERNALSYM OLEUI_CTERR_CLASSIDINVALID}
OLEUI_CTERR_CLASSIDINVALID = OLEUI_ERR_STANDARDMAX + 1;
{$EXTERNALSYM OLEUI_CTERR_DVASPECTINVALID}
OLEUI_CTERR_DVASPECTINVALID = OLEUI_ERR_STANDARDMAX + 2;
{$EXTERNALSYM OLEUI_CTERR_CBFORMATINVALID}
OLEUI_CTERR_CBFORMATINVALID = OLEUI_ERR_STANDARDMAX + 3;
{$EXTERNALSYM OLEUI_CTERR_HMETAPICTINVALID}
OLEUI_CTERR_HMETAPICTINVALID = OLEUI_ERR_STANDARDMAX + 4;
{$EXTERNALSYM OLEUI_CTERR_STRINGINVALID}
OLEUI_CTERR_STRINGINVALID = OLEUI_ERR_STANDARDMAX + 5;
{ **** Busy dialog **** }
type
POleUIBusyA = ^TOleUIBusyA;
POleUIBusyW = ^TOleUIBusyW;
POleUIBusy = POleUIBusyW;
tagOLEUIBUSYA = record
cbStruct: DWORD; { Structure Size }
dwFlags: DWORD; { IN-OUT: Flags }
hWndOwner: HWnd; { Owning window }
lpszCaption: PAnsiChar; { Dialog caption bar contents }
lpfnHook: TFNOleUIHook; { Hook callback }
lCustData: LPARAM; { Custom data to pass to hook }
hInstance: HInst; { Instance for customized template name }
lpszTemplate: PAnsiChar; { Customized template name }
hResource: HRsrc; { Customized template handle }
task: HTask; { IN: HTask which is blocking }
lphWndDialog: ^HWnd; { IN: Dialog's HWND is placed here }
end;
{$EXTERNALSYM tagOLEUIBUSYA}
tagOLEUIBUSYW = record
cbStruct: DWORD; { Structure Size }
dwFlags: DWORD; { IN-OUT: Flags }
hWndOwner: HWnd; { Owning window }
lpszCaption: PWideChar; { Dialog caption bar contents }
lpfnHook: TFNOleUIHook; { Hook callback }
lCustData: LPARAM; { Custom data to pass to hook }
hInstance: HInst; { Instance for customized template name }
lpszTemplate: PWideChar; { Customized template name }
hResource: HRsrc; { Customized template handle }
task: HTask; { IN: HTask which is blocking }
lphWndDialog: ^HWnd; { IN: Dialog's HWND is placed here }
end;
{$EXTERNALSYM tagOLEUIBUSYW}
tagOLEUIBUSY = tagOLEUIBUSYW;
TOleUIBusyA = tagOLEUIBUSYA;
TOleUIBusyW = tagOLEUIBUSYW;
TOleUIBusy = TOleUIBusyW;
function OleUIBusy(var Info: TOleUIBusy): Integer; stdcall;
{$EXTERNALSYM OleUIBusy}
function OleUIBusyA(var Info: TOleUIBusyA): Integer; stdcall;
{$EXTERNALSYM OleUIBusyA}
function OleUIBusyW(var Info: TOleUIBusyW): Integer; stdcall;
{$EXTERNALSYM OleUIBusyW}
{ Flags for the Busy dialog }
const
{$EXTERNALSYM BZ_DISABLECANCELBUTTON}
BZ_DISABLECANCELBUTTON = $00000001;
{$EXTERNALSYM BZ_DISABLESWITCHTOBUTTON}
BZ_DISABLESWITCHTOBUTTON = $00000002;
{$EXTERNALSYM BZ_DISABLERETRYBUTTON}
BZ_DISABLERETRYBUTTON = $00000004;
{$EXTERNALSYM BZ_NOTRESPONDINGDIALOG}
BZ_NOTRESPONDINGDIALOG = $00000008;
{ Busy specific error/return codes }
const
{$EXTERNALSYM OLEUI_BZERR_HTASKINVALID}
OLEUI_BZERR_HTASKINVALID = OLEUI_ERR_STANDARDMAX + 0;
{$EXTERNALSYM OLEUI_BZ_SWITCHTOSELECTED}
OLEUI_BZ_SWITCHTOSELECTED = OLEUI_ERR_STANDARDMAX + 1;
{$EXTERNALSYM OLEUI_BZ_RETRYSELECTED}
OLEUI_BZ_RETRYSELECTED = OLEUI_ERR_STANDARDMAX + 2;
{$EXTERNALSYM OLEUI_BZ_CALLUNBLOCKED}
OLEUI_BZ_CALLUNBLOCKED = OLEUI_ERR_STANDARDMAX + 3;
{ **** Object Properties dialog **** }
type
IOleUIObjInfo = interface(IUnknown)
['{00000000-0000-0000-0000-000000000000}'] //!!!
function GetObjectInfo(dwObject: Longint;
var dwObjSize: Longint; var lpszLabel: PChar;
var lpszType: PChar; var lpszShortType: PChar;
var lpszLocation: PChar): HResult; stdcall;
function GetConvertInfo(dwObject: Longint; var ClassID: TCLSID;
var wFormat: Word; var ConvertDefaultClassID: TCLSID;
var lpClsidExclude: PCLSID; var cClsidExclude: Longint): HResult; stdcall;
function ConvertObject(dwObject: Longint; const clsidNew: TCLSID): HResult; stdcall;
function GetViewInfo(dwObject: Longint; var hMetaPict: HGlobal;
var dvAspect: Longint; var nCurrentScale: Integer): HResult; stdcall;
function SetViewInfo(dwObject: Longint; hMetaPict: HGlobal;
dvAspect: Longint; nCurrentScale: Integer;
bRelativeToOrig: BOOL): HResult; stdcall;
end;
{$EXTERNALSYM IOleUIObjInfo}
{$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IOleUIObjInfo)' }
type
IOleUILinkInfo = interface(IOleUILinkContainer)
['{00000000-0000-0000-0000-000000000000}'] //!!!
function GetLastUpdate(dwLink: Longint; var LastUpdate: TFileTime): HResult; stdcall;
end;
{$EXTERNALSYM IOleUILinkInfo}
{$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IOleUILinkInfo)' }
type
POleUIGnrlPropsA = ^TOleUIGnrlPropsA;
POleUIGnrlPropsW = ^TOleUIGnrlPropsW;
POleUIGnrlProps = POleUIGnrlPropsW;
tagOLEUIGNRLPROPSA = record
cbStruct: DWORD;
dwFlags: DWORD;
dwReserved1: array[1..2] of DWORD;
lpfnHook: TFNOleUIHook;
lCustData: LPARAM;
dwReserved2: array[1..3] of DWORD;
lpOP: POleUIGnrlPropsA;
end;
{$EXTERNALSYM tagOLEUIGNRLPROPSA}
tagOLEUIGNRLPROPSW = record
cbStruct: DWORD;
dwFlags: DWORD;
dwReserved1: array[1..2] of DWORD;
lpfnHook: TFNOleUIHook;
lCustData: LPARAM;
dwReserved2: array[1..3] of DWORD;
lpOP: POleUIGnrlPropsW;
end;
{$EXTERNALSYM tagOLEUIGNRLPROPSW}
tagOLEUIGNRLPROPS = tagOLEUIGNRLPROPSW;
TOleUIGnrlPropsA = tagOLEUIGNRLPROPSA;
TOleUIGnrlPropsW = tagOLEUIGNRLPROPSW;
TOleUIGnrlProps = TOleUIGnrlPropsW;
OLEUIGNRLPROPSA = tagOLEUIGNRLPROPSA;
{$EXTERNALSYM OLEUIGNRLPROPSA}
OLEUIGNRLPROPSW = tagOLEUIGNRLPROPSW;
{$EXTERNALSYM OLEUIGNRLPROPSW}
OLEUIGNRLPROPS = OLEUIGNRLPROPSW;
type
POleUIViewPropsA = ^TOleUIViewPropsA;
POleUIViewPropsW = ^TOleUIViewPropsW;
POleUIViewProps = POleUIViewPropsW;
tagOLEUIVIEWPROPSA = record
cbStruct: DWORD;
dwFlags: DWORD;
dwReserved1: array[1..2] of DWORD;
lpfnHook: TFNOleUIHook;
lCustData: LPARAM;
dwReserved2: array[1..3] of DWORD;
lpOP: POleUIViewPropsA;
nScaleMin: Integer;
nScaleMax: Integer;
end;
{$EXTERNALSYM tagOLEUIVIEWPROPSA}
tagOLEUIVIEWPROPSW = record
cbStruct: DWORD;
dwFlags: DWORD;
dwReserved1: array[1..2] of DWORD;
lpfnHook: TFNOleUIHook;
lCustData: LPARAM;
dwReserved2: array[1..3] of DWORD;
lpOP: POleUIViewPropsW;
nScaleMin: Integer;
nScaleMax: Integer;
end;
{$EXTERNALSYM tagOLEUIVIEWPROPSW}
tagOLEUIVIEWPROPS = tagOLEUIVIEWPROPSW;
TOleUIViewPropsA = tagOLEUIVIEWPROPSA;
TOleUIViewPropsW = tagOLEUIVIEWPROPSW;
TOleUIViewProps = TOleUIViewPropsW;
OLEUIVIEWPROPSA = tagOLEUIVIEWPROPSA;
{$EXTERNALSYM OLEUIVIEWPROPSA}
OLEUIVIEWPROPSW = tagOLEUIVIEWPROPSW;
{$EXTERNALSYM OLEUIVIEWPROPSW}
OLEUIVIEWPROPS = OLEUIVIEWPROPSW;
{ Flags for TOleUIViewProps }
const
{$EXTERNALSYM VPF_SELECTRELATIVE}
VPF_SELECTRELATIVE = $00000001; { IN: relative to orig }
{$EXTERNALSYM VPF_DISABLERELATIVE}
VPF_DISABLERELATIVE = $00000002; { IN: disable relative to orig }
{$EXTERNALSYM VPF_DISABLESCALE}
VPF_DISABLESCALE = $00000004; { IN: disable scale option }
type
POleUILinkPropsA = ^TOleUILinkPropsA;
POleUILinkPropsW = ^TOleUILinkPropsW;
POleUILinkProps = POleUILinkPropsW;
tagOLEUILINKPROPSA = record
cbStruct: DWORD;
dwFlags: DWORD;
dwReserved1: array[1..2] of DWORD;
lpfnHook: TFNOleUIHook;
lCustData: LPARAM;
dwReserved2: array[1..3] of DWORD;
lpOP: POleUILinkPropsA;
end;
{$EXTERNALSYM tagOLEUILINKPROPSA}
tagOLEUILINKPROPSW = record
cbStruct: DWORD;
dwFlags: DWORD;
dwReserved1: array[1..2] of DWORD;
lpfnHook: TFNOleUIHook;
lCustData: LPARAM;
dwReserved2: array[1..3] of DWORD;
lpOP: POleUILinkPropsW;
end;
{$EXTERNALSYM tagOLEUILINKPROPSW}
tagOLEUILINKPROPS = tagOLEUILINKPROPSW;
TOleUILinkPropsA = tagOLEUILINKPROPSA;
TOleUILinkPropsW = tagOLEUILINKPROPSW;
TOleUILinkProps = TOleUILinkPropsW;
OLEUILINKPROPSA = tagOLEUILINKPROPSA;
{$EXTERNALSYM OLEUILINKPROPSA}
OLEUILINKPROPSW = tagOLEUILINKPROPSW;
{$EXTERNALSYM OLEUILINKPROPSW}
OLEUILINKPROPS = OLEUILINKPROPSW;
type
POleUIObjectPropsA = ^TOleUIObjectPropsA;
POleUIObjectPropsW = ^TOleUIObjectPropsW;
POleUIObjectProps = POleUIObjectPropsW;
tagOLEUIOBJECTPROPSA = record
cbStruct: Longint; { Structure Size }
dwFlags: Longint; { IN-OUT: global flags for the sheet }
lpPS: PPropSheetHeader; { IN: property sheet header }
dwObject: Longint; { IN: identifier for the object }
lpObjInfo: IOleUIObjInfo; { IN: interface to manipulate object }
dwLink: Longint; { IN: identifier for the link }
lpLinkInfo: IOleUILinkInfo; { IN: interface to manipulate link }
lpGP: POleUIGnrlPropsA; { IN: general page }
lpVP: POleUIViewPropsA; { IN: view page }
lpLP: POleUILinkPropsA; { IN: link page }
end;
{$EXTERNALSYM tagOLEUIOBJECTPROPSA}
tagOLEUIOBJECTPROPSW = record
cbStruct: Longint; { Structure Size }
dwFlags: Longint; { IN-OUT: global flags for the sheet }
lpPS: PPropSheetHeader; { IN: property sheet header }
dwObject: Longint; { IN: identifier for the object }
lpObjInfo: IOleUIObjInfo; { IN: interface to manipulate object }
dwLink: Longint; { IN: identifier for the link }
lpLinkInfo: IOleUILinkInfo; { IN: interface to manipulate link }
lpGP: POleUIGnrlPropsW; { IN: general page }
lpVP: POleUIViewPropsW; { IN: view page }
lpLP: POleUILinkPropsW; { IN: link page }
end;
{$EXTERNALSYM tagOLEUIOBJECTPROPSW}
tagOLEUIOBJECTPROPS = tagOLEUIOBJECTPROPSW;
TOleUIObjectPropsA = tagOLEUIOBJECTPROPSA;
TOleUIObjectPropsW = tagOLEUIOBJECTPROPSW;
TOleUIObjectProps = TOleUIObjectPropsW;
OLEUIOBJECTPROPSA = tagOLEUIOBJECTPROPSA;
{$EXTERNALSYM OLEUIOBJECTPROPSA}
OLEUIOBJECTPROPSW = tagOLEUIOBJECTPROPSW;
{$EXTERNALSYM OLEUIOBJECTPROPSW}
OLEUIOBJECTPROPS = OLEUIOBJECTPROPSW;
function OleUIObjectProperties(var Info: TOleUIObjectProps): Integer; stdcall;
{$EXTERNALSYM OleUIObjectProperties}
function OleUIObjectPropertiesA(var Info: TOleUIObjectPropsA): Integer; stdcall;
{$EXTERNALSYM OleUIObjectPropertiesA}
function OleUIObjectPropertiesW(var Info: TOleUIObjectPropsW): Integer; stdcall;
{$EXTERNALSYM OleUIObjectPropertiesW}
{ Flags for OLEUIOBJECTPROPS }
const
{$EXTERNALSYM OPF_OBJECTISLINK}
OPF_OBJECTISLINK = $00000001;
{$EXTERNALSYM OPF_NOFILLDEFAULT}
OPF_NOFILLDEFAULT = $00000002;
{$EXTERNALSYM OPF_SHOWHELP}
OPF_SHOWHELP = $00000004;
{$EXTERNALSYM OPF_DISABLECONVERT}
OPF_DISABLECONVERT = $00000008;
{ Errors for OleUIObjectProperties }
const
{$EXTERNALSYM OLEUI_OPERR_SUBPROPNULL}
OLEUI_OPERR_SUBPROPNULL = OLEUI_ERR_STANDARDMAX + 0;
{$EXTERNALSYM OLEUI_OPERR_SUBPROPINVALID}
OLEUI_OPERR_SUBPROPINVALID = OLEUI_ERR_STANDARDMAX + 1;
{$EXTERNALSYM OLEUI_OPERR_PROPSHEETNULL}
OLEUI_OPERR_PROPSHEETNULL = OLEUI_ERR_STANDARDMAX + 2;
{$EXTERNALSYM OLEUI_OPERR_PROPSHEETINVALID}
OLEUI_OPERR_PROPSHEETINVALID = OLEUI_ERR_STANDARDMAX + 3;
{$EXTERNALSYM OLEUI_OPERR_SUPPROP}
OLEUI_OPERR_SUPPROP = OLEUI_ERR_STANDARDMAX + 4;
{$EXTERNALSYM OLEUI_OPERR_PROPSINVALID}
OLEUI_OPERR_PROPSINVALID = OLEUI_ERR_STANDARDMAX + 5;
{$EXTERNALSYM OLEUI_OPERR_PAGESINCORRECT}
OLEUI_OPERR_PAGESINCORRECT = OLEUI_ERR_STANDARDMAX + 6;
{$EXTERNALSYM OLEUI_OPERR_INVALIDPAGES}
OLEUI_OPERR_INVALIDPAGES = OLEUI_ERR_STANDARDMAX + 7;
{$EXTERNALSYM OLEUI_OPERR_NOTSUPPORTED}
OLEUI_OPERR_NOTSUPPORTED = OLEUI_ERR_STANDARDMAX + 8;
{$EXTERNALSYM OLEUI_OPERR_DLGPROCNOTNULL}
OLEUI_OPERR_DLGPROCNOTNULL = OLEUI_ERR_STANDARDMAX + 9;
{$EXTERNALSYM OLEUI_OPERR_LPARAMNOTZERO}
OLEUI_OPERR_LPARAMNOTZERO = OLEUI_ERR_STANDARDMAX + 10;
{$EXTERNALSYM OLEUI_GPERR_STRINGINVALID}
OLEUI_GPERR_STRINGINVALID = OLEUI_ERR_STANDARDMAX + 11;
{$EXTERNALSYM OLEUI_GPERR_CLASSIDINVALID}
OLEUI_GPERR_CLASSIDINVALID = OLEUI_ERR_STANDARDMAX + 12;
{$EXTERNALSYM OLEUI_GPERR_LPCLSIDEXCLUDEINVALID}
OLEUI_GPERR_LPCLSIDEXCLUDEINVALID = OLEUI_ERR_STANDARDMAX + 13;
{$EXTERNALSYM OLEUI_GPERR_CBFORMATINVALID}
OLEUI_GPERR_CBFORMATINVALID = OLEUI_ERR_STANDARDMAX + 14;
{$EXTERNALSYM OLEUI_VPERR_METAPICTINVALID}
OLEUI_VPERR_METAPICTINVALID = OLEUI_ERR_STANDARDMAX + 15;
{$EXTERNALSYM OLEUI_VPERR_DVASPECTINVALID}
OLEUI_VPERR_DVASPECTINVALID = OLEUI_ERR_STANDARDMAX + 16;
{$EXTERNALSYM OLEUI_LPERR_LINKCNTRNULL}
OLEUI_LPERR_LINKCNTRNULL = OLEUI_ERR_STANDARDMAX + 17;
{$EXTERNALSYM OLEUI_LPERR_LINKCNTRINVALID}
OLEUI_LPERR_LINKCNTRINVALID = OLEUI_ERR_STANDARDMAX + 18;
{$EXTERNALSYM OLEUI_OPERR_PROPERTYSHEET}
OLEUI_OPERR_PROPERTYSHEET = OLEUI_ERR_STANDARDMAX + 19;
{ wParam used by PSM_QUERYSIBLINGS }
const
{$EXTERNALSYM OLEUI_QUERY_GETCLASSID}
OLEUI_QUERY_GETCLASSID = $FF00; { override class id for icon }
{$EXTERNALSYM OLEUI_QUERY_LINKBROKEN}
OLEUI_QUERY_LINKBROKEN = $FF01; { after link broken }
implementation
const
OleDlgDLL = 'oledlg.dll';
function OleUIAddVerbMenu; external OleDlgDLL name 'OleUIAddVerbMenuW';
function OleUIAddVerbMenuA; external OleDlgDLL name 'OleUIAddVerbMenuA';
function OleUIAddVerbMenuW; external OleDlgDLL name 'OleUIAddVerbMenuW';
function OleUIInsertObject; external OleDlgDLL name 'OleUIInsertObjectW';
function OleUIInsertObjectA; external OleDlgDLL name 'OleUIInsertObjectA';
function OleUIInsertObjectW; external OleDlgDLL name 'OleUIInsertObjectW';
function OleUIPasteSpecial; external OleDlgDLL name 'OleUIPasteSpecialW';
function OleUIPasteSpecialA; external OleDlgDLL name 'OleUIPasteSpecialA';
function OleUIPasteSpecialW; external OleDlgDLL name 'OleUIPasteSpecialW';
function OleUIEditLinks; external OleDlgDLL name 'OleUIEditLinksW';
function OleUIEditLinksA; external OleDlgDLL name 'OleUIEditLinksA';
function OleUIEditLinksW; external OleDlgDLL name 'OleUIEditLinksW';
function OleUIChangeIcon; external OleDlgDLL name 'OleUIChangeIconW';
function OleUIChangeIconA; external OleDlgDLL name 'OleUIChangeIconA';
function OleUIChangeIconW; external OleDlgDLL name 'OleUIChangeIconW';
function OleUIConvert; external OleDlgDLL name 'OleUIConvertW';
function OleUIConvertA; external OleDlgDLL name 'OleUIConvertA';
function OleUIConvertW; external OleDlgDLL name 'OleUIConvertW';
function OleUICanConvertOrActivateAs; external OleDlgDLL name 'OleUICanConvertOrActivateAs';
function OleUIBusy; external OleDlgDLL name 'OleUIBusyW';
function OleUIBusyA; external OleDlgDLL name 'OleUIBusyA';
function OleUIBusyW; external OleDlgDLL name 'OleUIBusyW';
function OleUIObjectProperties; external OleDlgDLL name 'OleUIObjectPropertiesW';
function OleUIObjectPropertiesA; external OleDlgDLL name 'OleUIObjectPropertiesA';
function OleUIObjectPropertiesW; external OleDlgDLL name 'OleUIObjectPropertiesW';
end.
|
unit Model.DMConnZeos;
interface
uses
SysUtils,
Classes,
DB,
// zeos
ZConnection,
ZAbstractConnection,
ZDataset,
ZAbstractDataset,
ZAbstractRODataset,
ZSqlMonitor,
// myclasse
Model.Interf;
type
TDMConnZeos = class(TDataModule, iModelConn)
ZConnection1: TZConnection;
ZSQLMonitor1: TZSQLMonitor;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function ConnZeos: iModelQuery;
end;
TModelConnZeosQuery = class(TInterfacedObject, iModelQuery)
private
ZConnection1: TZConnection;
ZQuery1: TZQuery;
FParams : TParams;
public
constructor Create;
destructor Destroy; override;
class function New : iModelQuery;
procedure ExecSQL;
procedure Open(aSQL : String); overload;
procedure Open; overload;
function SQL : TStrings;
function Params : TParams;
function DataSet : TDataSet;
end;
var
DMConnZeos: TDMConnZeos;
implementation
{$R *.dfm}
{ TModelConexaoZeos }
function TDMConnZeos.ConnZeos: iModelQuery;
begin
Result := TModelConnZeosQuery.New;
end;
{ TModelQueryZeos }
constructor TModelConnZeosQuery.Create;
begin
// sqlite
ZConnection1 := DMConnZeos.ZConnection1;
ZQuery1 := TZQuery.Create(nil);
ZQuery1.Connection := ZConnection1;
// SQL Server
//ZConnection1.Protocol := 'ado';
//ZConnection1.Database := 'Provider=SQLNCLI.1;Password=rkc;Persist Security Info=True;User ID=sa;Initial Catalog=NFE;Data Source=localhost';
end;
function TModelConnZeosQuery.DataSet: TDataSet;
begin
Result := ZQuery1;
end;
destructor TModelConnZeosQuery.Destroy;
begin
FreeAndNil(ZQuery1);
if Assigned(FParams) then
FreeAndNil(FParams);
inherited;
end;
procedure TModelConnZeosQuery.ExecSQL;
begin
// ZQuery1.Close;
ZQuery1.Params.Assign(FParams);
ZQuery1.Prepare;
ZQuery1.ExecSQL;
if Assigned(FParams) then
FreeAndNil(FParams);
end;
procedure TModelConnZeosQuery.Open(aSQL: String);
begin
ZQuery1.DisableControls;
try
ZQuery1.Close;
ZQuery1.SQL.Clear;
ZQuery1.SQL.Add(aSQL);
ZQuery1.Open;
finally
ZQuery1.EnableControls;
end;
end;
class function TModelConnZeosQuery.New: iModelQuery;
begin
Result := Self.Create;
end;
procedure TModelConnZeosQuery.Open;
begin
ZQuery1.Close;
if Assigned(FParams) then
ZQuery1.Params.Assign(FParams);
ZQuery1.Prepare;
ZQuery1.Open;
if Assigned(FParams) then
FreeAndNil(FParams);
end;
function TModelConnZeosQuery.Params: TParams;
begin
if not Assigned(FParams) then
begin
FParams := TParams.Create(nil);
FParams.Assign(ZQuery1.Params);
end;
Result := FParams;
end;
function TModelConnZeosQuery.SQL: TStrings;
begin
Result := ZQuery1.SQL;
end;
procedure TDMConnZeos.DataModuleCreate(Sender: TObject);
begin
ZConnection1.Protocol := 'sqlite';
ZConnection1.LibraryLocation := 'sqlite3.dll';
ZConnection1.Database := '..\DB\database.sdb3';
end;
end.
|
unit Form.ConnectionDialog;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Form.BaseEditForm, cxGraphics,
cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore,
dxSkinMetropolis, System.ImageList, Vcl.ImgList, cxClasses, dxSkinsForm,
Vcl.StdCtrls, cxButtons, Vcl.ExtCtrls, cxControls, cxContainer, cxEdit,
cxTextEdit, cxMaskEdit, cxDropDownEdit, cxPropertiesStore;
type
TfrmDlgConnection = class(TfrmBaseEditor)
cbbConnections: TcxComboBox;
psDefaultParams: TcxPropertiesStore;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
function GetDBFile: string;
public
property DBFile: string read GetDBFile;
end;
var
frmDlgConnection: TfrmDlgConnection;
implementation
uses
System.IniFiles, synautil;
{$R *.dfm}
procedure TfrmDlgConnection.FormCreate(Sender: TObject);
var
ini: TIniFile;
begin
ini := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'conn.ini');
try
ini.ReadSectionValues('Database', cbbConnections.Properties.Items);
finally
ini.Free;
end;
psDefaultParams.RestoreFrom;
end;
procedure TfrmDlgConnection.FormDestroy(Sender: TObject);
begin
inherited;
psDefaultParams.StoreTo();
end;
function TfrmDlgConnection.GetDBFile: string;
begin
Result := SeparateRight(cbbConnections.Text, '=');
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ SOAP client-side invoker }
{ }
{ Copyright (c) 2000 Inprise Corporation }
{ }
{*******************************************************}
unit SoapConn;
interface
uses
SysUtils, Variants, Classes, VarUtils, Midas, DBClient, SoapHTTPTrans, Rio, SoapHTTPClient;
type
TSoapConnection = class(TCustomRemoteServer)
private
FRIO: THTTPRIO;
FURL: string;
FAppServer: IAppServer;
function GetAgent: string;
function GetPassword: string;
function GetProxy: string;
function GetProxyByPass: string;
function GetUserName: string;
procedure SetAgent(const Value: string);
procedure SetPassword(const Value: string);
procedure SetProxy(const Value: string);
procedure SetProxyByPass(const Value: string);
procedure SetUserName(const Value: string);
protected
procedure DoConnect; override;
function GetConnected: Boolean; override;
function GetServerList: OleVariant; override;
procedure DoDisconnect; override;
procedure GetProviderNames(Proc: TGetStrProc); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetServer: IAppServer; override;
published
property Agent: string read GetAgent write SetAgent;
property Connected;
property Password: string read GetPassword write SetPassword;
property Proxy: string read GetProxy write SetProxy;
property ProxyByPass: string read GetProxyByPass write SetProxyByPass;
property URL: string read FURL write FURL;
property UserName: string read GetUserName write SetUserName;
end;
implementation
uses Windows, InvokeRegistry, SoapConst, Controls;
{ TSoapConnection }
constructor TSoapConnection.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TSoapConnection.Destroy;
begin
inherited;
end;
procedure TSoapConnection.DoDisconnect;
begin
inherited;
if Assigned(FRIO) then
FRIO := nil;
end;
procedure TSoapConnection.GetProviderNames(Proc: TGetStrProc);
var
List: Variant;
I: Integer;
begin
Connected := True;
VarClear(List);
try
List := FAppServer.AS_GetProviderNames;
except
{ Assume any errors means the list is not available. }
end;
if VarIsArray(List) and (VarArrayDimCount(List) = 1) then
for I := VarArrayLowBound(List, 1) to VarArrayHighBound(List, 1) do
Proc(List[I]);
end;
function TSoapConnection.GetServer: IAppServer;
begin
Connected := True;
Result := FAppServer;
end;
function TSoapConnection.GetServerList: OleVariant;
begin
end;
procedure TSoapConnection.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
end;
procedure TSoapConnection.DoConnect;
begin
if (URL = '') then
raise Exception.Create(SNoURL);
if not Assigned(FRIO) then
try
FRIO := THTTPRIO.Create(nil);
FAppServer := FRIO as IAppServer;
FRIO.URL := FURL;
except
Connected := False;
end;
end;
function TSoapConnection.GetConnected: Boolean;
begin
Result := Assigned(FRIO) and (Assigned(FRIO.HTTPWebNode));
end;
function TSoapConnection.GetAgent: string;
begin
if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then
Result := FRIO.HTTPWebNode.Agent;
end;
function TSoapConnection.GetPassword: string;
begin
if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then
Result := FRIO.HTTPWebNode.Password;
end;
function TSoapConnection.GetProxy: string;
begin
if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then
Result := FRIO.HTTPWebNode.Proxy;
end;
function TSoapConnection.GetProxyByPass: string;
begin
if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then
Result := FRIO.HTTPWebNode.ProxyByPass;
end;
function TSoapConnection.GetUserName: string;
begin
if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then
Result := FRIO.HTTPWebNode.Username;
end;
procedure TSoapConnection.SetAgent(const Value: string);
begin
if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then
FRIO.HTTPWebNode.Agent := Value
else if not (csLoading in ComponentState) then
raise Exception.Create(SNoURL);
end;
procedure TSoapConnection.SetPassword(const Value: string);
begin
if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then
FRIO.HTTPWebNode.Password := Value
else if not (csLoading in ComponentState) then
raise Exception.Create(SNoURL);
end;
procedure TSoapConnection.SetProxy(const Value: string);
begin
if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then
FRIO.HTTPWebNode.Proxy := Value
else if not (csLoading in ComponentState) then
raise Exception.Create(SNoURL);
end;
procedure TSoapConnection.SetProxyByPass(const Value: string);
begin
if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then
FRIO.HTTPWebNode.ProxyByPass := Value
else if not (csLoading in ComponentState) then
raise Exception.Create(SNoURL);
end;
procedure TSoapConnection.SetUserName(const Value: string);
begin
if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then
FRIO.HTTPWebNode.UserName := Value
else if not (csLoading in ComponentState) then
raise Exception.Create(SNoURL);
end;
initialization
GroupDescendentsWith(TSoapConnection, Controls.TControl);
InvRegistry.RegisterInterface(TypeInfo(IAppServer));
end.
|
unit SmallDownsizeBenchmark;
interface
uses
BenchmarkClassUnit, Math;
const
{The number of pointers}
NumPointers = 2000000;
{The maximum block size}
MaxBlockSize = 64;
type
TSmallDownsizeBench = class(TFastcodeMMBenchmark)
protected
FPointers: array[0..NumPointers - 1] of PChar;
public
constructor CreateBenchmark; override;
destructor Destroy; override;
procedure RunBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function GetSpeedWeight: Double; override;
class function GetCategory: TBenchmarkCategory; override;
end;
implementation
{ TSmallResizeBench }
constructor TSmallDownsizeBench.CreateBenchmark;
begin
inherited;
end;
destructor TSmallDownsizeBench.Destroy;
begin
inherited;
end;
class function TSmallDownsizeBench.GetBenchmarkDescription: string;
begin
Result := 'Allocates a small block and immediately resizes it to a smaller size. This checks '
+ ' that the block downsizing behaviour of the MM is acceptable. '
+ 'Benchmark submitted by Pierre le Riche.';
end;
class function TSmallDownsizeBench.GetBenchmarkName: string;
begin
Result := 'Small downsize benchmark';
end;
class function TSmallDownsizeBench.GetCategory: TBenchmarkCategory;
begin
Result := bmSingleThreadRealloc;
end;
class function TSmallDownsizeBench.GetSpeedWeight: Double;
begin
{Speed is not important here. It is just to check that the behaviour of the
MM is acceptable.}
Result := 0.2;
end;
procedure TSmallDownsizeBench.RunBenchmark;
var
i, j, LSize: integer;
begin
{Call the inherited handler}
inherited;
{Do the benchmark}
for i := 0 to high(FPointers) do
begin
{Get the initial block size}
LSize := MaxBlockSize + Random(3 * MaxBlockSize);
GetMem(FPointers[i], LSize);
FPointers[i][0] := #13;
FPointers[i][LSize - 1] := #13;
{Reallocate it a few times}
for j := 1 to 5 do
begin
LSize := Max(1, LSize - Random(MaxBlockSize));
ReallocMem(FPointers[i], LSize);
FPointers[i][LSize - 1] := #13;
end;
end;
{What we end with should be close to the peak usage}
UpdateUsageStatistics;
{Free the pointers}
for i := 0 to high(FPointers) do
FreeMem(FPointers[i]);
end;
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
//------------------------------------------------------------------------------
//单元说明:
// EasyPlate程序的公共方法单元
//主要实现:
//-----------------------------------------------------------------------------}
unit untEasyUtilMethod;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ShellAPI, StdCtrls, ActiveX, FileCtrl, UrlMon, TlHelp32, ExtCtrls,
ComObj, WinSock, ComCtrls, DB, ADODB, IdGlobal, ImageHlp, untEasyTabSet,
Menus, untEasyProgressBar;
type
//关闭子窗体事件类
TMDICloseNotify = procedure (Sender: TObject; var Action: TCloseAction) of object;
//插件导出函数
TShowBplForm = function (AParamList: TStrings): TForm; stdcall;
TSearchType = (stCurrent, stSub, stAll);
TCPUID = array[1..4] of Longint;
TVendor = array [0..11] of char;
TInformationStrings = ( isCompanyName, isFileDescription, isFileVersion,
isInternalName, isLegalCopyright, isOriginalFilename,
isProductName, isProductVersion, isComments,
isLegalTrademarks );
TFileTimeComparision = ( ftError, ftFileOneIsOlder, ftFileTimesAreEqual, ftFileTwoIsOlder );
TDriveType = (dtUnknown, dtNoDrive, dtFloppy, dtFixed, dtNetwork, dtCDROM, dtRAM);
TVolumeInfo = record
Name : String;
SerialNumber : DWORD;
MaxComponentLength : DWORD;
FileSystemFlags : DWORD;
FileSystemName : String;
end; // TVolumeInfo
PFixedFileInfo = ^TFixedFileInfo;
TFixedFileInfo = record
dwSignature : DWORD;
dwStrucVersion : DWORD;
wFileVersionMS : WORD; // Minor Version
wFileVersionLS : WORD; // Major Version
wProductVersionMS : WORD; // Build Number
wProductVersionLS : WORD; // Release Version
dwFileFlagsMask : DWORD;
dwFileFlags : DWORD;
dwFileOS : DWORD;
dwFileType : DWORD;
dwFileSubtype : DWORD;
dwFileDateMS : DWORD;
dwFileDateLS : DWORD;
end; // TFixedFileInfo
TSrbIoControl = packed record
HeaderLength : ULONG;
Signature : Array[0..7] of Char;
Timeout : ULONG;
ControlCode : ULONG;
ReturnCode : ULONG;
Length : ULONG;
end;
SRB_IO_CONTROL = TSrbIoControl;
PSrbIoControl = ^TSrbIoControl;
TIDERegs = packed record
bFeaturesReg : Byte; // Used for specifying SMART "commands".
bSectorCountReg : Byte; // IDE sector count register
bSectorNumberReg : Byte; // IDE sector number register
bCylLowReg : Byte; // IDE low order cylinder value
bCylHighReg : Byte; // IDE high order cylinder value
bDriveHeadReg : Byte; // IDE drive/head register
bCommandReg : Byte; // Actual IDE command.
bReserved : Byte; // reserved. Must be zero.
end;
IDEREGS = TIDERegs;
PIDERegs = ^TIDERegs;
TSendCmdInParams = packed record
cBufferSize : DWORD;
irDriveRegs : TIDERegs;
bDriveNumber : Byte;
bReserved : Array[0..2] of Byte;
dwReserved : Array[0..3] of DWORD;
bBuffer : Array[0..0] of Byte;
end;
SENDCMDINPARAMS = TSendCmdInParams;
PSendCmdInParams = ^TSendCmdInParams;
TIdSector = packed record
wGenConfig : Word;
wNumCyls : Word;
wReserved : Word;
wNumHeads : Word;
wBytesPerTrack : Word;
wBytesPerSector : Word;
wSectorsPerTrack : Word;
wVendorUnique : Array[0..2] of Word;
sSerialNumber : Array[0..19] of Char;
wBufferType : Word;
wBufferSize : Word;
wECCSize : Word;
sFirmwareRev : Array[0..7] of Char;
sModelNumber : Array[0..39] of Char;
wMoreVendorUnique : Word;
wDoubleWordIO : Word;
wCapabilities : Word;
wReserved1 : Word;
wPIOTiming : Word;
wDMATiming : Word;
wBS : Word;
wNumCurrentCyls : Word;
wNumCurrentHeads : Word;
wNumCurrentSectorsPerTrack : Word;
ulCurrentSectorCapacity : ULONG;
wMultSectorStuff : Word;
ulTotalAddressableSectors : ULONG;
wSingleWordDMA : Word;
wMultiWordDMA : Word;
bReserved : Array[0..127] of Byte;
end;
PIdSector = ^TIdSector;
const
NumberArray: array[0..9] of string =
('零', '壹','貳','叁','肆','伍','陆','柒','捌','玖');
//加密解密
C1 = 888888;
C2 = 999999;
{* 字符串加密用 }
XorKey:array[0..7] of Byte=(8,8,8,8,8,8,8,8); //$B2,$09,$AA,$55,$93,$6D,$84,$47
//CPU
IDE_ID_FUNCTION = $EC;
IDENTIFY_BUFFER_SIZE = 512;
DFP_RECEIVE_DRIVE_DATA = $0007c088;
IOCTL_SCSI_MINIPORT = $0004d008;
IOCTL_SCSI_MINIPORT_IDENTIFY = $001b0501;
DataSize = sizeof(TSendCmdInParams)-1+IDENTIFY_BUFFER_SIZE;
BufferSize = SizeOf(SRB_IO_CONTROL)+DataSize;
W9xBufferSize = IDENTIFY_BUFFER_SIZE+16;
PROCESSOR_INTEL_386 = 386;
PROCESSOR_INTEL_486 = 486;
PROCESSOR_INTEL_PENTIUM = 586;
PROCESSOR_MIPS_R4000 = 4000;
PROCESSOR_ALPHA_21064 = 21064;
//XML
//从XML文件提取模块信息 ./plugins/plugins-config.xml
{********************* 数字转换成人民币大写 ************} //*********** 数字转换成人民币大写
// 数字转与大写
function NumToRMB_0(AMoney: string): string;
// 数字转换成RMB 转换不超过千亿
function NumToRMB(const S:WideString):WideString;
//得到系统当前星期几
function GetSystemWeek : string;
//查找指定文件夹下的所有文件
//Flag为0 --查找文件 1--查找文件夹
procedure SearchFile(path: string; var AList : TStrings; AFileType: string = '*.*'; Flag: Integer = 0);
//注意,path后面要有'\';
//获取目录下的文件夹
procedure GetDirs(dirName: string; List: TStrings; ASerachType: TSearchType = stCurrent);
//查找窗体
function FindForm(FormClass: TFormClass): TForm;
//查找显示窗体
function FindShowForm(FormClass: TFormClass; const Caption: string): TForm;
//查找指定CAPTION的窗体
function InternalFindShowForm(FormClass: TFormClass;const Caption: string; Restore: Boolean): TForm;
//加载插件
//AType = 0表示不添加到MDITab
function LoadPkg(APluginFile: string; ATmpStrings: TStrings; AMDITabSet: TEasyMDITabSet;
AEasyProgressBar: TEasyProgressBar;
AMDICloseNotify: TMDICloseNotify; AType: Integer = 0): Boolean; overload;
//ShowModel加载插件
function LoadPkg(APluginFile: string; ATmpStrings: TStrings): Boolean; overload;
//获取硬盘序列号
function GetIdeDiskSerialNumber(i:Integer) : String;
function GetCPUID : TCPUID; assembler; register;
function GetCPUVendor : TVendor; assembler; register;
//字符加密 解密
//s 表示要加密的字符串,KEY是密钥
function Encrypt(const S: String; Key: Word): String;
function Decrypt(const S: String; Key: Word): String;
function EncStr(Str:String):String;//字符加密函數 這是用的一個異或加密
function DecStr(Str:String):String;//字符解密函數
//创建文件夹
function CreateDir_H(APath: string): Boolean;
//写入日志文档内容
//存成文本文件、以Base64编码
procedure WriteLog_H(ALogPath: String; AContent: String);
implementation
uses untEasyUtilConst;
procedure ChangeByteOrder( var Data; Size : Integer );
var
ptr : PChar;
i : Integer;
c : Char;
begin
ptr := @Data;
for i := 0 to (Size shr 1)-1 do
begin
c := ptr^;
ptr^ := (ptr+1)^;
(ptr+1)^ := c;
Inc(ptr,2);
end;
end;
function GetSystemWeek : string;
begin
Result := FormatDateTime('ddd',Date);
end;
//字符加密
//s 表示要加密的字符串,KEY是密钥
function Encrypt(const S: String; Key: Word): String;
var
I: Integer;
begin
Result := S;
for I := 1 to Length(S) do
begin
Result[I] := char(byte(S[I]) xor (Key shr 8));
Key := (byte(Result[I]) + Key) * C1 + C2;
end;
end;
//字符解密
//s 表示要未解密的字符串,KEY是密钥
function Decrypt(const S: String; Key: Word): String;
var
I: Integer;
begin
Result := S;
for I := 1 to Length(S) do
begin
Result[I] := char(byte(S[I]) xor (Key shr 8));
Key := (byte(S[I]) + Key) * C1 + C2;
end;
end;
function EncStr(Str:String):String;//字符加密函數 這是用的一個異或加密
var
i,j:Integer;
begin
Result:='';
j:=0;
for i:=1 to Length(Str) do
begin
Result:=Result+IntToHex(Byte(Str[i]) xor XorKey[j],2);
j:=(j+1) mod 8;
end;
end;
function DecStr(Str:String):String;//字符解密函數
var
i,j:Integer;
begin
Result:='';
j:=0;
for i:=1 to Length(Str) div 2 do
begin
Result:=Result+Char(StrToInt('$'+Copy(Str,i*2-1,2)) xor XorKey[j]);
j:=(j+1) mod 8;
end;
end;
// 数字转与大写
function NumToRMB_0(AMoney: string): string;
// 去除所有分隔符
procedure ClearComma(var AValue: string);
begin
while Pos(',', AValue) > 0 do
Delete(AValue, Pos(',', AValue), 1);
end;
// 测试如果为零将不返回值
function FiltrateValue(const AValue, AStr: string): string;
var
IntValue: Integer;
begin
IntValue:= StrToIntDef(AValue, 0);
if IntValue > 0 then Result:= AStr;
end;
// 直接将数字翻译成大写
function Direct(const AValue: string): string;
var
ResultStr: string;
iCount: Integer;
begin
for iCount:= 1 to Length(AValue) do
ResultStr:= ResultStr + NumberArray[StrToInt(AValue[iCount])];
Result:= ResultStr;
end;
// 将四位长度的数字翻译与大写
function FourBit(const AValue: string): string;
var
i, x, j: Integer;
IntValue: Integer;
ResultStr: string;
begin
IntValue:= StrToIntDef(AValue, 0);
x:= IntValue;
i := x div 1000;
j := x mod 1000;
if i <> 0 then ResultStr:= NumberArray[i] + '仟'
else begin
if Length(AValue) > 3 then ResultStr:= '零';
end;
i := j div 100;
j := j mod 100;
if i <> 0 then ResultStr:= ResultStr + NumberArray[i] + '佰'
else begin
if (ResultStr <> '') and (Length(AValue) > 2) and
(Copy(ResultStr, Length(ResultStr)-1, 2) <> '零') then
ResultStr:= ResultStr + '零';
end;
i := j div 10;
j := j mod 10;
if i <> 0 then ResultStr := ResultStr + NumberArray[i] + '拾'
else begin
if (ResultStr <> '') and (Length(AValue) > 1) and
(Copy(ResultStr, Length(ResultStr)-1, 2) <> '零') then
ResultStr:= ResultStr + '零';
end;
ResultStr := ResultStr + NumberArray[j];
while Copy(ResultStr, Length(ResultStr)-1, 2) = '零' do
Delete(ResultStr, Length(ResultStr)-1, 2);
Result := ResultStr;
end;
var
IntegerValue: string; // 整数部分的值
KilomegaValue: string; // 存储大于千兆的数字
AccountValue: string; // 在千兆以内的整数部分
DecimalValue: string; // 存在小数点后的值
ResultKilomega: string; // 大于千兆并翻译后的大写字符
ResultAccount: string; // 在千兆以内的整数部分并翻译后的大写字符
ResultDecimal: string; // 小数点后的值并翻译后的大写字符
FourBitStr: string; // 最大四位值的字符
begin
// 清除分隔符
ClearComma(AMoney);
// 验证字符串是否合法
try
AMoney:= FloatToStr(StrToFloat(AMoney));
except
raise Exception.Create('无效的数值字符串');
end;
// 取到小数据点后的值
// 取出整数部分的值
if Pos('.', AMoney) > 0 then
begin
DecimalValue:= Copy(AMoney, Pos('.', AMoney) + 1, Length(AMoney));
IntegerValue:= Copy(AMoney, 0, Pos('.', AMoney)-1);
ResultDecimal:= '.' + Direct(DecimalValue);
end
else IntegerValue:= AMoney;
// 取到大于千兆的数字
// 取到在千兆以内的整数部分
if Length(IntegerValue) > 16 then
begin
KilomegaValue:= Copy(IntegerValue, 0, Length(IntegerValue) - 12);
AccountValue:= Copy(IntegerValue,
Length(IntegerValue) - 11, Length(IntegerValue));
ResultKilomega:= Direct(KilomegaValue) + '兆';
end
else AccountValue:= IntegerValue;
{ 翻译在千兆以内的整数部分 }
// 翻译在兆与仟兆之间的部份
if Length(AccountValue) > 12 then
begin
FourBitStr:= Copy(AccountValue, 0, Length(AccountValue) - 12);
ResultAccount:= ResultAccount +
FourBit(FourBitStr) + FiltrateValue(FourBitStr, '兆');
Delete(AccountValue, 1, Length(AccountValue) - 12);
end;
// 翻译在亿与仟亿之间的部份
if Length(AccountValue) >= 8 then
begin
FourBitStr:= Copy(AccountValue, 0, Length(AccountValue) - 8);
ResultAccount:= ResultAccount +
FourBit(FourBitStr) + FiltrateValue(FourBitStr, '亿');
Delete(AccountValue, 1, Length(AccountValue) - 8);
end;
// 翻译在万与仟万之间的部份
if Length(AccountValue) >= 5 then
begin
FourBitStr:= Copy(AccountValue, 0, Length(AccountValue) - 4);
ResultAccount:= ResultAccount +
FourBit(FourBitStr) + FiltrateValue(FourBitStr, '万');
Delete(AccountValue, 1, Length(AccountValue) - 4);
end;
// 翻译万以下的部份
if Length(AccountValue) > 0 then
begin
ResultAccount:= ResultAccount +
FourBit(Copy(AccountValue, 0, Length(AccountValue)));
end;
// 组合字符串
Result:= ResultKilomega + ResultAccount + ResultDecimal;
end;
function NumToRMB(const S:WideString):WideString;
//[====防止出现000001的情况
procedure DeleZero(var S:WideString);
begin
if s[1]='0' then
begin
Delete(s,1,1);
if Length(s)>1 then
DeleZero(s); //递归
end;
end;
//=======]
const
ARmbUnits:WideString='仟佰拾万仟佰拾亿仟佰拾万仟佰拾元元角分厘';
AUpper:WideString='零壹贰叁肆伍陆柒捌玖';
AYuanPos=16;
AKeyWordPos=[4,8,12,16]; //万亿万元的位置
var
dotPos,Len,nUnitLen:integer;
Amount,RMB,sNum,sUnit:WideString;
i,n,k:integer;
begin
Amount:=Trim(S);
try
DeleZero(Amount); //调用内部过程
len:=Length(Amount);
dotPos:=pos('.',Amount); //小数点的位置
//===[判断数字长度有否越界
if dotPos>0 then
begin
if dotPos>AYuanPos+1 then
begin
Application.MessageBox('数值超过千亿位!', '提示', MB_OK +
MB_ICONWARNING);
Exit;
end else nUnitLen:=AYuanPos-dotPos+1; //对齐元
end else
begin
if Len>AYuanPos then
begin
Application.MessageBox('数值超过千亿位!', '提示', MB_OK +
MB_ICONWARNING);
Exit;
end else nUnitLen:=AYuanPos-Len; //对齐元
end; //======]
RMB:='';
// if dotPos>0 then
// nUnitLen:=AYuanPos-dotPos+1 //对齐元
// else nUnitLen:=AYuanPos-Len;
i:=1;
while i<=Len do
begin
if i=dotPos then inc(i); //碰到小数点挪到下位
n:=nUnitLen+i; //计算金额单位的位置
k:=strtoint(Amount[i]);
sNum:=AUpper[k+1]; //数字数值
sUnit:=ARmbUnits[n]; //单位
if k=0 then //为零的大写习惯
begin
if i<Len then
begin
if i+1<>dotPos then
begin
k:=strtoint(Amount[i+1]);
if (k=0) or (n in AKeyWordPos) then sNum:='';
end else sNum:='';
end else sNum:='';
if not(n in AKeyWordPos)
or (dotPos=2) then sUnit:='';
end;
RMB:=RMB+sNum+sUnit;
inc(i);
end;
if Pos('零',RMB)=1 then Delete(RMB,1,1);//解决0.09类的问题
k:=Pos('亿万',RMB); //解决亿万问题
if k>0 then Delete(RMB,k+1,1);
if RMB[1]='元' then
Result:=' ' //排除0000只出现一个元字的问题
else
Result:=RMB; //输出
except
Application.MessageBox('输入非法数值,请重新输入!', '提示', MB_OK +
MB_ICONWARNING);
end;
end;
function FindForm(FormClass: TFormClass): TForm;
var
I: Integer;
begin
Result := nil;
for I := 0 to Screen.FormCount - 1 do
begin
if Screen.Forms[I] is FormClass then
begin
Result := Screen.Forms[I];
Break;
end;
end;
end;
function InternalFindShowForm(FormClass: TFormClass;
const Caption: string; Restore: Boolean): TForm;
var
I: Integer;
begin
Result := nil;
for I := 0 to Screen.FormCount - 1 do
begin
if Screen.Forms[I].ClassNameIs(FormClass.ClassName) then
if (Caption = '') or (Caption = Screen.Forms[I].Caption) then
begin
Result := Screen.Forms[I];
Break;
end;
end;
if Result = nil then
begin
Application.CreateForm(FormClass, Result);
if Caption <> '' then
Result.Caption := Caption;
end;
with Result do begin
if Restore and (WindowState = wsMinimized) then
WindowState := wsNormal;
Show;
end;
end;
function FindShowForm(FormClass: TFormClass; const Caption: string): TForm;
begin
Result := InternalFindShowForm(FormClass, Caption, True);
end;
//注意,path后面要有'\';
procedure searchfile(path: string; var AList : TStrings; AFileType: string = '*.*'; Flag: Integer = 0);
var
SearchRec : TSearchRec;
found : integer; //,I
begin
AList.Clear;
found := FindFirst(path + AFileType, faAnyFile, SearchRec);
while found = 0 do
begin
if Flag = 1 then
begin
if (SearchRec.Name<>'.') and (SearchRec.Name<>'..') and (SearchRec.Attr = faDirectory) then
AList.Add(SearchRec.Name);
end else if Flag = 2 then
begin
if (SearchRec.Name<>'.') and (SearchRec.Name<>'..') and (SearchRec.Attr <> faDirectory) then
AList.Add(SearchRec.Name);
end;
found:=FindNext(SearchRec);
end;
FindClose(SearchRec);
end;
//获取硬盘序列号
function GetIdeDiskSerialNumber(i:Integer) : String;
var
Buffer : Array[0..BufferSize - 1] of Byte;
hDevice : THandle;
srbControl : TSrbIoControl absolute Buffer;
pInData : PSendCmdInParams;
pOutData : Pointer; // PSendCmdOutParams
cbBytesReturned : DWORD;
begin
Result := '';
FillChar(Buffer,BufferSize,#0);
if Win32Platform=VER_PLATFORM_WIN32_NT then
begin // Windows NT, Windows 2000
// Get SCSI port handle
hDevice := CreateFile( pchar('\\.\Scsi'+inttostr(i)+':'),
GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE,
nil, OPEN_EXISTING, 0, 0 );
if hDevice=INVALID_HANDLE_VALUE then Exit;
try
srbControl.HeaderLength := SizeOf(SRB_IO_CONTROL);
System.Move('SCSIDISK',srbControl.Signature,8);
srbControl.Timeout := 2;
srbControl.Length := DataSize;
srbControl.ControlCode := IOCTL_SCSI_MINIPORT_IDENTIFY;
pInData := PSendCmdInParams(PChar(@Buffer)
+SizeOf(SRB_IO_CONTROL));
pOutData := pInData;
with pInData^ do
begin
cBufferSize := IDENTIFY_BUFFER_SIZE;
bDriveNumber := 0;
with irDriveRegs do
begin
bFeaturesReg := 0;
bSectorCountReg := 1;
bSectorNumberReg := 1;
bCylLowReg := 0;
bCylHighReg := 0;
bDriveHeadReg := $A0;
bCommandReg := IDE_ID_FUNCTION;
end;
end;
if not DeviceIoControl( hDevice, IOCTL_SCSI_MINIPORT,
@Buffer, BufferSize, @Buffer, BufferSize,
cbBytesReturned, nil ) then Exit;
finally
CloseHandle(hDevice);
end;
end
else
begin // Windows 95 OSR2, Windows 98
hDevice := CreateFile( '\\.\SMARTVSD', 0, 0, nil,
CREATE_NEW, 0, 0 );
if hDevice=INVALID_HANDLE_VALUE then Exit;
try
pInData := PSendCmdInParams(@Buffer);
pOutData := @pInData^.bBuffer;
with pInData^ do
begin
cBufferSize := IDENTIFY_BUFFER_SIZE;
bDriveNumber := 0;
with irDriveRegs do
begin
bFeaturesReg := 0;
bSectorCountReg := 1;
bSectorNumberReg := 1;
bCylLowReg := 0;
bCylHighReg := 0;
bDriveHeadReg := $A0;
bCommandReg := IDE_ID_FUNCTION;
end;
end;
if not DeviceIoControl( hDevice, DFP_RECEIVE_DRIVE_DATA,
pInData, SizeOf(TSendCmdInParams)-1, pOutData,
W9xBufferSize, cbBytesReturned, nil ) then Exit;
finally
CloseHandle(hDevice);
end;
end;
with PIdSector(PChar(pOutData)+16)^ do
begin
ChangeByteOrder(sSerialNumber,SizeOf(sSerialNumber));
SetString(Result,sSerialNumber,SizeOf(sSerialNumber));
end;
end;
function GetCPUID : TCPUID; assembler; register;
asm
PUSH EBX {Save affected register}
PUSH EDI
MOV EDI,EAX {@Resukt}
MOV EAX,1
DW $A20F {CPUID Command}
STOSD {CPUID[1]}
MOV EAX,EBX
STOSD {CPUID[2]}
MOV EAX,ECX
STOSD {CPUID[3]}
MOV EAX,EDX
STOSD {CPUID[4]}
POP EDI {Restore registers}
POP EBX
end;
function GetCPUVendor : TVendor; assembler; register;
asm
PUSH EBX {Save affected register}
PUSH EDI
MOV EDI,EAX {@Result (TVendor)}
MOV EAX,0
DW $A20F {CPUID Command}
MOV EAX,EBX
XCHG EBX,ECX {save ECX result}
MOV ECX,4
@1:
STOSB
SHR EAX,8
LOOP @1
MOV EAX,EDX
MOV ECX,4
@2:
STOSB
SHR EAX,8
LOOP @2
MOV EAX,EBX
MOV ECX,4
@3:
STOSB
SHR EAX,8
LOOP @3
POP EDI {Restore registers}
POP EBX
end;
procedure GetDirs(dirName: string; List: TStrings; ASerachType: TSearchType = stCurrent);
const
attr: Integer = faDirectory; {文件属性常量, 表示这是文件夹}
var
SRec: TSearchRec; {定义 TSearchRec 结构变量}
dir : string;
begin
dirName := ExcludeTrailingBackslash(dirName) + '\'; {不知道最后是不是 \; 先去掉, 再加上}
dir := dirName + '*.*'; {加上 \; *.* 或 * 表示所有文件, 系统会把目录也当作一个文件}
if FindFirst(dir, attr, SRec) = 0 then {开始搜索,并给 SRec 赋予信息, 返回0表示找到第一个}
begin
repeat
if (SRec.Attr = attr) and {如果是文件夹}
(SRec.Name <> '.') and {排除上层目录}
(SRec.Name <> '..') then {排除根目录}
begin
case ASerachType of
stCurrent:
begin
List.Add(dirName + SRec.Name); {用List记下结果}
end;
stSub:
begin
List.Add(dirName + SRec.Name); {用List记下结果}
GetDirs(dirName + SRec.Name, List); {这句就是递归调用, 如果没有这句, 只能搜索当前目录}
end;
stAll:
begin
List.Add(dirName + SRec.Name); {用List记下结果}
GetDirs(dirName + SRec.Name, List); {这句就是递归调用, 如果没有这句, 只能搜索当前目录}
end;
end;
end;
until(FindNext(SRec)<>0); {找下一个, 返回0表示找到}
end;
FindClose(SRec); {结束搜索}
end;
//加载插件
function LoadPkg(APluginFile: string; ATmpStrings: TStrings; AMDITabSet: TEasyMDITabSet;
AEasyProgressBar: TEasyProgressBar;
AMDICloseNotify: TMDICloseNotify; AType: Integer = 0): Boolean;
var
BplHandle : THandle;
AShowBplForm: TShowBplForm;
TmpForm : TForm;
ATmpMenuItem: TMenuItem;
AExitsForm : TForm; //判断一个窗体是否存在
I : Integer;
begin
if not FileExists(APluginFile) then
begin
Application.MessageBox(PChar(Format(EASY_BPL_NOTFOUND, [APluginFile])),
PChar(EASY_SYS_ERROR), MB_OK + MB_ICONSTOP);
Result := False;
Exit;
end;
BplHandle := LoadPackage(APluginFile);
//进度窗体进度
AEasyProgressBar.Position := 30;
if BplHandle > 0 then
begin
try
AShowBplForm := GetProcAddress(BplHandle, PChar('ShowBplForm'));
//进度窗体进度
AEasyProgressBar.Position := 40;
if @AShowBplForm = nil then
raise Exception.Create('不能加载插件:'+ APluginFile + ' 原因:未找到插件入口函数!')
else
begin
TmpForm := AShowBplForm(ATmpStrings);
end;
//判断此窗体是否已经加载过
// for I := 0 to AMDITabSet.EasyOfficeTabCount - 1 do
// begin
// if TmpForm.Caption = TForm(AMDITabSet.GetChildForm(AMDITabSet.EasyOfficeTabs[I])).Caption then
// begin
// AExitsForm := AMDITabSet.GetChildForm(AMDITabSet.EasyOfficeTabs[I]);
// Break;
// end;
// end;
// if AExitsForm <> nil then
// begin
// Application.FreeNotification(TmpForm);
// FreeAndNil(TmpForm);
// AMDITabSet.ActiveTabIndex := I;
// 进度窗体进度
// AEasyProgressBar.Position := 80;
// end
// else
begin //找不到就呈现新建的
//进度窗体进度
AEasyProgressBar.Position := 60;
Application.FreeNotification(TmpForm);
if AType <> 0 then
begin
//增加MDITabSet
AMDITabSet.AddTab(TmpForm);
TmpForm.OnClose := AMDICloseNotify;
end;
//进度窗体进度
AEasyProgressBar.Position := 80;
TmpForm.Show;
end;
finally
// UnloadPackage(BplHandle);
end;
end;
Result := True;
end;
//ShowModel加载插件
function LoadPkg(APluginFile: string; ATmpStrings: TStrings): Boolean;
var
BplHandle : THandle;
AShowBplForm: TShowBplForm;
TmpForm : TForm;
begin
if not FileExists(APluginFile) then
begin
Application.MessageBox(PChar(Format(EASY_BPL_NOTFOUND, [APluginFile])),
PChar(EASY_SYS_ERROR), MB_OK + MB_ICONSTOP);
Result := False;
Exit;
end;
BplHandle := LoadPackage(APluginFile);
if BplHandle > 0 then
begin
try
AShowBplForm := GetProcAddress(BplHandle, PChar('ShowBplForm'));
if @AShowBplForm = nil then
raise Exception.Create('cannot load:'+ APluginFile)
else
begin
TmpForm := AShowBplForm(ATmpStrings);
end;
Application.FreeNotification(TmpForm);
TmpForm.ShowModal;
finally
// UnloadPackage(BplHandle);
end;
end;
Result := True;
end;
//创建文件夹
function CreateDir_H(APath: string): Boolean;
begin
Result := False;
if not DirectoryExists(APath) then
begin
try
Result := ForceDirectories(APath);
except on E: Exception do
raise Exception.Create('创建文件夹:' + APath + ' 失败!');
end;
end;
end;
//写入日志文档内容
//存成文本文件、以Base64编码
procedure WriteLog_H(ALogPath: String; AContent: String);
var
TmpPath,
TmpLogFile: string;
TmpFileLog: TextFile;
begin
TmpPath := ALogPath;
if not DirectoryExists(TmpPath) then
CreateDir_H(TmpPath);
if DirectoryExists(TmpPath) then
begin
TmpLogFile := TmpPath + '\' + FormatDateTime('YYYY-MM-DD', Date) + '.log';
AssignFile(TmpFileLog, TmpLogFile);
if not FileExists(TmpLogFile) then
Rewrite(TmpFileLog)
else
Append(TmpFileLog);
Writeln(TmpFileLog, AContent);
Flush(TmpFileLog);
CloseFile(TmpFileLog);
end;
end;
end.
|
unit mCoverSheetDisplayPanel_CPRS_WH;
{
================================================================================
*
* Application: CPRS - CoverSheet
* Developer: doma.user@domain.ext
* Site: Salt Lake City ISC
* Date: 2015-12-04
*
* Description: Inherited from TfraCoverSheetDisplayPanel_CPRS. This
* display panel adds the tweeks for properly displaying
* Womens Health data in the CPRS CoverSheet.
*
* Notes:
*
================================================================================
}
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.UITypes,
System.StrUtils,
System.Types,
System.ImageList,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.Menus,
Vcl.ImgList,
Vcl.ComCtrls,
Vcl.StdCtrls,
Vcl.Buttons,
Vcl.ExtCtrls,
mCoverSheetDisplayPanel_CPRS,
iCoverSheetIntf,
oDelimitedString;
type
TfraCoverSheetDisplayPanel_CPRS_WH = class(TfraCoverSheetDisplayPanel_CPRS)
private
fValidData: boolean;
fSeparator: TMenuItem;
fUpdateData: TMenuItem;
fMarkAsEnteredInError: TMenuItem;
fWebSitesRoot: TMenuItem;
protected
{ Inherited events - TfraGridPanel }
procedure OnPopupMenu(Sender: TObject); override;
procedure OnPopupMenuFree(Sender: TObject); override;
procedure OnPopupMenuInit(Sender: TObject); override;
{ Inherited events - TfraCoverSheetDisplayPanel_CPRS }
procedure OnAddItems(aList: TStrings); override;
procedure OnGetDetail(aRec: TDelimitedString; aResult: TStrings); override;
procedure OnEndUpdate(Sender: TObject); override;
{ Introduced events }
procedure OnEnteredInError(Sender: TObject);
procedure OnUpdateData(Sender: TObject);
procedure OnSelectWebSite(Sender: TObject);
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
end;
var
fraCoverSheetDisplayPanel_CPRS_WH: TfraCoverSheetDisplayPanel_CPRS_WH;
implementation
uses
uCore,
iWVInterface,
ORNet,
VAUtils;
{$R *.dfm}
{ TfraCoverSheetDisplayPanel_CPRS_WH }
constructor TfraCoverSheetDisplayPanel_CPRS_WH.Create(aOwner: TComponent);
begin
inherited;
fValidData := False;
end;
destructor TfraCoverSheetDisplayPanel_CPRS_WH.Destroy;
begin
inherited;
end;
procedure TfraCoverSheetDisplayPanel_CPRS_WH.OnAddItems(aList: TStrings);
var
aRec: TDelimitedString;
aStr: string;
begin
{ This is special because I have to delete [0] before loading }
if aList.Count > 0 then
begin
fValidData := StrToIntDef(Copy(aList[0], 1, 1), 0) > 0;
aList.Delete(0);
end;
{ Now load piece 1 and 2 as the Caption }
if aList.Count = 0 then
with lvData.Items.Add do
begin
Caption := 'Not Applicable.';
Data := TDelimitedString.Create('^Not Applicable');
end
else
for aStr in aList do
with lvData.Items.Add do
begin
aRec := TDelimitedString.Create(aStr);
Caption := Format('%s %s', [aRec.GetPiece(2), aRec.GetPiece(3)]);
Data := aRec;
end;
end;
procedure TfraCoverSheetDisplayPanel_CPRS_WH.OnGetDetail(aRec: TDelimitedString; aResult: TStrings);
begin
CallVistA(CPRSParams.DetailRPC, [aRec.GetPiece(1)], aResult);
end;
procedure TfraCoverSheetDisplayPanel_CPRS_WH.OnEndUpdate(Sender: TObject);
begin
inherited;
end;
procedure TfraCoverSheetDisplayPanel_CPRS_WH.OnPopupMenu(Sender: TObject);
var
aRec: TDelimitedString;
begin
inherited;
fUpdateData.Enabled := fValidData;
fMarkAsEnteredInError.Enabled := False;
fMarkAsEnteredInError.Caption := 'Nothing selected to Mark as entered in error.';
if lvData.Selected <> nil then
if lvData.Selected.Data <> nil then
begin
aRec := TDelimitedString(lvData.Selected.Data);
if Length(SplitString(aRec[1],';,')) > 1 then
if StrToIntDef(SplitString(aRec[1], ';,^')[1], 0) > 0 then
begin
fMarkAsEnteredInError.Enabled := True;
fMarkAsEnteredInError.Caption := 'Mark ''' + lvData.Selected.Caption + ''' as entered in error ...';
end;
{ -Changed from
4;1,61,^Lactating:^Not Applicable
^ Piece one is always Type of data (4=pregnancy, 5= lactating);iens
^ Piece two is always Caption
^ Piece three is always Value
if primary ien of iens string (AKA DA) = zero do NOT enable EnteredInError menu!
if aRec.GetPieceIsNotNull(1) then
begin
fMarkAsEnteredInError.Enabled := True;
fMarkAsEnteredInError.Caption := 'Mark ''' + lvData.Selected.Caption + ''' as entered in error ...';
end;
}
end;
end;
procedure TfraCoverSheetDisplayPanel_CPRS_WH.OnPopupMenuFree(Sender: TObject);
var
aSubMenu: TMenuItem;
begin
FreeAndNil(fSeparator);
FreeAndNil(fUpdateData);
FreeAndNil(fMarkAsEnteredInError);
for aSubMenu in fWebSitesRoot do
aSubMenu.Free;
fWebSitesRoot.Clear;
FreeAndNil(fWebSitesRoot);
inherited;
end;
procedure TfraCoverSheetDisplayPanel_CPRS_WH.OnPopupMenuInit(Sender: TObject);
var
aSubMenu: TMenuItem;
i: integer;
begin
inherited;
fSeparator := NewLine;
fUpdateData := NewItem('Add New Data ...', 0, False, False, OnUpdateData, 0, 'pmnWH_UpdateData');
fMarkAsEnteredInError := NewItem('Mark as Entered In Error ...', 0, False, False, OnEnteredInError, 0, 'pmnWH_EnteredInError');
fWebSitesRoot := NewSubMenu(WomensHealth.WebSiteListName, 0, 'pmnWH_WebSites', [], (WomensHealth.WebSiteCount > 0));
for i := 0 to WomensHealth.WebSiteCount - 1 do
begin
aSubMenu := NewItem(WomensHealth.WebSite[i].Name, 0, False, True, OnSelectWebSite, 0, Format('pmnWebSite_%d', [i]));
aSubMenu.Tag := i;
fWebSitesRoot.Add(aSubMenu);
end;
pmn.Items.Add(fSeparator);
pmn.Items.Add(fUpdateData);
pmn.Items.Add(fMarkAsEnteredInError);
pmn.Items.Add(fWebSitesRoot);
end;
procedure TfraCoverSheetDisplayPanel_CPRS_WH.OnSelectWebSite(Sender: TObject);
var
aWebSite: IWVWebSite;
begin
WomensHealth.WebSite[TMenuItem(Sender).Tag].QueryInterface(IWVWebSite, aWebSite);
if aWebSite = nil then
MessageDlg('Unable to get WebSite information', mtError, [mbOk], 0)
else if not WomensHealth.OpenExternalWebsite(aWebSite) then
MessageDlg(Format('Error: ', [WomensHealth.GetLastError]), mtError, [mbOk], 0);
end;
procedure TfraCoverSheetDisplayPanel_CPRS_WH.OnEnteredInError(Sender: TObject);
begin
if lvData.Selected <> nil then
if lvData.Selected.Data <> nil then
with TDelimitedString(lvData.Selected.Data) do
if WomensHealth.MarkAsEnteredInError(GetPiece(1)) then
begin
CoverSheet.OnRefreshPanel(Self, CV_CPRS_WVHT); // This is me, just letting the CoverSheet do it's thing!
CoverSheet.OnRefreshPanel(Self, CV_CPRS_POST);
CoverSheet.OnRefreshPanel(Self, CV_CPRS_RMND);
CoverSheet.OnRefreshCWAD(Self);
end;
end;
procedure TfraCoverSheetDisplayPanel_CPRS_WH.OnUpdateData(Sender: TObject);
begin
if WomensHealth.EditPregLacData(Patient.DFN) then
begin
CoverSheet.OnRefreshPanel(Self, CV_CPRS_WVHT); // This is me, just letting the CoverSheet do it's thing!
CoverSheet.OnRefreshPanel(Self, CV_CPRS_POST);
CoverSheet.OnRefreshPanel(Self, CV_CPRS_RMND);
CoverSheet.OnRefreshCWAD(Self);
end;
end;
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 untEasySysDataList;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, untEasyPlateDBBaseForm, untEasyToolBar, untEasyToolBarStylers,
ExtCtrls, untEasyGroupBox, ComCtrls, DB, DBClient, untEasyUtilMethod,
ActnList, ImgList, Grids, untEasyBaseGrid, untEasyGrid, untEasyDBGrid,
untEasyTreeView, untEasyUtilConst, DBGrids;
//插件导出函数
function ShowBplForm(AParamList: TStrings): TForm; stdcall; exports ShowBplForm;
type
TfrmEasySysDataList = class(TfrmEasyPlateDBBaseForm)
edpMain: TEasyDockPanel;
tlbMain: TEasyToolBar;
tbosMain: TEasyToolBarOfficeStyler;
EasyPanel1: TEasyPanel;
EasyPanel2: TEasyPanel;
EasyPanel3: TEasyPanel;
Splitter1: TSplitter;
cdsDataListMain: TClientDataSet;
dsDataListMain: TDataSource;
EasyDBGrid1: TEasyDBGrid;
tvDataListMain: TEasyTreeView;
imgDataList: TImageList;
EasyDockPanel1: TEasyDockPanel;
EasyToolBar1: TEasyToolBar;
EasyToolBarButton2: TEasyToolBarButton;
imgToolBar: TImageList;
EasyToolBarButton1: TEasyToolBarButton;
actDataList: TActionList;
actNewMst: TAction;
actEdit: TAction;
actDelete: TAction;
actExit: TAction;
actCopy: TAction;
actPaste: TAction;
actRedo: TAction;
actUndo: TAction;
actFind: TAction;
actPrint: TAction;
actAddDtl: TAction;
actEditDtl: TAction;
actDeleteDtl: TAction;
actCopyDtl: TAction;
EasyToolBarButton3: TEasyToolBarButton;
EasyToolBarSeparator1: TEasyToolBarSeparator;
EasyToolBarSeparator2: TEasyToolBarSeparator;
EasyToolBarButton9: TEasyToolBarButton;
EasyToolBarButton10: TEasyToolBarButton;
EasyToolBarButton12: TEasyToolBarButton;
actRedoDtl: TAction;
actUndoDtl: TAction;
cdsCloneData: TClientDataSet;
EasyToolBarButton11: TEasyToolBarButton;
actSave: TAction;
EasyToolBarButton14: TEasyToolBarButton;
actRefresh: TAction;
EasyToolBarButton15: TEasyToolBarButton;
EasyToolBarButton7: TEasyToolBarButton;
cdsMain: TClientDataSet;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure tvDataListMainChange(Sender: TObject; Node: TTreeNode);
procedure actExitExecute(Sender: TObject);
procedure actAddDtlExecute(Sender: TObject);
procedure actDeleteDtlExecute(Sender: TObject);
procedure actNewMstExecute(Sender: TObject);
procedure actEditUpdate(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure actDeleteUpdate(Sender: TObject);
procedure actDeleteExecute(Sender: TObject);
procedure actSaveUpdate(Sender: TObject);
procedure actSaveExecute(Sender: TObject);
procedure actEditDtlExecute(Sender: TObject);
procedure actRefreshExecute(Sender: TObject);
procedure actAddDtlUpdate(Sender: TObject);
procedure actEditDtlUpdate(Sender: TObject);
procedure actDeleteDtlUpdate(Sender: TObject);
procedure EasyDBGrid1EditingDone(Sender: TObject);
procedure actFindUpdate(Sender: TObject);
procedure actFindExecute(Sender: TObject);
procedure tvDataListMainKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
FSysDataListList: TList;
procedure InitDataSet;
procedure InitSysDataListTreeView;
procedure FindTV(tv: TEasyTreeView);
public
{ Public declarations }
end;
var
frmEasySysDataList: TfrmEasySysDataList;
implementation
{$R *.dfm}
uses
untEasyClassSysDataList, untEasySysDataListOP, untEasyInputQuery;
var
SysDataListRoot : string = '{00000000-0000-0000-0000-000000000000}';
FindText: string;
FindCurrIndex: Integer;
//引出函数实现
function ShowBplForm(AParamList: TStrings): TForm;
begin
frmEasySysDataList := TfrmEasySysDataList.Create(Application);
if frmEasySysDataList.FormStyle <> fsMDIChild then
frmEasySysDataList.FormStyle := fsMDIChild;
if frmEasySysDataList.WindowState <> wsMaximized then
frmEasySysDataList.WindowState := wsMaximized;
Result := frmEasySysDataList;
end;
{ TfrmEasySysDataList }
procedure TfrmEasySysDataList.InitDataSet;
var
ASysDataList: string;
begin
ASysDataList := 'SELECT * FROM SysDataList ORDER BY ParentDataListGUID,iOrder';
cdsDataListMain.Close;
cdsDataListMain.Data := EasyRDMDisp.EasyGetRDMData(ASysDataList);
with cdsDataListMain do
begin
Filtered := False;
Filter := 'ParentDataListGUID = ' + QuotedStr(SysDataListRoot);
Filtered := True;
end;
cdsMain.Close;
cdsMain.CloneCursor(cdsDataListMain, False);
cdsMain.IndexFieldNames := 'ParentDataListGUID;iOrder';
with cdsDataListMain do
begin
Filtered := False;
Filter := 'ParentDataListGUID <> ' + QuotedStr(SysDataListRoot);
Filtered := True;
end;
cdsCloneData.Close;
cdsCloneData.CloneCursor(cdsDataListMain, False);
cdsCloneData.IndexFieldNames := 'iOrder';
end;
procedure TfrmEasySysDataList.FormShow(Sender: TObject);
var
AOle: OleVariant;
begin
inherited;
//初始化数据
InitDataSet;
AOle := cdsMain.Data;
TEasySysDataList.GenerateSysDataList(AOle, FSysDataListList);
//初始化树
InitSysDataListTreeView;
//导航树不可编辑
tvDataListMain.ReadOnly := True;
//
FindCurrIndex := -1;
FindText := '';
end;
procedure TfrmEasySysDataList.FormCreate(Sender: TObject);
begin
inherited;
FSysDataListList := TList.Create;
end;
procedure TfrmEasySysDataList.FormDestroy(Sender: TObject);
begin
while (FSysDataListList.Count > 0) do
begin
TEasySysDataList(FSysDataListList[0]).Free;
FSysDataListList.Delete(0);
end;
FSysDataListList.Free;
inherited;
end;
procedure TfrmEasySysDataList.InitSysDataListTreeView;
var
I: Integer;
ATreeNode: TTreeNode;
begin
try
tvDataListMain.Items.BeginUpdate;
tvDataListMain.Items.Clear;
for I := 0 to FSysDataListList.Count - 1 do
begin
if TEasySysDataList(FSysDataListList[I]).ParentDataListGUID = SysDataListRoot then
begin
ATreeNode := tvDataListMain.Items.AddChild(nil,
IntToStr(tvDataListMain.Items.Count + 1) + '、'
+ TEasySysDataList(FSysDataListList[I]).SysDataName);
ATreeNode.Data := FSysDataListList[I];
ATreeNode.ImageIndex := 2;
ATreeNode.SelectedIndex := 1;
end;
end;
finally
tvDataListMain.Items.EndUpdate;
end;
end;
procedure TfrmEasySysDataList.tvDataListMainChange(Sender: TObject;
Node: TTreeNode);
begin
inherited;
try
EasyDBGrid1.BeginUpdate;
with cdsCloneData do
begin
Filtered := False;
Filter := 'ParentDataListGUID = ' + QuotedStr(TEasySysDataList(Node.Data).DataListGUID);
Filtered := True;
end;
EasyDBGrid1.AutoNumberCol(0);
EasyDBGrid1.Options := EasyDBGrid1.Options - [goEditing];
finally
EasyDBGrid1.EndUpdate;
end;
end;
procedure TfrmEasySysDataList.actExitExecute(Sender: TObject);
begin
inherited;
if (cdsMain.ChangeCount > 0) or (cdsCloneData.ChangeCount > 0) then
begin
case Application.MessageBox('数据已发生改变是否保存?', '提示',
MB_YESNOCANCEL + MB_ICONQUESTION) of
IDYES:
begin
actSaveExecute(Sender);
Close;
end;
IDNO:
begin
Close;
end;
end;
end else
Close;
end;
procedure TfrmEasySysDataList.actAddDtlExecute(Sender: TObject);
begin
inherited;
cdsCloneData.Last;
EasyDBGrid1.Options := EasyDBGrid1.Options + [goEditing];
with cdsCloneData do
begin
Append;
//1 DataListGUID
FieldByName('DataListGUID').AsString := GenerateGUID;
//2 SysDataName
FieldByName('SysDataName').AsString := '';
//3 SysDataValue
FieldByName('SysDataValue').AsString := '';
//4 ParentDataListGUID
FieldByName('ParentDataListGUID').AsString := TEasySysDataList(tvDataListMain.Selected.Data).DataListGUID;
//5 bEnable
FieldByName('bEnable').AsBoolean := True;
//6 iOrder
FieldByName('iOrder').AsInteger := EasyDBGrid1.RealRow;
//7 Remark
FieldByName('Remark').AsString := '';
end;
// EasyDBGrid1.AutoNumberCol(0);
end;
procedure TfrmEasySysDataList.actDeleteDtlExecute(Sender: TObject);
begin
inherited;
// if Trim(cdsCloneData.fieldbyname('SysDataName').AsString) <> '' then
begin
if Application.MessageBox(pchar('确定要删除【' + cdsCloneData.fieldbyname('SysDataName').AsString
+ '】吗?'), '提示', MB_OKCANCEL + MB_ICONQUESTION) = IDOK then
begin
cdsCloneData.Delete;
// EasyDBGrid1.AutoNumberCol(0);
end;
end;
end;
procedure TfrmEasySysDataList.actNewMstExecute(Sender: TObject);
var
ASysDataList: TEasySysDataList;
ATreeNode : TTreeNode;
begin
inherited;
try
ASysDataList := TEasySysDataList.Create;
ASysDataList.iOrder := tvDataListMain.Items.Count + 1;
ShowfrmuntEasySysDataListOP(ASysDataList, eotAdd);
if Trim(ASysDataList.DataListGUID) = '' then
ASysDataList.Free
else
begin
TEasySysDataList.AppendClientDataSet(cdsMain, ASysDataList, FSysDataListList);
ATreeNode := tvDataListMain.Items.AddChild(nil,
IntToStr(tvDataListMain.Items.Count + 1) + '、' + ASysDataList.SysDataName);
ATreeNode.ImageIndex := 2;
ATreeNode.SelectedIndex := 1;
ATreeNode.Data := ASysDataList;
tvDataListMain.Selected := ATreeNode;
end;
except on E:Exception do
begin
ASysDataList.Free;
raise Exception.Create(e.Message);
end;
end;
end;
procedure TfrmEasySysDataList.actEditUpdate(Sender: TObject);
begin
inherited;
actEdit.Enabled := tvDataListMain.Selected <> nil;
end;
procedure TfrmEasySysDataList.actEditExecute(Sender: TObject);
var
AData: TEasySysDataList;
begin
inherited;
AData := TEasySysDataList(tvDataListMain.Selected.Data);
ShowfrmuntEasySysDataListOP(AData, eotEdit);
TEasySysDataList.EditClientDataSet(cdsMain, AData, FSysDataListList);
tvDataListMain.Selected.Text := AData.SysDataName;
end;
procedure TfrmEasySysDataList.actDeleteUpdate(Sender: TObject);
begin
inherited;
actDelete.Enabled := tvDataListMain.Selected <> nil;
end;
procedure TfrmEasySysDataList.actDeleteExecute(Sender: TObject);
begin
inherited;
if cdsCloneData.RecordCount > 0 then
begin
Application.MessageBox('存在子记录,不能进行删除操作!', '提示', MB_OK +
MB_ICONINFORMATION);
Exit;
end;
if Application.MessageBox(PChar('确定要删除节点【'
+ TEasySysDataList(tvDataListMain.Selected.Data).SysDataName
+'】吗?'), '提示', MB_OKCANCEL + MB_ICONQUESTION) <> IDOK then
Exit
else
begin
TEasySysDataList.DeleteClientDataSet(cdsMain,
TEasySysDataList(tvDataListMain.Selected.Data), FSysDataListList);
tvDataListMain.Items.Delete(tvDataListMain.Selected);
end;
end;
procedure TfrmEasySysDataList.actSaveUpdate(Sender: TObject);
begin
inherited;
actSave.Enabled := (cdsCloneData.ChangeCount > 0) or (cdsMain.ChangeCount > 0);
end;
procedure TfrmEasySysDataList.actSaveExecute(Sender: TObject);
var
ATableOle,
AKeyFieldOle,
ADeltaOle,
ACodeErrorOle,
AResultOle: OleVariant;
cdsError : TClientDataSet;
I : Integer;
AErrorCode: Integer;
__Error : Boolean;
begin
inherited;
__Error := False;
if (cdsMain.ChangeCount > 0) and (cdsCloneData.ChangeCount = 0) then
AResultOle := EasyRDMDisp.EasySaveRDMData('SysDataList', cdsMain.Delta, 'DataListGUID', AErrorCode)
else
if (cdsMain.ChangeCount = 0) and (cdsCloneData.ChangeCount > 0) then
AResultOle := EasyRDMDisp.EasySaveRDMData('SysDataList', cdsCloneData.Delta, 'DataListGUID', AErrorCode)
else if (cdsMain.ChangeCount > 0) and (cdsCloneData.ChangeCount > 0) then
begin
ATableOle := VarArrayCreate([0, 1], varVariant);
ATableOle[0] := 'SysDataList';
ATableOle[1] := 'SysDataList';
AKeyFieldOle := VarArrayCreate([0, 1], varVariant);
AKeyFieldOle[0] := 'DataListGUID';
AKeyFieldOle[1] := 'DataListGUID';
ADeltaOle := VarArrayCreate([0, 1], varVariant);
ADeltaOle[0] := cdsMain.Delta;
ADeltaOle[1] := cdsCloneData.Delta;
ACodeErrorOle := VarArrayCreate([0, 1], varVariant);
AResultOle := EasyRDMDisp.EasySaveRDMDatas(ATableOle, ADeltaOle, AKeyFieldOle, ACodeErrorOle);
//如果 ACodeErrorOle > 0 即发生错误
for I := VarArrayLowBound(ACodeErrorOle, 1) to VarArrayHighBound(ACodeErrorOle, 1) do
begin
if ACodeErrorOLE[I] <> 0 then
begin
__Error := True;
Break;
end;
end;
end;
if (AErrorCode <> 0) or __Error then
begin
cdsError := TClientDataSet.Create(Self);
try
cdsError.Data := AResultOle;
Application.MessageBox(PChar(EASY_SYS_SAVE_FAILED + #13
+ cdsError.fieldbyname('ERROR_MESSAGE').AsString), EASY_SYS_HINT, MB_OK + MB_ICONERROR);
finally
cdsError.Free;
end;
end else
begin
if cdsMain.ChangeCount > 0 then
cdsMain.MergeChangeLog;
if cdsCloneData.ChangeCount > 0 then
cdsCloneData.MergeChangeLog;
Application.MessageBox(EASY_SYS_SAVE_SUCCESS, EASY_SYS_HINT, MB_OK + MB_ICONINFORMATION);
if tvDataListMain.Selected <> nil then
tvDataListMainChange(Sender, tvDataListMain.Selected);
end;
end;
procedure TfrmEasySysDataList.actEditDtlExecute(Sender: TObject);
begin
inherited;
if Trim(cdsCloneData.fieldbyname('DataListGUID').AsString) <> '' then
EasyDBGrid1.Options := EasyDBGrid1.Options + [goEditing];
end;
procedure TfrmEasySysDataList.actRefreshExecute(Sender: TObject);
begin
inherited;
//初始化树
InitSysDataListTreeView;
//
with cdsCloneData do
begin
Filtered := False;
Filter := '1=2';
Filtered := True;
end;
end;
procedure TfrmEasySysDataList.actAddDtlUpdate(Sender: TObject);
begin
inherited;
actAddDtl.Enabled := tvDataListMain.Selected <> nil;
end;
procedure TfrmEasySysDataList.actEditDtlUpdate(Sender: TObject);
begin
inherited;
actEditDtl.Enabled := cdsCloneData.FieldByName('DataListGUID').AsString <> '';
end;
procedure TfrmEasySysDataList.actDeleteDtlUpdate(Sender: TObject);
begin
inherited;
actDeleteDtl.Enabled := cdsCloneData.FieldByName('DataListGUID').AsString <> '';
end;
procedure TfrmEasySysDataList.EasyDBGrid1EditingDone(Sender: TObject);
begin
inherited;
cdsCloneData.Edit;
end;
procedure TfrmEasySysDataList.actFindUpdate(Sender: TObject);
begin
inherited;
actFind.Enabled := tvDataListMain.Items.Count > 0;
end;
procedure TfrmEasySysDataList.FindTV(tv: TEasyTreeView);
var
I: Integer;
begin
for I := FindCurrIndex + 1 to tv.Items.Count - 1 do
begin
if Pos(FindText, tv.Items.Item[I].Text) > 0 then
begin
tv.Items.Item[I].Selected := True;
FindCurrIndex := I;
Break;
end;
end;
if I = tv.Items.Count - 1 then
FindCurrIndex := -1;
end;
procedure TfrmEasySysDataList.actFindExecute(Sender: TObject);
begin
inherited;
if EasyInputQuery('查询', '内容', FindText) then
FindTV(tvDataListMain);
end;
procedure TfrmEasySysDataList.tvDataListMainKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if Key = VK_F3 then
begin
if Trim(FindText) <> '' then
FindTV(tvDataListMain);
end;
end;
end.
|
unit Support.NVMe.Intel;
interface
uses
SysUtils, Math,
Support, Device.SMART.List;
type
TIntelNVMeSupport = class sealed(TNSTSupport)
private
InterpretingSMARTValueList: TSMARTValueList;
function GetSemiSupport: TSupportStatus;
function GetTotalWrite: TTotalWrite;
function IsProductOfIntel: Boolean;
public
function GetSupportStatus: TSupportStatus; override;
function GetSMARTInterpreted(SMARTValueList: TSMARTValueList):
TSMARTInterpreted; override;
end;
implementation
{ TIntelNVMeSupport }
function TIntelNVMeSupport.IsProductOfIntel: Boolean;
begin
result :=
(Pos('INTEL SSDPE', UpperCase(Identify.Model)) = 1);
end;
function TIntelNVMeSupport.GetSemiSupport: TSupportStatus;
begin
result.Supported := Supported;
result.FirmwareUpdate := false;
result.TotalWriteType := TTotalWriteType.WriteSupportedAsValue;
end;
function TIntelNVMeSupport.GetSupportStatus: TSupportStatus;
begin
result.Supported := NotSupported;
if IsProductOfIntel then
result := GetSemiSupport;
end;
function TIntelNVMeSupport.GetTotalWrite: TTotalWrite;
function LBAToMB(const SizeInLBA: Int64): UInt64;
begin
result := SizeInLBA shr 1;
end;
const
IDOfHostWrite = 5;
var
RAWValue: UInt64;
begin
result.InValue.TrueHostWriteFalseNANDWrite := true;
RAWValue :=
InterpretingSMARTValueList.GetRAWByID(IDOfHostWrite);
result.InValue.ValueInMiB := LBAToMB(RAWValue);
end;
function TIntelNVMeSupport.GetSMARTInterpreted(
SMARTValueList: TSMARTValueList): TSMARTInterpreted;
const
IDOfEraseError = 13;
IDOfReplacedSector = 6;
IDOfUsedHour = 11;
IDOfCriticalError = 1;
ReplacedSectorThreshold = 50;
EraseErrorThreshold = 10;
begin
InterpretingSMARTValueList := SMARTValueList;
result.TotalWrite := GetTotalWrite;
result.UsedHour :=
InterpretingSMARTValueList.GetRAWByID(IDOfUsedHour);
result.ReadEraseError.TrueReadErrorFalseEraseError := true;
result.ReadEraseError.Value :=
InterpretingSMARTValueList.GetRAWByID(IDOfEraseError);
result.SMARTAlert.ReadEraseError :=
result.ReadEraseError.Value >= EraseErrorThreshold;
result.ReplacedSectors := 0;
result.SMARTAlert.ReplacedSector :=
result.ReplacedSectors >= ReplacedSectorThreshold;
result.SMARTAlert.CriticalError :=
InterpretingSMARTValueList.GetRAWByID(IDOfCriticalError) > 0;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLSLDiffuseSpecularShader<p>
This is a collection of GLSL diffuse-specular shaders.<p>
<b>History : </b><font size=-1><ul>
<li>09/03/13 - Yar - Added point, parallel, spot and parallel spot light's style support to TGLSLMLDiffuseSpecularShader
Deleted TGLSLDiffuseSpecularShaderAM, TGLSLDiffuseSpecularShaderAM
<li>17/02/13 - Yar - Added fog support to TGLSLMLDiffuseSpecularShader
<li>16/03/11 - Yar - Fixes after emergence of GLMaterialEx
<li>23/10/10 - Yar - Bugfixed memory leak
<li>23/08/10 - Yar - Replaced OpenGL1x to OpenGLTokens
<li>07/01/10 - DaStr - Bugfixed all DoInitialize() calls
(thanks YarUnderoaker)
<li>25/07/09 - DaStr - Fixed a bug with "dot(reflect_vec, LightVector)" clamping
which occured on all GeForce 8x and later graphic cards
<li>24/07/09 - DaStr - Added Fog support for single-light shaders and fixed
a bug with material Alpha (thanks Controller)
<li>02/09/07 - LC - Fixed texture bug in TGLSLMLDiffuseSpecularShader.
(Bugtracker ID = 1786286)
<li>03/04/07 - LC - Shader didn't respect the texture matrix. Changed
vertex shader to fix this. (Bugtracker ID = 1693389)
<li>20/03/07 - DaStr - Made changes related to the new parameter passing model
<li>06/03/07 - DaStr - Again replaced DecimalSeparator stuff with
a single Str procedure (thanks Uwe Raabe)
<li>03/03/07 - DaStr - Made compatible with Delphi6
Added more stuff to RegisterClasses()
<li>21/02/07 - DaStr - Initial version (contributed to GLScene)
This is a collection of GLSL Diffuse Specular shaders, comes in these variaties
(to know what these suffixes and prefixes mean see GLCustomShader.pas):
- TGLSLDiffuseSpecularShader
- TGLSLDiffuseSpecularShaderMT
- TGLSLMLDiffuseSpecularShader
- TGLSLMLDiffuseSpecularShaderMT
Notes:
1) TGLSLDiffuseSpecularShader takes all Material parameters directly
from OpenGL (that includes TGLMaterial's)
2) TGLSLDiffuseSpecularShader takes all Light parameters directly
from OpenGL (that includes TGLLightSource's)
Previous version history:
v1.0 01 November '2006 Creation
v1.1 19 December '2006 TGLBaseCustomGLSLDiffuseSpecular[MT] abstracted
5 different versions of this shader added
v1.1.2 06 February '2007 IGLMaterialLibrarySupported renamed to
IGLMaterialLibrarySupported
v1.2 16 February '2007 Updated to the latest CVS version of GLScene
}
unit GLSLDiffuseSpecularShader;
interface
{$I GLScene.inc}
uses
// VCL
Classes, SysUtils,
// GLScene
GLTexture, GLScene, GLVectorGeometry, OpenGLTokens, GLStrings, GLCustomShader,
GLSLShader, GLColor, GLRenderContextInfo, GLMaterial;
type
EGLSLDiffuseSpecularShaderException = class(EGLSLShaderException);
//: Abstract class.
TGLBaseCustomGLSLDiffuseSpecular = class(TGLCustomGLSLShader)
private
FLightPower: Single;
FRealisticSpecular: Boolean;
FFogSupport: TGLShaderFogSupport;
procedure SetRealisticSpecular(const Value: Boolean);
procedure SetFogSupport(const Value: TGLShaderFogSupport);
protected
procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override;
function DoUnApply(var rci: TRenderContextInfo): Boolean; override;
public
constructor Create(AOwner : TComponent); override;
property LightPower: Single read FLightPower write FLightPower;
property RealisticSpecular: Boolean read FRealisticSpecular write SetRealisticSpecular;
//: User can disable fog support and save some FPS if he doesn't need it.
property FogSupport: TGLShaderFogSupport read FFogSupport write SetFogSupport default sfsAuto;
end;
//: Abstract class.
TGLBaseGLSLDiffuseSpecularShaderMT = class(TGLBaseCustomGLSLDiffuseSpecular, IGLMaterialLibrarySupported)
private
FMaterialLibrary: TGLMaterialLibrary;
FMainTexture: TGLTexture;
FMainTextureName: TGLLibMaterialName;
function GetMainTextureName: TGLLibMaterialName;
procedure SetMainTextureName(const Value: TGLLibMaterialName);
//: Implementing IGLMaterialLibrarySupported.
function GetMaterialLibrary: TGLAbstractMaterialLibrary;
protected
procedure SetMaterialLibrary(const Value: TGLMaterialLibrary); virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override;
public
property MainTexture: TGLTexture read FMainTexture write FMainTexture;
property MainTextureName: TGLLibMaterialName read GetMainTextureName write SetMainTextureName;
property MaterialLibrary: TGLMaterialLibrary read FMaterialLibrary write SetMaterialLibrary;
end;
{******** Single Light ************}
TGLCustomGLSLDiffuseSpecularShader = class(TGLBaseCustomGLSLDiffuseSpecular)
protected
procedure DoInitialize(var rci: TRenderContextInfo; Sender: TObject); override;
procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override;
end;
TGLCustomGLSLDiffuseSpecularShaderMT = class(TGLBaseGLSLDiffuseSpecularShaderMT)
protected
procedure DoInitialize(var rci: TRenderContextInfo; Sender: TObject); override;
end;
{******** Multi Light ************}
{: Note: probably LightCount should be replaced by LightSources, like in
GLSLBumpShader.pas }
TLightRecord = record
Enabled: Boolean;
Style: TLightStyle;
end;
TGLCustomGLSLMLDiffuseSpecularShader = class(TGLBaseCustomGLSLDiffuseSpecular)
private
FLightTrace: array[0..7] of TLightRecord;
protected
procedure DoInitialize(var rci: TRenderContextInfo; Sender: TObject); override;
procedure DoApply(var rci: TRenderContextInfo; Sender: TObject); override;
public
constructor Create(AOwner : TComponent); override;
end;
TGLCustomGLSLMLDiffuseSpecularShaderMT = class(TGLBaseGLSLDiffuseSpecularShaderMT)
private
FLightTrace: array[0..7] of TLightRecord;
protected
procedure DoInitialize(var rci: TRenderContextInfo; Sender: TObject); override;
procedure DoApply(var rci: TRenderContextInfo; Sender: TObject); override;
public
constructor Create(AOwner : TComponent); override;
end;
{******** Published Stuff ************}
TGLSLDiffuseSpecularShaderMT = class(TGLCustomGLSLDiffuseSpecularShaderMT)
published
property MainTextureName;
property LightPower;
property FogSupport;
end;
TGLSLDiffuseSpecularShader = class(TGLCustomGLSLDiffuseSpecularShader)
published
property LightPower;
property FogSupport;
end;
TGLSLMLDiffuseSpecularShaderMT = class(TGLCustomGLSLMLDiffuseSpecularShaderMT)
published
property MainTextureName;
property LightPower;
property FogSupport;
end;
TGLSLMLDiffuseSpecularShader = class(TGLCustomGLSLMLDiffuseSpecularShader)
published
property LightPower;
property FogSupport;
end;
implementation
procedure GetVertexProgramCode(const Code: TStrings;
AFogSupport: Boolean; var rci: TRenderContextInfo);
begin
with Code do
begin
Clear;
Add('varying vec3 Normal; ');
Add('varying vec4 Position; ');
if AFogSupport then
begin
Add('varying float fogFactor; ');
end;
Add(' ');
Add(' ');
Add('void main(void) ');
Add('{ ');
Add(' gl_Position = ftransform(); ');
Add(' gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0; ');
Add(' Normal = normalize(gl_NormalMatrix * gl_Normal); ');
Add(' Position = gl_ModelViewMatrix * gl_Vertex; ');
if AFogSupport then
begin
Add(' const float LOG2 = 1.442695; ');
Add(' gl_FogFragCoord = length(Position.xyz); ');
case TGLSceneBuffer(rci.buffer).FogEnvironment.FogMode of
fmLinear:
Add(' fogFactor = (gl_Fog.end - gl_FogFragCoord) * gl_Fog.scale; ');
fmExp, // Yep, I don't know about this type, so I use fmExp2.
fmExp2:
begin
Add(' fogFactor = exp2( -gl_Fog.density * ');
Add(' gl_Fog.density * ');
Add(' gl_FogFragCoord * ');
Add(' gl_FogFragCoord * ');
Add(' LOG2 ); ');
end;
else
Assert(False, glsUnknownType);
end;
Add(' fogFactor = clamp(fogFactor, 0.0, 1.0); ');
end;
Add('} ');
end;
end;
procedure AddLightSub(const Code: TStrings);
begin
with Code do
begin
Add('void pointLight(in int i, in vec3 normal, in vec3 eye, in vec3 ecPosition3)');
Add('{');
Add(' float nDotVP; // normal . light direction');
Add(' float nDotHV; // normal . light half vector');
Add(' float pf; // power factor');
Add(' float attenuation; // computed attenuation factor');
Add(' float d; // distance from surface to light source');
Add(' vec3 VP; // direction from surface to light position');
Add(' vec3 halfVector; // direction of maximum highlights');
Add(' ');
Add(' // Compute vector from surface to light position');
Add(' VP = vec3 (gl_LightSource[i].position) - ecPosition3;');
Add(' ');
Add(' // Compute distance between surface and light position');
Add(' d = length(VP);');
Add(' ');
Add(' // Normalize the vector from surface to light position');
Add(' VP = normalize(VP);');
Add(' ');
Add(' // Compute attenuation');
Add(' attenuation = 1.0 / (gl_LightSource[i].constantAttenuation +');
Add(' gl_LightSource[i].linearAttenuation * d +');
Add(' gl_LightSource[i].quadraticAttenuation * d * d);');
Add(' ');
Add(' halfVector = normalize(VP + eye);');
Add(' ');
Add(' nDotVP = max(0.0, dot(normal, VP));');
Add(' nDotHV = max(0.0, dot(normal, halfVector));');
Add(' ');
Add(' if (nDotVP == 0.0)');
Add(' {');
Add(' pf = 0.0;');
Add(' }');
Add(' else');
Add(' {');
Add(' pf = pow(nDotHV, gl_FrontMaterial.shininess);');
Add(' ');
Add(' }');
Add(' Ambient += gl_LightSource[i].ambient * attenuation;');
Add(' Diffuse += gl_LightSource[i].diffuse * nDotVP * attenuation;');
Add(' Specular += gl_LightSource[i].specular * pf * attenuation;');
Add('}');
Add(' ');
Add('void directionalLight(in int i, in vec3 normal)');
Add('{');
Add(' float nDotVP; // normal . light direction');
Add(' float nDotHV; // normal . light half vector');
Add(' float pf; // power factor');
Add(' ');
Add(' nDotVP = max(0.0, dot(normal, normalize(vec3 (gl_LightSource[i].position))));');
Add(' nDotHV = max(0.0, dot(normal, vec3 (gl_LightSource[i].halfVector)));');
Add(' ');
Add(' if (nDotVP == 0.0)');
Add(' {');
Add(' pf = 0.0;');
Add(' }');
Add(' else');
Add(' {');
Add(' pf = pow(nDotHV, gl_FrontMaterial.shininess);');
Add(' ');
Add(' }');
Add(' Ambient += gl_LightSource[i].ambient;');
Add(' Diffuse += gl_LightSource[i].diffuse * nDotVP;');
Add(' Specular += gl_LightSource[i].specular * pf;');
Add('}');
Add('void spotLight(in int i, in vec3 normal, in vec3 eye, in vec3 ecPosition3)');
Add('{');
Add(' float nDotVP; // normal . light direction');
Add(' float nDotHV; // normal . light half vector');
Add(' float pf; // power factor');
Add(' float spotDot; // cosine of angle between spotlight');
Add(' float spotAttenuation; // spotlight attenuation factor');
Add(' float attenuation; // computed attenuation factor');
Add(' float d; // distance from surface to light source');
Add(' vec3 VP; // direction from surface to light position');
Add(' vec3 halfVector; // direction of maximum highlights');
Add(' ');
Add(' // Compute vector from surface to light position');
Add(' VP = vec3 (gl_LightSource[i].position) - ecPosition3;');
Add(' ');
Add(' // Compute distance between surface and light position');
Add(' d = length(VP);');
Add(' ');
Add(' // Normalize the vector from surface to light position');
Add(' VP = normalize(VP);');
Add(' ');
Add(' // Compute attenuation');
Add(' attenuation = 1.0 / (gl_LightSource[i].constantAttenuation +');
Add(' gl_LightSource[i].linearAttenuation * d +');
Add(' gl_LightSource[i].quadraticAttenuation * d * d);');
Add(' ');
Add(' // See if point on surface is inside cone of illumination');
Add(' spotDot = dot(-VP, normalize(gl_LightSource[i].spotDirection));');
Add(' ');
Add(' if (spotDot < gl_LightSource[i].spotCosCutoff)');
Add(' {');
Add(' spotAttenuation = 0.0; // light adds no contribution');
Add(' }');
Add(' else');
Add(' {');
Add(' spotAttenuation = pow(spotDot, gl_LightSource[i].spotExponent);');
Add(' ');
Add(' }');
Add(' // Combine the spotlight and distance attenuation.');
Add(' attenuation *= spotAttenuation;');
Add(' ');
Add(' halfVector = normalize(VP + eye);');
Add(' ');
Add(' nDotVP = max(0.0, dot(normal, VP));');
Add(' nDotHV = max(0.0, dot(normal, halfVector));');
Add(' ');
Add(' if (nDotVP == 0.0)');
Add(' {');
Add(' pf = 0.0;');
Add(' }');
Add(' else');
Add(' {');
Add(' pf = pow(nDotHV, gl_FrontMaterial.shininess);');
Add(' ');
Add(' }');
Add(' Ambient += gl_LightSource[i].ambient * attenuation;');
Add(' Diffuse += gl_LightSource[i].diffuse * nDotVP * attenuation;');
Add(' Specular += gl_LightSource[i].specular * pf * attenuation;');
Add(' ');
Add('}');
Add('void infiniteSpotLight(in int i, in vec3 normal)');
Add('{');
Add(' float nDotVP; // normal . light direction');
Add(' float nDotHV; // normal . light half vector');
Add(' float pf; // power factor');
Add(' float spotAttenuation;');
Add(' vec3 Ppli;');
Add(' vec3 Sdli;');
Add(' ');
Add(' nDotVP = max(0.0, dot(normal, normalize(vec3 (gl_LightSource[i].position))));');
Add(' nDotHV = max(0.0, dot(normal, vec3 (gl_LightSource[i].halfVector)));');
Add(' ');
Add(' Ppli = -normalize(vec3(gl_LightSource[i].position));');
Add(' Sdli = normalize(vec3(gl_LightSource[i].spotDirection));');
Add(' ');
Add(' spotAttenuation = pow(dot(Ppli, Sdli), gl_LightSource[i].spotExponent);');
Add(' if (nDotVP == 0.0)');
Add(' {');
Add(' pf = 0.0;');
Add(' }');
Add(' else');
Add(' {');
Add(' pf = pow(nDotHV, gl_FrontMaterial.shininess);');
Add(' ');
Add(' }');
Add(' Ambient += gl_LightSource[i].ambient * spotAttenuation;');
Add(' Diffuse += gl_LightSource[i].diffuse * nDotVP * spotAttenuation;');
Add(' Specular += gl_LightSource[i].specular * pf * spotAttenuation;');
Add('}');
end;
end;
procedure GetMLFragmentProgramCodeMid(const Code: TStrings;
const CurrentLight: Integer; AStyle: TLightStyle);
begin
with Code do
begin
case AStyle of
lsOmni: Add(Format(' pointLight(%d, N, eye, Pos); ', [CurrentLight]));
lsSpot: Add(Format(' spotLight(%d, N, eye, Pos); ', [CurrentLight]));
lsParallel: Add(Format(' directionalLight(%d, N); ', [CurrentLight]));
lsParallelSpot: Add(Format(' infiniteSpotLight(%d, N); ', [CurrentLight]));
end;
end;
end;
procedure GetFragmentProgramCode(const Code: TStrings;
const ARealisticSpecular: Boolean; const AFogSupport: Boolean;
aRci: TRenderContextInfo);
var
scene: TGLScene;
begin
with Code do
begin
Clear;
Add('uniform float LightIntensity; ');
Add('uniform sampler2D MainTexture; ');
Add(' ');
Add('varying vec3 Normal; ');
Add('varying vec4 Position; ');
if AFogSupport then
begin
Add('varying float fogFactor; ');
end;
Add('vec4 Ambient;');
Add('vec4 Diffuse;');
Add('vec4 Specular;');
AddLightSub(Code);
Add('void main(void) ');
Add('{ ');
Add(' vec4 TextureContrib = texture2D(MainTexture, gl_TexCoord[0].xy); ');
Add(' vec3 eye = vec3(0.0, 0.0, 1.0); ');
Add(' Diffuse = vec4(0.0); ');
Add(' Specular = vec4(0.0); ');
Add(' Ambient = vec4(0.0); ');
Add(' vec3 Pos = Position.xyz; ');
Add(' vec3 N = normalize(Normal); ');
scene := TGLScene(ARci.scene);
if (scene.Lights.Count > 0) then
GetMLFragmentProgramCodeMid(Code, 0,
TGLLightSource(scene.Lights[0]).LightStyle);
if ARealisticSpecular then
Add(' gl_FragColor = LightIntensity * (TextureContrib * (gl_FrontLightModelProduct.sceneColor + Ambient * gl_FrontMaterial.ambient + Diffuse * gl_FrontMaterial.diffuse) + Specular * gl_FrontMaterial.specular); ')
else
Add(' gl_FragColor = LightIntensity * TextureContrib * (gl_FrontLightModelProduct.sceneColor + Ambient * gl_FrontMaterial.ambient + Diffuse * gl_FrontMaterial.diffuse + Specular * gl_FrontMaterial.specular); ');
if AFogSupport then
Add(' gl_FragColor = mix(gl_Fog.color, gl_FragColor, fogFactor);');
Add(' gl_FragColor.a = TextureContrib.a; ');
Add('} ');
end;
end;
procedure GetMLFragmentProgramCodeBeg(const Code: TStrings;
const AFogSupport: Boolean);
begin
with Code do
begin
Clear;
Add('uniform sampler2D MainTexture;');
Add('uniform float LightIntensity; ');
Add('uniform float SpecPower; ');
Add('varying vec3 Normal;');
Add('varying vec4 Position;');
if AFogSupport then
begin
Add('varying float fogFactor;');
end;
Add('vec4 Ambient;');
Add('vec4 Diffuse;');
Add('vec4 Specular;');
AddLightSub(Code);
Add('void main(void) ');
Add('{ ');
Add(' vec4 TextureContrib = texture2D(MainTexture, gl_TexCoord[0].st); ');
Add(' vec3 eye = vec3(0.0, 0.0, 1.0); ');
Add(' Diffuse = vec4(0.0); ');
Add(' Specular = vec4(0.0); ');
Add(' Ambient = vec4(0.0); ');
Add(' vec3 Pos = Position.xyz; ');
Add(' vec3 N = normalize(Normal); ');
end;
end;
procedure GetMLFragmentProgramCodeEnd(const Code: TStrings;
const ARealisticSpecular: Boolean;
AFogSupport: Boolean);
begin
with Code do
begin
if ARealisticSpecular then
Add(' gl_FragColor = LightIntensity * (TextureContrib * (gl_FrontLightModelProduct.sceneColor + Ambient * gl_FrontMaterial.ambient + Diffuse * gl_FrontMaterial.diffuse) + Specular * gl_FrontMaterial.specular); ')
else
Add(' gl_FragColor = LightIntensity * TextureContrib * (gl_FrontLightModelProduct.sceneColor + Ambient * gl_FrontMaterial.ambient + Diffuse * gl_FrontMaterial.diffuse + Specular * gl_FrontMaterial.specular); ');
if AFogSupport then
Add(' gl_FragColor = mix(gl_Fog.color, gl_FragColor, fogFactor);');
Add(' gl_FragColor.a = TextureContrib.a; ');
Add('} ');
end;
end;
{ TGLBaseCustomGLSLDiffuseSpecular }
constructor TGLBaseCustomGLSLDiffuseSpecular.Create(
AOwner: TComponent);
begin
inherited;
FLightPower := 1;
FFogSupport := sfsAuto;
TStringList(VertexProgram.Code).OnChange := nil;
TStringList(FragmentProgram.Code).OnChange := nil;
VertexProgram.Enabled := true;
FragmentProgram.Enabled := true;
end;
procedure TGLBaseCustomGLSLDiffuseSpecular.DoApply(
var rci: TRenderContextInfo; Sender: TObject);
begin
GetGLSLProg.UseProgramObject;
Param['LightIntensity'].AsVector1f := FLightPower;
end;
function TGLBaseCustomGLSLDiffuseSpecular.DoUnApply(
var rci: TRenderContextInfo): Boolean;
begin
Result := False;
GetGLSLProg.EndUseProgramObject;
end;
procedure TGLBaseCustomGLSLDiffuseSpecular.SetFogSupport(
const Value: TGLShaderFogSupport);
begin
if FFogSupport <> Value then
begin
FFogSupport := Value;
Self.FinalizeShader;
end;
end;
procedure TGLBaseCustomGLSLDiffuseSpecular.SetRealisticSpecular(
const Value: Boolean);
begin
if FRealisticSpecular <> Value then
begin
FRealisticSpecular := Value;
Self.FinalizeShader;
end;
end;
{ TGLBaseGLSLDiffuseSpecularShaderMT }
procedure TGLBaseGLSLDiffuseSpecularShaderMT.DoApply(
var rci: TRenderContextInfo; Sender: TObject);
begin
inherited;
Param['MainTexture'].AsTexture2D[0] := FMainTexture;
end;
function TGLBaseGLSLDiffuseSpecularShaderMT.GetMainTextureName: TGLLibMaterialName;
begin
Result := FMaterialLibrary.GetNameOfTexture(FMainTexture);
end;
function TGLBaseGLSLDiffuseSpecularShaderMT.GetMaterialLibrary: TGLAbstractMaterialLibrary;
begin
Result := FMaterialLibrary;
end;
procedure TGLBaseGLSLDiffuseSpecularShaderMT.Notification(
AComponent: TComponent; Operation: TOperation);
var
Index: Integer;
begin
inherited;
if Operation = opRemove then
if AComponent = FMaterialLibrary then
if FMaterialLibrary <> nil then
begin
//need to nil the textures that were ownned by it
if FMainTexture <> nil then
begin
Index := FMaterialLibrary.Materials.GetTextureIndex(FMainTexture);
if Index <> -1 then
FMainTexture := nil;
end;
FMaterialLibrary := nil;
end;
end;
procedure TGLBaseGLSLDiffuseSpecularShaderMT.SetMainTextureName(
const Value: TGLLibMaterialName);
begin
if FMaterialLibrary = nil then
begin
FMainTextureName := Value;
if not (csLoading in ComponentState) then
raise EGLSLDiffuseSpecularShaderException.Create(glsErrorEx + glsMatLibNotDefined);
end
else
begin
FMainTexture := FMaterialLibrary.TextureByName(Value);
FMainTextureName := '';
end;
end;
procedure TGLBaseGLSLDiffuseSpecularShaderMT.SetMaterialLibrary(
const Value: TGLMaterialLibrary);
begin
if FMaterialLibrary <> nil then
FMaterialLibrary.RemoveFreeNotification(Self);
FMaterialLibrary := Value;
if FMaterialLibrary <> nil then
begin
FMaterialLibrary.FreeNotification(Self);
if FMainTextureName <> '' then
SetMainTextureName(FMainTextureName);
end
else
FMainTextureName := '';
end;
{ TGLCustomGLSLDiffuseSpecularShaderMT }
procedure TGLCustomGLSLDiffuseSpecularShaderMT.DoInitialize(var rci: TRenderContextInfo; Sender: TObject);
begin
GetVertexProgramCode(VertexProgram.Code, IsFogEnabled(FFogSupport, rci), rci);
GetFragmentProgramCode(FragmentProgram.Code, FRealisticSpecular, IsFogEnabled(FFogSupport, rci), rci);
VertexProgram.Enabled := True;
FragmentProgram.Enabled := True;
inherited;
end;
{ TGLCustomGLSLDiffuseSpecularShader }
procedure TGLCustomGLSLDiffuseSpecularShader.DoApply(
var rci: TRenderContextInfo; Sender: TObject);
begin
inherited;
Param['MainTexture'].AsVector1i := 0; // Use the current texture.
end;
procedure TGLCustomGLSLDiffuseSpecularShader.DoInitialize(var rci: TRenderContextInfo; Sender: TObject);
begin
GetVertexProgramCode(VertexProgram.Code, IsFogEnabled(FFogSupport, rci), rci);
GetFragmentProgramCode(FragmentProgram.Code, FRealisticSpecular, IsFogEnabled(FFogSupport, rci), rci);
VertexProgram.Enabled := True;
FragmentProgram.Enabled := True;
inherited;
end;
{ TGLCustomGLSLMLDiffuseSpecularShader }
constructor TGLCustomGLSLMLDiffuseSpecularShader.Create(
AOwner: TComponent);
begin
inherited;
end;
procedure TGLCustomGLSLMLDiffuseSpecularShader.DoApply(var rci: TRenderContextInfo; Sender: TObject);
var
I: Integer;
scene: TGLScene;
needRecompile: Boolean;
begin
scene := TGLScene(rci.scene);
needRecompile := False;
for I := 0 to scene.Lights.Count - 1 do
begin
if Assigned(scene.Lights[I]) then
begin
if FLightTrace[I].Enabled <> TGLLightSource(scene.Lights[I]).Shining then
begin
needRecompile := True;
break;
end;
if FLightTrace[I].Style <> TGLLightSource(scene.Lights[I]).LightStyle then
begin
needRecompile := True;
break;
end;
end
else
if FLightTrace[I].Enabled then
begin
needRecompile := True;
break;
end;
end;
if needRecompile then
begin
FinalizeShader;
InitializeShader(rci, Sender);
end;
inherited;
Param['MainTexture'].AsVector1i := 0; // Use the current texture.
end;
procedure TGLCustomGLSLMLDiffuseSpecularShader.DoInitialize(var rci: TRenderContextInfo; Sender: TObject);
var
I: Integer;
scene: TGLScene;
begin
GetVertexProgramCode(VertexProgram.Code, IsFogEnabled(FFogSupport, rci), rci);
with FragmentProgram.Code do
begin
GetMLFragmentProgramCodeBeg(FragmentProgram.Code, IsFogEnabled(FFogSupport, rci));
// Repeat for all lights.
scene := TGLScene(rci.scene);
for I := 0 to scene.Lights.Count - 1 do
begin
if Assigned(scene.Lights[I]) then
begin
FLightTrace[I].Enabled := TGLLightSource(scene.Lights[I]).Shining;
FLightTrace[I].Style := TGLLightSource(scene.Lights[I]).LightStyle;
if FLightTrace[I].Enabled then
GetMLFragmentProgramCodeMid(FragmentProgram.Code, I, FLightTrace[I].Style);
end
else
FLightTrace[I].Enabled := False;
end;
GetMLFragmentProgramCodeEnd(FragmentProgram.Code,
FRealisticSpecular, IsFogEnabled(FFogSupport, rci));
end;
VertexProgram.Enabled := True;
FragmentProgram.Enabled := True;
inherited DoInitialize(rci, Sender);
end;
{ TGLCustomGLSLMLDiffuseSpecularShaderMT }
constructor TGLCustomGLSLMLDiffuseSpecularShaderMT.Create(
AOwner: TComponent);
begin
inherited;
end;
procedure TGLCustomGLSLMLDiffuseSpecularShaderMT.DoApply(
var rci: TRenderContextInfo; Sender: TObject);
var
I: Integer;
scene: TGLScene;
needRecompile: Boolean;
begin
scene := TGLScene(rci.scene);
needRecompile := False;
for I := 0 to scene.Lights.Count - 1 do
begin
if Assigned(scene.Lights[I]) then
begin
if FLightTrace[I].Enabled <> TGLLightSource(scene.Lights[I]).Shining then
begin
needRecompile := True;
break;
end;
if FLightTrace[I].Style <> TGLLightSource(scene.Lights[I]).LightStyle then
begin
needRecompile := True;
break;
end;
end
else
if FLightTrace[I].Enabled then
begin
needRecompile := True;
break;
end;
end;
if needRecompile then
begin
FinalizeShader;
InitializeShader(rci, Sender);
end;
inherited;
end;
procedure TGLCustomGLSLMLDiffuseSpecularShaderMT.DoInitialize(var rci: TRenderContextInfo; Sender: TObject);
var
I: Integer;
scene: TGLScene;
begin
GetVertexProgramCode(VertexProgram.Code, IsFogEnabled(FFogSupport, rci), rci);
with FragmentProgram.Code do
begin
GetMLFragmentProgramCodeBeg(FragmentProgram.Code, IsFogEnabled(FFogSupport, rci));
// Repeat for all lights.
scene := TGLScene(rci.scene);
for I := 0 to scene.Lights.Count - 1 do
begin
if Assigned(scene.Lights[I]) then
begin
FLightTrace[I].Enabled := TGLLightSource(scene.Lights[I]).Shining;
FLightTrace[I].Style := TGLLightSource(scene.Lights[I]).LightStyle;
if FLightTrace[I].Enabled then
GetMLFragmentProgramCodeMid(FragmentProgram.Code, I, FLightTrace[I].Style);
end
else
FLightTrace[I].Enabled := False;
end;
GetMLFragmentProgramCodeEnd(FragmentProgram.Code,
FRealisticSpecular, IsFogEnabled(FFogSupport, rci));
end;
VertexProgram.Enabled := True;
FragmentProgram.Enabled := True;
inherited;
end;
initialization
RegisterClasses([
TGLCustomGLSLDiffuseSpecularShader,
TGLCustomGLSLDiffuseSpecularShaderMT,
TGLCustomGLSLMLDiffuseSpecularShader,
TGLCustomGLSLMLDiffuseSpecularShaderMT,
TGLSLDiffuseSpecularShader,
TGLSLDiffuseSpecularShaderMT,
TGLSLMLDiffuseSpecularShader,
TGLSLMLDiffuseSpecularShaderMT
]);
end.
|
{ @exclude }
unit rtcActiveX;
interface
uses
Classes, ActiveX, rtcThrPool;
type
TRtcActiveX=class(TRtcThreadCallback)
procedure AfterThreadStart; override;
{ Called from inside each Thread, before it will be stopped/destroyed }
procedure BeforeThreadStop; override;
{ Callled after all threads have been stopped.
This is the method from which you should destroy the object by calling "Free" }
procedure DestroyCallback; override;
end;
implementation
{ TRtcActiveX }
procedure TRtcActiveX.AfterThreadStart;
begin
CoInitialize(nil);
end;
procedure TRtcActiveX.BeforeThreadStop;
begin
CoUninitialize;
end;
procedure TRtcActiveX.DestroyCallback;
begin
Free;
end;
initialization
AddThreadCallback( TRtcActiveX.Create );
finalization
end.
|
{
Create Armor Variants
darkconsole http://darkconsole.tumblr.com
Given an ARMO record (or list of) create any variants (cloth, light, heavy)
of that item properly editing the EditorID, Title, and swapping out the
various keywords that make an armor Cloth, Light, or Heavy.
Personally I suggest you create Cloth variants of all your armors, and then
let this script generate the Light and Heavy. Given a base armor damage
resist value that you would expect to see on a chest piece (say, 35), this
script will calculate what the values for gloves, boots, and helmets for
you based on that value. Cloth items will be automatically set to 0 armor
so mages work properly.
For it to work to its fullest there are a few requirements:
* The EditorID should contain _Cloth, _Light, or _Heavy. If this is missing
it will add the tag to the editor ID but your original will still have
a bad (in my opinion) EditorID.
* The Full Name should contain Cloth Light or Heavy in it. If this is
missing then it will add (Cloth), (Light), or (Heavy) to the end of the
full name. IT IS ACCEPTABLE if you are starting from cloth originals to
not have the word Cloth in the name, letting the script add Light and
Heavy for you.
* For Keywords to work well, your originals will have to be properly
keyworded as well. This means your original keywords should have their
proper body part and armor type keywords. For example turning cloth into
heavy will convert the following Keywords:
ClothingBody => ArmorCuirass
ArmorClothing => ArmorHeavy
VendorItemClothing => VendorItemArmor
If your original is not properly keyworded then we cant replace them for
you. KEYWORDS ARE IMPORTANT FOR PERKS AND SHIT SO TAKE THE TIME.
}
Unit
UserScript;
Uses
'Dcc\Skyrim';
Var
ArmorRating: Integer;
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
Procedure DccMakeArmorVariant(Form: IInterface; ArmorType: Integer; ArmorRating: Integer);
Var
FormNew: IInterface;
RegEx: TPerlRegex;
Begin
RegEx := TPerlRegex.Create();
RegEx.RegEx := '_(armor)?(cloth|light|heavy)';
RegEx.Options := [ preCaseless ];
RegEx.Replacement := '_Armor' + GetArmorTypeWord(ArmorType);
RegEx.Subject := EditorID(Form);
If(RegEx.Match())
Then RegEx.ReplaceAll()
Else RegEx.Subject := EditorID(Form) + '_' + GetArmorTypeWord(ArmorType);
If(Assigned(Skyrim.FormFind(GetFile(Form),'ARMO',RegEx.Subject)))
Then Begin
AddMessage('[***] ' + RegEx.Subject + ' already exists, updating values.');
FormNew := Skyrim.FormFind(GetFile(Form),'ARMO',RegEx.Subject)
End
Else Begin
AddMessage('[***] ' + RegEx.Subject + ' does not exist yet, creating.');
FormNew := Skyrim.FormCopy(Form);
Skyrim.FormSetEditorID(FormNew,RegEx.Subject);
Skyrim.ArmoSetArmorType(FormNew,ArmorType);
Skyrim.ArmoReplaceArmorTypeKeywords(FormNew,ArmorType);
Skyrim.ArmoReplaceArmorTypeName(FormNew,ArmorType);
End;
// then handling updating values that depend on the type of armor.
Skyrim.ArmoSetArmorRatingAuto(FormNew,ArmorRating);
RegEx.Free();
End;
Procedure DccProcessArmor(Form: IInterface);
Var
ArmorType: Integer;
Begin
ArmorType := 0;
While(ArmorType <= 2)
Do Begin
// If(Skyrim.ArmoGetArmorType(Form) <> ArmorType)
//Then
DccMakeArmorVariant(Form,ArmorType,ArmorRating);
Inc(ArmorType);
End;
End;
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
Function Initialize: Integer;
Var
InputResult: Boolean;
InputArmorRating: String;
Begin
InputResult := InputQuery(
'Enter Armor Rating',
(
'Enter the armor rating the chest piece of this set should have. ' +
'The other pieces if they exist will be auto-calculated based on the chest piece. '+
'Here are some values to help you make reasonable not game-breaking armor. '+
'Cloth will always be given an armor value of 0 so mage perks work.' +
Skyrim.LineBreak + Skyrim.LineBreak +
'49 = Daedric' + Skyrim.LineBreak +
'46 = Dragonplate, Stalhrim'+ Skyrim.LineBreak +
'43 = Ebony and Nordic' + Skyrim.LineBreak +
'41 = Dragonscale' + Skyrim.LineBreak +
'40 = Orcish, Steel Plate, Chitin' + Skyrim.LineBreak +
'38 = Glass' + Skyrim.LineBreak +
'34 = Dwarven' + Skyrim.LineBreak +
'31 = Steel' + Skyrim.LineBreak +
'29 = Elven' + Skyrim.LineBreak +
'28 = Banded Iron' + Skyrim.LineBreak +
'25 = Iron' + Skyrim.LineBreak +
'20 = Hide' + Skyrim.LineBreak + + Skyrim.LineBreak +
'Default: 35' + Skyrim.LineBreak
),
InputArmorRating
);
If(InputResult = FALSE)
Then Result := 1;
InputArmorRating := Trim(InputArmorRating);
ArmorRating := StrToIntDef(InputArmorRating,35);
End;
Function Process(Form: IInterface): Integer;
Begin
If(CompareText('ARMO',Signature(Form)) <> 0)
Then Begin
AddMessage('[!!!] ' + EditorID(Form) + ' is not an armor.');
End
Else Begin
DccProcessArmor(Form);
End;
Result := 0;
End;
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
End.
|
unit uHik;
interface
uses
System.Classes, Generics.Collections, IdHTTP, SysUtils, uGlobal, uCommon,
uDecodeHikResult, DateUtils, ActiveX, uEntity;
type
TImageInfo = Record
GCXH: String;
KDBH: String;
CDBH: String;
Url: String;
PassTime: String;
End;
THik = class
private
class function HttPPost(AUrl: String; AParams: TStrings;
var AResult: String; AEncoding: TEncoding = nil): Boolean;
class function DFLogin(AUser, APwd: String; var AToken: String): Boolean;
class procedure DFLogout(AToken: String);
public
class function GetK08SearchParam(param, page, pageSize: string): TStrings;
class function DFCreateImageJob(AImages: TList<TImageInfo>): Boolean;
class function DFAnalysisOnePic(Url: String; var AMsg: String)
: TList<TDFVehInfo>; overload;
class function DFAnalysisOnePic(Url: String): String; overload;
class function GetK08VehInfo(hphm, hpzl: String): String;
class function GetK08PassList(kssj, jssj, hphm, hpzl, KDBH, clpp, csys,
clpp1, aqd, aqd1, zyb, zyb1, gj, page, pageSize: string): String;
overload;
class function GetK08PassList(AParams: TStrings; var totalPage: Integer;
var currentPage: Integer): TList<TK08VehInfo>; overload;
class function GetMaxPassTime(): String;
end;
implementation
class function THik.DFAnalysisOnePic(Url: String; var AMsg: String)
: TList<TDFVehInfo>;
var
Params: TStrings;
token, s: String;
begin
Result := nil;
ActiveX.CoInitializeEx(nil, COINIT_MULTITHREADED);
Params := TStringList.Create;
try
if not DFLogin(gHikConfig.DFUser, gHikConfig.DFPwd, s) then
exit;
if s = '' then
exit;
token := s;
Params.Add
('<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:wsdl="http://www.hikvision.com.cn/ver1/ivms/wsdl">');
Params.Add(' <soap:Header>');
Params.Add(' <wsdl:HeaderReq>');
Params.Add(' <wsdl:token>' + token + '</wsdl:token>');
Params.Add(' <wsdl:version>1.2</wsdl:version>');
Params.Add(' </wsdl:HeaderReq>');
Params.Add(' </soap:Header>');
Params.Add(' <soap:Body>');
Params.Add(' <wsdl:PicAnalysisReq>');
Params.Add(' <wsdl:nDataType>1</wsdl:nDataType>');
Params.Add(' <wsdl:algorithmType>258</wsdl:algorithmType>');
Params.Add(' <wsdl:strPicUrl>' + Url + '</wsdl:strPicUrl>');
Params.Add(' <wsdl:PicData>cid:1211963137164</wsdl:PicData>');
Params.Add(' </wsdl:PicAnalysisReq>');
Params.Add(' </soap:Body>');
Params.Add('</soap:Envelope>');
if HttPPost(gHikConfig.DFUrl, Params, s) then
begin
Result := TDecodeHikResult.DecodeDFAnalysisOnePicResult(s);
end
else
begin
glogger.Error(s);
AMsg := s;
end;
DFLogout(token);
except
on e: exception do
begin
glogger.Error(e.Message);
AMsg := e.Message;
end;
end;
Params.Free;
ActiveX.CoUninitialize;
end;
class function THik.DFAnalysisOnePic(Url: String): String;
var
msg: String;
ls: TList<TDFVehInfo>;
begin
Result := '';
ls := DFAnalysisOnePic(Url, msg);
if ls <> nil then
Result := TCommon.RecordListToJSON<TDFVehInfo>(ls);
end;
class function THik.DFCreateImageJob(AImages: TList<TImageInfo>): Boolean;
var
Params: TStrings;
token, s, imgStr: String;
img: TImageInfo;
begin
Result := False;
ActiveX.CoInitializeEx(nil, COINIT_MULTITHREADED);
if not DFLogin(gHikConfig.DFUser, gHikConfig.DFPwd, s) then
exit;
if s = '' then
exit;
token := s;
Params := TStringList.Create;
Params.Add
('<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:wsdl="http://www.hikvision.com.cn/ver1/ivms/wsdl" xmlns:ivms="http://www.hikvision.com.cn/ver1/schema/ivms/">');
Params.Add(' <soap:Header>');
Params.Add(' <wsdl:HeaderReq>');
Params.Add(' <wsdl:token>' + token + '</wsdl:token>');
Params.Add(' <wsdl:version>1.2</wsdl:version>');
Params.Add(' </wsdl:HeaderReq>');
Params.Add(' </soap:Header>');
Params.Add(' <soap:Body>');
Params.Add(' <wsdl:SubmitJobReq>');
Params.Add(' <wsdl:jobInfo>');
Params.Add(' <ivms:jobName>job_' +
FormatDateTime('yyyymmddhhnnsszzz', Now()) + '</ivms:jobName>');
Params.Add(' <ivms:jobType>2</ivms:jobType>');
Params.Add(' <ivms:dataSourceType>2</ivms:dataSourceType>');
Params.Add(' <ivms:priority>30</ivms:priority>');
Params.Add(' <ivms:source>test111</ivms:source>');
Params.Add(' <ivms:algorithmType>770</ivms:algorithmType>');
Params.Add(' <!--1 or more repetitions:-->');
Params.Add(' <ivms:destinationInfos>');
Params.Add(' <ivms:destinationUrl>' + gHikConfig.K08SaveUrl +
'</ivms:destinationUrl>');
Params.Add(' <ivms:destinationType>17</ivms:destinationType>');
Params.Add(' </ivms:destinationInfos>');
Params.Add(' <ivms:streamInfo>');
Params.Add(' <ivms:streamType>2</ivms:streamType>');
imgStr := ' <ivms:streamUrl>images://{"imageInfos": [';
for img in AImages do
begin
imgStr := imgStr + '{"data": "' + img.Url + '",' +
'"dataType": 1,"id": "dddddddddddddd","LaneNO": 1,"plate": "","vehicleDir": 0,'
+ '"targetAttrs": "{\n\t\"crossing_id\":\t\"' + img.KDBH +
'\",\n\t\"pass_id\":\t\"' + img.GCXH + '\",\n\t\"lane_no\":\t\"' +
img.CDBH + '\",\n\t\"pass_time\":\t\"' + img.PassTime + '\"\n}"},'
end;
imgStr := copy(imgStr, 1, Length(imgStr) - 1) +
'],"operate":524287,"targetNum":100,"plateRegMode": 0}</ivms:streamUrl>';
Params.Add(imgStr);
Params.Add(' <ivms:smart>false</ivms:smart>');
Params.Add(' <ivms:maxSplitCount>0</ivms:maxSplitCount>');
Params.Add(' <ivms:splitTime>0</ivms:splitTime>');
Params.Add(' </ivms:streamInfo>');
Params.Add(' </wsdl:jobInfo>');
Params.Add(' </wsdl:SubmitJobReq>');
Params.Add(' </soap:Body>');
Params.Add('</soap:Envelope>');
Result := HttPPost(gHikConfig.DFUrl, Params, s);
DFLogout(token);
glogger.Debug(s);
Params.Free;
ActiveX.CoUninitialize;
end;
class function THik.DFLogin(AUser, APwd: String; var AToken: String): Boolean;
var
Params: TStrings;
token: String;
begin
AToken := '';
Result := False;
Params := TStringList.Create;
Params.Add
('<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:wsdl="http://www.hikvision.com.cn/ver1/ivms/wsdl">');
Params.Add(' <soap:Header/>');
Params.Add(' <soap:Body>');
Params.Add(' <wsdl:LoginReq>');
Params.Add(' <wsdl:userName>' + AUser + '</wsdl:userName>');
Params.Add(' <wsdl:password>' + APwd + '</wsdl:password>');
Params.Add(' </wsdl:LoginReq>');
Params.Add(' </soap:Body>');
Params.Add('</soap:Envelope>');
if HttPPost(gHikConfig.DFUrl, Params, token) then
begin
if pos('<token>', token) > 0 then
token := copy(token, pos('<token>', token) + 7, Length(token));
if pos('</token>', token) > 0 then
AToken := copy(token, 1, pos('</token>', token) - 1);
Result := True;
end;
Params.Free;
end;
class procedure THik.DFLogout(AToken: String);
var
Params: TStrings;
s: String;
begin
Params := TStringList.Create;
Params.Add
('<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:wsdl="http://www.hikvision.com.cn/ver1/ivms/wsdl">');
Params.Add(' <soap:Header>');
Params.Add(' <wsdl:HeaderReq>');
Params.Add(' <wsdl:token>' + AToken + '</wsdl:token>');
Params.Add(' <wsdl:version>1.2</wsdl:version>');
Params.Add(' </wsdl:HeaderReq>');
Params.Add(' </soap:Header>');
Params.Add(' <soap:Body>');
Params.Add(' <wsdl:LogoutReq>');
Params.Add(' <wsdl:token>' + AToken + '</wsdl:token>');
Params.Add(' </wsdl:LogoutReq>');
Params.Add(' </soap:Body>');
Params.Add('</soap:Envelope>');
HttPPost(gHikConfig.DFUrl, Params, s);
Params.Free;
end;
class function THik.GetK08PassList(AParams: TStrings; var totalPage: Integer;
var currentPage: Integer): TList<TK08VehInfo>;
var
s: String;
begin
Result := nil;
ActiveX.CoInitializeEx(nil, COINIT_MULTITHREADED);
if HttPPost(gHikConfig.K08SearchURL, AParams, s, TEncoding.UTF8) then
begin
try
Result := TDecodeHikResult.DecodeK08SearchResult(s, totalPage,
currentPage);
except
glogger.Error(s);
end;
end;
ActiveX.CoUninitialize;
end;
class function THik.GetK08SearchParam(param, page, pageSize: string): TStrings;
begin
Result := TStringList.Create;
Result.Add
('<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://www.hikvision.com/kms/ws/">');
Result.Add(' <soapenv:Header/>');
Result.Add(' <soapenv:Body>');
Result.Add(' <ws:moreLikeThis>');
Result.Add(' <arg0>');
Result.Add(' <appCode>ivms8200_hare</appCode>');
Result.Add(' <beanId>pass</beanId>');
Result.Add(' <currentPage>' + page + '</currentPage>');
Result.Add(' <pageSize>' + pageSize + '</pageSize>');
Result.Add(' <password>vlss</password>');
Result.Add(' <q>' + param + '</q>');
Result.Add(' <tableName>BayonetVehiclePass</tableName>');
Result.Add(' <userName>vlss</userName>');
Result.Add(' </arg0>');
Result.Add(' </ws:moreLikeThis>');
Result.Add(' </soapenv:Body>');
Result.Add('</soapenv:Envelope>');
end;
class function THik.GetK08PassList(kssj, jssj, hphm, hpzl, KDBH, clpp, csys,
clpp1, aqd, aqd1, zyb, zyb1, gj, page, pageSize: string): String;
var
Params: TStrings;
param, s, h: String;
vehList: TList<TK08VehInfo>;
veh: TK08VehInfo;
totalPage, currentPage: Integer;
begin
Result := '';
ActiveX.CoInitializeEx(nil, COINIT_MULTITHREADED);
param := 'passtime:([' + kssj + ' TO ' + jssj + '])';
if (KDBH <> '') and gDevKDBH.ContainsKey(KDBH) then
param := param + ' AND crossingid:(' + gDevKDBH[KDBH] + ')';
if hphm <> '' then
param := param + ' AND plateinfono:(' + hphm + ')';
if (hpzl <> '') and (gK08Hpzl.ContainsKey(hpzl)) then
begin
for s in gK08Hpzl[hpzl] do
h := h + ' ' + s;
param := param + ' AND vehicletype:(' + h.Substring(1) + ')';
end;
if clpp <> '' then
param := param + ' AND vehiclelogo:(' + clpp + ')';
if csys <> '' then
param := param + ' AND vehiclecolor:(' + csys + ')';
if clpp1 <> '' then
param := param + ' AND vehiclesublogo:(' + clpp1 + ')';
if aqd <> '' then
param := param + ' AND pilotsafebelt:(' + aqd + ')';
if aqd1 <> '' then
param := param + ' AND vicepilotsafebelt:(' + aqd1 + ')';
if zyb <> '' then
param := param + ' AND vehiclesunvisor:(' + zyb + ')';
if zyb1 <> '' then
param := param + ' AND vicepilotsunvisor:(' + zyb1 + ')';
if gj <> '' then
param := param + ' AND pendant:(' + gj + ')';
param := '(' + param + ')';
Params := GetK08SearchParam(param, page, pageSize);
if HttPPost(gHikConfig.K08SearchURL, Params, s, TEncoding.UTF8) then
begin
try
vehList := TDecodeHikResult.DecodeK08SearchResult(s, totalPage,
currentPage);
except
glogger.Error(s);
end;
if (vehList <> nil) and (vehList.Count > 0) then
begin
for veh in vehList do
begin
// HPHM,HPZL,GCSJ,KDBH,CDBH,CLSD FWQDZ, TP1
// if Length(veh.plateinfono) < 6 then
// continue;
s := '"HPHM":"' + veh.plateinfono + '",';
if gHpzl.ContainsKey(veh.vehicletype) then
s := s + '"HPZL":"' + gHpzl[veh.vehicletype] + '"'
else
s := s + '"HPZL":"' + veh.vehicletype + '"';
s := s + ',"GCSJ":"' + veh.PassTime + '",';
if gDevID.ContainsKey(veh.crossingid) then
s := s + '"KDBH":"' + gDevID[veh.crossingid] + '"'
else
s := s + '"KDBH":"' + veh.crossingid + '"';
if gK08Clpp.ContainsKey(veh.vehiclesublogoall) then
s := s + ',"CLPP":"' + gK08Clpp[veh.vehiclesublogoall] + '"'
else if gK08Clpp.ContainsKey(veh.vehiclelogo + '-0') then
s := s + ',"CLPP":"' + gK08Clpp[veh.vehiclelogo + '-0'] + '"'
else
s := s + ',"CLPP":"' + veh.vehiclesublogoall + '"';
if gK08Csys.ContainsKey(veh.vehiclecolor) then
s := s + ',"CSYS":"' + gK08Csys[vehList[0].vehiclecolor] + '"'
else
s := s + ',"CSYS":"' + veh.vehiclecolor + '"';
s := '{' + s + ',"CDBH":"' + veh.laneid + '","CLSD":"' +
veh.vehiclespeed + '","FWQDZ":"","TP1":"' + veh.picvehicle + '"}';
Result := Result + ',' + s;
end;
Result := '[' + Result.Substring(1) + ']';
vehList.Free;
end
end;
Params.Free;
ActiveX.CoUninitialize;
end;
class function THik.GetK08VehInfo(hphm, hpzl: String): String;
var
Params: TStrings;
param, s: String;
vehList: TList<TK08VehInfo>;
totalPage, currentPage: Integer;
begin
Result := '';
ActiveX.CoInitializeEx(nil, COINIT_MULTITHREADED);
if gK08Hpzl.ContainsKey(hpzl) then
begin
for s in gK08Hpzl[hpzl] do
param := param + ' ' + s;
end;
param := '(vehicletype:(' + param.Substring(1) + ') AND plateinfono:(' +
hphm + '))';
Params := GetK08SearchParam(param, '1', '1');
if HttPPost(gHikConfig.K08SearchURL, Params, s, TEncoding.UTF8) then
begin
vehList := TDecodeHikResult.DecodeK08SearchResult(s, totalPage,
currentPage);
if (vehList <> nil) and (vehList.Count > 0) then
begin
if gK08Clpp.ContainsKey(vehList[0].vehiclesublogoall) then
Result := '"CLPP":"' + gK08Clpp[vehList[0].vehiclesublogoall] + '"'
else if gK08Clpp.ContainsKey(vehList[0].vehiclelogo + '-0') then
Result := 'CLPP:"' + gK08Clpp[vehList[0].vehiclelogo + '-0'] + '"'
else
Result := '"CLPP":"' + vehList[0].vehiclesublogoall + '"';
if gK08Csys.ContainsKey(vehList[0].vehiclecolor) then
Result := Result + ',"CSYS":"' + gK08Csys[vehList[0].vehiclecolor] + '"'
else
Result := Result + ',"CSYS":"' + vehList[0].vehiclecolor + '"';
Result := '[{' + Result + '}]';
vehList.Free;
end
end;
Params.Free;
ActiveX.CoUninitialize;
end;
class function THik.GetMaxPassTime: String;
var
Params: TStrings;
param: String;
vehList: TList<TK08VehInfo>;
c, t: Integer;
begin
Result := '';
param := 'vehicletype:(3)';
Params := GetK08SearchParam(param, '1', '1');
vehList := GetK08PassList(Params, c, t);
if (vehList <> nil) and (vehList.Count > 0) then
begin
Result := vehList[0].PassTime;
vehList.Free;
end;
Params.Free;
end;
class function THik.HttPPost(AUrl: String; AParams: TStrings;
var AResult: String; AEncoding: TEncoding = nil): Boolean;
var
http: TIdHTTP;
stream: TMemoryStream;
response: TStream;
bytes: TBytes;
begin
AResult := '';
Result := False;
http := TIdHTTP.Create(nil);
stream := TMemoryStream.Create;
try
if AEncoding = nil then
AParams.SaveToStream(stream)
else
AParams.SaveToStream(stream, AEncoding);
response := TMemoryStream.Create();
http.Post(AUrl, stream, response);
SetLength(bytes, response.Size);
response.Seek(0, TSeekOrigin.soBeginning);
response.ReadBuffer(bytes, response.Size);
response.Free;
AResult := TEncoding.UTF8.GetString(bytes);
Result := True;
except
AResult := UTF8Decode(http.ResponseText);
end;
stream.Free;
http.Disconnect;
http.Free;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ Web server application components }
{ }
{ Copyright (c) 1997,99 Inprise Corporation }
{ }
{*******************************************************}
{$DENYPACKAGEUNIT}
unit WebBroker;
interface
uses SyncObjs, SysUtils, Classes, Masks, Forms, HTTPApp, Contnrs;
type
TWebApplication = class(TComponent)
private
FWebModuleClass: TComponentClass;
FCriticalSection: TCriticalSection;
FActiveWebModules: TList;
FInactiveWebModules: TList;
FTitle: string;
FMaxConnections: Integer;
FCacheConnections: Boolean;
function GetActiveCount: Integer;
function GetInactiveCount: Integer;
procedure SetCacheConnections(Value: Boolean);
procedure OnExceptionHandler(Sender: TObject; E: Exception);
protected
function ActivateWebModule: TDataModule;
procedure DeactivateWebModule(DataModule: TDataModule);
procedure DoHandleException(E: Exception); dynamic;
function HandleRequest(Request: TWebRequest; Response: TWebResponse): Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
// The following is uses the current behaviour of the IDE module manager
procedure CreateForm(InstanceClass: TComponentClass; var Reference); virtual;
procedure Initialize; virtual;
procedure Run; virtual;
property ActiveCount: Integer read GetActiveCount;
property CacheConnections: Boolean read FCacheConnections write SetCacheConnections;
property InactiveCount: Integer read GetInactiveCount;
property MaxConnections: Integer read FMaxConnections write FMaxConnections;
property Title: string read FTitle write FTitle;
end;
var
Application: TWebApplication = nil;
implementation
uses BrkrConst, Windows;
{ TWebApplication }
procedure DoneVCLApplication;
begin
with Forms.Application do
begin
if Handle <> 0 then ShowOwnedPopups(Handle, False);
ShowHint := False;
Destroying;
DestroyComponents;
end;
with Application do
begin
Destroying;
DestroyComponents;
end;
end;
procedure DLLExitProc(Reason: Integer); register;
begin
if Reason = DLL_PROCESS_DETACH then DoneVCLApplication;
end;
constructor TWebApplication.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCriticalSection := TCriticalSection.Create;
FActiveWebModules := TList.Create;
FInactiveWebModules := TList.Create;
FMaxConnections := 32;
FCacheConnections := True;
if IsLibrary then
begin
IsMultiThread := True;
DLLProc := @DLLExitProc;
end;
end;
destructor TWebApplication.Destroy;
begin
Forms.Application.OnException := nil;
FCriticalSection.Free;
FActiveWebModules.Free;
FInactiveWebModules.Free;
inherited Destroy;
end;
procedure TWebApplication.CreateForm(InstanceClass: TComponentClass;
var Reference);
begin
if FWebModuleClass = nil then
FWebModuleClass := InstanceClass
else raise Exception.CreateRes(@sOnlyOneDataModuleAllowed);
end;
function TWebApplication.ActivateWebModule: TDataModule;
begin
FCriticalSection.Enter;
try
Result := nil;
if (FMaxConnections > 0) and (FActiveWebModules.Count >= FMaxConnections) then
raise Exception.CreateRes(@sTooManyActiveConnections);
if FInactiveWebModules.Count > 0 then
begin
Result := FInactiveWebModules[0];
FInactiveWebModules.Delete(0);
FActiveWebModules.Add(Result);
end else if FWebModuleClass <> nil then
begin
TComponent(Result) := FWebModuleClass.Create(Self);
FActiveWebModules.Add(Result);
end else raise Exception.CreateRes(@sNoDataModulesRegistered);
finally
FCriticalSection.Leave;
end;
end;
procedure TWebApplication.DeactivateWebModule(DataModule: TDataModule);
begin
FCriticalSection.Enter;
try
FActiveWebModules.Remove(DataModule);
if FCacheConnections then
FInactiveWebModules.Add(DataModule)
else DataModule.Free;
finally
FCriticalSection.Leave;
end;
end;
procedure TWebApplication.DoHandleException(E: Exception);
begin
end;
function TWebApplication.GetActiveCount: Integer;
begin
FCriticalSection.Enter;
try
Result := FActiveWebModules.Count;
finally
FCriticalSection.Leave;
end;
end;
function TWebApplication.GetInactiveCount: Integer;
begin
FCriticalSection.Enter;
try
Result := FInactiveWebModules.Count;
finally
FCriticalSection.Leave;
end;
end;
type
TWebDispatcherAccess = class(TCustomWebDispatcher);
function TWebApplication.HandleRequest(Request: TWebRequest;
Response: TWebResponse): Boolean;
var
DataModule: TDataModule;
Dispatcher: TCustomWebDispatcher;
I: Integer;
begin
Result := False;
DataModule := ActivateWebModule;
if DataModule <> nil then
try
if DataModule is TCustomWebDispatcher then
Dispatcher := TCustomWebDispatcher(DataModule)
else with DataModule do
begin
Dispatcher := nil;
for I := 0 to ComponentCount - 1 do
begin
if Components[I] is TCustomWebDispatcher then
begin
Dispatcher := TCustomWebDispatcher(Components[I]);
Break;
end;
end;
end;
if Dispatcher <> nil then
begin
Result := TWebDispatcherAccess(Dispatcher).DispatchAction(Request, Response);
if Result and not Response.Sent then
Response.SendResponse;
end else raise Exception.CreateRes(@sNoDispatcherComponent);
finally
DeactivateWebModule(DataModule);
end;
end;
procedure TWebApplication.Initialize;
begin
// This is a place holder
if InitProc <> nil then TProcedure(InitProc);
end;
procedure TWebApplication.OnExceptionHandler(Sender: TObject; E: Exception);
begin
DoHandleException(E);
end;
procedure TWebApplication.SetCacheConnections(Value: Boolean);
var
I: Integer;
begin
if Value <> FCacheConnections then
begin
FCacheConnections := Value;
if not Value then
begin
FCriticalSection.Enter;
try
for I := 0 to FInactiveWebModules.Count - 1 do
TDataModule(FInactiveWebModules[I]).Free;
FInactiveWebModules.Clear;
finally
FCriticalSection.Leave;
end;
end;
end;
end;
procedure TWebApplication.Run;
begin
if not IsLibrary then AddExitProc(DoneVCLApplication);
Forms.Application.OnException := OnExceptionHandler;
end;
end.
|
unit uRelatorioAlunoProfessor;
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, RLReport, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client;
type
TfrmRelatorioAlunoProfessor = class(TForm)
qrDados: TFDQuery;
dsDados: TDataSource;
rpAlunoProfessor: TRLReport;
rlbHeader: TRLBand;
rllTitulo: TRLLabel;
rbbBtHeader: TRLBand;
rllAluno: TRLLabel;
rllProfessor: TRLLabel;
rlBtDetalhes: TRLBand;
rbtAluno: TRLDBText;
qrAlunos: TFDQuery;
dsAlunos: TDataSource;
qrDadosID: TIntegerField;
qrDadosDISCIPLINA_ID: TIntegerField;
qrDadosALUNO_ID: TIntegerField;
qrDadosPROFESSOR_ID: TIntegerField;
qrDadosNOTA_PERIODO_1: TSingleField;
qrDadosNOTA_PERIODO_2: TSingleField;
qrDadosNOTA_TRABLHO: TSingleField;
qrDadosMEDIA: TSingleField;
qrDadosSITUACAO: TStringField;
qrAlunosID: TIntegerField;
qrAlunosNOME: TStringField;
qrAlunosCPF: TStringField;
qrDadosALUNOS: TStringField;
qrProfessores: TFDQuery;
dsProfessor: TDataSource;
qrProfessoresID: TIntegerField;
qrProfessoresNOME: TStringField;
qrProfessoresCPF: TStringField;
rbtProfessor: TRLDBText;
qrDadosPROFESSORES: TStringField;
RLGroup1: TRLGroup;
rlSumario: TRLBand;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure rpAlunoProfessorBeforePrint(Sender: TObject;
var PrintIt: Boolean);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmRelatorioAlunoProfessor: TfrmRelatorioAlunoProfessor;
implementation
{$R *.dfm}
uses udmPrincipal;
procedure TfrmRelatorioAlunoProfessor.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
frmRelatorioAlunoProfessor := nil;
end;
procedure TfrmRelatorioAlunoProfessor.rpAlunoProfessorBeforePrint(
Sender: TObject; var PrintIt: Boolean);
begin
qrDados.Open;
qrAlunos.Open;
qrProfessores.Open;
qrDados.Refresh;
end;
end.
|
unit ProductsViewForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, RootForm, ProductsView;
type
TfrmProducts = class(TfrmRoot)
procedure FormActivate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDeactivate(Sender: TObject);
private
FViewProducts: TViewProducts;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
property ViewProducts: TViewProducts read FViewProducts;
{ Public declarations }
end;
var
frmProducts: TfrmProducts;
implementation
{$R *.dfm}
constructor TfrmProducts.Create(AOwner: TComponent);
begin
inherited;
FViewProducts := TViewProducts.Create(Self);
FViewProducts.Parent := Self;
FViewProducts.Align := alClient;
FViewProducts.actFullScreen.Visible := False;
end;
procedure TfrmProducts.FormActivate(Sender: TObject);
begin
inherited;
ViewProducts.ConnectView;
// Выводим в заголовок формы название текущего склада
Caption := ViewProducts.ProductsModel.StorehouseListInt.StoreHouseTitle;
end;
procedure TfrmProducts.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
Action := caFree;
frmProducts := nil;
end;
procedure TfrmProducts.FormDeactivate(Sender: TObject);
begin
inherited;
ViewProducts.DisconnectView;
end;
end.
|
{******************************************}
{ }
{ vtk GridReport library }
{ }
{ Copyright (c) 2004 by vtkTools }
{ }
{******************************************}
{Contains the some base classes which are used in other modules.}
unit vgr_Button;
interface
{$I vtk.inc}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
stdctrls,Buttons;
type
TvgrDropDownForm = class;
TvgrDropDownFormClass = class of TvgrDropDownForm;
/////////////////////////////////////////////////
//
// TvgrBaseButton
//
/////////////////////////////////////////////////
{Base class for buttons.
See also:
TvgrColorButton, TvgrMultiPageButton}
TvgrBaseButton = class(TButtonControl)
private
FFlat: Boolean;
FDropDownArrow: Boolean;
FMouseInControl: Boolean;
FDropDownForm: TvgrDropDownForm;
procedure SetDropDownArrow(Value: Boolean);
procedure SetFlat(Value: Boolean);
protected
function GetDropDownFormClass: TvgrDropDownFormClass; virtual;
function GetDrawFocusRect: Boolean; virtual;
procedure ShowDropDownForm; virtual;
procedure DrawFocusedBorder(ADC: HDC; var ARect: TRect; AFillInnerRect: Boolean);
procedure DrawRaiseBorder(ADC: HDC; var ARect: TRect; AFillInnerRect: Boolean);
procedure DrawInnerBorder(ADC: HDC; var ARect: TRect; AFillInnerRect: Boolean);
procedure DrawNoBorder(ADC: HDC; var ARect: TRect; AFillInnerRect: Boolean);
procedure DrawButton(ADC: HDC; ADisabled, APushed, AFocused, AUnderMouse: Boolean); virtual;
procedure DrawButtonInternal(ADC: HDC; ADisabled, APushed, AFocused, AUnderMouse: Boolean; const AInternalRect: TRect); virtual;
procedure CNDrawItem(var Msg: TWMDrawItem); message CN_DRAWITEM;
procedure CMMouseEnter(var Msg: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Msg: TMessage); message CM_MOUSELEAVE;
//procedure CNCommand(var Msg: TWMCommand); message CN_COMMAND;
procedure CreateParams(var Params: TCreateParams); override;
property DropDownForm: TvgrDropDownForm read FDropDownForm write FDropDownForm;
property MouseInControl: Boolean read FMouseInControl write FMouseInControl;
public
{Creates an instance of the TvgrBaseButton class.
Parameters:
AOwner - The component - owner.}
constructor Create(AOwner: TComponent); override;
published
{Set Flat to true to remove the raised border when the button is unselected and the lowered border when the button is clicked or selected.}
property Flat: Boolean read FFlat write SetFlat default False;
{Specifies the value indicating whether the arrow is visible.}
property DropDownArrow: Boolean read FDropDownArrow write SetDropDownArrow default False;
end;
/////////////////////////////////////////////////
//
// TvgrDropDownForm
//
/////////////////////////////////////////////////
{Base class for drop-down panels.
See also:
TvgrColorPaletteForm, TvgrMultiPagePaletteForm}
TvgrDropDownForm = class(TForm)
private
FButton: TvgrBaseButton;
protected
procedure WMEraseBkgnd(var Msg: TWMEraseBkgnd); message WM_ERASEBKGND;
procedure CreateParams(var Params: TCreateParams); override;
procedure DoClose(var Action: TCloseAction); override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure Deactivate; override;
property Button: TvgrBaseButton read FButton write FButton;
public
constructor Create(AOwner: TComponent); override;
procedure BeforeDestruction; override;
end;
implementation
uses
vgr_Functions, vgr_GUIFunctions;
/////////////////////////////////////////////////
//
// TvgrBaseButton
//
/////////////////////////////////////////////////
constructor TvgrBaseButton.Create(AOwner: TComponent);
begin
inherited;
end;
procedure TvgrBaseButton.SetFlat(Value: Boolean);
begin
if FFlat <> Value then
begin
FFlat := Value;
Invalidate;
end;
end;
procedure TvgrBaseButton.SetDropDownArrow(Value: Boolean);
begin
if FDropDownArrow <> Value then
begin
FDropDownArrow := Value;
Invalidate;
end;
end;
procedure TvgrBaseButton.CreateParams(var Params: TCreateParams);
begin
inherited;
CreateSubClass(Params, 'BUTTON');
Params.Style := Params.Style or BS_PUSHBUTTON or BS_OWNERDRAW;
end;
{
procedure TvgrBaseButton.CNCommand(var Msg: TWMCommand);
begin
if Msg.NotifyCode = BN_CLICKED then
begin
Click;
Msg.Result := 1;
end;
end;
}
procedure TvgrBaseButton.CMMouseEnter(var Msg: TMessage);
begin
if not (csDesigning in ComponentState) then
begin
FMouseInControl := True;
Invalidate;
end;
inherited;
end;
procedure TvgrBaseButton.CMMouseLeave(var Msg: TMessage);
begin
if not (csDesigning in ComponentState) then
begin
FMouseInControl := False;
Invalidate;
end;
inherited;
end;
procedure TvgrBaseButton.CNDrawItem(var Msg: TWMDrawItem);
begin
with Msg.DrawItemStruct^ do
DrawButton(hDC,
(itemState and ODS_DISABLED) <> 0,
(itemState and ODS_SELECTED) <> 0,
(itemState and ODS_FOCUS) <> 0,
FMouseInControl or (csDesigning in ComponentState));
Msg.Result := 1;
end;
procedure TvgrBaseButton.DrawRaiseBorder(ADC: HDC; var ARect: TRect; AFillInnerRect: Boolean);
var
ABrush: HBRUSH;
begin
ABrush := CreateSolidBrush(GetRGBColor(clBtnHighlight));
with ARect do
begin
FillRect(ADC, Rect(Left, Top, Left + 1, Bottom - 1), ABrush);
FillRect(ADC, Rect(Left, Top, Right - 1, Top + 1), ABrush);
end;
DeleteObject(ABrush);
ABrush := CreateSolidBrush(GetRGBColor(clBtnShadow));
with ARect do
begin
FillRect(ADC, Rect(Left, Bottom - 1, Right, Bottom), ABrush);
FillRect(ADC, Rect(Right - 1, Top, Right, Bottom), ABrush);
end;
DeleteObject(ABrush);
InflateRect(ARect, -1, -1);
if AFillInnerRect then
begin
ABrush := CreateSolidBrush(GetRGBColor(clBtnFace));
FillRect(ADC, ARect, ABrush);
DeleteObject(ABrush);
end;
end;
procedure TvgrBaseButton.DrawInnerBorder(ADC: HDC; var ARect: TRect; AFillInnerRect: Boolean);
var
ABrush: HBRUSH;
begin
ABrush := CreateSolidBrush(GetRGBColor(clBtnShadow));
with ARect do
begin
FillRect(ADC, Rect(Left, Top, Left + 1, Bottom - 1), ABrush);
FillRect(ADC, Rect(Left, Top, Right - 1, Top + 1), ABrush);
end;
DeleteObject(ABrush);
ABrush := CreateSolidBrush(GetRGBColor(clBtnHighlight));
with ARect do
begin
FillRect(ADC, Rect(Left, Bottom - 1, Right, Bottom), ABrush);
FillRect(ADC, Rect(Right - 1, Top, Right, Bottom), ABrush);
end;
DeleteObject(ABrush);
InflateRect(ARect, -1, -1);
if AFillInnerRect then
begin
ABrush := CreateSolidBrush(GetRGBColor(clBtnFace));
FillRect(ADC, ARect, ABrush);
DeleteObject(ABrush);
end;
end;
procedure TvgrBaseButton.DrawFocusedBorder(ADC: HDC; var ARect: TRect; AFillInnerRect: Boolean);
var
ABrush: HBRUSH;
begin
ABrush := CreateSolidBrush(GetRGBColor(clBtnShadow));
with ARect do
begin
FillRect(ADC, Rect(Left, Top, Left + 1, Bottom - 1), ABrush);
FillRect(ADC, Rect(Left, Top, Right - 1, Top + 1), ABrush);
FillRect(ADC, Rect(Left, Bottom - 1, Right, Bottom), ABrush);
FillRect(ADC, Rect(Right - 1, Top, Right, Bottom), ABrush);
end;
DeleteObject(ABrush);
InflateRect(ARect, -1, -1);
if AFillInnerRect then
begin
ABrush := CreateSolidBrush(GetRGBColor(clBtnHighlight));
FillRect(ADC, ARect, ABrush);
DeleteObject(ABrush);
end;
end;
procedure TvgrBaseButton.DrawNoBorder(ADC: HDC; var ARect: TRect; AFillInnerRect: Boolean);
var
ABrush: HBRUSH;
begin
if AFillInnerRect then
begin
ABrush := CreateSolidBrush(GetRGBColor(clBtnFace));
FillRect(ADC, ARect, ABrush);
DeleteObject(ABrush);
end;
InflateRect(ARect, -1, -1);
end;
function TvgrBaseButton.GetDropDownFormClass: TvgrDropDownFormClass;
begin
Result := nil;
end;
function TvgrBaseButton.GetDrawFocusRect: Boolean;
begin
Result := True;
end;
procedure TvgrBaseButton.ShowDropDownForm;
var
R: TRect;
P: TPoint;
begin
FDropDownForm := GetDropDownFormClass.Create(Self);
FDropDownForm.Button := Self;
SystemParametersInfo(SPI_GETWORKAREA, 0, @R, 0);
P := ClientToScreen(Point(0, 0));
P.Y := P.Y + Height;
if P.X + FDropDownForm.Width > R.Right then
P.X := P.X - FDropDownForm.Width;
if P.Y + FDropDownForm.Height > r.Bottom then
P.Y := p.Y - FDropDownForm.Height - Height;
FDropDownForm.Left := P.X;
FDropDownForm.Top := P.Y;
FDropDownForm.Show;
end;
procedure TvgrBaseButton.DrawButton(ADC: HDC; ADisabled, APushed, AFocused, AUnderMouse: Boolean);
const
APushedArray: Array [Boolean] of Integer = (0, DFCS_PUSHED);
ADisabledArray: Array [Boolean] of Integer = (0, DFCS_INACTIVE);
var
R: TRect;
y: Integer;
nbr: HBRUSH;
begin
r := ClientRect;
if FFlat then
begin
if ADisabled then
DrawNoBorder(ADC, r, True)
else
begin
if APushed then
DrawInnerBorder(ADC, r, True)
else
begin
if AUnderMouse then
DrawRaiseBorder(ADC, r, True)
else
DrawNoBorder(ADC, r, True);
end
end;
InflateRect(r, -1, -1);
end
else
begin
DrawFrameControl(ADC, r, DFC_BUTTON, DFCS_ADJUSTRECT or DFCS_BUTTONPUSH or APushedArray[APushed] or ADisabledArray[ADisabled]);
InflateRect(r, -1, -1);
end;
if GetDrawFocusRect then
begin
if not ADisabled and AFocused then
DrawFocusRect(ADC, r);
InflateRect(r, -2, -2);
end;
if DropDownArrow then
begin
// draw arrow
nbr := CreateSolidBrush(GetRGBColor(clBlack));
with R do
begin
y := Top + (Bottom - Top) div 2 - 1;
FillRect(ADC, Rect(Right - 7, y, Right - 2, y + 1), nbr);
FillRect(ADC, Rect(Right - 6, y + 1, Right - 3, y + 2), nbr);
FillRect(ADC, Rect(Right - 5, y + 2, Right - 4, y + 3), nbr);
end;
DeleteObject(nbr);
r.Right := r.Right - 10;
nbr := CreateSolidBrush(GetRGBColor(clBtnShadow));
with r do
FillRect(ADC, Rect(Right, Top + 1, Right + 1, Bottom - 2), nbr);
DeleteObject(nbr);
nbr := CreateSolidBrush(GetRGBColor(clBtnHighlight));
with r do
FillRect(ADC, Rect(Right + 1, Top + 1, Right + 2, Bottom - 2), nbr);
DeleteObject(nbr);
end;
DrawButtonInternal(ADC, ADisabled, APushed, AFocused, AUnderMouse, r);
end;
procedure TvgrBaseButton.DrawButtonInternal(ADC: HDC; ADisabled, APushed, AFocused, AUnderMouse: Boolean; const AInternalRect: TRect);
begin
end;
/////////////////////////////////////////////////
//
// TvgrDropDownForm
//
/////////////////////////////////////////////////
constructor TvgrDropDownForm.Create(AOwner: TComponent);
begin
inherited;
end;
procedure TvgrDropDownForm.CreateParams;
begin
inherited;
Params.Style := Params.Style and not WS_CAPTION;
end;
procedure TvgrDropDownForm.WMEraseBkgnd(var Msg: TWMEraseBkgnd);
begin
Msg.Result := 1;
end;
procedure TvgrDropDownForm.DoClose(var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TvgrDropDownForm.Deactivate;
begin
inherited;
Close;
end;
procedure TvgrDropDownForm.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited;
if (Key = VK_ESCAPE) and (Shift = []) then
Close;
end;
procedure TvgrDropDownForm.BeforeDestruction;
begin
if FButton <> nil then
FButton.DropDownForm := nil;
end;
end.
|
unit amqp.framing;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
{$INCLUDE config.inc}
interface
uses {$IFNDEF FPC}
{$IFDEF _WIN32}
Net.Winsock2,
{$ELSE}
Net.SocketAPI,
{$ENDIF}
{$ELSE}
winsock2,
{$ENDIF}
AMQP.Types;
function amqp_encode_method(methodNumber : amqp_method_number_t;decoded: Pointer; encoded : Tamqp_bytes):integer;
function amqp_decode_method(methodNumber : amqp_method_number_t;pool : Pamqp_pool; encoded : Tamqp_bytes; out decoded: Pointer):integer;
function amqp_encode_properties(class_id : uint16;decoded: Pointer; encoded : Tamqp_bytes):integer;
function amqp_decode_properties(class_id : uint16; pool : Pamqp_pool; encoded : Tamqp_bytes; decoded: PPointer):integer;
function amqp_channel_open( state : Pamqp_connection_state; channel : amqp_channel_t): Pamqp_channel_open_ok;
function amqp_queue_bind( state : Pamqp_connection_state;
channel : amqp_channel_t; queue, exchange,
routing_key : Tamqp_bytes;
arguments : Tamqp_table): Pamqp_queue_bind_ok;
function amqp_exchange_declare( Astate : Pamqp_connection_state;
Achannel : amqp_channel_t;
Aexchange, Atype : Tamqp_bytes;
Apassive, Adurable, Aauto_delete, Ainternal : amqp_boolean_t;
Aarguments : Tamqp_table):Pamqp_exchange_declare_ok;
function amqp_queue_unbind( state : Pamqp_connection_state;
channel : amqp_channel_t;
queue, exchange, routing_key : Tamqp_bytes;
arguments : Tamqp_table): Pamqp_queue_unbind_ok;
function amqp_queue_declare( state : Pamqp_connection_state;
channel : amqp_channel_t; queue : Tamqp_bytes;
passive, durable, exclusive, auto_delete : amqp_boolean_t;
arguments : Tamqp_table): Pamqp_queue_declare_ok;
function amqp_method_name( methodNumber : amqp_method_number_t): PAnsiChar;
implementation
uses
amqp.privt, amqp.table, amqp.mem, amqp.socket;
function amqp_method_name( methodNumber : amqp_method_number_t): PAnsiChar;
begin
case methodNumber of
AMQP_CONNECTION_START_METHOD:
Exit('AMQP_CONNECTION_START_METHOD');
AMQP_CONNECTION_START_OK_METHOD:
Exit('AMQP_CONNECTION_START_OK_METHOD');
AMQP_CONNECTION_SECURE_METHOD:
Exit('AMQP_CONNECTION_SECURE_METHOD');
AMQP_CONNECTION_SECURE_OK_METHOD:
Exit('AMQP_CONNECTION_SECURE_OK_METHOD');
AMQP_CONNECTION_TUNE_METHOD:
Exit('AMQP_CONNECTION_TUNE_METHOD');
AMQP_CONNECTION_TUNE_OK_METHOD:
Exit('AMQP_CONNECTION_TUNE_OK_METHOD');
AMQP_CONNECTION_OPEN_METHOD:
Exit('AMQP_CONNECTION_OPEN_METHOD');
AMQP_CONNECTION_OPEN_OK_METHOD:
Exit('AMQP_CONNECTION_OPEN_OK_METHOD');
AMQP_CONNECTION_CLOSE_METHOD:
Exit('AMQP_CONNECTION_CLOSE_METHOD');
AMQP_CONNECTION_CLOSE_OK_METHOD:
Exit('AMQP_CONNECTION_CLOSE_OK_METHOD');
AMQP_CONNECTION_BLOCKED_METHOD:
Exit('AMQP_CONNECTION_BLOCKED_METHOD');
AMQP_CONNECTION_UNBLOCKED_METHOD:
Exit('AMQP_CONNECTION_UNBLOCKED_METHOD');
AMQP_CONNECTION_UPDATE_SECRET_METHOD:
Exit('AMQP_CONNECTION_UPDATE_SECRET_METHOD');
AMQP_CONNECTION_UPDATE_SECRET_OK_METHOD:
Exit('AMQP_CONNECTION_UPDATE_SECRET_OK_METHOD');
AMQP_CHANNEL_OPEN_METHOD:
Exit('AMQP_CHANNEL_OPEN_METHOD');
AMQP_CHANNEL_OPEN_OK_METHOD:
Exit('AMQP_CHANNEL_OPEN_OK_METHOD');
AMQP_CHANNEL_FLOW_METHOD:
Exit('AMQP_CHANNEL_FLOW_METHOD');
AMQP_CHANNEL_FLOW_OK_METHOD:
Exit('AMQP_CHANNEL_FLOW_OK_METHOD');
AMQP_CHANNEL_CLOSE_METHOD:
Exit('AMQP_CHANNEL_CLOSE_METHOD');
AMQP_CHANNEL_CLOSE_OK_METHOD:
Exit('AMQP_CHANNEL_CLOSE_OK_METHOD');
AMQP_ACCESS_REQUEST_METHOD:
Exit('AMQP_ACCESS_REQUEST_METHOD');
AMQP_ACCESS_REQUEST_OK_METHOD:
Exit('AMQP_ACCESS_REQUEST_OK_METHOD');
AMQP_EXCHANGE_DECLARE_METHOD:
Exit('AMQP_EXCHANGE_DECLARE_METHOD');
AMQP_EXCHANGE_DECLARE_OK_METHOD:
Exit('AMQP_EXCHANGE_DECLARE_OK_METHOD');
AMQP_EXCHANGE_DELETE_METHOD:
Exit('AMQP_EXCHANGE_DELETE_METHOD');
AMQP_EXCHANGE_DELETE_OK_METHOD:
Exit('AMQP_EXCHANGE_DELETE_OK_METHOD');
AMQP_EXCHANGE_BIND_METHOD:
Exit('AMQP_EXCHANGE_BIND_METHOD');
AMQP_EXCHANGE_BIND_OK_METHOD:
Exit('AMQP_EXCHANGE_BIND_OK_METHOD');
AMQP_EXCHANGE_UNBIND_METHOD:
Exit('AMQP_EXCHANGE_UNBIND_METHOD');
AMQP_EXCHANGE_UNBIND_OK_METHOD:
Exit('AMQP_EXCHANGE_UNBIND_OK_METHOD');
AMQP_QUEUE_DECLARE_METHOD:
Exit('AMQP_QUEUE_DECLARE_METHOD');
AMQP_QUEUE_DECLARE_OK_METHOD:
Exit('AMQP_QUEUE_DECLARE_OK_METHOD');
AMQP_QUEUE_BIND_METHOD:
Exit('AMQP_QUEUE_BIND_METHOD');
AMQP_QUEUE_BIND_OK_METHOD:
Exit('AMQP_QUEUE_BIND_OK_METHOD');
AMQP_QUEUE_PURGE_METHOD:
Exit('AMQP_QUEUE_PURGE_METHOD');
AMQP_QUEUE_PURGE_OK_METHOD:
Exit('AMQP_QUEUE_PURGE_OK_METHOD');
AMQP_QUEUE_DELETE_METHOD:
Exit('AMQP_QUEUE_DELETE_METHOD');
AMQP_QUEUE_DELETE_OK_METHOD:
Exit('AMQP_QUEUE_DELETE_OK_METHOD');
AMQP_QUEUE_UNBIND_METHOD:
Exit('AMQP_QUEUE_UNBIND_METHOD');
AMQP_QUEUE_UNBIND_OK_METHOD:
Exit('AMQP_QUEUE_UNBIND_OK_METHOD');
AMQP_BASIC_QOS_METHOD:
Exit('AMQP_BASIC_QOS_METHOD');
AMQP_BASIC_QOS_OK_METHOD:
Exit('AMQP_BASIC_QOS_OK_METHOD');
AMQP_BASIC_CONSUME_METHOD:
Exit('AMQP_BASIC_CONSUME_METHOD');
AMQP_BASIC_CONSUME_OK_METHOD:
Exit('AMQP_BASIC_CONSUME_OK_METHOD');
AMQP_BASIC_CANCEL_METHOD:
Exit('AMQP_BASIC_CANCEL_METHOD');
AMQP_BASIC_CANCEL_OK_METHOD:
Exit('AMQP_BASIC_CANCEL_OK_METHOD');
AMQP_BASIC_PUBLISH_METHOD:
Exit('AMQP_BASIC_PUBLISH_METHOD');
AMQP_BASIC_RETURN_METHOD:
Exit('AMQP_BASIC_RETURN_METHOD');
AMQP_BASIC_DELIVER_METHOD:
Exit('AMQP_BASIC_DELIVER_METHOD');
AMQP_BASIC_GET_METHOD:
Exit('AMQP_BASIC_GET_METHOD');
AMQP_BASIC_GET_OK_METHOD:
Exit('AMQP_BASIC_GET_OK_METHOD');
AMQP_BASIC_GET_EMPTY_METHOD:
Exit('AMQP_BASIC_GET_EMPTY_METHOD');
AMQP_BASIC_ACK_METHOD:
Exit('AMQP_BASIC_ACK_METHOD');
AMQP_BASIC_REJECT_METHOD:
Exit('AMQP_BASIC_REJECT_METHOD');
AMQP_BASIC_RECOVER_ASYNC_METHOD:
Exit('AMQP_BASIC_RECOVER_ASYNC_METHOD');
AMQP_BASIC_RECOVER_METHOD:
Exit('AMQP_BASIC_RECOVER_METHOD');
AMQP_BASIC_RECOVER_OK_METHOD:
Exit('AMQP_BASIC_RECOVER_OK_METHOD');
AMQP_BASIC_NACK_METHOD:
Exit('AMQP_BASIC_NACK_METHOD');
AMQP_TX_SELECT_METHOD:
Exit('AMQP_TX_SELECT_METHOD');
AMQP_TX_SELECT_OK_METHOD:
Exit('AMQP_TX_SELECT_OK_METHOD');
AMQP_TX_COMMIT_METHOD:
Exit('AMQP_TX_COMMIT_METHOD');
AMQP_TX_COMMIT_OK_METHOD:
Exit('AMQP_TX_COMMIT_OK_METHOD');
AMQP_TX_ROLLBACK_METHOD:
Exit('AMQP_TX_ROLLBACK_METHOD');
AMQP_TX_ROLLBACK_OK_METHOD:
Exit('AMQP_TX_ROLLBACK_OK_METHOD');
AMQP_CONFIRM_SELECT_METHOD:
Exit('AMQP_CONFIRM_SELECT_METHOD');
AMQP_CONFIRM_SELECT_OK_METHOD:
Exit('AMQP_CONFIRM_SELECT_OK_METHOD');
else
Exit(nil);
end;
end;
function amqp_queue_declare( state : Pamqp_connection_state;
channel : amqp_channel_t; queue : Tamqp_bytes;
passive, durable, exclusive, auto_delete : amqp_boolean_t;
arguments : Tamqp_table): Pamqp_queue_declare_ok;
var
req : Tamqp_queue_declare;
begin
req.ticket := 0;
req.queue := queue;
req.passive := passive;
req.durable := durable;
req.exclusive := exclusive;
req.auto_delete := auto_delete;
req.nowait := 0;
req.arguments := arguments;
Result := amqp_simple_rpc_decoded(state, channel, AMQP_QUEUE_DECLARE_METHOD,
AMQP_QUEUE_DECLARE_OK_METHOD, @req);
end;
(**
* amqp_queue_unbind
*
* @param [in] state connection state
* @param [in] channel the channel to do the RPC on
* @param [in] queue queue
* @param [in] exchange exchange
* @param [in] routing_key routing_key
* @param [in] arguments arguments
* @returns amqp_queue_unbind_ok_t
*)
function amqp_queue_unbind( state : Pamqp_connection_state;
channel : amqp_channel_t;
queue, exchange, routing_key : Tamqp_bytes;
arguments : Tamqp_table): Pamqp_queue_unbind_ok;
var
req : Tamqp_queue_unbind;
begin
req.ticket := 0;
req.queue := queue;
req.exchange := exchange;
req.routing_key := routing_key;
req.arguments := arguments;
Result := amqp_simple_rpc_decoded(state, channel, AMQP_QUEUE_UNBIND_METHOD,
AMQP_QUEUE_UNBIND_OK_METHOD, @req);
end;
(**
* amqp_exchange_declare
*
* @param [in] state connection state
* @param [in] channel the channel to do the RPC on
* @param [in] exchange exchange
* @param [in] type type
* @param [in] passive passive
* @param [in] durable durable
* @param [in] auto_delete auto_delete
* @param [in] internal internal
* @param [in] arguments arguments
* @returns amqp_exchange_declare_ok_t
*)
function amqp_exchange_declare( Astate : Pamqp_connection_state;
Achannel : amqp_channel_t;
Aexchange, Atype : Tamqp_bytes;
Apassive, Adurable, Aauto_delete, Ainternal : amqp_boolean_t;
Aarguments : Tamqp_table):Pamqp_exchange_declare_ok;
var
req : Tamqp_exchange_declare;
begin
req.ticket := 0;
req.exchange := Aexchange;
req.&type := Atype;
req.passive := Apassive;
req.durable := Adurable;
req.auto_delete := Aauto_delete;
req.internal := Ainternal;
req.nowait := 0;
req.arguments := Aarguments;
Result := amqp_simple_rpc_decoded(Astate, Achannel, AMQP_EXCHANGE_DECLARE_METHOD,
AMQP_EXCHANGE_DECLARE_OK_METHOD, @req);
end;
(**
* amqp_queue_bind
*
* @param [in] state connection state
* @param [in] channel the channel to do the RPC on
* @param [in] queue queue
* @param [in] exchange exchange
* @param [in] routing_key routing_key
* @param [in] arguments arguments
* @returns amqp_queue_bind_ok_t
*)
function amqp_queue_bind( state : Pamqp_connection_state;
channel : amqp_channel_t; queue, exchange,
routing_key : Tamqp_bytes;
arguments : Tamqp_table): Pamqp_queue_bind_ok;
var
req : Tamqp_queue_bind;
begin
req.ticket := 0;
req.queue := queue;
req.exchange := exchange;
req.routing_key := routing_key;
req.nowait := 0;
req.arguments := arguments;
Result := amqp_simple_rpc_decoded(state, channel, AMQP_QUEUE_BIND_METHOD,
AMQP_QUEUE_BIND_OK_METHOD, @req);
end;
function amqp_channel_open( state : Pamqp_connection_state; channel : amqp_channel_t):Pamqp_channel_open_ok;
var
req : Tamqp_channel_open;
begin
req.out_of_band := amqp_empty_bytes;
Result := amqp_simple_rpc_decoded(state, channel, AMQP_CHANNEL_OPEN_METHOD,
AMQP_CHANNEL_OPEN_OK_METHOD, @req);
end;
function amqp_decode_properties(class_id : uint16; pool : Pamqp_pool;
encoded : Tamqp_bytes; decoded: PPointer):integer;
var
offset : size_t;
flags : amqp_flags_t;
flagword_index : integer;
partial_flags : uint16;
connection_p : Pamqp_connection_properties;
channel_p : Pamqp_channel_properties;
access_p : Pamqp_access_properties;
exchange_p : Pamqp_exchange_properties;
queue_p : Pamqp_queue_properties;
basic_p : Pamqp_basic_properties;
tx_p : Pamqp_tx_properties ;
confirm_p : Pamqp_confirm_properties;
res : integer;
len: uint8_t;
begin
offset := 0;
flags := 0;
flagword_index := 0;
while (partial_flags and 1) > 0 do
begin
if 0= amqp_decode_16(encoded, @offset, &partial_flags ) then
Exit(Int(AMQP_STATUS_BAD_AMQP_DATA));
flags := flags or ((partial_flags shl (flagword_index * 16)));
Inc(flagword_index);
end;
case class_id of
10:
begin
connection_p := Pamqp_connection_properties(pool.alloc( sizeof(Tamqp_connection_properties)));
if connection_p = nil then
Exit(Int(AMQP_STATUS_NO_MEMORY));
connection_p._flags := flags;
decoded^ := connection_p;
Exit(0);
end;
20:
begin
channel_p := Pamqp_channel_properties(pool.alloc( sizeof(Tamqp_channel_properties)));
if channel_p = nil then
Exit(int(AMQP_STATUS_NO_MEMORY));
channel_p._flags := flags;
decoded^ := channel_p;
Exit(0);
end;
30:
begin
access_p := Pamqp_access_properties(pool.alloc( sizeof(Tamqp_access_properties)));
if access_p = nil then
Exit(int(AMQP_STATUS_NO_MEMORY));
access_p._flags := flags;
decoded^ := access_p;
Exit(0);
end;
40:
begin
exchange_p := Pamqp_exchange_properties(pool.alloc(sizeof(Tamqp_exchange_properties)));
if exchange_p = nil then
Exit(int(AMQP_STATUS_NO_MEMORY));
exchange_p._flags := flags;
decoded^ := exchange_p;
Exit(0);
end;
50:
begin
queue_p := Pamqp_queue_properties(pool.alloc(sizeof(Tamqp_queue_properties)));
if queue_p = nil then
Exit(int(AMQP_STATUS_NO_MEMORY));
queue_p._flags := flags;
decoded^ := queue_p;
Exit(0);
end;
60:
begin
basic_p := Pamqp_basic_properties(pool.alloc( sizeof(Tamqp_basic_properties)));
if basic_p = nil then
Exit(int(AMQP_STATUS_NO_MEMORY));
basic_p._flags := flags;
if (flags and AMQP_BASIC_CONTENT_TYPE_FLAG)>0 then
begin
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, &len)) or
(0= amqp_decode_bytes(encoded, @offset, basic_p.content_type, len)) then
Exit(Int(AMQP_STATUS_BAD_AMQP_DATA));
end;
end;
if (flags and AMQP_BASIC_CONTENT_ENCODING_FLAG)>0 then
begin
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, &len)) or
(0= amqp_decode_bytes(encoded, @offset, basic_p.content_encoding, len)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
end;
if (flags and AMQP_BASIC_HEADERS_FLAG)>0 then
begin
begin
res := amqp_decode_table(encoded, pool, basic_p.headers, @offset);
if res < 0 then Exit(res);
end;
end;
if (flags and AMQP_BASIC_DELIVERY_MODE_FLAG)>0 then
begin
if (0= amqp_decode_8(encoded, @offset, basic_p.delivery_mode)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (flags and AMQP_BASIC_PRIORITY_FLAG)>0 then
begin
if (0= amqp_decode_8(encoded, @offset, basic_p.priority)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (flags and AMQP_BASIC_CORRELATION_ID_FLAG)>0 then
begin
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, &len)) or
(0= amqp_decode_bytes(encoded, @offset, basic_p.correlation_id, len)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
end;
if (flags and AMQP_BASIC_REPLY_TO_FLAG)>0 then
begin
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, &len)) or
(0= amqp_decode_bytes(encoded, @offset, basic_p.reply_to, len)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
end;
if (flags and AMQP_BASIC_EXPIRATION_FLAG)>0 then
begin
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, &len)) or
(0= amqp_decode_bytes(encoded, @offset, basic_p.expiration, len))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
end;
if (flags and AMQP_BASIC_MESSAGE_ID_FLAG)>0 then
begin
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, &len)) or
(0= amqp_decode_bytes(encoded, @offset, basic_p.message_id, len)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
end;
if (flags and AMQP_BASIC_TIMESTAMP_FLAG)>0 then
begin
if 0= amqp_decode_64(encoded, @offset, basic_p.timestamp) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (flags and AMQP_BASIC_TYPE_FLAG)>0 then
begin
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, &len)) or
(0= amqp_decode_bytes(encoded, @offset, basic_p.&type, len)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
end;
if (flags and AMQP_BASIC_USER_ID_FLAG)>0 then
begin
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, &len)) or
(0= amqp_decode_bytes(encoded, @offset, basic_p.user_id, len)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
end;
if (flags and AMQP_BASIC_APP_ID_FLAG)>0 then
begin
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, &len)) or
(0= amqp_decode_bytes(encoded, @offset, basic_p.app_id, len)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
end;
if (flags and AMQP_BASIC_CLUSTER_ID_FLAG)>0 then
begin
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, &len)) or
(0= amqp_decode_bytes(encoded, @offset, basic_p.cluster_id, len)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
end;
decoded^ := basic_p;
Exit(0);
end;
90:
begin
tx_p := Pamqp_tx_properties(pool.alloc( sizeof(Tamqp_tx_properties)));
if tx_p = nil then
Exit(int(AMQP_STATUS_NO_MEMORY));
tx_p._flags := flags;
decoded^ := tx_p;
Exit(0);
end;
85:
begin
confirm_p := Pamqp_confirm_properties(pool.alloc(sizeof(Tamqp_confirm_properties)));
if confirm_p = nil then
Exit(int(AMQP_STATUS_NO_MEMORY));
confirm_p._flags := flags;
decoded^ := confirm_p;
Exit(0);
end;
else
Exit(Int(AMQP_STATUS_UNKNOWN_CLASS));
end;
end;
function ReturnVal(bits: Byte;IsTrue, IsFalse: Int): Integer;
begin
if bits > 0 then
Exit(IsTrue)
else
Exit(IsFalse);
end;
function amqp_decode_method(methodNumber : amqp_method_number_t;pool : Pamqp_pool; encoded : Tamqp_bytes; out decoded: Pointer):integer;
var
offset : size_t;
bit_buffer : byte;
res : integer;
len: uint32;
len8: uint8;
START : Pamqp_connection_start;
START_OK : Pamqp_connection_start_ok;
SECURE : Pamqp_connection_secure;
SECURE_OK : Pamqp_connection_secure_ok;
TUNE : Pamqp_connection_tune;
TUNE_OK : Pamqp_connection_tune_ok;
OPEN : Pamqp_connection_open;
OPEN_OK : Pamqp_connection_open_ok;
CLOSE : Pamqp_connection_close;
CLOSE_OK : Pamqp_connection_close_ok;
BLOCKED : Pamqp_connection_blocked;
UNBLOCKED : Pamqp_connection_unblocked;
UPDATE_SECRET : Pamqp_connection_update_secret;
UPDATE_SECRET_OK : Pamqp_connection_update_secret_ok;
CHANNEL_OPEN : Pamqp_channel_open;
CHANNEL_OPEN_OK : Pamqp_channel_open_ok;
CHANNEL_FLOW : Pamqp_channel_flow;
CHANNEL_FLOW_OK : Pamqp_channel_flow_ok;
CHANNEL_CLOSE : Pamqp_channel_close;
CHANNEL_CLOSE_OK : Pamqp_channel_close_ok;
REQUEST : Pamqp_access_request;
REQUEST_OK : Pamqp_access_request_ok;
EXCHANGE_DECLARE : Pamqp_exchange_declare;
EXCHANGE_DECLARE_OK : Pamqp_exchange_declare_ok;
EXCHANGE_DELETE : Pamqp_exchange_delete;
EXCHANGE_BIND_OK : Pamqp_exchange_bind_ok;
EXCHANGE_UNBIND : Pamqp_exchange_unbind;
EXCHANGE_DELETE_OK : Pamqp_exchange_delete_ok;
EXCHANGE_BIND : Pamqp_exchange_bind;
EXCHANGE_UNBIND_OK : Pamqp_exchange_unbind_ok;
QUEUE_DECLARE:Pamqp_queue_declare;
QUEUE_DECLARE_OK :Pamqp_queue_declare_ok;
QUEUE_BIND :Pamqp_queue_bind;
QUEUE_BIND_OK :Pamqp_queue_bind_ok;
QUEUE_PURGE :Pamqp_queue_purge;
QUEUE_PURGE_OK:Pamqp_queue_purge_ok;
QUEUE_DELETE :Pamqp_queue_delete;
QUEUE_DELETE_OK :Pamqp_queue_delete_ok;
QUEUE_UNBIND :Pamqp_queue_unbind;
QUEUE_UNBIND_OK :Pamqp_queue_unbind_ok;
BASIC_QOS : Pamqp_basic_qos;
BASIC_QOS_OK :Pamqp_basic_qos_ok;
BASIC_CONSUME : Pamqp_basic_consume;
BASIC_CONSUME_OK :Pamqp_basic_consume_ok;
BASIC_CANCEL :Pamqp_basic_cancel;
BASIC_CANCEL_OK :Pamqp_basic_cancel_ok;
BASIC_PUBLISH : Pamqp_basic_publish;
BASIC_RETURN :Pamqp_basic_return;
BASIC_DELIVER :Pamqp_basic_deliver;
BASIC_GET : Pamqp_basic_get;
BASIC_GET_OK :Pamqp_basic_get_ok;
BASIC_GET_EMPTY : Pamqp_basic_get_empty;
BASIC_ACK :Pamqp_basic_ack;
BASIC_REJECT : Pamqp_basic_reject;
BASIC_RECOVER_ASYNC :Pamqp_basic_recover_async;
BASIC_RECOVER : Pamqp_basic_recover;
BASIC_RECOVER_OK : Pamqp_basic_recover_ok;
BASIC_NACK:Pamqp_basic_nack;
TX_SELECT :Pamqp_tx_select;
TX_SELECT_OK : Pamqp_tx_select_ok;
TX_COMMIT :Pamqp_tx_commit;
TX_COMMIT_OK : Pamqp_tx_commit_ok;
TX_ROLLBACK : Pamqp_tx_rollback;
TX_ROLLBACK_OK : Pamqp_tx_rollback_ok;
CONFIRM_SELECT : Pamqp_confirm_select;
CONFIRM_SELECT_OK : Pamqp_confirm_select_ok;
begin
offset := 0;
case methodNumber of
AMQP_CONNECTION_START_METHOD:
begin
START := Pamqp_connection_start(pool.alloc( sizeof(Tamqp_connection_start)));
if START = nil then
Exit(Int(AMQP_STATUS_NO_MEMORY));
if 0= amqp_decode_8(encoded, @offset, START.version_major ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if 0= amqp_decode_8(encoded, @offset, START.version_minor ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
begin
res := amqp_decode_table(encoded, pool, START.server_properties, @offset);
if res < 0 then Exit(res);
end;
begin
//var len: uint32;
if (0= amqp_decode_32(encoded, @offset, len)) or
(0= amqp_decode_bytes(encoded, @offset, START.mechanisms, len)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//var len: uint32;
if (0= amqp_decode_32(encoded, @offset, len)) or
(0= amqp_decode_bytes(encoded, @offset, START.locales, len)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
decoded := START;
Exit(0);
end;
AMQP_CONNECTION_START_OK_METHOD:
begin
START_OK := Pamqp_connection_start_ok(pool.alloc( sizeof(Tamqp_connection_start_ok)));
if START_OK = nil then
Exit(Int(AMQP_STATUS_NO_MEMORY));
begin
res := amqp_decode_table(encoded, pool, START_OK.client_properties, @offset);
if res < 0 then Exit(res);
end;
begin
//var len8: uint8;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0=amqp_decode_bytes(encoded, @offset, START_OK.mechanism, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//var len: uint32;
if (0= amqp_decode_32(encoded, @offset, len)) or
(0= amqp_decode_bytes(encoded, @offset, START_OK.response, len)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//var len: uint8;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, START_OK.locale, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
decoded := START_OK;
Exit(0);
end;
AMQP_CONNECTION_SECURE_METHOD:
begin
SECURE := Pamqp_connection_secure(pool.alloc( sizeof(Tamqp_connection_secure)));
if SECURE = nil then
Exit(Int(AMQP_STATUS_NO_MEMORY));
begin
//var len: uint32;
if (0= amqp_decode_32(encoded, @offset, len)) or
(0= amqp_decode_bytes(encoded, @offset, SECURE.challenge, len)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
decoded := SECURE;
Exit(0);
end;
AMQP_CONNECTION_SECURE_OK_METHOD:
begin
SECURE_OK := Pamqp_connection_secure_ok(pool.alloc( sizeof(Tamqp_connection_secure_ok)));
if SECURE_OK = nil then
Exit(Int(AMQP_STATUS_NO_MEMORY));
begin
//var len: uint32;
if (0= amqp_decode_32(encoded, @offset, len)) or
(0= amqp_decode_bytes(encoded, @offset, SECURE_OK.response, len)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
decoded := SECURE_OK;
Exit(0);
end;
AMQP_CONNECTION_TUNE_METHOD:
begin
TUNE := Pamqp_connection_tune(pool.alloc( sizeof(Tamqp_connection_tune)));
if TUNE= nil then
Exit(Int(AMQP_STATUS_NO_MEMORY));
if (0= amqp_decode_16(encoded, @offset, TUNE.channel_max )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (0= amqp_decode_32(encoded, @offset, TUNE.frame_max )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (0= amqp_decode_16(encoded, @offset, TUNE.heartbeat )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
decoded := TUNE;
Exit(0);
end;
AMQP_CONNECTION_TUNE_OK_METHOD:
begin
TUNE_OK := Pamqp_connection_tune_ok(pool.alloc( sizeof(Tamqp_connection_tune_ok)));
if TUNE_OK = nil then
Exit(Int(AMQP_STATUS_NO_MEMORY));
if (0= amqp_decode_16(encoded, @offset, TUNE_OK.channel_max)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (0= amqp_decode_32(encoded, @offset, TUNE_OK.frame_max )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (0= amqp_decode_16(encoded, @offset, TUNE_OK.heartbeat )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
decoded := TUNE_OK;
Exit(0);
end;
AMQP_CONNECTION_OPEN_METHOD:
begin
OPEN := Pamqp_connection_open(pool.alloc( sizeof(Tamqp_connection_open)));
if OPEN = nil then
Exit(Int(AMQP_STATUS_NO_MEMORY));
begin
//var len: uint8;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, OPEN.virtual_host, len8))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//var len: uint8;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, OPEN.capabilities, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (0= amqp_decode_8(encoded, @offset, bit_buffer )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (bit_buffer and (1 shl 0)) > 0 then
OPEN.insist := 1
else
OPEN.insist := 0;
decoded := OPEN;
Exit(0);
end;
AMQP_CONNECTION_OPEN_OK_METHOD:
begin
OPEN_OK := Pamqp_connection_open_ok(pool.alloc( sizeof(Tamqp_connection_open_ok)));
if OPEN_OK = nil then
Exit(Int(AMQP_STATUS_NO_MEMORY));
begin
//var len: uint8;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, OPEN_OK.known_hosts, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
decoded := OPEN_OK;
Exit(0);
end;
AMQP_CONNECTION_CLOSE_METHOD:
begin
CLOSE := Pamqp_connection_close(pool.alloc( sizeof(Tamqp_connection_close)));
if CLOSE = nil then
Exit(Int(AMQP_STATUS_NO_MEMORY));
if (0= amqp_decode_16(encoded, @offset, CLOSE.reply_code )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
begin
//var len: uint8;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, CLOSE.reply_text, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (0= amqp_decode_16(encoded, @offset, CLOSE.class_id )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (0= amqp_decode_16(encoded, @offset, CLOSE.method_id ) ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
decoded := CLOSE;
Exit(0);
end;
AMQP_CONNECTION_CLOSE_OK_METHOD:
begin
CLOSE_OK := Pamqp_connection_close_ok(pool.alloc( sizeof(Tamqp_connection_close_ok)));
if CLOSE_OK = nil then begin
Exit(Int(AMQP_STATUS_NO_MEMORY));
end;
decoded := CLOSE_OK;
Exit(0);
end;
AMQP_CONNECTION_BLOCKED_METHOD:
begin
BLOCKED := Pamqp_connection_blocked(pool.alloc( sizeof(Tamqp_connection_blocked)));
if BLOCKED = nil then
Exit(Int(AMQP_STATUS_NO_MEMORY));
begin
//var len: uint8;
if (0= amqp_decode_8(encoded, @offset, len8 )) or
(0= amqp_decode_bytes(encoded, @offset, BLOCKED.reason, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
decoded := BLOCKED;
Exit(0);
end;
AMQP_CONNECTION_UNBLOCKED_METHOD:
begin
UNBLOCKED := Pamqp_connection_unblocked(pool.alloc( sizeof(Tamqp_connection_unblocked)));
if UNBLOCKED = nil then
Exit(Int(AMQP_STATUS_NO_MEMORY));
decoded := UNBLOCKED;
Exit(0);
end;
AMQP_CONNECTION_UPDATE_SECRET_METHOD:
begin
UPDATE_SECRET := Pamqp_connection_update_secret(pool.alloc( sizeof(Tamqp_connection_update_secret)));
if UPDATE_SECRET = nil then
Exit(Int(AMQP_STATUS_NO_MEMORY));
begin
//var len: uint32;
if (0= amqp_decode_32(encoded, @offset, len)) or
(0= amqp_decode_bytes(encoded, @offset, UPDATE_SECRET.new_secret, len))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//var len: uint8;
if (0= amqp_decode_8(encoded, @offset, len8 )) or
(0= amqp_decode_bytes(encoded, @offset, UPDATE_SECRET.reason, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
decoded := UPDATE_SECRET;
Exit(0);
end;
AMQP_CONNECTION_UPDATE_SECRET_OK_METHOD:
begin
UPDATE_SECRET_OK := Pamqp_connection_update_secret_ok(pool.alloc( sizeof(Tamqp_connection_update_secret_ok)));
if UPDATE_SECRET_OK = nil then
Exit(Int(AMQP_STATUS_NO_MEMORY));
decoded := UPDATE_SECRET_OK;
Exit(0);
end;
AMQP_CHANNEL_OPEN_METHOD:
begin
CHANNEL_OPEN := Pamqp_channel_open(pool.alloc( sizeof(Tamqp_channel_open)));
if CHANNEL_OPEN = nil then begin
Exit(Int(AMQP_STATUS_NO_MEMORY));
end;
begin
//var len: uint8;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, CHANNEL_OPEN.out_of_band, len8))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
decoded := CHANNEL_OPEN;
Exit(0);
end;
AMQP_CHANNEL_OPEN_OK_METHOD:
begin
CHANNEL_OPEN_OK := Pamqp_channel_open_ok(pool.alloc( sizeof(Tamqp_channel_open_ok)));
if CHANNEL_OPEN_OK = nil then begin
Exit(Int(AMQP_STATUS_NO_MEMORY));
end;
begin
//var len: uint32;
if (0= amqp_decode_32(encoded, @offset, len)) or
(0= amqp_decode_bytes(encoded, @offset, CHANNEL_OPEN_OK.channel_id, len))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
decoded := CHANNEL_OPEN_OK;
Exit(0);
end;
AMQP_CHANNEL_FLOW_METHOD:
begin
CHANNEL_FLOW := Pamqp_channel_flow(pool.alloc( sizeof(Tamqp_channel_flow)));
if CHANNEL_FLOW = nil then begin
Exit(Int(AMQP_STATUS_NO_MEMORY));
end;
if (0= amqp_decode_8(encoded, @offset, bit_buffer)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (bit_buffer and (1 shl 0)) > 0 then
CHANNEL_FLOW.active := 1
else CHANNEL_FLOW.active := 0;
decoded := CHANNEL_FLOW;
Exit(0);
end;
AMQP_CHANNEL_FLOW_OK_METHOD:
begin
CHANNEL_FLOW_OK := Pamqp_channel_flow_ok(pool.alloc( sizeof(Tamqp_channel_flow_ok)));
if CHANNEL_FLOW_OK = nil then begin
Exit(Int(AMQP_STATUS_NO_MEMORY));
end;
if (0= amqp_decode_8(encoded, @offset, bit_buffer)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (bit_buffer and (1 shl 0))>0 then
CHANNEL_FLOW_OK.active := 1
else CHANNEL_FLOW_OK.active := 0;
decoded := CHANNEL_FLOW_OK;
Exit(0);
end;
AMQP_CHANNEL_CLOSE_METHOD:
begin
CHANNEL_CLOSE := Pamqp_channel_close(pool.alloc( sizeof(Tamqp_channel_close)));
if CHANNEL_CLOSE = nil then begin
Exit(Int(AMQP_STATUS_NO_MEMORY));
end;
if (0= amqp_decode_16(encoded, @offset, CHANNEL_CLOSE.reply_code )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, CHANNEL_CLOSE.reply_text, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (0= amqp_decode_16(encoded, @offset, CHANNEL_CLOSE.class_id )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (0= amqp_decode_16(encoded, @offset, CHANNEL_CLOSE.method_id )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
decoded := CHANNEL_CLOSE;
Exit(0);
end;
AMQP_CHANNEL_CLOSE_OK_METHOD:
begin
CHANNEL_CLOSE_OK := Pamqp_channel_close_ok(pool.alloc( sizeof(Tamqp_channel_close_ok)));
if CHANNEL_CLOSE_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
decoded := CHANNEL_CLOSE_OK;
Exit(0);
end;
AMQP_ACCESS_REQUEST_METHOD:
begin
REQUEST := Pamqp_access_request(pool.alloc( sizeof(Tamqp_access_request)));
if REQUEST = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, REQUEST.realm, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (0= amqp_decode_8(encoded, @offset, &bit_buffer )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
REQUEST.exclusive := ReturnVal((bit_buffer and (1 shl 0)) , 1 , 0);
REQUEST.passive := ReturnVal((bit_buffer and (1 shl 1)) , 1 , 0);
REQUEST.active := ReturnVal((bit_buffer and (1 shl 2)) , 1 , 0);
REQUEST.write := ReturnVal((bit_buffer and (1 shl 3)) , 1 , 0);
REQUEST.read := ReturnVal((bit_buffer and (1 shl 4)) , 1 , 0);
decoded := REQUEST;
Exit(0);
end;
AMQP_ACCESS_REQUEST_OK_METHOD:
begin
REQUEST_OK := Pamqp_access_request_ok(pool.alloc( sizeof(Tamqp_access_request_ok)));
if REQUEST_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if (0= amqp_decode_16(encoded, @offset, REQUEST_OK.ticket )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
decoded := REQUEST_OK;
Exit(0);
end;
AMQP_EXCHANGE_DECLARE_METHOD:
begin
EXCHANGE_DECLARE := Pamqp_exchange_declare(pool.alloc( sizeof(Tamqp_exchange_declare)));
if EXCHANGE_DECLARE = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if (0= amqp_decode_16(encoded, @offset, EXCHANGE_DECLARE.ticket) ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, EXCHANGE_DECLARE.exchange, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, EXCHANGE_DECLARE.&type, len8))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (0= amqp_decode_8(encoded, @offset, bit_buffer)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
EXCHANGE_DECLARE.passive := ReturnVal((bit_buffer and (1 shl 0)) , 1 ,0);
EXCHANGE_DECLARE.durable := ReturnVal((bit_buffer and (1 shl 1)) , 1 , 0);
EXCHANGE_DECLARE.auto_delete := ReturnVal((bit_buffer and (1 shl 2)) , 1 , 0);
EXCHANGE_DECLARE.internal := ReturnVal((bit_buffer and (1 shl 3)), 1 , 0);
EXCHANGE_DECLARE.nowait := ReturnVal((bit_buffer and (1 shl 4)) , 1 , 0);
begin
res := amqp_decode_table(encoded, pool, EXCHANGE_DECLARE.arguments, @offset);
if res < 0 then Exit(res);
end;
decoded := EXCHANGE_DECLARE;
Exit(0);
end;
AMQP_EXCHANGE_DECLARE_OK_METHOD:
begin
EXCHANGE_DECLARE_OK := Pamqp_exchange_declare_ok(pool.alloc( sizeof(Tamqp_exchange_declare_ok)));
if EXCHANGE_DECLARE_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
decoded := EXCHANGE_DECLARE_OK;
Exit(0);
end;
AMQP_EXCHANGE_DELETE_METHOD:
begin
EXCHANGE_DELETE := Pamqp_exchange_delete(pool.alloc( sizeof(Tamqp_exchange_delete)));
if EXCHANGE_DELETE = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_16(encoded, @offset, EXCHANGE_DELETE.ticket) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, EXCHANGE_DELETE.exchange, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if 0= amqp_decode_8(encoded, @offset, bit_buffer) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
EXCHANGE_DELETE.if_unused := ReturnVal((bit_buffer and (1 shl 0)) , 1 , 0);
EXCHANGE_DELETE.nowait := ReturnVal((bit_buffer and (1 shl 1)) , 1 , 0);
decoded := EXCHANGE_DELETE;
Exit(0);
end;
AMQP_EXCHANGE_DELETE_OK_METHOD:
begin
EXCHANGE_DELETE_OK := Pamqp_exchange_delete_ok(pool.alloc( sizeof(Tamqp_exchange_delete_ok)));
if EXCHANGE_DELETE_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
decoded := EXCHANGE_DELETE_OK;
Exit(0);
end;
AMQP_EXCHANGE_BIND_METHOD:
begin
EXCHANGE_BIND := Pamqp_exchange_bind(pool.alloc( sizeof(Tamqp_exchange_bind)));
if EXCHANGE_BIND = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if (0= amqp_decode_16(encoded, @offset, EXCHANGE_BIND.ticket )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
begin
//r len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, EXCHANGE_BIND.destination, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//r len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, EXCHANGE_BIND.source, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//r len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, EXCHANGE_BIND.routing_key, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if 0= amqp_decode_8(encoded, @offset, bit_buffer) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
EXCHANGE_BIND.nowait := ReturnVal((bit_buffer and (1 shl 0)) , 1 , 0);
begin
res := amqp_decode_table(encoded, pool, EXCHANGE_BIND.arguments, @offset);
if res < 0 then Exit(res);
end;
decoded := EXCHANGE_BIND;
Exit(0);
end;
AMQP_EXCHANGE_BIND_OK_METHOD:
begin
EXCHANGE_BIND_OK := Pamqp_exchange_bind_ok(pool.alloc( sizeof(Tamqp_exchange_bind_ok)));
if EXCHANGE_BIND_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
decoded := EXCHANGE_BIND_OK;
Exit(0);
end;
AMQP_EXCHANGE_UNBIND_METHOD:
begin
EXCHANGE_UNBIND := Pamqp_exchange_unbind(pool.alloc( sizeof(Tamqp_exchange_unbind)));
if EXCHANGE_UNBIND = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if (0= amqp_decode_16(encoded, @offset, EXCHANGE_UNBIND.ticket )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, EXCHANGE_UNBIND.destination, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, EXCHANGE_UNBIND.source, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, EXCHANGE_UNBIND.routing_key, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if 0= amqp_decode_8(encoded, @offset, &bit_buffer) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
EXCHANGE_UNBIND.nowait := ReturnVal((bit_buffer and (1 shl 0)) , 1 , 0);
begin
res := amqp_decode_table(encoded, pool, EXCHANGE_UNBIND.arguments, @offset);
if res < 0 then Exit(res);
end;
decoded := EXCHANGE_UNBIND;
Exit(0);
end;
AMQP_EXCHANGE_UNBIND_OK_METHOD:
begin
EXCHANGE_UNBIND_OK := Pamqp_exchange_unbind_ok(pool.alloc( sizeof(Tamqp_exchange_unbind_ok)));
if EXCHANGE_UNBIND_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
decoded := EXCHANGE_UNBIND_OK;
Exit(0);
end;
AMQP_QUEUE_DECLARE_METHOD:
begin
QUEUE_DECLARE:=Pamqp_queue_declare(pool.alloc( sizeof(Tamqp_queue_declare)));
if QUEUE_DECLARE = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_16(encoded, @offset, QUEUE_DECLARE.ticket )then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, QUEUE_DECLARE.queue, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if 0= amqp_decode_8(encoded, @offset, &bit_buffer ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
QUEUE_DECLARE.passive := ReturnVal((bit_buffer and (1 shl 0)) , 1 , 0);
QUEUE_DECLARE.durable := ReturnVal((bit_buffer and (1 shl 1)) , 1 , 0);
QUEUE_DECLARE.exclusive := ReturnVal((bit_buffer and (1 shl 2)) , 1 , 0);
QUEUE_DECLARE.auto_delete := ReturnVal((bit_buffer and (1 shl 3)) , 1 , 0);
QUEUE_DECLARE.nowait := ReturnVal((bit_buffer and (1 shl 4)) , 1, 0);
begin
res := amqp_decode_table(encoded, pool, QUEUE_DECLARE.arguments, @offset);
if res < 0 then Exit(res);
end;
decoded := QUEUE_DECLARE;
Exit(0);
end;
AMQP_QUEUE_DECLARE_OK_METHOD:
begin
QUEUE_DECLARE_OK :=Pamqp_queue_declare_ok(pool.alloc( sizeof(Tamqp_queue_declare_ok)));
if QUEUE_DECLARE_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8 )) or
(0= amqp_decode_bytes(encoded, @offset, QUEUE_DECLARE_OK.queue, len8))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if 0= amqp_decode_32(encoded, @offset, QUEUE_DECLARE_OK.message_count) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if 0= amqp_decode_32(encoded, @offset, QUEUE_DECLARE_OK.consumer_count) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
decoded := QUEUE_DECLARE_OK;
Exit(0);
end;
AMQP_QUEUE_BIND_METHOD:
begin
QUEUE_BIND :=Pamqp_queue_bind(pool.alloc( sizeof(Tamqp_queue_bind)));
if QUEUE_BIND = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_16(encoded, @offset, QUEUE_BIND.ticket) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
begin
// var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, QUEUE_BIND.queue, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, QUEUE_BIND.exchange, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, QUEUE_BIND.routing_key, len8))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if 0= amqp_decode_8(encoded, @offset, &bit_buffer) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
QUEUE_BIND.nowait := ReturnVal((bit_buffer and (1 shl 0)) , 1 , 0);
begin
res := amqp_decode_table(encoded, pool, QUEUE_BIND.arguments, @offset);
if res < 0 then Exit(res);
end;
decoded := QUEUE_BIND;
Exit(0);
end;
AMQP_QUEUE_BIND_OK_METHOD:
begin
QUEUE_BIND_OK :=Pamqp_queue_bind_ok(pool.alloc( sizeof(Tamqp_queue_bind_ok)));
if QUEUE_BIND_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
decoded := QUEUE_BIND_OK;
Exit(0);
end;
AMQP_QUEUE_PURGE_METHOD:
begin
QUEUE_PURGE :=Pamqp_queue_purge(pool.alloc( sizeof(Tamqp_queue_purge)));
if QUEUE_PURGE = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_16(encoded, @offset, QUEUE_PURGE.ticket) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, QUEUE_PURGE.queue, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if 0= amqp_decode_8(encoded, @offset, bit_buffer) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
QUEUE_PURGE.nowait := ReturnVal((bit_buffer and (1 shl 0)) , 1 , 0);
decoded := QUEUE_PURGE;
Exit(0);
end;
AMQP_QUEUE_PURGE_OK_METHOD:
begin
QUEUE_PURGE_OK:=Pamqp_queue_purge_ok(pool.alloc( sizeof(Tamqp_queue_purge_ok)));
if QUEUE_PURGE_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_32(encoded, @offset, QUEUE_PURGE_OK.message_count) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
decoded := QUEUE_PURGE_OK;
Exit(0);
end;
AMQP_QUEUE_DELETE_METHOD:
begin
QUEUE_DELETE :=Pamqp_queue_delete(pool.alloc( sizeof(Tamqp_queue_delete)));
if QUEUE_DELETE = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_16(encoded, @offset, QUEUE_DELETE.ticket) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, QUEUE_DELETE.queue, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if 0= amqp_decode_8(encoded, @offset, bit_buffer ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
QUEUE_DELETE.if_unused := ReturnVal((bit_buffer and (1 shl 0)) , 1 , 0);
QUEUE_DELETE.if_empty := ReturnVal((bit_buffer and (1 shl 1)) , 1 , 0);
QUEUE_DELETE.nowait := ReturnVal((bit_buffer and (1 shl 2)) , 1 , 0);
decoded := QUEUE_DELETE;
Exit(0);
end;
AMQP_QUEUE_DELETE_OK_METHOD:
begin
QUEUE_DELETE_OK :=Pamqp_queue_delete_ok(pool.alloc( sizeof(Tamqp_queue_delete_ok)));
if QUEUE_DELETE_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_32(encoded, @offset, QUEUE_DELETE_OK.message_count) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
decoded := QUEUE_DELETE_OK;
Exit(0);
end;
AMQP_QUEUE_UNBIND_METHOD:
begin
QUEUE_UNBIND :=Pamqp_queue_unbind(pool.alloc( sizeof(Tamqp_queue_unbind)));
if QUEUE_UNBIND = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_16(encoded, @offset, QUEUE_UNBIND.ticket ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, QUEUE_UNBIND.queue, len8))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, QUEUE_UNBIND.exchange, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8 )) or
(0= amqp_decode_bytes(encoded, @offset, QUEUE_UNBIND.routing_key, len8))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
res := amqp_decode_table(encoded, pool, QUEUE_UNBIND.arguments, @offset);
if res < 0 then Exit(res);
end;
decoded := QUEUE_UNBIND;
Exit(0);
end;
AMQP_QUEUE_UNBIND_OK_METHOD:
begin
QUEUE_UNBIND_OK :=Pamqp_queue_unbind_ok(pool.alloc( sizeof(Tamqp_queue_unbind_ok)));
if QUEUE_UNBIND_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
decoded := QUEUE_UNBIND_OK;
Exit(0);
end;
AMQP_BASIC_QOS_METHOD:
begin
BASIC_QOS := Pamqp_basic_qos(pool.alloc( sizeof(Tamqp_basic_qos)));
if BASIC_QOS = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_32(encoded, @offset, BASIC_QOS.prefetch_size) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if 0= amqp_decode_16(encoded, @offset, BASIC_QOS.prefetch_count) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if 0= amqp_decode_8(encoded, @offset, bit_buffer) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
BASIC_QOS.global := ReturnVal((bit_buffer and (1 shl 0)) , 1,0);
decoded := BASIC_QOS;
Exit(0);
end;
AMQP_BASIC_QOS_OK_METHOD:
begin
BASIC_QOS_OK :=Pamqp_basic_qos_ok(pool.alloc( sizeof(Tamqp_basic_qos_ok)));
if BASIC_QOS_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
decoded := BASIC_QOS_OK;
Exit(0);
end;
AMQP_BASIC_CONSUME_METHOD:
begin
BASIC_CONSUME := Pamqp_basic_consume(pool.alloc( sizeof(Tamqp_basic_consume)));
if BASIC_CONSUME = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_16(encoded, @offset, BASIC_CONSUME.ticket) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, BASIC_CONSUME.queue, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, BASIC_CONSUME.consumer_tag, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if 0= amqp_decode_8(encoded, @offset, &bit_buffer ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
BASIC_CONSUME.no_local := ReturnVal((bit_buffer and (1 shl 0)) , 1,0);
BASIC_CONSUME.no_ack := ReturnVal((bit_buffer and (1 shl 1)) , 1,0);
BASIC_CONSUME.exclusive := ReturnVal((bit_buffer and (1 shl 2)) , 1,0);
BASIC_CONSUME.nowait := ReturnVal((bit_buffer and (1 shl 3)) , 1,0);
begin
res := amqp_decode_table(encoded, pool, BASIC_CONSUME.arguments, @offset);
if res < 0 then Exit(res);
end;
decoded := BASIC_CONSUME;
Exit(0);
end;
AMQP_BASIC_CONSUME_OK_METHOD:
begin
BASIC_CONSUME_OK :=Pamqp_basic_consume_ok(pool.alloc( sizeof(Tamqp_basic_consume_ok)));
if BASIC_CONSUME_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, BASIC_CONSUME_OK.consumer_tag, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
decoded := BASIC_CONSUME_OK;
Exit(0);
end;
AMQP_BASIC_CANCEL_METHOD:
begin
BASIC_CANCEL :=Pamqp_basic_cancel(pool.alloc( sizeof(Tamqp_basic_cancel)));
if BASIC_CANCEL = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, BASIC_CANCEL.consumer_tag, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if 0= amqp_decode_8(encoded, @offset, bit_buffer) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
BASIC_CANCEL.nowait := ReturnVal((bit_buffer and (1 shl 0)) , 1,0);
decoded := BASIC_CANCEL;
Exit(0);
end;
AMQP_BASIC_CANCEL_OK_METHOD:
begin
BASIC_CANCEL_OK :=Pamqp_basic_cancel_ok(pool.alloc( sizeof(Tamqp_basic_cancel_ok)));
if BASIC_CANCEL_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, BASIC_CANCEL_OK.consumer_tag, len8))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
decoded := BASIC_CANCEL_OK;
Exit(0);
end;
AMQP_BASIC_PUBLISH_METHOD:
begin
BASIC_PUBLISH := Pamqp_basic_publish(pool.alloc( sizeof(Tamqp_basic_publish)));
if BASIC_PUBLISH = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_16(encoded, @offset, BASIC_PUBLISH.ticket) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, BASIC_PUBLISH.exchange, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, BASIC_PUBLISH.routing_key, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if 0= amqp_decode_8(encoded, @offset, &bit_buffer) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
BASIC_PUBLISH.mandatory := ReturnVal((bit_buffer and (1 shl 0)) , 1,0);
BASIC_PUBLISH.immediate := ReturnVal((bit_buffer and (1 shl 1)) , 1,0);
decoded := BASIC_PUBLISH;
Exit(0);
end;
AMQP_BASIC_RETURN_METHOD:
begin
BASIC_RETURN :=Pamqp_basic_return(pool.alloc( sizeof(Tamqp_basic_return)));
if BASIC_RETURN = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_16(encoded, @offset, BASIC_RETURN.reply_code ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, BASIC_RETURN.reply_text, len8))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, BASIC_RETURN.exchange, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, BASIC_RETURN.routing_key, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
decoded := BASIC_RETURN;
Exit(0);
end;
AMQP_BASIC_DELIVER_METHOD:
begin
BASIC_DELIVER :=Pamqp_basic_deliver(pool.alloc( sizeof(Tamqp_basic_deliver)));
if BASIC_DELIVER = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, BASIC_DELIVER.consumer_tag, len8))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if 0= amqp_decode_64(encoded, @offset, BASIC_DELIVER.delivery_tag ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if 0= amqp_decode_8(encoded, @offset, bit_buffer ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
BASIC_DELIVER.redelivered := ReturnVal((bit_buffer and (1 shl 0)) , 1,0);
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, BASIC_DELIVER.exchange, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, BASIC_DELIVER.routing_key, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
decoded := BASIC_DELIVER;
Exit(0);
end;
AMQP_BASIC_GET_METHOD:
begin
BASIC_GET := Pamqp_basic_get(pool.alloc( sizeof(Tamqp_basic_get)));
if BASIC_GET = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_16(encoded, @offset, BASIC_GET.ticket) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, BASIC_GET.queue, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (0= amqp_decode_8(encoded, @offset, bit_buffer )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
BASIC_GET.no_ack := ReturnVal((bit_buffer and (1 shl 0)) , 1,0);
decoded := BASIC_GET;
Exit(0);
end;
AMQP_BASIC_GET_OK_METHOD:
begin
BASIC_GET_OK :=Pamqp_basic_get_ok(pool.alloc( sizeof(Tamqp_basic_get_ok)));
if BASIC_GET_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if (0= amqp_decode_64(encoded, @offset, BASIC_GET_OK.delivery_tag )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (0= amqp_decode_8(encoded, @offset, bit_buffer )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
BASIC_GET_OK.redelivered := ReturnVal((bit_buffer and (1 shl 0)) , 1,0);
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, BASIC_GET_OK.exchange, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, BASIC_GET_OK.routing_key, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (0= amqp_decode_32(encoded, @offset, BASIC_GET_OK.message_count )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
decoded := BASIC_GET_OK;
Exit(0);
end;
AMQP_BASIC_GET_EMPTY_METHOD:
begin
BASIC_GET_EMPTY := Pamqp_basic_get_empty(pool.alloc( sizeof(Tamqp_basic_get_empty)));
if BASIC_GET_EMPTY = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
begin
//var len: uint8_t;
if (0= amqp_decode_8(encoded, @offset, len8)) or
(0= amqp_decode_bytes(encoded, @offset, BASIC_GET_EMPTY.cluster_id, len8)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
decoded := BASIC_GET_EMPTY;
Exit(0);
end;
AMQP_BASIC_ACK_METHOD:
begin
BASIC_ACK :=Pamqp_basic_ack(pool.alloc( sizeof(Tamqp_basic_ack)));
if BASIC_ACK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_64(encoded, @offset, BASIC_ACK.delivery_tag ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if 0= amqp_decode_8(encoded, @offset, &bit_buffer ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
BASIC_ACK.multiple := ReturnVal((bit_buffer and (1 shl 0)) , 1,0);
decoded := BASIC_ACK;
Exit(0);
end;
AMQP_BASIC_REJECT_METHOD:
begin
BASIC_REJECT := Pamqp_basic_reject(pool.alloc( sizeof(Tamqp_basic_reject)));
if BASIC_REJECT = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_64(encoded, @offset, BASIC_REJECT.delivery_tag ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if 0= amqp_decode_8(encoded, @offset, &bit_buffer ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
BASIC_REJECT.requeue := ReturnVal((bit_buffer and (1 shl 0)) , 1,0);
decoded := BASIC_REJECT;
Exit(0);
end;
AMQP_BASIC_RECOVER_ASYNC_METHOD:
begin
BASIC_RECOVER_ASYNC :=Pamqp_basic_recover_async(pool.alloc( sizeof(Tamqp_basic_recover_async)));
if BASIC_RECOVER_ASYNC = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_8(encoded, @offset, &bit_buffer ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
BASIC_RECOVER_ASYNC.requeue := ReturnVal((bit_buffer and (1 shl 0)) , 1,0);
decoded := BASIC_RECOVER_ASYNC;
Exit(0);
end;
AMQP_BASIC_RECOVER_METHOD:
begin
BASIC_RECOVER := Pamqp_basic_recover(pool.alloc( sizeof(Tamqp_basic_recover)));
if BASIC_RECOVER = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_8(encoded, @offset, &bit_buffer ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
BASIC_RECOVER.requeue := ReturnVal((bit_buffer and (1 shl 0)) , 1,0);
decoded := BASIC_RECOVER;
Exit(0);
end;
AMQP_BASIC_RECOVER_OK_METHOD: begin
BASIC_RECOVER_OK := Pamqp_basic_recover_ok(pool.alloc( sizeof(Tamqp_basic_recover_ok)));
if BASIC_RECOVER_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
decoded := BASIC_RECOVER_OK;
Exit(0);
end;
AMQP_BASIC_NACK_METHOD:
begin
BASIC_NACK:=Pamqp_basic_nack(pool.alloc( sizeof(Tamqp_basic_nack)));
if BASIC_NACK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_64(encoded, @offset, BASIC_NACK.delivery_tag ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if 0= amqp_decode_8(encoded, @offset, &bit_buffer ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
BASIC_NACK.multiple := ReturnVal((bit_buffer and (1 shl 0)) , 1,0);
BASIC_NACK.requeue := ReturnVal((bit_buffer and (1 shl 1)) , 1,0);
decoded := BASIC_NACK;
Exit(0);
end;
AMQP_TX_SELECT_METHOD:
begin
TX_SELECT :=Pamqp_tx_select(pool.alloc( sizeof(Tamqp_tx_select)));
if TX_SELECT = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
decoded := TX_SELECT;
Exit(0);
end;
AMQP_TX_SELECT_OK_METHOD:
begin
TX_SELECT_OK := Pamqp_tx_select_ok(pool.alloc( sizeof(Tamqp_tx_select_ok)));
if TX_SELECT_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
decoded := TX_SELECT_OK;
Exit(0);
end;
AMQP_TX_COMMIT_METHOD:
begin
TX_COMMIT :=Pamqp_tx_commit(pool.alloc( sizeof(Tamqp_tx_commit)));
if TX_COMMIT = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
decoded := TX_COMMIT;
Exit(0);
end;
AMQP_TX_COMMIT_OK_METHOD:
begin
TX_COMMIT_OK := Pamqp_tx_commit_ok(pool.alloc( sizeof(Tamqp_tx_commit_ok)));
if TX_COMMIT_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
decoded := TX_COMMIT_OK;
Exit(0);
end;
AMQP_TX_ROLLBACK_METHOD:
begin
TX_ROLLBACK := Pamqp_tx_rollback(pool.alloc( sizeof(Tamqp_tx_rollback)));
if TX_ROLLBACK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
decoded := TX_ROLLBACK;
Exit(0);
end;
AMQP_TX_ROLLBACK_OK_METHOD:
begin
TX_ROLLBACK_OK := Pamqp_tx_rollback_ok(pool.alloc( sizeof(Tamqp_tx_rollback_ok)));
if TX_ROLLBACK_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
decoded := TX_ROLLBACK_OK;
Exit(0);
end;
AMQP_CONFIRM_SELECT_METHOD:
begin
CONFIRM_SELECT := Pamqp_confirm_select(pool.alloc( sizeof(Tamqp_confirm_select)));
if CONFIRM_SELECT = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
if 0= amqp_decode_8(encoded, @offset, &bit_buffer ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
CONFIRM_SELECT.nowait := ReturnVal((bit_buffer and (1 shl 0)) , 1,0);
decoded := CONFIRM_SELECT;
Exit(0);
end;
AMQP_CONFIRM_SELECT_OK_METHOD:
begin
CONFIRM_SELECT_OK := Pamqp_confirm_select_ok(pool.alloc( sizeof(Tamqp_confirm_select_ok)));
if CONFIRM_SELECT_OK = nil then begin
Exit(int(AMQP_STATUS_NO_MEMORY));
end;
decoded := CONFIRM_SELECT_OK;
Exit(0);
end;
else
Exit(Int(AMQP_STATUS_UNKNOWN_METHOD));
end;
end;
function amqp_encode_properties(class_id : uint16;decoded: Pointer; encoded : Tamqp_bytes):integer;
var
offset : size_t;
flags,
remaining_flags,
remainder : amqp_flags_t;
partial_flags : uint16;
p : Pamqp_basic_properties;
res : integer;
begin
offset := 0;
{ Cheat, and get the flags out generically, relying on the
similarity of structure between classes }
//flags := *(amqp_flags(decoded;
flags := Pamqp_flags_t(decoded)^;
begin
{ We take a copy of flags to avoid destroying it, as it is used
in the autogenerated code below. }
remaining_flags := flags;
while (remaining_flags <> 0) do
begin
remainder := remaining_flags shr 16;
partial_flags := remaining_flags and $FFFE;
if remainder <> 0 then
partial_flags := partial_flags or 1;
if 0= amqp_encode_n(16,encoded, @offset, partial_flags) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
remaining_flags := remainder;
end;
end;
case class_id of
10,
20,
30,
40,
50:
begin
Exit(int(offset));
end;
60:
begin
p := Pamqp_basic_properties(decoded);
if (flags and AMQP_BASIC_CONTENT_TYPE_FLAG) > 0 then
begin
if (UINT8_MAX < p.content_type.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(p.content_type.len))) or
(0 = amqp_encode_bytes(encoded, @offset, p.content_type)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (flags and AMQP_BASIC_CONTENT_ENCODING_FLAG)>0 then
begin
if (UINT8_MAX < p.content_encoding.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(p.content_encoding.len))) or
(0 = amqp_encode_bytes(encoded, @offset, p.content_encoding))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (flags and AMQP_BASIC_HEADERS_FLAG)>0 then
begin
begin
res := amqp_encode_table(encoded, @(p.headers), @offset);
if res < 0 then Exit(res);
end;
end;
if (flags and AMQP_BASIC_DELIVERY_MODE_FLAG)>0 then
begin
if (0 = amqp_encode_n(8,encoded, @offset, p.delivery_mode)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (flags and AMQP_BASIC_PRIORITY_FLAG)>0 then
begin
if (0 = amqp_encode_n(8,encoded, @offset, p.priority)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (flags and AMQP_BASIC_CORRELATION_ID_FLAG)>0 then
begin
if (UINT8_MAX < p.correlation_id.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(p.correlation_id.len))) or
(0 = amqp_encode_bytes(encoded, @offset, p.correlation_id)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (flags and AMQP_BASIC_REPLY_TO_FLAG)>0 then
begin
if (UINT8_MAX < p.reply_to.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(p.reply_to.len))) or
(0 = amqp_encode_bytes(encoded, @offset, p.reply_to)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (flags and AMQP_BASIC_EXPIRATION_FLAG)>0 then
begin
if (UINT8_MAX < p.expiration.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(p.expiration.len))) or
(0 = amqp_encode_bytes(encoded, @offset, p.expiration)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (flags and AMQP_BASIC_MESSAGE_ID_FLAG)>0 then
begin
if (UINT8_MAX < p.message_id.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(p.message_id.len))) or
(0 = amqp_encode_bytes(encoded, @offset, p.message_id))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (flags and AMQP_BASIC_TIMESTAMP_FLAG)>0 then
begin
if (0 = amqp_encode_n(64,encoded, @offset, p.timestamp)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (flags and AMQP_BASIC_TYPE_FLAG)>0 then
begin
if (UINT8_MAX < p.&type.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(p.&type.len))) or
(0 = amqp_encode_bytes(encoded, @offset, p.&type))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (flags and AMQP_BASIC_USER_ID_FLAG)>0 then
begin
if (UINT8_MAX < p.user_id.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(p.user_id.len))) or
(0 = amqp_encode_bytes(encoded, @offset, p.user_id))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (flags and AMQP_BASIC_APP_ID_FLAG)>0 then
begin
if (UINT8_MAX < p.app_id.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(p.app_id.len))) or
(0 = amqp_encode_bytes(encoded, @offset, p.app_id)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
if (flags and AMQP_BASIC_CLUSTER_ID_FLAG)>0 then
begin
if (UINT8_MAX < p.cluster_id.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(p.cluster_id.len))) or
(0 = amqp_encode_bytes(encoded, @offset, p.cluster_id)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
end;
Exit(int(offset));
end;
90:
begin
Exit(int(offset));
end;
85:
begin
Exit(int(offset));
end;
else
Exit(Integer(AMQP_STATUS_UNKNOWN_CLASS));
end;
end;
function amqp_encode_method(methodNumber : amqp_method_number_t;decoded: Pointer; encoded : Tamqp_bytes):integer;
var
offset : size_t;
bit_buffer : byte;
res : Integer;
START : Pamqp_connection_start;
START_OK : Pamqp_connection_start_ok;
SECURE_OK : Pamqp_connection_secure_ok;
SECURE : Pamqp_connection_secure;
TUNE : Pamqp_connection_tune;
TUNE_OK : Pamqp_connection_tune_ok;
open : Pamqp_connection_open;
OPEN_OK : Pamqp_connection_open_ok;
CONNECTION_CLOSE : Pamqp_connection_close;
UPDATE_SECRET : Pamqp_connection_update_secret;
BLOCKED : Pamqp_connection_blocked;
CHANNEL_OPEN : Pamqp_channel_open;
CHANNEL_OPEN_OK : Pamqp_channel_open_ok;
CHANNEL_FLOW : Pamqp_channel_flow;
CHANNEL_FLOW_OK : Pamqp_channel_flow_ok;
CHANNEL_CLOSE : Pamqp_channel_close;
ACCESS_REQUEST : Pamqp_access_request;
ACCESS_REQUEST_OK : Pamqp_access_request_ok;
EXCHANGE_DECLARE : Pamqp_exchange_declare;
EXCHANGE_DELETE : Pamqp_exchange_delete;
EXCHANGE_BIND : Pamqp_exchange_bind;
EXCHANGE_UNBIND : Pamqp_exchange_unbind;
QUEUE_DECLARE : Pamqp_queue_declare;
QUEUE_DECLARE_OK : Pamqp_queue_declare_ok;
QUEUE_BIND : Pamqp_queue_bind;
QUEUE_PURGE : Pamqp_queue_purge;
QUEUE_PURGE_OK : Pamqp_queue_purge_ok;
QUEUE_DELETE : Pamqp_queue_delete;
QUEUE_DELETE_OK : Pamqp_queue_delete_ok;
QUEUE_UNBIND : Pamqp_queue_unbind;
BASIC_QOS : Pamqp_basic_qos;
BASIC_CONSUME : Pamqp_basic_consume;
BASIC_CONSUME_OK : Pamqp_basic_consume_ok;
BASIC_CANCEL : Pamqp_basic_cancel;
BASIC_CANCEL_OK : Pamqp_basic_cancel_ok;
pub : Pamqp_basic_publish;
BASIC_RETURN : Pamqp_basic_return;
BASIC_DELIVER : Pamqp_basic_deliver;
BASIC_GET_OK : Pamqp_basic_get_ok;
BASIC_GET_EMPTY : Pamqp_basic_get_empty;
BASIC_ACK : Pamqp_basic_ack;
BASIC_REJECT : Pamqp_basic_reject;
BASIC_RECOVER_ASYNC : Pamqp_basic_recover_async;
BASIC_GET : Pamqp_basic_get;
BASIC_RECOVER : Pamqp_basic_recover;
BASIC_NACK : Pamqp_basic_nack;
CONFIRM_SELECT : Pamqp_confirm_select;
begin
offset := 0;
case methodNumber of
AMQP_CONNECTION_START_METHOD:
begin
START := Pamqp_connection_start(decoded);
if 0 = amqp_encode_n(8, encoded, @offset, START.version_major ) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if 0 = amqp_encode_n(8, encoded, @offset, START.version_minor) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
begin
res := amqp_encode_table(encoded, @(START.server_properties), @offset);
if res < 0 then Exit(res);
end;
if (UINT32_MAX < START.mechanisms.len) or
(0= amqp_encode_n(32, encoded, @offset, uint32_t(START.mechanisms.len))) or
(0= amqp_encode_bytes(encoded, @offset, START.mechanisms)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT32_MAX < START.locales.len) or
(0= amqp_encode_n(32, encoded, @offset, uint32_t(START.locales.len))) or
(0= amqp_encode_bytes(encoded, @offset, START.locales)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_CONNECTION_START_OK_METHOD:
begin
START_OK := Pamqp_connection_start_ok(decoded);
begin
res := amqp_encode_table(encoded, @START_OK.client_properties, @offset);
if res < 0 then Exit(res);
end;
if (UINT8_MAX < START_OK.mechanism.len) or
(0= amqp_encode_n(8, encoded, @offset, uint8_t(START_OK.mechanism.len))) or
(0= amqp_encode_bytes(encoded, @offset, START_OK.mechanism)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT32_MAX < START_OK.response.len) or
(0= amqp_encode_n(32, encoded, @offset, uint32_t( START_OK.response.len))) or
(0= amqp_encode_bytes(encoded, @offset, START_OK.response)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < START_OK.locale.len) or
(0= amqp_encode_n(8, encoded, @offset, uint8_t(START_OK.locale.len))) or
(0= amqp_encode_bytes(encoded, @offset, START_OK.locale)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_CONNECTION_SECURE_METHOD:
begin
SECURE := Pamqp_connection_secure (decoded);
if (UINT32_MAX < SECURE.challenge.len) or
(0= amqp_encode_n(32, encoded, @offset, uint32_t(SECURE.challenge.len))) or
(0= amqp_encode_bytes(encoded, @offset, SECURE.challenge)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_CONNECTION_SECURE_OK_METHOD:
begin
SECURE_OK := Pamqp_connection_secure_ok(decoded);
if (UINT32_MAX < SECURE_OK.response.len) or
(0= amqp_encode_n(32, encoded, @offset, uint32_t(SECURE_OK.response.len))) or
(0= amqp_encode_bytes(encoded, @offset, SECURE_OK.response)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_CONNECTION_TUNE_METHOD:
begin
TUNE := Pamqp_connection_tune(decoded);
if 0= amqp_encode_n(16, encoded, @offset, tune.channel_max )then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if 0= amqp_encode_n(32, encoded, @offset, tune.frame_max ) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if 0= amqp_encode_n(16, encoded, @offset, tune.heartbeat ) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_CONNECTION_TUNE_OK_METHOD:
begin
tune_ok := Pamqp_connection_tune_ok(decoded);
if 0= amqp_encode_n(16, encoded, @offset, tune_ok.channel_max )then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if 0= amqp_encode_n(32, encoded, @offset, tune_ok.frame_max) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if 0= amqp_encode_n(16, encoded, @offset, tune_ok.heartbeat) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_CONNECTION_OPEN_METHOD:
begin
open := Pamqp_connection_open(decoded);
if (UINT8_MAX < open.virtual_host.len) or
(0= amqp_encode_n(8, encoded, @offset, uint8_t(open.virtual_host.len))) or
(0= amqp_encode_bytes(encoded, @offset, open.virtual_host)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < open.capabilities.len) or
(0 = amqp_encode_n(8, encoded, @offset, uint8_t(open.capabilities.len))) or
(0= amqp_encode_bytes(encoded, @offset, open.capabilities))then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if open.insist > 0 then
bit_buffer := bit_buffer or ((1 shl 0));
if 0= amqp_encode_n(8, encoded, @offset, bit_buffer ) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_CONNECTION_OPEN_OK_METHOD:
begin
OPEN_OK := Pamqp_connection_open_ok(decoded);
if (UINT8_MAX < OPEN_OK.known_hosts.len) or
(0= amqp_encode_n(8, encoded, @offset, uint8_t(OPEN_OK.known_hosts.len))) or
(0= amqp_encode_bytes(encoded, @offset, OPEN_OK.known_hosts))then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_CONNECTION_CLOSE_METHOD:
begin
CONNECTION_CLOSE := Pamqp_connection_close(decoded);
if 0= amqp_encode_n(16, encoded, @offset, CONNECTION_CLOSE.reply_code ) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < CONNECTION_CLOSE.reply_text.len) or
(0= amqp_encode_n(8, encoded, @offset, uint8_t(CONNECTION_CLOSE.reply_text.len))) or
(0= amqp_encode_bytes(encoded, @offset, CONNECTION_CLOSE.reply_text)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if 0= amqp_encode_n(16, encoded, @offset, CONNECTION_CLOSE.class_id ) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if 0= amqp_encode_n(16, encoded, @offset, CONNECTION_CLOSE.method_id) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_CONNECTION_CLOSE_OK_METHOD:
begin
Exit(int(offset));
end;
AMQP_CONNECTION_BLOCKED_METHOD:
begin
BLOCKED := Pamqp_connection_blocked(decoded);
if (UINT8_MAX < BLOCKED.reason.len) or
(0= amqp_encode_n(8, encoded, @offset, uint8_t( BLOCKED.reason.len))) or
(0= amqp_encode_bytes(encoded, @offset, BLOCKED.reason))then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_CONNECTION_UNBLOCKED_METHOD:
begin
Exit(int(offset));
end;
AMQP_CONNECTION_UPDATE_SECRET_METHOD:
begin
UPDATE_SECRET := Pamqp_connection_update_secret(decoded);
if (UINT32_MAX < UPDATE_SECRET.new_secret.len) or
(0= amqp_encode_n(32, encoded, @offset, uint32_t(UPDATE_SECRET.new_secret.len))) or
(0= amqp_encode_bytes(encoded, @offset, UPDATE_SECRET.new_secret))then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < UPDATE_SECRET.reason.len) or
(0= amqp_encode_n(8, encoded, @offset, uint8_t(UPDATE_SECRET.reason.len))) or
(0= amqp_encode_bytes(encoded, @offset, UPDATE_SECRET.reason))then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_CONNECTION_UPDATE_SECRET_OK_METHOD:
begin
Exit(int(offset));
end;
AMQP_CHANNEL_OPEN_METHOD:
begin
CHANNEL_OPEN := Pamqp_channel_open(decoded);
if (UINT8_MAX < CHANNEL_OPEN.out_of_band.len) or
(0= amqp_encode_n(8, encoded, @offset, uint8_t(CHANNEL_OPEN.out_of_band.len))) or
(0= amqp_encode_bytes(encoded, @offset, CHANNEL_OPEN.out_of_band)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_CHANNEL_OPEN_OK_METHOD:
begin
CHANNEL_OPEN_OK := Pamqp_channel_open_ok(decoded);
if (UINT32_MAX < CHANNEL_OPEN_OK.channel_id.len) or
(0= amqp_encode_n(32, encoded, @offset, uint32_t (CHANNEL_OPEN_OK.channel_id.len))) or
(0= amqp_encode_bytes(encoded, @offset, CHANNEL_OPEN_OK.channel_id)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_CHANNEL_FLOW_METHOD:
begin
CHANNEL_FLOW := Pamqp_channel_flow(decoded);
bit_buffer := 0;
if CHANNEL_FLOW.active > 0 then
bit_buffer := bit_buffer or ((1 shl 0));
if 0= amqp_encode_n(8, encoded, @offset, bit_buffer) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_CHANNEL_FLOW_OK_METHOD:
begin
CHANNEL_FLOW_OK := Pamqp_channel_flow_ok(decoded);
bit_buffer := 0;
if CHANNEL_FLOW_OK.active > 0 then
bit_buffer := bit_buffer or ((1 shl 0));
if 0= amqp_encode_n(8, encoded, @offset, bit_buffer) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_CHANNEL_CLOSE_METHOD:
begin
CHANNEL_CLOSE := Pamqp_channel_close(decoded);
if (0 = amqp_encode_n(16, encoded, @offset, CHANNEL_CLOSE.reply_code)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < CHANNEL_CLOSE.reply_text.len) or
(0 = amqp_encode_n(8, encoded, @offset, uint8_t(CHANNEL_CLOSE.reply_text.len))) or
(0 = amqp_encode_bytes(encoded, @offset, CHANNEL_CLOSE.reply_text)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (0 = amqp_encode_n(16, encoded, @offset, CHANNEL_CLOSE.class_id )) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (0 = amqp_encode_n(16, encoded, @offset, CHANNEL_CLOSE.method_id)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_CHANNEL_CLOSE_OK_METHOD:
begin
Exit(int(offset));
end;
AMQP_ACCESS_REQUEST_METHOD:
begin
ACCESS_REQUEST := Pamqp_access_request(decoded);
if (UINT8_MAX < ACCESS_REQUEST.realm.len) or
(0 = amqp_encode_n(8, encoded, @offset, uint8_t( ACCESS_REQUEST.realm.len))) or
(0 = amqp_encode_bytes(encoded, @offset, ACCESS_REQUEST.realm)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if ACCESS_REQUEST.exclusive > 0 then
bit_buffer := bit_buffer or ((1 shl 0));
if ACCESS_REQUEST.passive > 0 then
bit_buffer := bit_buffer or ((1 shl 1));
if ACCESS_REQUEST.active > 0 then
bit_buffer := bit_buffer or ((1 shl 2));
if ACCESS_REQUEST.write > 0 then
bit_buffer := bit_buffer or ((1 shl 3));
if ACCESS_REQUEST.read > 0 then
bit_buffer := bit_buffer or ((1 shl 4));
if (0 = amqp_encode_n(8, encoded, @offset, bit_buffer)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_ACCESS_REQUEST_OK_METHOD:
begin
ACCESS_REQUEST_OK := Pamqp_access_request_ok(decoded);
if (0 = amqp_encode_n(16, encoded, @offset, ACCESS_REQUEST_OK.ticket )) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_EXCHANGE_DECLARE_METHOD:
begin
EXCHANGE_DECLARE := Pamqp_exchange_declare(decoded);
if (0 = amqp_encode_n(16, encoded, @offset, EXCHANGE_DECLARE.ticket)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < EXCHANGE_DECLARE.exchange.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(EXCHANGE_DECLARE.exchange.len))) or
(0 = amqp_encode_bytes(encoded, @offset, EXCHANGE_DECLARE.exchange)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < EXCHANGE_DECLARE.&type.len) or
(0 = amqp_encode_n(8, encoded, @offset, uint8_t(EXCHANGE_DECLARE.&type.len))) or
(0 = amqp_encode_bytes(encoded, @offset, EXCHANGE_DECLARE.&type))then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if EXCHANGE_DECLARE.passive >0 then
bit_buffer := bit_buffer or ((1 shl 0));
if EXCHANGE_DECLARE.durable > 0 then
bit_buffer := bit_buffer or ((1 shl 1));
if EXCHANGE_DECLARE.auto_delete > 0 then
bit_buffer := bit_buffer or ((1 shl 2));
if EXCHANGE_DECLARE.internal > 0 then
bit_buffer := bit_buffer or ((1 shl 3));
if EXCHANGE_DECLARE.nowait > 0 then
bit_buffer := bit_buffer or ((1 shl 4));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer ))then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
begin
res := amqp_encode_table(encoded, @(EXCHANGE_DECLARE.arguments), @offset);
if res < 0 then
Exit(res);
end;
Exit(int(offset));
end;
AMQP_EXCHANGE_DECLARE_OK_METHOD:
begin
Exit(int(offset));
end;
AMQP_EXCHANGE_DELETE_METHOD:
begin
EXCHANGE_DELETE := Pamqp_exchange_delete(decoded);
if (0 = amqp_encode_n(16,encoded, @offset, EXCHANGE_DELETE.ticket )) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < EXCHANGE_DELETE.exchange.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(EXCHANGE_DELETE.exchange.len))) or
(0 = amqp_encode_bytes(encoded, @offset, EXCHANGE_DELETE.exchange))then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if EXCHANGE_DELETE.if_unused > 0 then
bit_buffer := bit_buffer or ((1 shl 0));
if EXCHANGE_DELETE.nowait > 0 then
bit_buffer := bit_buffer or ((1 shl 1));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_EXCHANGE_DELETE_OK_METHOD:
begin
Exit(int(offset));
end;
AMQP_EXCHANGE_BIND_METHOD:
begin
EXCHANGE_BIND := Pamqp_exchange_bind(decoded);
if (0 = amqp_encode_n(16, encoded, @offset, EXCHANGE_BIND.ticket )) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < EXCHANGE_BIND.destination.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t( EXCHANGE_BIND.destination.len))) or
(0 = amqp_encode_bytes(encoded, @offset, EXCHANGE_BIND.destination)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < EXCHANGE_BIND.source.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(EXCHANGE_BIND.source.len))) or
(0 = amqp_encode_bytes(encoded, @offset, EXCHANGE_BIND.source)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < EXCHANGE_BIND.routing_key.len) or
(0 = amqp_encode_n(8, encoded, @offset, uint8_t(EXCHANGE_BIND.routing_key.len))) or
(0 = amqp_encode_bytes(encoded, @offset, EXCHANGE_BIND.routing_key)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if EXCHANGE_BIND.nowait > 0 then
bit_buffer := bit_buffer or ((1 shl 0));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer )) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
begin
res := amqp_encode_table(encoded, @(EXCHANGE_BIND.arguments), @offset);
if res < 0 then Exit(res);
end;
Exit(int(offset));
end;
AMQP_EXCHANGE_BIND_OK_METHOD:
begin
Exit(int(offset));
end;
AMQP_EXCHANGE_UNBIND_METHOD:
begin
EXCHANGE_UNBIND := Pamqp_exchange_unbind(decoded);
if (0 = amqp_encode_n(16,encoded, @offset, EXCHANGE_UNBIND.ticket ))then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < EXCHANGE_UNBIND.destination.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t( EXCHANGE_UNBIND.destination.len))) or
(0 = amqp_encode_bytes(encoded, @offset, EXCHANGE_UNBIND.destination)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < EXCHANGE_UNBIND.source.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(EXCHANGE_UNBIND.source.len))) or
(0 = amqp_encode_bytes(encoded, @offset, EXCHANGE_UNBIND.source)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < EXCHANGE_UNBIND.routing_key.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t( EXCHANGE_UNBIND.routing_key.len))) or
(0 = amqp_encode_bytes(encoded, @offset, EXCHANGE_UNBIND.routing_key)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if EXCHANGE_UNBIND.nowait > 0 then
bit_buffer := bit_buffer or ((1 shl 0));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer )) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
begin
res := amqp_encode_table(encoded, @(EXCHANGE_UNBIND.arguments), @offset);
if res < 0 then Exit(res);
end;
Exit(int(offset));
end;
AMQP_EXCHANGE_UNBIND_OK_METHOD:
begin
Exit(int(offset));
end;
AMQP_QUEUE_DECLARE_METHOD:
begin
QUEUE_DECLARE := Pamqp_queue_declare(decoded);
if (0 = amqp_encode_n(16,encoded, @offset, QUEUE_DECLARE.ticket)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < QUEUE_DECLARE.queue.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t (QUEUE_DECLARE.queue.len))) or
(0 = amqp_encode_bytes(encoded, @offset, QUEUE_DECLARE.queue))then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if QUEUE_DECLARE.passive > 0 then
bit_buffer := bit_buffer or ((1 shl 0));
if QUEUE_DECLARE.durable > 0 then
bit_buffer := bit_buffer or ((1 shl 1));
if QUEUE_DECLARE.exclusive > 0 then
bit_buffer := bit_buffer or ((1 shl 2));
if QUEUE_DECLARE.auto_delete > 0 then
bit_buffer := bit_buffer or ((1 shl 3));
if QUEUE_DECLARE.nowait > 0 then
bit_buffer := bit_buffer or ((1 shl 4));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
begin
res := amqp_encode_table(encoded, @(QUEUE_DECLARE.arguments), @offset);
if res < 0 then Exit(res);
end;
Exit(int(offset));
end;
AMQP_QUEUE_DECLARE_OK_METHOD:
begin
QUEUE_DECLARE_OK := Pamqp_queue_declare_ok(decoded);
if (UINT8_MAX < QUEUE_DECLARE_OK.queue.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t( QUEUE_DECLARE_OK.queue.len))) or
(0 = amqp_encode_bytes(encoded, @offset, QUEUE_DECLARE_OK.queue)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (0 = amqp_encode_n(32,encoded, @offset, QUEUE_DECLARE_OK.message_count)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (0 = amqp_encode_n(32,encoded, @offset, QUEUE_DECLARE_OK.consumer_count)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_QUEUE_BIND_METHOD:
begin
QUEUE_BIND := Pamqp_queue_bind(decoded);
if (0 = amqp_encode_n(16,encoded, @offset, QUEUE_BIND.ticket)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < QUEUE_BIND.queue.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t ( QUEUE_BIND.queue.len))) or
(0 = amqp_encode_bytes(encoded, @offset, QUEUE_BIND.queue)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < QUEUE_BIND.exchange.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t ( QUEUE_BIND.exchange.len))) or
(0 = amqp_encode_bytes(encoded, @offset, QUEUE_BIND.exchange))then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < QUEUE_BIND.routing_key.len ) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t( QUEUE_BIND.routing_key.len))) or
(0 = amqp_encode_bytes(encoded, @offset, QUEUE_BIND.routing_key)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if QUEUE_BIND.nowait > 0 then
bit_buffer := bit_buffer or ((1 shl 0));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer )) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
begin
res := amqp_encode_table(encoded, @(QUEUE_BIND.arguments), @offset);
if res < 0 then Exit(res);
end;
Exit(int(offset));
end;
AMQP_QUEUE_BIND_OK_METHOD:
begin
Exit(int(offset));
end;
AMQP_QUEUE_PURGE_METHOD:
begin
QUEUE_PURGE := Pamqp_queue_purge(decoded);
if (0 = amqp_encode_n(16,encoded, @offset, QUEUE_PURGE.ticket )) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < QUEUE_PURGE.queue.len ) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t ( QUEUE_PURGE.queue.len))) or
(0 = amqp_encode_bytes(encoded, @offset, QUEUE_PURGE.queue)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if QUEUE_PURGE.nowait > 0 then
bit_buffer := bit_buffer or ((1 shl 0));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer )) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_QUEUE_PURGE_OK_METHOD:
begin
QUEUE_PURGE_OK := Pamqp_queue_purge_ok(decoded);
if (0 = amqp_encode_n(32,encoded, @offset, QUEUE_PURGE_OK.message_count )) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_QUEUE_DELETE_METHOD:
begin
QUEUE_DELETE := Pamqp_queue_delete(decoded);
if (0 = amqp_encode_n(16,encoded, @offset, QUEUE_DELETE.ticket )) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < QUEUE_DELETE.queue.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t( QUEUE_DELETE.queue.len))) or
(0 = amqp_encode_bytes(encoded, @offset, QUEUE_DELETE.queue)) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if QUEUE_DELETE.if_unused > 0 then
bit_buffer := bit_buffer or ((1 shl 0));
if QUEUE_DELETE.if_empty > 0 then
bit_buffer := bit_buffer or ((1 shl 1));
if QUEUE_DELETE.nowait > 0 then
bit_buffer := bit_buffer or ((1 shl 2));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer )) then
Exit(Integer(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_QUEUE_DELETE_OK_METHOD:
begin
QUEUE_DELETE_OK := Pamqp_queue_delete_ok(decoded);
if (0 = amqp_encode_n(32,encoded, @offset, QUEUE_DELETE_OK.message_count )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_QUEUE_UNBIND_METHOD:
begin
QUEUE_UNBIND := Pamqp_queue_unbind(decoded);
if (0 = amqp_encode_n(16,encoded, @offset, QUEUE_UNBIND.ticket )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < QUEUE_UNBIND.queue.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(QUEUE_UNBIND.queue.len))) or
(0 = amqp_encode_bytes(encoded, @offset, QUEUE_UNBIND.queue))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < QUEUE_UNBIND.exchange.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(QUEUE_UNBIND.exchange.len))) or
(0 = amqp_encode_bytes(encoded, @offset, QUEUE_UNBIND.exchange))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < QUEUE_UNBIND.routing_key.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(QUEUE_UNBIND.routing_key.len))) or
(0 = amqp_encode_bytes(encoded, @offset, QUEUE_UNBIND.routing_key)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
begin
res := amqp_encode_table(encoded, @(QUEUE_UNBIND.arguments), @offset);
if res < 0 then Exit(res);
end;
Exit(int(offset));
end;
AMQP_QUEUE_UNBIND_OK_METHOD:
begin
Exit(int(offset));
end;
AMQP_BASIC_QOS_METHOD:
begin
BASIC_QOS := Pamqp_basic_qos(decoded);
if (0 = amqp_encode_n(32,encoded, @offset, BASIC_QOS.prefetch_size )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (0 = amqp_encode_n(16,encoded, @offset, BASIC_QOS.prefetch_count )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if BASIC_QOS.global > 0 then
bit_buffer := bit_buffer or ((1 shl 0));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer ) )then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_BASIC_QOS_OK_METHOD:
begin
Exit(int(offset));
end;
AMQP_BASIC_CONSUME_METHOD:
begin
BASIC_CONSUME := Pamqp_basic_consume(decoded);
if (0 = amqp_encode_n(16,encoded, @offset, BASIC_CONSUME.ticket ) )then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < BASIC_CONSUME.queue.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(BASIC_CONSUME.queue.len))) or
(0 = amqp_encode_bytes(encoded, @offset, BASIC_CONSUME.queue))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < BASIC_CONSUME.consumer_tag.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t(BASIC_CONSUME.consumer_tag.len))) or
(0 = amqp_encode_bytes(encoded, @offset, BASIC_CONSUME.consumer_tag)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if BASIC_CONSUME.no_local >0 then
bit_buffer := bit_buffer or ((1 shl 0));
if BASIC_CONSUME.no_ack>0 then
bit_buffer := bit_buffer or ((1 shl 1));
if BASIC_CONSUME.exclusive>0 then
bit_buffer := bit_buffer or ((1 shl 2));
if BASIC_CONSUME.nowait>0 then
bit_buffer := bit_buffer or ((1 shl 3));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
begin
res := amqp_encode_table(encoded, @(BASIC_CONSUME.arguments), @offset);
if res < 0 then Exit(res);
end;
Exit(int(offset));
end;
AMQP_BASIC_CONSUME_OK_METHOD:
begin
BASIC_CONSUME_OK := Pamqp_basic_consume_ok(decoded);
if (UINT8_MAX < BASIC_CONSUME_OK.consumer_tag.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t (BASIC_CONSUME_OK.consumer_tag.len))) or
(0 = amqp_encode_bytes(encoded, @offset, BASIC_CONSUME_OK.consumer_tag)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_BASIC_CANCEL_METHOD:
begin
BASIC_CANCEL := Pamqp_basic_cancel(decoded);
if (UINT8_MAX < BASIC_CANCEL.consumer_tag.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t ( BASIC_CANCEL.consumer_tag.len))) or
(0 = amqp_encode_bytes(encoded, @offset, BASIC_CANCEL.consumer_tag))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if BASIC_CANCEL.nowait>0 then
bit_buffer := bit_buffer or ((1 shl 0));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_BASIC_CANCEL_OK_METHOD:
begin
BASIC_CANCEL_OK := Pamqp_basic_cancel_ok(decoded);
if (UINT8_MAX < BASIC_CANCEL_OK.consumer_tag.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t ( BASIC_CANCEL_OK.consumer_tag.len))) or
(0 = amqp_encode_bytes(encoded, @offset, BASIC_CANCEL_OK.consumer_tag)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_BASIC_PUBLISH_METHOD:
begin
pub := Pamqp_basic_publish(decoded);
if (0 = amqp_encode_n(16,encoded, @offset, pub.ticket ) )then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < pub.exchange.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t ( pub.exchange.len))) or
(0 = amqp_encode_bytes(encoded, @offset, pub.exchange)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < pub.routing_key.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t ( pub.routing_key.len))) or
(0 = amqp_encode_bytes(encoded, @offset, pub.routing_key))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if pub.mandatory>0 then
bit_buffer := bit_buffer or ((1 shl 0));
if pub.immediate>0 then
bit_buffer := bit_buffer or ((1 shl 1));
if 0 = amqp_encode_n(8,encoded, @offset, bit_buffer ) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_BASIC_RETURN_METHOD:
begin
BASIC_RETURN := Pamqp_basic_return(decoded);
if (0 = amqp_encode_n(16,encoded, @offset, BASIC_RETURN.reply_code ) )then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < BASIC_RETURN.reply_text.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t ( BASIC_RETURN.reply_text.len))) or
(0 = amqp_encode_bytes(encoded, @offset, BASIC_RETURN.reply_text)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < BASIC_RETURN.exchange.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t ( BASIC_RETURN.exchange.len))) or
(0 = amqp_encode_bytes(encoded, @offset, BASIC_RETURN.exchange))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < BASIC_RETURN.routing_key.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t ( BASIC_RETURN.routing_key.len))) or
(0 = amqp_encode_bytes(encoded, @offset, BASIC_RETURN.routing_key))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_BASIC_DELIVER_METHOD:
begin
BASIC_DELIVER := Pamqp_basic_deliver(decoded);
if (UINT8_MAX < BASIC_DELIVER.consumer_tag.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t ( BASIC_DELIVER.consumer_tag.len))) or
(0 = amqp_encode_bytes(encoded, @offset, BASIC_DELIVER.consumer_tag))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (0 = amqp_encode_n(64,encoded, @offset, BASIC_DELIVER.delivery_tag )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if BASIC_DELIVER.redelivered>0 then
bit_buffer := bit_buffer or ((1 shl 0));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < BASIC_DELIVER.exchange.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t ( BASIC_DELIVER.exchange.len))) or
(0 = amqp_encode_bytes(encoded, @offset, BASIC_DELIVER.exchange)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < BASIC_DELIVER.routing_key.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t ( BASIC_DELIVER.routing_key.len))) or
(0 = amqp_encode_bytes(encoded, @offset, BASIC_DELIVER.routing_key))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_BASIC_GET_METHOD:
begin
BASIC_GET := Pamqp_basic_get(decoded);
if (0 = amqp_encode_n(16,encoded, @offset, BASIC_GET.ticket )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < BASIC_GET.queue.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t ( BASIC_GET.queue.len))) or
(0 = amqp_encode_bytes(encoded, @offset, BASIC_GET.queue)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if BASIC_GET.no_ack>0 then
bit_buffer := bit_buffer or ((1 shl 0));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_BASIC_GET_OK_METHOD:
begin
BASIC_GET_OK := Pamqp_basic_get_ok(decoded);
if (0 = amqp_encode_n(64,encoded, @offset, BASIC_GET_OK.delivery_tag )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if BASIC_GET_OK.redelivered>0 then
bit_buffer := bit_buffer or ((1 shl 0));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < BASIC_GET_OK.exchange.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t ( BASIC_GET_OK.exchange.len))) or
(0 = amqp_encode_bytes(encoded, @offset, BASIC_GET_OK.exchange))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (UINT8_MAX < BASIC_GET_OK.routing_key.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t ( BASIC_GET_OK.routing_key.len))) or
(0 = amqp_encode_bytes(encoded, @offset, BASIC_GET_OK.routing_key))then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
if (0 = amqp_encode_n(32,encoded, @offset, BASIC_GET_OK.message_count)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_BASIC_GET_EMPTY_METHOD:
begin
BASIC_GET_EMPTY := Pamqp_basic_get_empty(decoded);
if (UINT8_MAX < BASIC_GET_EMPTY.cluster_id.len) or
(0 = amqp_encode_n(8,encoded, @offset, uint8_t ( BASIC_GET_EMPTY.cluster_id.len))) or
(0 = amqp_encode_bytes(encoded, @offset, BASIC_GET_EMPTY.cluster_id)) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_BASIC_ACK_METHOD:
begin
BASIC_ACK := Pamqp_basic_ack(decoded);
if (0 = amqp_encode_n(64,encoded, @offset, BASIC_ACK.delivery_tag )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if BASIC_ACK.multiple>0 then
bit_buffer := bit_buffer or ((1 shl 0));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_BASIC_REJECT_METHOD:
begin
BASIC_REJECT := Pamqp_basic_reject(decoded);
if (0 = amqp_encode_n(64,encoded, @offset, BASIC_REJECT.delivery_tag )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if BASIC_REJECT.requeue>0 then
bit_buffer := bit_buffer or ((1 shl 0));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_BASIC_RECOVER_ASYNC_METHOD:
begin
BASIC_RECOVER_ASYNC := Pamqp_basic_recover_async(decoded);
bit_buffer := 0;
if BASIC_RECOVER_ASYNC.requeue >0 then
bit_buffer := bit_buffer or ((1 shl 0));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_BASIC_RECOVER_METHOD:
begin
BASIC_RECOVER := Pamqp_basic_recover(decoded);
bit_buffer := 0;
if BASIC_RECOVER.requeue>0 then
bit_buffer := bit_buffer or ((1 shl 0));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_BASIC_RECOVER_OK_METHOD:
begin
Exit(int(offset));
end;
AMQP_BASIC_NACK_METHOD:
begin
BASIC_NACK := Pamqp_basic_nack(decoded);
if (0 = amqp_encode_n(64,encoded, @offset, BASIC_NACK.delivery_tag )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
bit_buffer := 0;
if BASIC_NACK.multiple>0 then
bit_buffer := bit_buffer or ((1 shl 0));
if BASIC_NACK.requeue>0 then
bit_buffer := bit_buffer or ((1 shl 1));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
AMQP_TX_SELECT_METHOD,
AMQP_TX_SELECT_OK_METHOD,
AMQP_TX_COMMIT_METHOD,
AMQP_TX_COMMIT_OK_METHOD,
AMQP_TX_ROLLBACK_METHOD,
AMQP_CONFIRM_SELECT_OK_METHOD,
AMQP_TX_ROLLBACK_OK_METHOD:
begin
Exit(int(offset));
end;
AMQP_CONFIRM_SELECT_METHOD:
begin
CONFIRM_SELECT := Pamqp_confirm_select(decoded);
bit_buffer := 0;
if CONFIRM_SELECT.nowait>0 then
bit_buffer := bit_buffer or ((1 shl 0));
if (0 = amqp_encode_n(8,encoded, @offset, bit_buffer )) then
Exit(int(AMQP_STATUS_BAD_AMQP_DATA));
Exit(int(offset));
end;
else
Exit(Integer(AMQP_STATUS_UNKNOWN_METHOD));
end;
end;
initialization
end.
|
{===============================================================================
Copyright(c) 2012, 北京北研兴电力仪表有限责任公司
All rights reserved.
错误接线,公式绘制单元
+ TWE_VECTOR_EQUATION 画公式
===============================================================================}
unit U_WE_VECTOR_EQUATION;
interface
uses SysUtils, Classes, Windows, StrUtils, Graphics, IniFiles, Forms,
U_WE_EQUATION, U_WIRING_ERROR, U_WE_EXPRESSION, U_WE_EQUATION_MATH,
U_DIAGRAM_TYPE, U_WE_ORGAN, U_WE_VECTOR_MAP, Math, system.Types, System.UITypes;
const
/// <summary>
/// 最小字体
/// </summary>
C_FONT_SIZE_MIN = 8;
type
/// <summary>
/// 画公式
/// </summary>
TWE_VECTOR_EQUATION = class( TComponent )
private
FCanvas : TCanvas;
FRect: TRect;
FScaleRate: Double;
// Fabc : Boolean;
Fabc : Integer;
procedure SetRect(const Value: TRect);
procedure SetScaleRate(const Value: Double);
protected
/// <summary>
/// 获取字体大小
/// </summary>
function DrawFontSize( ADefaultSize : Integer = 12 ) : Integer;
/// <summary>
/// 初始化区域
/// </summary>
procedure IniCanvas( AColorBg, AColor : Integer );
/// <summary>
/// 画单元件表达式
/// </summary>
procedure DrawPhaseEquation( AEquation : TWE_PHASE_EXPRESSION; APos : TPoint;
var AYPos : Integer; AID : Integer );
/// <summary>
/// 缩放后大小
/// </summary>
function ScaledValue( n : Integer ) : Integer;
/// <summary>
/// 画分数
/// </summary>
function DrawFrac( APos : TPoint; AStr : string ) : TPoint;
public
/// <summary>
/// 画布
/// </summary>
property Canvas : TCanvas read FCanvas write FCanvas;
/// <summary>
/// 绘图的区域
/// </summary>
property Rect : TRect read FRect write SetRect;
/// <summary>
/// 缩放比例
/// </summary>
property ScaleRate : Double read FScaleRate write SetScaleRate;
public
constructor Create(AOwner: TComponent); override;
/// <summary>
/// 画字符串
/// </summary>
function DrawText( ACanvas : TCanvas; APos : TPoint; AStr : string;
AFontColor, ABgColor : TColor; AScale : Double ) : TPoint; overload;
/// <summary>
/// 画字符串
/// </summary>
function DrawText( APos : TPoint; AStr : string ) : TPoint; overload;
/// <summary>
/// 画字符串
/// </summary>
function DrawString( APos : TPoint; AString : string ) : Integer;
/// <summary>
/// 绘制功率P
/// </summary>
function DrawEquationP( ROrgans: TStringList;dUIAngle : Double;
AColorBg : Integer = -1; AColor : Integer = -1 ) : Integer;
end;
implementation
{ TWE_VECTOR_EQUATION }
constructor TWE_VECTOR_EQUATION.Create(AOwner: TComponent);
begin
inherited;
FScaleRate := 1;
end;
function TWE_VECTOR_EQUATION.DrawEquationP(ROrgans: TStringList;dUIAngle : Double;
AColorBg, AColor : Integer ) : Integer;
var
s : string;
i : Integer;
ptPos : TPoint;
AOrgan: TWE_ORGAN;
nTemp : Integer;
slList : TStringList;
procedure GetAngle;
var
AVectorIn, AVectorOut:TVECTOR_LINE;
dTemp, dTemp1, dX, dY : Double;
dLen, dUAngle : Double;
begin
// 电压角度
AVectorIn:=VectorLines.GetLine(AOrgan.UInType);
AVectorOut:= VectorLines.GetLine(AOrgan.UOutType);
if Assigned(AVectorIn) and Assigned(AVectorOut) then
begin
dTemp := DegToRad(AVectorIn.LineAngle);
dTemp1 := DegToRad(AVectorOut.LineAngle);
dX := Cos(dTemp)-Cos(dTemp1);
dY := Sin(dTemp)-Sin(dTemp1);
if (dX <> 0) or (dY<>0) then
begin
GetLenAngle(0,0,dX*100,dY*100, dLen, dUAngle);
dUAngle := dUAngle + DegToRad(30);
AOrgan.UAngle := RadToDeg(dUAngle);
end;
end;
// 电流角度
AVectorIn:=VectorLines.GetLine(AOrgan.IInType);
AVectorOut:= VectorLines.GetLine(AOrgan.IOutType);
if Assigned(AVectorIn) then
AOrgan.IAngle := AVectorIn.LineAngle
else if Assigned(AVectorOut) then
AOrgan.IAngle := AVectorOut.LineAngle+180
else
AOrgan.IAngle := 90;
end;
begin
// 清理背景
IniCanvas( AColorBg, AColor );
if not ( Assigned( ROrgans ) and Assigned( FCanvas ) ) then
begin
Result := FRect.Top;
Exit;
end;
slList := TStringList.Create;
FCanvas.Font.Size := Round( FScaleRate * 11 );
FCanvas.Font.Name := '宋体';
FCanvas.Font.Style := [];
for i := 0 to ROrgans.Count - 1 do
begin
AOrgan := TWE_ORGAN(ROrgans.Objects[i]);
GetAngle;
nTemp := Round(Abs(AOrgan.UAngle - AOrgan.IAngle));
if (AOrgan.UInType = AOrgan.UOutType) or (AOrgan.IInType = AOrgan.IOutType) then
begin
s := '0';
end
else
begin
if AOrgan.UAngle > AOrgan.IAngle then
begin
if nTemp > 180 then
begin
s := 'cos(' + IntToStr(360-nTemp)+'-\o)';
end
else
begin
s := 'cos(' + IntToStr(nTemp)+'+\o)';
end;
end
else
begin
if nTemp > 180 then
begin
s := 'cos(' + IntToStr(360-nTemp)+'+\o)';
end
else
begin
s := 'cos(' + IntToStr(nTemp)+'-\o)';
end;
end;
s := AOrgan.UType + AOrgan.IType + s;
if AOrgan.UParam = pt1_2 then
s := '{1,2}' + s;
slList.Add('Q_'+inttostr(i+1)+'''');
end;
s := 'Q_'+inttostr(i+1)+''' = ' + s;
ptPos.X := FRect.Left + 20;
ptPos.Y := FRect.Top + 20+ 40*i;
DrawText( ptPos, s );
end;
ptPos.y := ptPos.y+40;
s := '';
for i := 0 to slList.Count - 1 do
begin
if i = slList.Count - 1 then
s := s + slList[i]
else
s := s + slList[i] + '+';
end;
if s = '' then
s := '0';
DrawText( ptPos, 'Q'' = ' + s );
slList.Free;
Result := ptPos.y + 40;
end;
procedure TWE_VECTOR_EQUATION.DrawPhaseEquation(AEquation: TWE_PHASE_EXPRESSION;
APos: TPoint; var AYPos: Integer; AID : Integer);
var
ptPos : TPoint;
begin
// 写 P'
ptPos := APos;
ptPos := DrawText( Point( ptPos.X, AYPos ), 'P' + SuffixVar( IntToStr( AID ) )
+ ''' = ' );
with AEquation do
begin
ptPos := DrawText( Point( ptPos.X, AYPos ), ExpressionT );
// 如果不存在断相
if ExpressionT <> Expression then
ptPos := DrawText( Point( ptPos.X, AYPos ), ' = ' + Expression );
AYPos := ptPos.Y;
end;
end;
function TWE_VECTOR_EQUATION.DrawString(APos: TPoint; AString: string): Integer;
begin
Result := DrawText( APos, AString ).Y;
end;
function TWE_VECTOR_EQUATION.DrawText(APos: TPoint; AStr: string): TPoint;
var
s, sText : string;
pt, ptMax : TPoint;
nPos : Integer;
p : PChar;
procedure IncPointX( var APt : TPoint; AVal : Integer );
begin
APt.X := APt.X + AVal;
end;
procedure SetMaxPos( var APosMax : TPoint; APos : TPoint );
begin
if APos.X > APosMax.X then
APosMax.X := APos.X;
if APos.Y > APosMax.Y then
APosMax.Y := APos.Y;
end;
function TextStr( APt : TPoint; AStr : string ) : TPoint;
begin
with FCanvas do
begin
TextOut( APt.X, APt.Y, AStr );
Result := APt;
IncPointX( Result, TextWidth( AStr ) );
end;
end;
procedure SetFont( AName : string; ASize : Integer; AStyle : TFontStyles );
begin
with FCanvas do
begin
Font.Name := AName;
Font.Style := AStyle;
if ASize < C_FONT_SIZE_MIN then
Font.Size := C_FONT_SIZE_MIN
else
Font.Size := ASize;
end;
end;
procedure DrawDot( pt1, pt2 : TPoint );
var
nPos : Integer;
begin
nPos := ( pt2.X - pt1.X - ScaledValue( 2 ) ) div 2 + ScaledValue( 2 );
FCanvas.Polyline([ Point( pt1.X + nPos, pt1.Y ),
Point( pt1.X + nPos + ScaledValue( 2 ), pt1.Y)]);
end;
function DrawSqrt3( pt : TPoint ) : TPoint;
begin
SetFont( 'Times New Roman', ScaledValue( 12 ), [] );
TextStr( Point( pt.X + ScaledValue( 9 ), pt.Y ), '3' );
with FCanvas do
begin
Polyline( [ Point(pt.X, pt.Y + ScaledValue( 12 ) ),
Point(pt.X + ScaledValue( 2 ), pt.Y + ScaledValue( 11 )),
Point(pt.X + ScaledValue( 5 ), pt.Y + ScaledValue( 16 )),
Point(pt.X + ScaledValue( 9 ), pt.Y ),
Point(pt.X + ScaledValue( 18 ), pt.Y ) ] );
Result := pt;
IncPointX( Result, ScaledValue( 18 ) );
end;
end;
begin
if not Assigned( FCanvas ) then
begin
Result := APos;
Exit;
end;
sText := AStr;
nPos := 1;
Result := APos;
pt := APos;
// 输出分数
if Pos( '/', sText ) > 0 then
begin
if Copy( sText, 1, 1 ) = '-' then
begin
sText := Copy( sText, 2, Length( sText ) - 1 ); // 去掉 -
SetFont( 'Symbol', ScaledValue( 12 ), [] );
pt := TextStr( pt, '-' );
IncPointX( pt, ScaledValue( 4 ) );
end;
pt.Y := pt.Y + ScaledValue( 11 );
Result := DrawFrac( pt, sText );
Exit;
end;
repeat
s := GetElementsFromExpression( sText, nPos );
if s <> '' then
begin
p := PChar( s );
case ElementType( s ) of
etFrac : // 分数
begin
// 去掉括号{}, 并将 ','-> '/'
s:= StringReplace( Copy( s, 2, Length( s ) -2 ), ',', '/', [] );
ptMax := DrawFrac( Point( pt.X, pt.Y + ScaledValue( 11 ) ), s );
SetMaxPos( Result, ptMax );
pt.X := ptMax.X;
IncPointX( pt, ScaledValue( 2 ) );
end;
etSuffix : // 下标 '1', '2', '3', 'a', 'b', 'c', 'x'
begin
p := PChar( s );
inc( p );
if p^ = 'b' then
IncPointX( pt, ScaledValue( 1 ) );
// 下表 a, b, c, 改为u,v,w
if CharInSet(p^, ['a','b','c'])then
begin
with TIniFile.Create( ChangeFileExt( Application.ExeName, '.ini' ) ) do
begin
Fabc := ReadInteger('Like', 'abc', 0) ;
Free;
end;
{if not Fabc then
begin
case p^ of
'a': p := 'u';
'b': p := 'v';
'c': p := 'w';
end;
end; }
case Fabc of
1:
begin
case p^ of
'a': p := 'u';
'b': p := 'v';
'c': p := 'w';
end;
end;
2:
begin
case p^ of
'a': p := '1';
'b': p := '2';
'c': p := '3';
end;
end;
end;
end;
SetFont( 'Times New Roman', ScaledValue( 8 ), [] );
ptMax := TextStr( Point( pt.X, pt.Y + ScaledValue( 6 ) ), p^ );
pt.X := ptMax.X;
end;
etDot: // 矢量
begin
Inc( p );
SetFont( 'Times New Roman', ScaledValue( 12 ), [ fsItalic ] );
ptMax := TextStr( pt, p^ );
DrawDot( pt, ptMax );
pt.X := ptMax.X;
end;
etSpc: // 特殊
begin
inc( p );
SetFont( 'MS Reference Sans Serif', ScaledValue( 10 ), [ fsItalic ] );
case p^ of
'o' : pt := TextStr( pt, 'φ' );
'a' : pt := TextStr( pt, 'α' );
'b' : pt := TextStr( pt, 'β' );
'q' : pt := TextStr( pt, '∞' );
end;
end;
else
case p^ of
'(', ')' :
begin
IncPointX( pt, ScaledValue( 3 ) );
SetFont( 'Symbol', ScaledValue( 12 ), [] );
pt := TextStr( pt, p^ );
IncPointX( pt, ScaledValue( 3 ) );
end;
'+', '-', '=':
begin
IncPointX( pt, ScaledValue( 3 ) );
SetFont( 'Symbol', ScaledValue( 12 ), [] );
pt := TextStr( pt, p^ );
IncPointX( pt, ScaledValue( 4 ) );
end;
'`' :
begin
SetFont( 'Times New Roman', ScaledValue( 10 ), [] );
pt := TextStr( pt, '°');
end;
'K', 'P', 'U', 'I' :
begin
SetFont( 'Times New Roman', ScaledValue( 12 ), [ fsItalic ] );
IncPointX( pt, ScaledValue( 2 ) );
pt := TextStr( pt, p^ );
if p^ = '-' then
IncPointX( pt, ScaledValue( 1 ) );
end;
else
// '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
// 's', 'n', 'i', 'c', 'o', 's', ''''...
if p^ = '#' then
pt := DrawSqrt3( pt )
else
begin
SetFont( 'Times New Roman', ScaledValue( 12 ), [] );
pt := TextStr( pt, s );
end;
end;
end;
end;
until nPos = -1;
// SetMaxPos( Result, Point( pt.X, pt.Y + ScaledValue( 40 ) ) );
SetMaxPos( Result, Point( pt.X, pt.Y + ScaledValue( 35 ) ) );
end;
function TWE_VECTOR_EQUATION.DrawFontSize(ADefaultSize: Integer): Integer;
begin
Result := Round( ADefaultSize * FScaleRate );
if Result < C_FONT_SIZE_MIN then
Result := C_FONT_SIZE_MIN;
end;
function TWE_VECTOR_EQUATION.DrawFrac( APos: TPoint; AStr: string ): TPoint;
procedure SetMaxPos( var APosMax : TPoint; APos : TPoint );
begin
if APos.X > APosMax.X then
APosMax.X := APos.X;
if APos.Y > APosMax.Y then
APosMax.Y := APos.Y;
end;
var
s1, s2 : string;
pts1, pts2 : TPoint;
pt1, pt2 : TPoint;
rectOld, rectNew : TRect;
Bitmap : TBitmap;
n : Integer;
rectStore : TRect; // 用于存储
begin
Result := APos;
DivStr( AStr, '/', s1, s2 ); // 分割分子,分母
s2 := Copy( s2, 2, Length( s2 ) - 1 ); // 去掉 /
// 输出分子和分母
pts1 := Point( APos.X, APos.Y - ScaledValue( 20 ) );
pt1 := DrawText( pts1, s1 );
if Pos( '{', s2 ) > 0 then // 如果有分数,则下移,腾出空间
ptS2 := Point( APos.X, APos.Y + ScaledValue( 12 ) )
else
ptS2 := Point( APos.X, APos.Y + ScaledValue( 2 ) );
pt2 := DrawText( ptS2, s2 );
SetMaxPos( Result, pt1 );
SetMaxPos( Result, pt2 );
// 调整画图位置
if pt1.x <> pt2.x then
begin
if pt1.X < pt2.X then // 分子短,调整分子位置
begin
n := ( pt2.x - pt1.x ) div 2;
if Pos( '{', s1 ) > 0 then // 如果有分数,调整位置
begin
rectOld.TopLeft := Point( pts1.X, pts1.Y - ScaledValue( 8 ) );
rectNew.TopLeft := Point( pts1.X + n, pts1.Y - ScaledValue( 8 ) )
end
else
begin
rectOld.TopLeft := pts1;
rectNew.TopLeft := Point( pts1.X + n, pts1.Y );
end;
rectOld.BottomRight := Point( pt1.X, pt1.Y - ScaledValue( 15 ) );
rectNew.BottomRight := Point( pt1.X + n, pt1.Y - ScaledValue( 15 ));
end
else if pt1.X > pt2.X then // 调整分母
begin
n := ( pt1.X - pt2.X ) div 2;
if Pos( '{', s2 ) > 0 then
begin
rectOld.TopLeft := Point( pts2.X, pts2.Y - ScaledValue( 8 ) );
rectNew.TopLeft := Point( pts2.X + n, pts2.Y - ScaledValue( 8 ) )
end
else
begin
rectOld.TopLeft := pts2;
rectNew.TopLeft := Point( pts2.X + n, pts2.Y );
end;
rectOld.BottomRight := Point( pt2.X, pt2.Y - ScaledValue( 15 ) );
rectNew.BottomRight := Point( pt2.X + n, pt2.Y - ScaledValue( 15 ));
end;
rectStore.Top := rectOld.Top - rectOld.Top;
rectStore.Bottom := rectOld.Bottom - rectOld.Top;
rectStore.Left := rectOld.Left - rectOld.Left;
rectStore.Right := rectOld.Right - rectOld.Left;
with FCanvas do
begin
Bitmap := TBitmap.Create;
Bitmap.Width := rectStore.Right + 1;
Bitmap.Height := rectStore.Bottom + 1;
Bitmap.Canvas.CopyRect( rectStore, FCanvas, rectOld );
Brush.Style := bsSolid;
FillRect(rectOld);
Brush.Style := bsClear;
CopyRect( rectNew, Bitmap.Canvas, rectStore);
Bitmap.Free;
end;
end;
FCanvas.Polyline( [ Point( APos.X, APos.Y ), Point( Result.X, APos.Y ) ] );
end;
procedure TWE_VECTOR_EQUATION.IniCanvas(AColorBg, AColor: Integer);
begin
with FCanvas do
begin
Brush.Style := bsSolid;
if AColorBg = -1 then
Brush.Color := clWhite
else
Brush.Color := AColorBg;
Pen.Style := psSolid;
if AColor = -1 then
begin
Pen.Color := clBlack;
Font.Color := clBlack;
end
else
begin
Pen.Color := AColor;
Font.Color := AColor;
end;
FillRect( FRect );
end;
end;
function TWE_VECTOR_EQUATION.ScaledValue(n: Integer): Integer;
begin
Result := Round( n * FScaleRate );
end;
procedure TWE_VECTOR_EQUATION.SetRect(const Value: TRect);
begin
FRect := Value;
end;
procedure TWE_VECTOR_EQUATION.SetScaleRate(const Value: Double);
begin
FScaleRate := Value;
end;
function TWE_VECTOR_EQUATION.DrawText(ACanvas: TCanvas; APos: TPoint; AStr: string;
AFontColor, ABgColor: TColor; AScale: Double): TPoint;
begin
if Assigned( ACanvas ) and ( AStr <> '' ) then
begin
FCanvas := ACanvas;
FScaleRate := AScale;
FCanvas.Brush.Style := bsClear;
FCanvas.Brush.Color := ABgColor;
FCanvas.Font.Color := AFontColor;
FCanvas.Pen.Color := AFontColor;
FCanvas.Pen.Style := psSolid;
Result := DrawText( APos, AStr );
end
else
Result := APos;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ Copyright(c) 2012-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Datasnap.DSSession;
interface
uses
System.SysUtils, System.Classes, System.Generics.Collections, System.SyncObjs,
System.JSON, Data.DBXCommon, Data.DbxDataSnap, Data.DBXTransport,
Data.DBXMessageHandlerCommon,
{$IFDEF CLR}
DBXSocketChannelManaged,
{$ELSE}
Data.DbxSocketChannelNative,
{$ENDIF}
Datasnap.DSAuth, Datasnap.DSCommonServer, Datasnap.DSTransport,
Datasnap.DSCommon, Datasnap.DSService;
type
/// <summary>Record holding information that is mapped to a specific tunnel,
/// which is to be associated with a session.</summary>
TDSSessionTunnelInfo = record
/// <summary> The Channel Name associated with the tunnel. </summary>
ChannelName: string;
/// <summary> The ID of the tunnel, as specified by the client. </summary>
ClientChannelId: string;
/// <summary> Security token associated with the tunnel, for authorised modification. </summary>
SecurityToken: string;
/// <summary> The User associated with the tunnel. </summary>
AuthUser: string;
/// <summary> The password of the user associated with the tunnel. </summary>
AuthPassword: string;
end;
TDSSessionCacheKeys = TList<Integer>;
/// <summary>Implements a cache for holding commands with complex parameter
/// types, stored for later reuse.</summary>
TDSSessionCache = class
private
FItems : TDictionary<Integer, TResultCommandHandler>;
public
constructor Create;
destructor Destroy; override;
/// <summary> Trys to add the given item to the list of items managed by the cache. If successful
/// this will return the unique ID for the item in the cache. If not successful, -1 will be returned.
/// </summary>
function AddItem(Item: TResultCommandHandler): Integer;
/// <summary> Removes the given item from the list of managed items if found.
/// </summary>
/// <remarks> Does not claim ownership of the item. </remarks>
procedure RemoveItem(Item: TResultCommandHandler); overload;
/// <summary> Removes the item with the given ID from the list of managed items if found.
/// </summary>
/// <remarks> If InstanceOwner is set to false, the item will be returned if found, or nil if not found.
/// If InstanceOwner is true, nil will always be returned.
/// </remarks>
function RemoveItem(ID: Integer; InstanceOwner: Boolean = True): TResultCommandHandler; overload;
/// <summary> Returns the item with the given ID, or nil if not found.
/// </summary>
function GetItem(ID: Integer): TResultCommandHandler;
/// <summary> Returns the ID for the item, or -1 if not found
/// </summary>
function GetItemID(Item: TResultCommandHandler): Integer;
/// <summary> Returns a list of IDs currently helf by the cache </summary>
function GetItemIDs: TDSSessionCacheKeys;
/// <summary> Clears all of the items stred in this cache,
/// freeing them if InstanceOwner is True. (defaults to true)
/// </summary>
procedure ClearAllItems(InstanceOwner: Boolean = True);
end;
{$SCOPEDENUMS ON}
/// <summary>Represents the current value of the lifetime of the HTTP
/// session.</summary>
TDSSessionLifetime = (TimeOut, Request);
{$SCOPEDENUMS OFF}
/// <summary>Represents the type of the session status.</summary>
TDSSessionStatus = (Active, Closed, Idle, Terminated, Connected, Expired);
TDSSession = class;
TDSSessionData = class(TObject)
private
[weak] FDSSession: TDSSession;
procedure SetSession(const ASession: TDSSession);
public
constructor Create; virtual;
/// <summary> Returns true if the session holds data for the given key. </summary>
function HasData(const AKey: string): Boolean; virtual; abstract;
/// <summary> Retrieve a value string stored in this session for the given key </summary>
function GetData(const AKey: string): string; virtual; abstract;
/// <summary> Store a value string in this session with the given key </summary>
procedure PutData(const AKey, LValue: string); virtual; abstract;
/// <summary> Remove a value string from this session matching the given key </summary>
procedure RemoveData(const AKey: string); virtual; abstract;
/// <summary> Returns true if the session holds an Object for the given key. </summary>
function HasObject(const AKey: string): Boolean; virtual; abstract;
/// <summary> Retrieve a value Object stored in this session for the given key </summary>
function GetObject(const AKey: string): TObject; virtual; abstract;
/// <summary> Store an Object in this session with the given key </summary>
/// <remarks> Returns false is the object couldn't be inserted. (Invalid/in-use key) </remarks>
function PutObject(const AKey: string; AValue: TObject): Boolean; virtual; abstract;
/// <summary> Remove an Object from this session matching the given key </summary>
function RemoveObject(const AKey: string; AInstanceOwner: Boolean): TObject; virtual; abstract;
property Session: TDSSession read FDSSession;
end;
TDSSessionDictionaryData = class(TDSSessionData)
private
FMetaData: TDictionary<string,string>; /// map of metadata stored in the session
FMetaObjects: TDictionary<string,TObject>;
procedure CheckTransient;
public
constructor Create; override;
destructor Destroy; override;
function HasData(const AKey: string): Boolean; override;
function GetData(const AKey: string): string; override;
procedure PutData(const AKey, LValue: string); override;
procedure RemoveData(const AKey: string); override;
function HasObject(const AKey: string): Boolean; override;
function GetObject(const AKey: string): TObject; override;
function PutObject(const AKey: string; AValue: TObject): Boolean; override;
function RemoveObject(const AKey: string; AInstanceOwner: Boolean): TObject; override;
end;
TDSSession = class(TPersistent)
private
FSessionData: TDSSessionData;
FStartDateTime: TDateTime; /// creation timestamp
FDuration: Integer; /// in miliseconds, 0 for infinite (default)
FStatus: TDSSessionStatus; /// default idle
FLastActivity: Cardinal; /// timestamp of the last activity on this session
FUserName: string; /// user name that was authenticated with this session
FSessionName: string; /// session name, may be internally generated, exposed to 3rd party
FUserRoles: TStrings; /// user roles defined through authentication
FCache: TDSSessionCache;
FLastResultStream: TObject; /// Allow any object which owns a stream, or the stream itself, to be stored here
[weak] FCreator: TObject; /// Creator of the session object reference
FSessionLifetime: TDSSessionLifetime;
private
procedure SetSessionName(const sessionId: string);
procedure SetUserName(const userName: string);
procedure SetLifetime(Value: TDSSessionLifetime);
procedure CheckSessionData;
function CreateSessionData: TDSSessionData;
protected
/// <return> session internal id </return>
function GetId: NativeInt;
/// <summary> terminates the current session, normally triggered by a scheduler </summary>
procedure TerminateSession; virtual;
/// <summary> Terminates the session only if LifeDuration is less than than the
/// difference between the last active time and now.</summary>
procedure TerminateInactiveSession; virtual;
/// <summary>returns true if session did not have any activity for number of seconds specified</summary>
function IsIdle(Seconds: Cardinal): Boolean;
function IsIdleMS(Milliseconds: Cardinal): Boolean;
/// <summary> Returns the session status </summary>
/// <remarks> Sets the session to expired if it was not already terminated, and it has been idle for Duration.
/// </remarks>
function GetSessionStatus: TDSSessionStatus; virtual;
procedure GetAuthRoleInternal(ServerMethod: TDSServerMethod; AuthManager : TDSCustomAuthenticationManager;
out AuthorizedRoles, DeniedRoles: TStrings);
/// <summary> Raise an exception if this is a transient session</summary>
/// <remarks> Transient sessions have limitations. For example, transient sessions can't store data
/// </remarks>
procedure CheckTransient; virtual;
public
/// <summary>Creates an anonymous session</summary>
constructor Create; overload; virtual;
constructor Create(const SessionName: string); overload; virtual;
constructor Create(const SessionName: string; const AUser: string); overload; virtual;
destructor Destroy; override;
/// <summary> Marks session be active </summary>
procedure MarkActivity;
/// <summary> Schedules an event in elapsed time
/// </summary>
/// <param name="event">Event to be run after the time elapses</param>
/// <param name="elapsedTime">Elapsed time in miliseconds</param>
procedure ScheduleUserEvent(Event: TDBXScheduleEvent; ElapsedTime: Integer);
/// <summary> Schedule a session termination event at FCreateDateTime + FDuration
/// </summary>
procedure ScheduleTerminationEvent;
/// <summary> Similar to ScheduleTerminationEvent, but will be called continually each time the event
/// is executed until the session has been idle for longer than LifeDuration.
/// </summary>
procedure ScheduleInactiveTerminationEvent;
/// <summary> Cancel the last shceduled event </summary>
procedure CancelScheduledEvent;
/// <summary> Authenticate a connection from the given properties and any data stored in the Session. </summary>
/// <remarks> Subclasses of TDSSession should override this, to be useful, but also call into this base
/// implementation (ignoring the return value of this base implementation.)
/// </remarks>
function Authenticate(const AuthenticateEventObject: TDSAuthenticateEventObject; connectionProps: TDBXProperties): Boolean; overload; virtual;
/// <summary> Checks that the user of the current session has authorization for the given method. </summary>
function Authorize(EventObject: TDSAuthorizeEventObject): Boolean; overload; virtual;
/// <summary> Returns true if the given method requires authorization, false otherwise. </summary>
/// <remarks> For example 'DSMetadata.GetDatabase' is called when a SQLConnection to the server
/// is established, so checking for authorization would be redundant (and possibly falsly fail)
/// as the connection is already authenticated.
/// </remarks>
function RequiresAuthorization(MethodInfo: TDSMethodInfo): Boolean; virtual;
/// <summary> Get authorized and denied roles associated with server method </summary>
procedure GetAuthRoles(ServerMethod: TDSServerMethod; out AuthorizedRoles,
DeniedRoles: TStrings); virtual;
/// <summary> Convenience function which returns true if status is Active, Connected or Idle
/// </summary>
function IsValid: Boolean; virtual;
/// <summary>
/// Generates a unique session id
/// </summary>
/// <remarks>
/// No assumptions should be made about the id structure or content other
/// than unicity on the current process
/// </remarks>
/// <return>session id as a string</return>
class function GenerateSessionId: string; static;
/// <summary>
/// To be called when session ends. The communication channel is closed.
/// </summary>
procedure Close; virtual;
/// <summary> Terminates the session </summary>
/// <remarks> It is exceptionally used when a session needs to be terminated
/// due to the overall process state. All memory is released as session ends
/// normally. Calling terminate may induce abnormal termination of
/// dependent mid-tier apps</remarks>
procedure Terminate; virtual;
/// <summary> Returns true if the session holds data for the given key. </summary>
function HasData(Key: string): Boolean;
/// <summary> Retrieve a value string stored in this session for the given key </summary>
function GetData(Key: string): string;
/// <summary> Store a value string in this session with the given key </summary>
procedure PutData(Key, Value: string);
/// <summary> Remove a value string from this session matching the given key </summary>
procedure RemoveData(Key: string);
/// <summary> Returns true if the session holds an Object for the given key. </summary>
function HasObject(Key: string): Boolean;
/// <summary> Retrieve a value Object stored in this session for the given key </summary>
function GetObject(Key: string): TObject;
/// <summary> Store an Object in this session with the given key </summary>
/// <remarks> Returns false is the object couldn't be inserted. (Invalid/in-use key) </remarks>
function PutObject(Key: string; Value: TObject): Boolean;
/// <summary> Remove an Object from this session matching the given key </summary>
function RemoveObject(Key: string; InstanceOwner: Boolean = True): TObject;
/// <summary> Returns the miliseconds since last activity </summary>
function ElapsedSinceLastActvity: Cardinal;
/// <summary> Returns the miliseconds remaining before the session expires </summary>
function ExpiresIn: Cardinal;
/// <summary> session duration in miliseconds </summary>
property LifeDuration: Integer read FDuration write FDuration;
/// <summary> session id </summary>
property Id: NativeInt read GetId;
/// <summary> Session status </summary>
property Status: TDSSessionStatus read GetSessionStatus;
/// <summary> For scheduled managed sessions, has the scheduled time</summary>
property StartDateTime: TDateTime read FStartDateTime;
/// <summary>Session's user name, empty for anonymous</summary>
property UserName: string read FUserName;
/// <summary>Session name, immutable</summary>
property SessionName: string read FSessionName;
/// <summary>User roles set through authentication</summary>
property UserRoles: TStrings read FUserRoles;
/// <summary>Cache for storing and retrieving previously executed commands and their results.</summary>
/// <remarks>Optionally used in conjunction with REST when a command execution results
/// in multiple complex typed result objects. (Streams, Tables, Objects.)
/// </remarks>
property ParameterCache: TDSSessionCache read FCache;
/// <summary> Holds a reference to the last result stream sent to a client. </summary>
/// <remarks> Used for REST, when sending a result stream back to the client, as there is no
/// easy way to tie in with the response sent to the client to know whent he stream is no longer needed.
/// The object stored here is a TObject instead of a stream to handle the case where there is an object
/// wrapping the stream which needs to be freed with the stream.
/// </remarks>
property LastResultStream: TObject read FLastResultStream write FLastResultStream;
/// <summary>Exposes the creator object. It can be the server transport, http service, etc</summary>
/// <remarks>It is used usually to distinguish between sessions in a Close event, or to extract more
/// metadata about the session context
/// </remarks>
property ObjectCreator: TObject read FCreator write FCreator;
/// <summary>Lifetime of session </summary>
property SessionLifetime: TDSSessionLifetime read FSessionLifetime;
end;
/// <summary>Exception raised by TDSSession.</summary>
TDSSessionError = class(Exception)
end;
TDSAuthSession = class(TDSSession)
private
protected
FAuthManager : TDSCustomAuthenticationManager;
public
procedure GetAuthRoles(ServerMethod: TDSServerMethod; out AuthorizedRoles,
DeniedRoles: TStrings); override;
function Authorize(EventObject: TDSAuthorizeEventObject): Boolean; override;
/// <summary> The Authentication manager held by this session. Used for
/// user (role) Authorization.
/// </summary>
property AuthManager: TDSCustomAuthenticationManager read FAuthManager;
end;
/// <summary>Session class for the REST communication protocol that holds an
/// instance of an authentication manager.</summary>
TDSRESTSession = class(TDSAuthSession)
public
/// <summary> Creates an instance of a REST Session, passing in the
/// authentication manager to hold a reference to.
/// </summary>
constructor Create(AAuthManager: TDSCustomAuthenticationManager); virtual;
/// <summary> Extension of Authenticate to wrap the TCP authentication manager call
/// </summary>
function Authenticate(const AuthenticateEventObject: TDSAuthenticateEventObject; connectionProps: TDBXProperties): Boolean; override;
end;
/// <summary>Session class for the HTTP communication protocol, which acts
/// like a proxy for the socket channel with the DataSnap server.</summary>
TDSTunnelSession = class(TDSAuthSession)
private
/// <summary>
/// User pointer
/// </summary>
FUserPointer: Pointer;
/// <summary>
/// User flag
/// </summary>
FUserFlag: Integer;
protected
procedure TerminateSession; override;
public
constructor Create; reintroduce;
destructor Destroy; override;
/// <summary>
/// To be called when the session starts. The communication channel is
/// being setup at thie moment.
/// </summary>
procedure Open; virtual; abstract;
/// <summary>
/// Reopens the socket channel toward a different location. All required parameters
/// are expected to be present in the argument
/// </summary>
/// <param name="DBXDatasnapProperties">connection properties</param>
procedure Reopen(DBXDatasnapProperties: TDBXDatasnapProperties); virtual;
/// <summary> Reads bytes from communication layer. </summary>
/// <remarks>If none are avaiable yet the call may be blocking. </remarks>
/// <param name="Buffer">Byte array buffer with capacity to store data</param>
/// <param name="Offset">Byte array index from where the read bytes are stored</param>
/// <param name="Count">Expected number of bytes to be read. It is assumed there
/// is enough capacity in the buffer area for them</param>
/// <return>Actual number of bytes being read, -1 on error</return>
function Read(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer; virtual; abstract;
/// <summary> Sends bytes into the communication layer. </summary>
/// <remarks> The operation may be blocking until data is consumed by the mid-tier. </remarks>
/// <param name="Buffer">Byte array buffer with data to be written</param>
/// <param name="Offset">Index from the bytes are written</param>
/// <param name="Count">Number of bytes to be written. It is expected that
/// the buffer has enough capacity to match the parameter</param>
/// <return>Actual number of bytes being written</return>
function Write(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer; virtual; abstract;
property UserPointer: Pointer read FUserPointer write FUserPointer;
property UserFlag: Integer read FUserFlag write FUserFlag;
end;
/// <summary>Manages the HTTP session for a remote DataSnap
/// instance.</summary>
TDSRemoteSession = class(TDSTunnelSession)
private
/// <summary>
/// Communication channel with the actual resources
/// </summary>
FSocketChannel: TDBXSocketChannel;
public
constructor Create(DBXDatasnapProperties: TDBXDatasnapProperties);
destructor Destroy; override;
procedure Open; override;
procedure Reopen(DBXDatasnapProperties: TDBXDatasnapProperties); override;
procedure Close; override;
procedure Terminate; override;
function Read(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer; override;
function Write(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer; override;
/// <summary> Extension of Authenticate to wrap the TCP authentication manager call
/// </summary>
function Authenticate(const AuthenticateEventObject: TDSAuthenticateEventObject; connectionProps: TDBXProperties): Boolean; override;
property SocketChannel: TDBXSocketChannel read FSocketChannel write FSocketChannel;
end;
/// <summary>Type of user events.</summary>
TDSSessionEventType = (SessionCreate, SessionClose);
/// <summary>User event for notification of session events, such as Create and
/// Terminate.</summary>
TDSSessionEvent = reference to procedure(Sender: TObject;
const EventType: TDSSessionEventType;
const Session: TDSSession);
TDSSessionVisitor = reference to procedure(const Session: TDSSession);
/// <summary>Implements a singleton that will manage the session
/// objects.</summary>
TDSSessionManager = class
type
TFactoryMethod = reference to function: TDSSession;
strict private
FSessionContainer: TDictionary<string, TDSSession>;
FListeners: TList<TDSSessionEvent>;
private
class var
FInstance: TDSSessionManager;
/// <summary> Returns the session object based on its id
/// </summary>
/// <param name="SessionId">session identifier</param>
/// <return>a session object, nil if not found</return>
function GetSession(SessionId: string): TDSSession;
/// <summary> Returns the tunnel session object based on its id
/// </summary>
/// <param name="SessionId">session identifier</param>
/// <return>tunnel session object, nil if not found or is not a tunnel session</return>
function GetTunnelSession(SessionId: string): TDSTunnelSession;
function GetUniqueSessionId: string;
procedure TerminateSession(session: TDSSession); overload;
procedure CloseSession(session: TDSSession); overload;
/// <summary> Internal function for notifying the registered events
/// </summary>
procedure NotifyEvents(session: TDSSession; EventType: TDSSessionEventType);
procedure TerminateAllSessions(const ACreator: TObject;
AAllSessions: Boolean); overload;
public
constructor Create;
destructor Destroy; override;
function CreateSession<T: TDSSession>(factory: TFactoryMethod;
ASessionLifetime: TDSSessionLifetime; DoNotify: Boolean = True): T; overload;
function CreateSession<T: TDSSession>(factory: TFactoryMethod; userName: string): T; overload;
function CreateSession<T: TDSSession>(factory: TFactoryMethod; userName: string; ASessionLifetime: TDSSessionLifetime): T; overload;
function CreateSession<T: TDSSession>(factory: TFactoryMethod; DoNotify: Boolean = True): T; overload;
/// <summary> Add the given session event to the list of events which gets
/// executed when a change occurrs with a session through this manager.
/// </summary>
procedure AddSessionEvent(Event: TDSSessionEvent);
/// <summary> Remove the given session event to the list of events which gets
/// executed when a change occurrs with a session through this manager.
/// </summary>
/// <returns> true if successfully removed, false otherwise. </returns>
function RemoveSessionEvent(Event: TDSSessionEvent): Boolean;
/// <summary>Closes the session identified by argument
/// </summary>
/// <remarks> The session object is freed, no further access to it is expected
/// </remarks>
/// <param name="SessionId">session identifier</param>
procedure CloseSession(SessionId: string); overload;
/// <summary> Terminates all registered sessions for a given owner. Usually when the owner is taken
/// offline or being closed.
/// </summary>
procedure TerminateAllSessions(const ACreator: TObject); overload;
/// <summary> Terminates all registered sessions. Usually when the the server is stopped.
/// </summary>
procedure TerminateAllSessions; overload;
/// <summary> Iterates over all sessions and invokes the TDSSessionVisitor for each.
/// </summary>
procedure ForEachSession(AVisitor: TDSSessionVisitor);
/// <summary> Removes the session from session container and invokes session's Teminate method
/// </summary>
/// <remarks> Further session access will not be possible
/// </remarks>
/// <param name="SessionId">session unique name</param>
procedure TerminateSession(const sessionId: string); overload;
/// <summary> Returns number of open sessions
/// </summary>
/// <returns>number of open session</returns>
function GetSessionCount: Integer;
/// <summary>Removes the session from session container
/// </summary>
/// <param name="SessionId">session identifier</param>
function RemoveSession(SessionId: string): TDSSession;
/// <summary> Adds all open session keys to parameter container
/// </summary>
/// <param name="Container">string list</param>
procedure GetOpenSessionKeys(Container: TStrings); overload;
procedure GetOpenSessionKeys(Container: TStrings; ACreator: TObject); overload;
/// <summary> Returns the Session for the current thread.
/// </summary>
class function GetThreadSession: TDSSession;
/// <summary> Sets the given session as the session for the thread calling this function.
/// </summary>
class procedure SetAsThreadSession(Session: TDSSession);
/// <summary> Removes any session set to be the session for the current thread
/// </summary>
class procedure ClearThreadSession;
property Session[id: string]: TDSSession read GetSession;
property TunnelSession[id: string]: TDSTunnelSession read GetTunnelSession;
class property Instance: TDSSessionManager read FInstance;
end;
/// <summary>Synchronizes the local channel.</summary>
TDSSynchronizedLocalChannel = class(TDBXLocalChannel)
private
FReadSemaphore: TSemaphore;
FLocalReadSemaphore: TSemaphore;
FWriteSemaphore: TSemaphore;
FLocalWriteSemaphore: TSemaphore;
FTerminated: Boolean;
public
constructor Create(const ServerName: string);
destructor Destroy; override;
function Read(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer; override;
function WriteLocalData(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer; override;
function Write(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer; override;
function ReadLocalData(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer; override;
procedure Terminate;
end;
/// <summary>Consumes the remote byte stream produced by a remote source. The
/// remote source is proxied by a local session instance passed to the
/// constructor.</summary>
TDSLocalServer = class(TThread)
private
FErrorMsg: string;
[weak] FLocalChannel: TDBXLocalChannel;
FDBXProtocolHandler: TDBXProtocolHandler;
[weak] FSession: TDSSession;
protected
procedure Execute; override;
/// <summary> Processes the byte stream as it comes along
/// </summary>
/// <remarks> The tunnel session is synchronizing the read/write semaphores
/// </remarks>
procedure ConsumeByteStream;
public
constructor Create(ALocalChannel: TDBXLocalChannel; AProtocolHandlerFactory: TDSJSONProtocolHandlerFactory;
AFilters: TTransportFilterCollection; Session: TDSSession);
destructor Destroy; override;
/// <summary> Returns true if the local server protocol failed at some point</summary>
/// <remarks>Error management is passive due to multi-threaded environment. It
/// is the responsability of the user thread to use this flag appropriately.
/// The error message can be acquired using ErrorMsg property.
/// </remarks>
/// <returns>true if the communication protocol exprienced an error</returns>
function HasError: Boolean;
/// <summary>Error message when HasError function returns true</summary>
property ErrorMsg: string read FErrorMsg;
end;
/// <summary>Manages the HTTP session for a local DataSnap instance.</summary>
TDSLocalSession = class(TDSTunnelSession)
private
FFilters: TTransportFilterCollection;
FProtocolHandlerFactory: TDSJSONProtocolHandlerFactory;
FLocalChannel: TDSSynchronizedLocalChannel;
FDSLocalServer: TDSLocalServer;
public
constructor Create(AFilters: TTransportFilterCollection; AProtocolHandlerFactory: TDSJSONProtocolHandlerFactory);
destructor Destroy; override;
procedure Open; override;
procedure Close; override;
procedure Terminate; override;
/// <summary> Extension of Authenticate to wrap the TCP authentication manager call
/// </summary>
function Authenticate(const AuthenticateEventObject: TDSAuthenticateEventObject; connectionProps: TDBXProperties): Boolean; override;
function Read(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer; override;
function Write(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer; override;
end;
TTunnelSessionEvent = procedure(Sender: TObject; Session: TDSTunnelSession; Content: TArray<Byte>;
var Count: Integer) of object;
/// <summary>Implements the HTTP tunneling logic.</summary>
TDSTunnelService = class
strict private
FFilters: TTransportFilterCollection;
FProtocolHandlerFactory: TDSJSONProtocolHandlerFactory;
FDSHostname: string;
FDSPort: Integer;
FHasLocalServer: Boolean;
private
FDBXProperties: TDBXDatasnapProperties;
FOnOpenSession: TTunnelSessionEvent;
FOnErrorOpenSession: TTunnelSessionEvent;
FOnCloseSession: TTunnelSessionEvent;
FOnWriteSession: TTunnelSessionEvent;
FOnReadSession: TTunnelSessionEvent;
FOnErrorWriteSession: TTunnelSessionEvent;
FOnErrorReadSession: TTunnelSessionEvent;
FDSAuthenticationManager: TDSCustomAuthenticationManager;
protected
/// <summary> True if the current session id signals the session closure
/// </summary>
/// <return>true if current session should be closed</return>
class function CanCloseSession(var id: string): Boolean;
/// <summary> Creates a tunnel session based on the tunnel creation parameters
/// </summary>
/// <param name="Session">output tunnel session object</param>
/// <param name="RemoteIP">The connecting client's IP address</param>
procedure CreateSession(out Session: TDSTunnelSession; RemoteIP: string = ''); overload;
/// <summary> Creates a tunnel session based on the tunnel creation parameters
/// </summary>
/// <param name="Session">output tunnel session object</param>
/// <param name="ClientInfo">Info about the connecting client</param>
procedure CreateSession(out Session: TDSTunnelSession; ClientInfo: TDBXClientInfo); overload;
function GetSession(const SessionId: string): TDSTunnelSession;
/// <summary>Default implementation of the OpenSession event</summary>
/// <remarks>Event is triggered each time a session is opened successfully.
/// Default implementation delegates to OnOpenSession property if set</remarks>
/// <param name="Sender">Event sender</param>
/// <param name="Session">Tunnel session instance that manages current comunication</param>
/// <param name="Content">Bytes content</param>
/// <param name="Count">Byte content size (in bytes)</param>
procedure DefaultOpenSessionEvent(Sender: TObject; Session: TDSTunnelSession;
Content: TArray<Byte>; var Count: Integer);
/// <summary>Default implementation of the ErrorOpenSession event</summary>
/// <remarks>Event is triggered when a session cannot be opened. Default implementation
/// delegates to OnOpenSessionError property if set, otherwise re-throws the
/// exception.</remarks>
/// <param name="Sender">Event sender</param>
/// <param name="Session">Tunnel session instance that manages current comunication</param>
/// <param name="Content">Bytes content</param>
/// <param name="Count">Byte content size (in bytes)</param>
procedure DefaultErrorOpenSessionEvent(Sender: TObject; Session: TDSTunnelSession;
Content: TArray<Byte>; var Count: Integer);
/// <summary>Default implementation of the CloseSession event</summary>
/// <remarks>Event is triggered each time a session is closed successfully.
/// Default implementation delegates to OnCloseSession property if set</remarks>
/// <param name="Sender">Event sender</param>
/// <param name="Session">Tunnel session instance that manages current comunication</param>
/// <param name="Content">Bytes content</param>
/// <param name="Count">Byte content size (in bytes)</param>
procedure DefaultCloseSessionEvent(Sender: TObject; Session: TDSTunnelSession;
Content: TArray<Byte>; var Count: Integer);
/// <summary>Default implementation of the WriteSession event</summary>
/// <remarks>Event is triggered each time a session performs a write operation successfully.
/// Default implementation delegates to OnWriteSession property if set</remarks>
/// <param name="Sender">Event sender</param>
/// <param name="Session">Tunnel session instance that manages current comunication</param>
/// <param name="Content">Bytes content</param>
/// <param name="Count">Byte content size (in bytes)</param>
procedure DefaultWriteSessionEvent(Sender: TObject; Session: TDSTunnelSession;
Content: TArray<Byte>; var Count: Integer);
/// <summary>Default implementation of the ReadSession event</summary>
/// <remarks>Event is triggered each time a session performs a read operation successfully.
/// Default implementation delegates to OnReadSession property if set</remarks>
/// <param name="Sender">Event sender</param>
/// <param name="Session">Tunnel session instance that manages current comunication</param>
/// <param name="Content">Bytes content</param>
/// <param name="Count">Byte content size (in bytes)</param>
procedure DefaultReadSessionEvent(Sender: TObject; Session: TDSTunnelSession;
Content: TArray<Byte>; var Count: Integer);
/// <summary>Default implementation of the ErrorWriteSession event</summary>
/// <remarks>Event is triggered each time a session fails to write data.
/// Default implementation delegates to OnErrorWriteSession property if set, otherwise it
/// rethrows the exception.
/// </remarks>
/// <param name="Sender">Event sender</param>
/// <param name="Session">Tunnel session instance that manages current comunication</param>
/// <param name="Content">Bytes content</param>
/// <param name="Count">Byte content size (in bytes)</param>
procedure DefaultErrorWriteSessionEvent(Sender: TObject; Session: TDSTunnelSession;
Content: TArray<Byte>; var Count: Integer);
/// <summary>Default implementation of the ErrorReadSession event</summary>
/// <remarks>Event is triggered each time a session fails to write data.
/// Default implementation delegates to OnErrorReadSession property if set, otherwise it
/// rethrows the exception.
/// </remarks>
/// <param name="Sender">Event sender</param>
/// <param name="Session">Tunnel session instance that manages current comunication</param>
/// <param name="Content">Bytes content</param>
/// <param name="Count">Byte content size (in bytes)</param>
procedure DefaultErrorReadSessionEvent(Sender: TObject; Session: TDSTunnelSession;
Content: TArray<Byte>; var Count: Integer);
procedure SetDSHostname(AHostname: string);
procedure SetDSPort(APort: Integer);
public
/// <summary> Constructor with hostname and port to write and read the byte stream
/// </summary>
/// <param name="DSHostname">datasnap server machine</param>
/// <param name="DSPort">datasnap server port it listens to</param>
/// <param name="AFilters">the filters collection</param>
/// <param name="AProtocolHandlerFactory">the protocol handler factory</param>
constructor Create(DSHostname: string; DSPort: Integer; AFilters: TTransportFilterCollection;
AProtocolHandlerFactory: TDSJSONProtocolHandlerFactory); virtual;
destructor Destroy; override;
/// <summary>Pass through of user credentials</summary>
/// <param name="userName">user name</param>
/// <param name="userPass">user password</param>
procedure AddUserCredentials(const userName: string; const userPass: string);
/// <summary> Terminates all registered sessions. Usually when the server is taken
/// offline or being closed.
/// </summary>
procedure TerminateAllSessions;
/// <summary> Terminates session with session id among the input parameters
/// </summary>
/// <remarks> Further session access will not be possible
/// </remarks>
/// <param name="Params">Parameter collection</param>
class procedure TerminateSession(const Params: TStrings); overload;
/// <summary> Returns number of open sessions
/// </summary>
/// <returns>number of open session</returns>
function GetSessionCount: Integer;
/// <summary>Closes the session identified by argument
/// </summary>
/// <remarks> The session object is freed, no further access to it is expected
/// </remarks>
/// <param name="SessionId">session identifier</param>
procedure CloseSession(SessionId: string); overload;
/// <summary> Adds all open session keys to parameter container
/// </summary>
/// <param name="Container">string list</param>
procedure GetOpenSessionKeys(Container: TStrings);
/// <summary>
/// Initializes the session pointed to by the specified parameter value for 'dss'
/// If the value of the 'dss' parameter is 0, then a new session will be created and the
/// value for dss in the given params will be replaced.
/// </summary>
function InitializeSession(Params: TStrings; RemoteIP: string = ''): TDSTunnelSession; overload;
function InitializeSession(Params: TStrings; ClientInfo: TDBXClientInfo): TDSTunnelSession; overload;
/// <summary>
/// Handles the POST requests. They are assimilated to write operations.
/// The response consists in the session id and the actual amount of bytes
/// successfully delivered to the destination.
/// </summary>
/// <param name="Params">HTTP parameters (name=value) that provide the session id
/// (dss) and eventually the content size (c). The content is expected to be available
/// in the byte stream. A session id zero (0) is equivalent to a new session.
/// The code will generate a new session id that will be returned as content
/// in the JSON object.
/// </param>
/// <param name="Content">Byte content to be forwarded to the session's communication channel</param>
/// <param name="JsonResponse">Output parameters with the session id and actual data write size.
/// <param name="CloseConnection">true if server has to signal client to close the connection</param>
/// Upon success the response is: {"response":[[sessionId],[count]]
/// </param>
procedure ProcessPOST(Params: TStrings; Content: TArray<Byte>; out JsonResponse: TJSONValue; out CloseConnection: Boolean);
/// <summary>
/// Handles the GET requests. They are assimilated to the read operations. The
/// response is returned as a byte stream.
/// </summary>
/// <param name="Params">Request parameters with session id (dss) and expected byte
/// count to be read (c).
/// </param>
/// <param name="Len">Actual number of bytes read</param>
/// <param name="CloseConnection">true if server has to signal client to close the connection</param>
/// <return>byte stream</return>
function ProcessGET(Params: TStrings; var Len: Integer; out CloseConnection: Boolean): TStream;
/// <summary> Returns true if the request parameters provide user name and paasword
/// </summary>
/// <returns>true if the request needs authentication</returns>
function NeedsAuthentication(Params: TStrings): Boolean;
/// <summary>Remote host name where the DataSnap Server will process the requests
/// </summary>
property DSHostname: string read FDSHostname write SetDSHostname;
/// <summary>Remote DataSnap port that processes the requests</summary>
property DSPort: Integer read FDSPort write SetDSPort;
/// <summary>True if the DataSnap process is in process.</summary>
/// <remarks>In process servers have precedence over the remote ones. Hence, if
/// property is true DSHostname and DSPort will be ignored.
/// </remarks>
property HasLocalServer: Boolean read FHasLocalServer write FHasLocalServer;
/// <summary>Communication filters such as compression or encryption</summary>
property Filters: TTransportFilterCollection read FFilters write FFilters;
/// <summary>Factory that will provide the protocol handler</summary>
property ProtocolHandlerFactory: TDSJSONProtocolHandlerFactory read FProtocolHandlerFactory
write FProtocolHandlerFactory;
/// <summary>
/// Event invoked after the tunnel session was open
/// </summary>
property OnOpenSession: TTunnelSessionEvent read FOnOpenSession write FOnOpenSession;
/// <summary>
/// Event invoked if a session cannot open
/// </summary>
property OnErrorOpenSession: TTunnelSessionEvent read FOnErrorOpenSession write FOnErrorOpenSession;
/// <summary> Event invoked before the session is closed
/// </summary>
property OnCloseSession: TTunnelSessionEvent read FOnCloseSession write FOnCloseSession;
/// <summary> Event invoked after the data has been written into the tunnel channel
/// </summary>
property OnWriteSession: TTunnelSessionEvent read FOnWriteSession write FOnWriteSession;
/// <summary> Event invoked after the data has been read from the tunnel channel
/// </summary>
property OnReadSession: TTunnelSessionEvent read FOnReadSession write FOnReadSession;
/// <summary> Event invoked if channel write failed because of connection error
/// </summary>
property OnErrorWriteSession: TTunnelSessionEvent read FOnErrorWriteSession write FOnErrorWriteSession;
/// <summary> Event invoked if channel read failed because of connection error or timeout
/// </summary>
property OnErrorReadSession: TTunnelSessionEvent read FOnErrorReadSession write FOnErrorReadSession;
/// <summary> Returns number of open sessions
/// </summary>
property SessionCount: Integer read GetSessionCount;
/// <summary> The Authentication manager for use with this tunnel service
/// </summary>
property DSAuthenticationManager: TDSCustomAuthenticationManager read FDSAuthenticationManager
write FDSAuthenticationManager;
end;
/// <summary>Represents the session class for the TCP communication
/// protocol.</summary>
TDSTCPSession = class(TDSAuthSession)
public
/// <summary> Creates an instance of a TCP Session, passing in the
/// authentication manager to hold a reference to.
/// </summary>
constructor Create(AAuthManager: TDSCustomAuthenticationManager); overload; virtual;
constructor Create(AAuthManager: TObject); overload; virtual;
/// <summary> Extension of Authenticate to wrap the TCP authentication manager call
/// </summary>
function Authenticate(const AuthenticateEventObject: TDSAuthenticateEventObject; connectionProps: TDBXProperties): Boolean; override;
end;
implementation
uses
{$IFNDEF POSIX}
Winapi.ActiveX,
System.Win.ComObj,
Winapi.Windows,
{$ELSE}
{$IFNDEF LINUX64}
Macapi.CoreServices,
{$ENDIF}
{$ENDIF}
Data.DBXPlatform,
Data.DBXClientResStrs,
DataSnap.DSServerResStrs,
Data.DBXTransportFilter;
ThreadVar
[unsafe] VDSSession: TDSSession; {Session for the current thread}
const
QP_DSS = 'dss';
QP_COUNT = 'c';
DRIVER_NAME = 'Datasnap';
type
TAnonymousBlock = reference to procedure;
procedure Synchronized(monitor: TObject; proc: TAnonymousBlock);
begin
TMonitor.Enter(monitor);
try
proc;
finally
TMonitor.Exit(monitor);
end;
end;
{TDSTunnelSession}
constructor TDSTunnelSession.Create;
begin
inherited;
FUserFlag := 0;
FUserPointer := nil;
end;
destructor TDSTunnelSession.Destroy;
begin
inherited;
end;
procedure TDSTunnelSession.Reopen(DBXDatasnapProperties: TDBXDatasnapProperties);
begin
// do nothing
end;
procedure TDSTunnelSession.TerminateSession;
begin
inherited;
end;
{TDSRemoteSession}
constructor TDSRemoteSession.Create(DBXDatasnapProperties: TDBXDatasnapProperties);
begin
inherited Create;
FSocketChannel := TDBXSocketChannel.Create;
FSocketChannel.DBXProperties := DBXDatasnapProperties;
end;
destructor TDSRemoteSession.Destroy;
begin
FreeAndNil(FSocketChannel);
inherited;
end;
procedure TDSRemoteSession.Open;
begin
FSocketChannel.Open;
FStatus := Connected;
end;
procedure TDSRemoteSession.Reopen(DBXDatasnapProperties: TDBXDatasnapProperties);
begin
try
Close;
finally
FreeAndNil(FSocketChannel);
end;
FSocketChannel := TDBXSocketChannel.Create;
FSocketChannel.DBXProperties := DBXDatasnapProperties;
Open;
end;
function TDSRemoteSession.Authenticate(
const AuthenticateEventObject: TDSAuthenticateEventObject;
connectionProps: TDBXProperties): Boolean;
begin
inherited;
{Authentication will be done elsewhere for HTTP}
exit(True);
end;
procedure TDSRemoteSession.Close;
begin
inherited;
FSocketChannel.Close;
end;
procedure TDSRemoteSession.Terminate;
begin
inherited;
FSocketChannel.Terminate;
end;
function TDSRemoteSession.Read(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer;
begin
Result := FSocketChannel.Read(Buffer, Offset, Count);
end;
function TDSRemoteSession.Write(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer;
begin
Result := FSocketChannel.Write(Buffer, Offset, Count);
end;
{TDSSynchronizedLocalChannel}
constructor TDSSynchronizedLocalChannel.Create(const ServerName: string);
begin
inherited Create(ServerName);
FReadSemaphore := TSemaphore.Create(nil, 0, MaxInt, '');
FLocalReadSemaphore := TSemaphore.Create(nil, 1, MaxInt, '');
FWriteSemaphore := TSemaphore.Create(nil, 0, MaxInt, '');
FLocalWriteSemaphore := TSemaphore.Create(nil, 1, MaxInt, '');
FTerminated := false;
end;
destructor TDSSynchronizedLocalChannel.Destroy;
begin
FreeAndNil(FReadSemaphore);
FreeAndNil(FWriteSemaphore);
FreeAndNil(FLocalReadSemaphore);
FreeAndNil(FLocalWriteSemaphore);
inherited;
end;
procedure TDSSynchronizedLocalChannel.Terminate;
begin
FTerminated := true;
FLocalWriteSemaphore.Release;
FLocalReadSemaphore.Release;
FWriteSemaphore.Release;
FReadSemaphore.Release;
end;
function TDSSynchronizedLocalChannel.Read(const Buffer: TArray<Byte>; const Offset: Integer;
const Count: Integer): Integer;
var
status: TWaitResult;
begin
status := FReadSemaphore.WaitFor(INFINITE);
if status = wrError then
Raise TDBXError.Create(0, Format(SWaitFailure, ['Read']));
if status = wrTimeout then
Raise TDBXError.Create(0, Format(SWaitTimeout, ['Read']));
if FTerminated then
Raise TDBXError.Create(0, SWaitTerminated);
Result := inherited Read(Buffer, Offset, Count);
// if all written data was consumed allow subsequent write local data
if not HasWriteData then
FLocalWriteSemaphore.Release
else
FReadSemaphore.Release;
end;
function TDSSynchronizedLocalChannel.WriteLocalData(const Buffer: TArray<Byte>; const Offset: Integer;
const Count: Integer): Integer;
var
status: TWaitResult;
begin
if FTerminated then
Raise TDBXError.Create(0, SWaitTerminated);
status := FLocalWriteSemaphore.WaitFor(INFINITE);
if status = wrError then
Raise TDBXError.Create(0, Format(SWaitFailure, ['WriteLocalData']));
if status = wrTimeout then
Raise TDBXError.Create(0, Format(SWaitTimeout, ['WriteLocalData']));
if FTerminated then
Raise TDBXError.Create(0, SWaitTerminated);
Result := inherited WriteLocalData(Buffer, Offset, Count);
FReadSemaphore.Release;
end;
function TDSSynchronizedLocalChannel.Write(const Buffer: TArray<Byte>; const Offset: Integer;
const Count: Integer): Integer;
var
status: TWaitResult;
begin
status := FLocalReadSemaphore.WaitFor(INFINITE);
if status = wrError then
Raise TDBXError.Create(0, Format(SWaitFailure, ['Write']));
if status = wrTimeout then
Raise TDBXError.Create(0, Format(SWaitTimeout, ['Write']));
if FTerminated then
Raise TDBXError.Create(0, SWaitTerminated);
Result := inherited Write(Buffer, Offset, Count);
FWriteSemaphore.Release;
end;
function TDSSynchronizedLocalChannel.ReadLocalData(const Buffer: TArray<Byte>; const Offset: Integer;
const Count: Integer): Integer;
var
status: TWaitResult;
begin
if FTerminated then
Raise TDBXError.Create(0, SWaitTerminated);
status := FWriteSemaphore.WaitFor(INFINITE);
if status = wrError then
Raise TDBXError.Create(0, Format(SWaitFailure, ['ReadLocalData']));
if status = wrTimeout then
Raise TDBXError.Create(0, Format(SWaitTimeout, ['ReadLocalData']));
if FTerminated then
Raise TDBXError.Create(0, SWaitTerminated);
Result := inherited ReadLocalData(Buffer, Offset, Count);
if not HasReadData then
FLocalReadSemaphore.Release
else
FWriteSemaphore.Release;
end;
{TDSLocalSession}
constructor TDSLocalSession.Create(AFilters: TTransportFilterCollection; AProtocolHandlerFactory: TDSJSONProtocolHandlerFactory);
begin
inherited Create;
FFilters := AFilters;
FProtocolHandlerFactory := AProtocolHandlerFactory;
end;
destructor TDSLocalSession.Destroy;
begin
FFilters := nil; // no ownership
FProtocolHandlerFactory := nil; // no ownership
if not FDSLocalServer.Terminated then
FDSLocalServer.Terminate;
FreeAndNil(FDSLocalServer);
inherited
end;
procedure TDSLocalSession.Open;
var
RemoteIP: string;
ClientInfo: TDBXClientInfo;
begin
RemoteIP := GetData('RemoteIP');
if RemoteIP = EmptyStr then
RemoteIP := 'local';
FLocalChannel := TDSSynchronizedLocalChannel.Create(RemoteIP);
ClientInfo.IpAddress := RemoteIP;
ClientInfo.Protocol := GetData('CommunicationProtocol');
ClientInfo.AppName := GetData('RemoteAppName');
FLocalChannel.ChannelInfo.ClientInfo := ClientInfo;
// start DS local
FDSLocalServer := TDSLocalServer.Create(FLocalChannel, FProtocolHandlerFactory, FFilters, Self);
FStatus := Connected;
end;
function TDSLocalSession.Authenticate(
const AuthenticateEventObject: TDSAuthenticateEventObject;
connectionProps: TDBXProperties): Boolean;
begin
inherited;
if FAuthManager <> nil then
exit(FAuthManager.Authenticate(AuthenticateEventObject, connectionProps));
exit(True);
end;
procedure TDSLocalSession.Close;
begin
// stop the DS local
FStatus := Closed;
FLocalChannel.Terminate;
FDSLocalServer.Terminate;
if not FDSLocalServer.Finished then
FDSLocalServer.WaitFor;
end;
procedure TDSLocalSession.Terminate;
begin
Close;
end;
function TDSLocalSession.Read(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer;
begin
Result := FLocalChannel.ReadLocalData(Buffer, Offset, Count);
if (FStatus = Connected) and FDSLocalServer.HasError then
Raise TDBXError.Create(0, FDSLocalServer.ErrorMsg);
end;
function TDSLocalSession.Write(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer;
begin
Result := FLocalChannel.WriteLocalData(Buffer, Offset, Count);
if (FStatus = Connected) and FDSLocalServer.HasError then
Raise TDBXError.Create(0, FDSLocalServer.ErrorMsg);
end;
{TDSLocalServer}
constructor TDSLocalServer.Create(ALocalChannel: TDBXLocalChannel; AProtocolHandlerFactory: TDSJSONProtocolHandlerFactory;
AFilters: TTransportFilterCollection; Session: TDSSession);
var
FilterChannel: TDBXFilterSocketChannel;
begin
inherited Create(false);
FSession := Session;
FLocalChannel := ALocalChannel;
FilterChannel := TDBXFilterSocketChannel.Create(AFilters);
FilterChannel.Channel := FLocalChannel;
FDBXProtocolHandler := AProtocolHandlerFactory.CreateProtocolHandler(FilterChannel);
end;
destructor TDSLocalServer.Destroy;
begin
FreeAndNil( FDBXProtocolHandler );
FLocalChannel := nil; // soft reference
inherited Destroy;
end;
procedure TDSLocalServer.ConsumeByteStream;
begin
try
FDBXProtocolHandler.HandleProtocol;
except
on ex: Exception do
if not Terminated then
begin
FErrorMsg := ex.Message;
Terminate;
end;
end;
end;
procedure TDSLocalServer.Execute;
begin
{$IFNDEF POSIX}
if CoInitFlags = -1 then
CoInitializeEx(nil, COINIT_MULTITHREADED)
else
CoInitializeEx(nil, CoInitFlags);
{$ENDIF}
try
if FSession <> nil then
TDSSessionManager.SetAsThreadSession(FSession);
ConsumeByteStream;
finally
{$IFNDEF POSIX}
CoUninitialize;
{$ENDIF}
end
end;
function TDSLocalServer.HasError: Boolean;
begin
Result := FErrorMsg <> EmptyStr;
end;
{TDSTunnelService}
constructor TDSTunnelService.Create(DSHostname: string; DSPort: Integer; AFilters: TTransportFilterCollection;
AProtocolHandlerFactory: TDSJSONProtocolHandlerFactory );
begin
FDSHostname := DSHostname;
FDSPort := DSPort;
FFilters := AFilters;
FProtocolHandlerFactory := AProtocolHandlerFactory;
FDBXProperties := TDBXDatasnapProperties.Create(nil);
FDBXProperties.Values[ TDBXPropertyNames.DriverName ] := DRIVER_NAME;
FDBXProperties.Values[ TDBXPropertyNames.HostName ] := FDSHostname;
FDBXProperties.Values[ TDBXPropertyNames.Port ] := IntToStr( FDSPort );
end;
destructor TDSTunnelService.Destroy;
begin
FreeAndNil(FDBXProperties);
FFilters := nil; // no ownership
FProtocolHandlerFactory := nil; // no ownership
inherited;
end;
procedure TDSTunnelService.AddUserCredentials(const userName, userPass: string);
begin
FDBXProperties.DSAuthUser := userName;
FDBXProperties.DSAuthPassword := userPass;
end;
class function TDSTunnelService.CanCloseSession(var id: string): Boolean;
begin
Result := id.StartsWith('-');
if Result then
id := id.Remove(0, 1);
end;
procedure TDSTunnelService.CreateSession(out Session: TDSTunnelSession; RemoteIP: string);
var
ClientInfo: TDBXClientInfo;
begin
ClientInfo.IpAddress := RemoteIP;
CreateSession(Session, ClientInfo);
end;
procedure TDSTunnelService.CreateSession(out Session: TDSTunnelSession; ClientInfo: TDBXClientInfo);
var
Len: Integer;
begin
Session := TDSSessionManager.Instance.CreateSession<TDSTunnelSession>(function: TDSSession begin
if HasLocalServer then
Result := TDSLocalSession.Create(FFilters, FProtocolHandlerFactory)
else
begin
Result := TDSRemoteSession.Create(FDBXProperties);
end;
Result.ObjectCreator := self;
if ClientInfo.IpAddress <> EmptyStr then
Result.PutData('RemoteIP', ClientInfo.IpAddress);
if ClientInfo.Protocol <> EmptyStr then
Result.PutData('CommunicationProtocol', ClientInfo.Protocol);
if ClientInfo.AppName <> EmptyStr then
Result.PutData('RemoteAppName', ClientInfo.AppName);
Result.PutData('ProtocolSubType', 'tunnel');
end, FDBXProperties.UserName);
try
Session.FAuthManager := FDSAuthenticationManager;
Session.Open;
except
on ex: Exception do
try
DefaultErrorOpenSessionEvent(ex, Session, nil, Len);
except
TDSSessionManager.Instance.RemoveSession(Session.SessionName);
FreeAndNil(Session);
raise;
end;
end;
DefaultOpenSessionEvent(self, Session, nil, Len);
end;
procedure TDSTunnelService.CloseSession(SessionId: string);
var
Session: TDSSession;
Len: Integer;
begin
Session := TDSSessionManager.Instance.Session[SessionId];
if (Session <> nil) and (Session is TDSTunnelSession) then
begin
try
DefaultCloseSessionEvent(self, TDSTunnelSession(Session), nil, Len);
finally
TDSSessionManager.Instance.CloseSession(SessionId);
end
end
end;
procedure TDSTunnelService.TerminateAllSessions;
var
I: Integer;
openSessions: TStringList;
begin
openSessions := TStringList.Create;
try
TDSSessionManager.Instance.GetOpenSessionKeys(openSessions, self);
for I := 0 to openSessions.Count - 1 do
TDSSessionManager.Instance.TerminateSession(openSessions[I]);
finally
openSessions.Free;
end;
end;
class procedure TDSTunnelService.TerminateSession(const Params: TStrings);
var
SessionId: string;
begin
SessionId := Params.Values[QP_DSS];
if (SessionId <> '') and (SessionId <> '0') then
TDSSessionManager.Instance.TerminateSession(SessionId);
end;
function TDSTunnelService.GetSession(const SessionId: string): TDSTunnelSession;
begin
Result := TDSSessionManager.Instance.TunnelSession[SessionId];
end;
function TDSTunnelService.GetSessionCount: Integer;
var
openSessions: TStringList;
begin
openSessions := TStringList.Create;
try
TDSSessionManager.Instance.GetOpenSessionKeys(openSessions, self);
Result := openSessions.Count;
finally
openSessions.Free;
end;
end;
function TDSTunnelService.InitializeSession(Params: TStrings; RemoteIP: string): TDSTunnelSession;
var
ClientInfo: TDBXClientInfo;
begin
ClientInfo.IpAddress := RemoteIp;
Result := InitializeSession(Params, ClientInfo);
end;
function TDSTunnelService.InitializeSession(Params: TStrings; ClientInfo: TDBXClientInfo): TDSTunnelSession;
var
Session: TDSTunnelSession;
PSessionId: string;
begin
Session := nil;
PSessionId := Params.Values[QP_DSS];
if PSessionId = '0' then
begin
// first time - implicit session creation
CreateSession(Session, ClientInfo);
PSessionId := Session.SessionName;
// save the session id for error processing
Params.Values[QP_DSS] := PSessionId;
end
else
// get the session object
Session := GetSession(PSessionId);
if Session <> nil then
//associate session and thread
TDSSessionManager.SetAsThreadSession(Session);
Result := Session;
end;
function TDSTunnelService.NeedsAuthentication(Params: TStrings): Boolean;
var
PSessionId: string;
begin
PSessionId := Params.Values[QP_DSS];
Result := PSessionId = '0';
end;
procedure TDSTunnelService.GetOpenSessionKeys(Container: TStrings);
begin
TDSSessionManager.Instance.GetOpenSessionKeys(Container, self);
end;
procedure TDSTunnelService.ProcessPOST(Params: TStrings; Content: TArray<Byte>; out JsonResponse: TJSONValue;
out CloseConnection: Boolean);
var
Session: TDSTunnelSession;
PLen, PSessionId: string;
Len: Integer;
JsonParams: TJSONArray;
begin
// get the session id
PSessionId := Params.Values[QP_DSS];
if PSessionId <> '' then
begin
// close session request?
if (Length(Content) >= 5) and (Content[0] = 100) and (Content[1] = 115) and (Content[2] = 115) and (Content[3] = 61) and
(Content[4] = 45) then //dss=-
begin
CloseConnection := True;
CloseSession(PSessionId);
end
else
begin
CloseConnection := False;
//creates or looks-up session for given session ID.
//content of Params will be replaced for 'dss' if session is created
Session := InitializeSession(Params);
if Session <> nil then
begin
//associate session and thread
TDSSessionManager.SetAsThreadSession(Session);
// number of bytes to be written
PLen := Params.Values[QP_COUNT];
if PLen = '' then
Len := Length(Content)
else
Len := StrToInt(PLen);
try
// write Len bytes
Len := Session.Write(Content, 0, Len);
except
on ex: Exception do
DefaultErrorWriteSessionEvent(ex, Session, Content, Len);
end;
JsonResponse := TJSONObject.Create;
JsonParams := TJSONArray.Create;
TJSONObject(JsonResponse).AddPair(
TJSONPair.Create(TJSONString.Create('response'),
JsonParams));
JsonParams.AddElement(TJSONString.Create(PSessionId));
JsonParams.AddElement(TJSONNumber.Create(Len));
//dis-associate the session from the thread
// Session cleared by TDSApplication.EndDispatch
// TDSSessionManager.ClearThreadSession;
DefaultWriteSessionEvent(self, Session, Content, Len);
end
else
raise TDSServiceException.Create(SNoSessionFound);
end;
end
else
raise TDSServiceException.Create(Format(SNoSessionInRequest, [QP_DSS]));
end;
function TDSTunnelService.ProcessGET(Params: TStrings; var Len: Integer; out CloseConnection: Boolean): TStream;
var
Session: TDSTunnelSession;
PLen, PSessionId: string;
Buff: TArray<Byte>;
Count: Integer;
begin
Result := nil;
// get the session id
PSessionId := Params.Values[QP_DSS];
if PSessionId <> '' then
begin
// close session request?
if CanCloseSession(PSessionId) then
begin
CloseSession(PSessionId);
CloseConnection := True;
end
else
begin
CloseConnection := False;
//creates or looks-up session for given session ID.
//content of Params will be replaced for 'dss' if session is created
Session := InitializeSession(Params);
if Session <> nil then
begin
//associate session and thread
// TDSSessionManager.SetAsThreadSession(Session);
Assert(TDSSessionManager.GetThreadSession = Session);
// number of bytes to be read
PLen := Params.Values[QP_COUNT];
if PLen = '' then
raise TDSServiceException.Create(Format(SNoCountParam, [QP_COUNT]))
else
Count := StrToInt(PLen);
SetLength(Buff, Count);
Len := Count;
try
// read Len bytes
Len := Session.Read(Buff, 0, Count);
except
on ex: Exception do
DefaultErrorReadSessionEvent(ex, Session, Buff, Len);
end;
//dis-associate the session from the thread
// See TDSHTTPAppliction.EndDispatch
// TDSSessionManager.ClearThreadSession;
DefaultReadSessionEvent(self, Session, Buff, Len);
if Len < Count then
SetLength(Buff, Len);
// write then into the stream
Result := TBytesStream.Create(Buff);
end
else
raise TDSServiceException.Create(SNoSessionFound);
end;
end
else
raise TDSServiceException.Create(Format(SNoSessionInRequest, [QP_DSS]));
end;
procedure TDSTunnelService.DefaultOpenSessionEvent(Sender: TObject; Session: TDSTunnelSession; Content: TArray<Byte>; var Count: Integer);
begin
if Assigned(FOnOpenSession) then
FOnOpenSession(Sender, Session, Content, Count);
end;
procedure TDSTunnelService.DefaultErrorOpenSessionEvent(Sender: TObject; Session: TDSTunnelSession; Content: TArray<Byte>; var Count: Integer);
begin
if Assigned(FOnErrorOpenSession) then
FOnErrorOpenSession(Sender, Session, Content, Count)
else if Sender is Exception then
raise TDSServiceException.Create(Exception(Sender).Message)
else
raise TDSServiceException.Create(SCommunicationErr);
end;
procedure TDSTunnelService.DefaultCloseSessionEvent(Sender: TObject; Session: TDSTunnelSession; Content: TArray<Byte>; var Count: Integer);
begin
if Assigned(FOnCloseSession) then
FOnCloseSession(Sender, Session, Content, Count)
end;
procedure TDSTunnelService.DefaultWriteSessionEvent(Sender: TObject; Session: TDSTunnelSession; Content: TArray<Byte>; var Count: Integer);
begin
if Assigned(FOnWriteSession) then
FOnWriteSession(Sender, Session, Content, Count)
end;
procedure TDSTunnelService.DefaultReadSessionEvent(Sender: TObject; Session: TDSTunnelSession; Content: TArray<Byte>; var Count: Integer);
begin
if Assigned(FOnReadSession) then
FOnReadSession(Sender, Session, Content, Count)
end;
procedure TDSTunnelService.DefaultErrorWriteSessionEvent(Sender: TObject; Session: TDSTunnelSession; Content: TArray<Byte>; var Count: Integer);
begin
if Assigned(FOnErrorWriteSession) then
FOnErrorWriteSession(Sender, Session, Content, Count)
else if Sender is Exception then
raise TDSServiceException.Create(Exception(Sender).Message)
else
raise TDSServiceException.Create(SCommunicationErr);
end;
procedure TDSTunnelService.DefaultErrorReadSessionEvent(Sender: TObject; Session: TDSTunnelSession; Content: TArray<Byte>; var Count: Integer);
begin
if Assigned(FOnErrorReadSession) then
FOnErrorReadSession(Sender, Session, Content, Count)
else if Sender is Exception then
raise TDSServiceException.Create(Exception(Sender).Message)
else
raise TDSServiceException.Create(SCommunicationErr);
end;
procedure TDSTunnelService.SetDSHostname(AHostname: string);
begin
FDSHostname := AHostname;
FDBXProperties.Values[ TDBXPropertyNames.HostName ] := FDSHostname;
end;
procedure TDSTunnelService.SetDSPort(APort: Integer);
begin
FDSPort := APort;
FDBXProperties.Values[ TDBXPropertyNames.Port ] := IntToStr( FDSPort );
end;
{ TDSTCPSession }
function TDSTCPSession.Authenticate(const AuthenticateEventObject: TDSAuthenticateEventObject; connectionProps: TDBXProperties): Boolean;
begin
inherited;
if FAuthManager <> nil then
exit(FAuthManager.Authenticate(AuthenticateEventObject, connectionProps));
exit(True);
end;
constructor TDSTCPSession.Create(AAuthManager: TObject);
begin
Create(TDSCustomAuthenticationManager(AAuthManager));
end;
constructor TDSTCPSession.Create(AAuthManager: TDSCustomAuthenticationManager);
begin
FAuthManager := AAuthManager;
inherited Create;
end;
{ TDSSession }
function TDSSession.Authenticate(const AuthenticateEventObject: TDSAuthenticateEventObject; connectionProps: TDBXProperties): Boolean;
begin
{If FUserName has not yet been assigned then try to populate it from the connection properties.
Note that the usefulness of this attempt will depend on the extended implementation of this session.}
if FUserName = '' then
FUserName := connectionProps.Values[TDBXPropertyNames.DSAuthenticationUser];
Result := True;
end;
function TDSSession.Authorize(EventObject: TDSAuthorizeEventObject): Boolean;
begin
Result := True;
end;
procedure TDSSession.CancelScheduledEvent;
begin
if TDBXScheduler.Instance <> nil then
TDBXScheduler.Instance.CancelEvent(Id);
end;
procedure TDSSession.CheckTransient;
begin
case FSessionLifetime of
TDSSessionLifetime.TimeOut: ;
TDSSessionLifetime.Request:
raise TDSSessionError.Create(sOperationNotAllowedOnTransientSession);
end;
end;
constructor TDSSession.Create(const SessionName: string);
begin
FSessionName := SessionName;
Create;
end;
constructor TDSSession.Create(const SessionName: string; const AUser: string);
begin
FUserName := AUser;
Create(SessionName);
end;
constructor TDSSession.Create;
var
LSessionData: TDSSessionData;
begin
FDuration := 0;
FStatus := Idle;
FStartDateTime := Now;
LSessionData := CreateSessionData;
LSessionData.SetSession(Self);
Assert(FSessionData = LSessionData);
FUserRoles := TStringList.Create;
FCache := TDSSessionCache.Create;
MarkActivity;
end;
destructor TDSSession.Destroy;
begin
if TDSSessionManager.GetThreadSession = Self then
TDSSessionManager.ClearThreadSession;
FreeAndNil(FSessionData);
FreeAndNil(FUserRoles);
FreeAndNil(FCache);
if LastResultStream <> nil then
try
FreeAndNil(FLastResultStream);
except
end;
inherited;
end;
function TDSSession.CreateSessionData: TDSSessionData;
begin
Result := TDSSessionDictionaryData.Create;
end;
function TDSSession.ElapsedSinceLastActvity: Cardinal;
begin
exit( TThread.GetTickCount - FLastActivity );
end;
function TDSSession.ExpiresIn: Cardinal;
var
Elapsed: Integer;
begin
Elapsed := Integer(ElapsedSinceLastActvity);
if (Elapsed >= LifeDuration) then
Exit(0);
Result := LifeDuration - Elapsed;
end;
class function TDSSession.GenerateSessionId: string;
begin
Result := TDSSessionHelper.GenerateSessionId;
end;
procedure TDSSession.CheckSessionData;
begin
if FSessionData = nil then
raise TDSSessionError.Create(sNoSessionData);
end;
function TDSSession.HasData(Key: string): Boolean;
begin
CheckSessionData;
Result := FSessionData.HasData(Key);
end;
function TDSSession.HasObject(Key: string): Boolean;
begin
CheckSessionData;
Result := FSessionData.HasObject(Key);
end;
function TDSSession.GetObject(Key: string): TObject;
begin
CheckSessionData;
Result := FSessionData.GetObject(Key);
end;
function TDSSession.PutObject(Key: string; Value: TObject): Boolean;
begin
CheckSessionData;
Result := FSessionData.PutObject(Key, Value);
end;
function TDSSession.RemoveObject(Key: string; InstanceOwner: Boolean): TObject;
begin
CheckSessionData;
Result := FSessionData.RemoveObject(Key, InstanceOwner)
end;
procedure TDSSession.GetAuthRoleInternal(ServerMethod: TDSServerMethod;
AuthManager: TDSCustomAuthenticationManager; out AuthorizedRoles, DeniedRoles: TStrings);
var
RoleAuth: TRoleAuth;
MethodInfo: TDSMethodInfo;
FreeAuthRole: Boolean;
begin
AuthorizedRoles := nil;
DeniedRoles := nil;
FreeAuthRole := true;
RoleAuth := nil;
if (ServerMethod <> nil) and (ServerMethod.MethodInfo <> nil) then
begin
MethodInfo := ServerMethod.MethodInfo;
//Try to find a design time auth role
if (AuthManager <> nil) and (MethodInfo.DSClassInfo <> nil) then
begin
//only compute the design time Role Auth once
if (MethodInfo.AuthRole = nil) or
(not TRoleAuth(MethodInfo.AuthRole).IsDesignTime) then
begin
RoleAuth := TRoleAuth(AuthManager.GetAuthRole(MethodInfo.DSClassInfo.DSClassName, MethodInfo.DSMethodName));
if (RoleAuth = nil) and (MethodInfo.AuthRole = nil) then
// Create an empty roleauth if there isn't one from RTTI or authentication manager
RoleAuth := TRoleAuth.Create(nil, nil, True);
end;
end;
//if no design-time role found, use the one populated through RTI, if one exists
if RoleAuth = nil then
begin
RoleAuth := TRoleAuth(MethodInfo.AuthRole);
FreeAuthRole := false;
end;
end;
//copy the string lists being sent back, so users can't modify them,
//and so the TRoleAuth itself can be freed, unless it was a code attribute.
if RoleAuth <> nil then
begin
if RoleAuth.AuthorizedRoles <> nil then
begin
AuthorizedRoles := TStringList.Create;
AuthorizedRoles.AddStrings(RoleAuth.AuthorizedRoles);
end;
if RoleAuth.DeniedRoles <> nil then
begin
DeniedRoles := TStringList.Create;
DeniedRoles.AddStrings(RoleAuth.DeniedRoles);
end;
end;
if FreeAuthRole then
FreeAndNil(Roleauth);
end;
procedure TDSSession.GetAuthRoles(ServerMethod: TDSServerMethod;
out AuthorizedRoles, DeniedRoles: TStrings);
begin
AuthorizedRoles := nil;
DeniedRoles := nil;
end;
function TDSSession.GetData(Key: string): string;
begin
CheckSessionData;
Result := FSessionData.GetData(Key);
end;
function TDSSession.GetId: NativeInt;
begin
exit(IntPtr(Pointer(Self)));
end;
function TDSSession.GetSessionStatus: TDSSessionStatus;
begin
if ((FStatus = TDSSessionStatus.Active) or
(FStatus = TDSSessionStatus.Idle) or
(FStatus = TDSSessionStatus.Connected))
and (FDuration > 0) and IsIdleMS(FDuration) then
begin
FStatus := TDSSessionStatus.Expired;
end;
Result := FStatus;
end;
procedure TDSSession.Close;
begin
FStatus := Closed;
end;
procedure TDSSession.Terminate;
begin
FStatus := Closed;
end;
function TDSSession.IsValid: Boolean;
begin
Result := (Status = TDSSessionStatus.Active) or
(Status = TDSSessionStatus.Idle) or
(Status = TDSSessionStatus.Connected);
end;
function TDSSession.IsIdle(Seconds: Cardinal): Boolean;
begin
Result := IsIdleMS(Seconds * 1000);
end;
function TDSSession.IsIdleMS(Milliseconds: Cardinal): Boolean;
begin
Result := ElapsedSinceLastActvity > Milliseconds;
end;
procedure TDSSession.MarkActivity;
begin
FStatus := Active;
FLastActivity := TThread.GetTickCount;
end;
procedure TDSSession.PutData(Key, Value: string);
begin
CheckSessionData;
FSessionData.PutData(Key, Value);
end;
procedure TDSSession.RemoveData(Key: string);
begin
CheckSessionData;
FSessionData.RemoveData(Key);
end;
function TDSSession.RequiresAuthorization(MethodInfo: TDSMethodInfo): Boolean;
begin
Result := (MethodInfo <> nil) and
(MethodInfo.MethodAlias <> 'DSMetadata.GetDatabase') and
//GetPlatformName is often used to validate a connection, we will allow this call by anyone
(MethodInfo.MethodAlias <> 'DSAdmin.GetPlatformName');
end;
procedure TDSSession.TerminateInactiveSession;
begin
if (FDuration > 0) and (IsIdleMS(FDuration)) then
begin
try
TerminateSession;
TDSSessionManager.Instance.TerminateSession(SessionName);
except
end;
end
else
ScheduleInactiveTerminationEvent;
end;
procedure TDSSession.ScheduleInactiveTerminationEvent;
begin
if FDuration > 0 then
ScheduleUserEvent(TerminateInactiveSession, FDuration);
end;
procedure TDSSession.ScheduleTerminationEvent;
begin
if FDuration > 0 then
ScheduleUserEvent(TerminateSession, FDuration);
end;
procedure TDSSession.ScheduleUserEvent(Event: TDBXScheduleEvent; ElapsedTime: Integer);
begin
if TDBXScheduler.Instance <> nil then
TDBXScheduler.Instance.AddEvent(Id, Event, ElapsedTime);
end;
procedure TDSSession.SetSessionName(const sessionId: string);
begin
FSessionName := sessionId;
end;
procedure TDSSession.SetUserName(const userName: string);
begin
FUserName := userName;
end;
procedure TDSSession.SetLifetime(Value: TDSSessionLifetime);
begin
FSessionLifetime := Value;
end;
procedure TDSSession.TerminateSession;
begin
FStatus := Terminated;
end;
{ TDSSessionManager }
procedure TDSSessionManager.CloseSession(session: TDSSession);
begin
try
if Assigned(session) then
begin
Assert(session.SessionName <> '');
// Session should have been removed from the list by now
Assert(GetSession(session.SessionName) = nil);
if TDBXScheduler.Instance <> nil then
TDBXScheduler.Instance.CancelEvent(session.Id);
NotifyEvents(session, SessionClose);
session.Close;
end
finally
// Under ARC terminate session here
session.DisposeOf;
end;
end;
procedure TDSSessionManager.AddSessionEvent(Event: TDSSessionEvent);
begin
if not Assigned(FListeners) then
FListeners := TList<TDSSessionEvent>.Create;
System.TMonitor.Enter(FListeners);
try
if not FListeners.Contains(Event) then
FListeners.Add(Event);
finally
System.TMonitor.Exit(FListeners);
end;
end;
function TDSSessionManager.RemoveSessionEvent(Event: TDSSessionEvent): Boolean;
begin
if Assigned(FListeners) then
begin
System.TMonitor.Enter(FListeners);
try
exit(FListeners.Remove(Event) > -1);
finally
System.TMonitor.Exit(FListeners);
end;
end;
Result := False;
end;
class procedure TDSSessionManager.SetAsThreadSession(Session: TDSSession);
begin
VDSSession := Session;
end;
class procedure TDSSessionManager.ClearThreadSession;
begin
VDSSession := nil;
end;
procedure TDSSessionManager.CloseSession(SessionId: string);
var
session: TDSSession;
begin
Assert(sessionId <> '');
session := RemoveSession(SessionId);
if Assigned(session) then
CloseSession(session);
end;
constructor TDSSessionManager.Create;
begin
FSessionContainer := TDictionary<string, TDSSession>.Create;
end;
function TDSSessionManager.CreateSession<T>(factory: TFactoryMethod; userName: string;
ASessionLifetime: TDSSessionLifetime): T;
begin
Result := CreateSession<T>(factory, ASessionLifetime, False);
Result.SetUserName(userName);
case ASessionLifetime of
TDSSessionLifetime.TimeOut:
NotifyEvents(Result, SessionCreate);
TDSSessionLifetime.Request: ;
else
Assert(False);
end;
end;
function TDSSessionManager.CreateSession<T>(factory: TFactoryMethod; userName: string): T;
begin
Result := CreateSession<T>(factory, False);
Result.SetUserName(userName);
NotifyEvents(Result, SessionCreate);
end;
function TDSSessionManager.CreateSession<T>(factory: TFactoryMethod; ASessionLifetime: TDSSessionLifetime; DoNotify: Boolean): T;
var
sessionId: string;
begin
case ASessionLifetime of
TDSSessionLifetime.TimeOut:
begin
TMonitor.Enter(self);
try
sessionId := GetUniqueSessionId;
Result := T(factory);
Result.SetLifetime(ASessionLifetime);
Result.SetSessionName(sessionId);
FSessionContainer.Add(sessionId, Result);
finally
TMonitor.Exit(self);
end;
end;
TDSSessionLifetime.Request:
begin
Assert(DoNotify = False);
DoNotify := False;
Result := T(factory);
Result.SetLifetime(ASessionLifetime);
end;
end;
if DoNotify then
NotifyEvents(Result, SessionCreate);
end;
function TDSSessionManager.CreateSession<T>(factory: TFactoryMethod; DoNotify: Boolean): T;
var
sessionId: string;
begin
Result := CreateSession<T>(factory, TDSSessionLifetime.TimeOut, DoNotify);
// TMonitor.Enter(self);
// try
// sessionId := GetUniqueSessionId;
// Result := T(factory);
// Result.SetSessionName(sessionId);
// FSessionContainer.Add(sessionId, Result);
// finally
// TMonitor.Exit(self);
// end;
//
// if DoNotify then
// NotifyEvents(Result, SessionCreate);
end;
destructor TDSSessionManager.Destroy;
var
keys: TStrings;
key: string;
begin
keys := TStringList.Create;
try
GetOpenSessionKeys(keys);
for key in keys do
begin
TerminateSession(key);
end;
finally
FInstance := nil;
FreeAndNil(FListeners);
FreeAndNil(FSessionContainer);
FreeAndNil(keys);
inherited;
end;
end;
procedure TDSSessionManager.GetOpenSessionKeys(Container: TStrings);
begin
Synchronized(self, procedure
var
keyEnumerator: TDictionary<string, TDSSession>.TKeyEnumerator;
begin
keyEnumerator := FSessionContainer.Keys.GetEnumerator;
while keyEnumerator.MoveNext do
Container.Add(keyEnumerator.Current);
keyEnumerator.Free
end);
end;
procedure TDSSessionManager.GetOpenSessionKeys(Container: TStrings; ACreator: TObject);
begin
Synchronized(self, procedure
var
valueEnumerator: TDictionary<string, TDSSession>.TValueEnumerator;
begin
valueEnumerator := FSessionContainer.Values.GetEnumerator;
while valueEnumerator.MoveNext do
if valueEnumerator.Current.ObjectCreator = ACreator then
Container.Add(valueEnumerator.Current.SessionName);
valueEnumerator.Free
end);
end;
function TDSSessionManager.GetSession(SessionId: string): TDSSession;
begin
TMonitor.Enter(self);
try
FSessionContainer.TryGetValue(SessionId, Result);
finally
TMonitor.Exit(self);
end;
end;
function TDSSessionManager.GetSessionCount: Integer;
var
Count: Integer;
begin
Synchronized(Self, procedure begin
Count := FSessionContainer.Count;
end);
Result := Count;
end;
class function TDSSessionManager.GetThreadSession: TDSSession;
begin
Result := VDSSession;
end;
function TDSSessionManager.GetTunnelSession(
SessionId: string): TDSTunnelSession;
var
session: TDSSession;
begin
session := GetSession(SessionId);
if (session <> nil) and (session is TDSTunnelSession) then
Result := TDSTunnelSession(session)
else
Result := nil;
end;
function TDSSessionManager.GetUniqueSessionId: string;
begin
// assumes the container is thread secure
repeat
Result := TDSSession.GenerateSessionId
until not FSessionContainer.ContainsKey(Result);
end;
procedure TDSSessionManager.NotifyEvents(session: TDSSession; EventType: TDSSessionEventType);
var
Event: TDSSessionEvent;
I, Count: Integer;
LListeners: TList<TDSSessionEvent>;
begin
if Assigned(FListeners) then
begin
System.TMonitor.Enter(Self);
try
LListeners := TList<TDSSessionEvent>.Create;
//copy the events into a new list, so the FListeners
//doesn't need to remain locked while calling each event.
//this prevents deadlocks if events try to remove themselves, for example
System.TMonitor.Enter(FListeners);
try
Count := FListeners.Count - 1;
for I := 0 to Count do
LListeners.Add(FListeners.Items[I]);
finally
System.TMonitor.Exit(FListeners);
end;
try
Count := LListeners.Count - 1;
for I := Count downto 0 do
begin
Event := LListeners.Items[I];
try
if FListeners.Contains(Event) then
Event(Self, EventType, session);
except
end;
end;
finally
FreeAndNil(LListeners);
end;
finally
System.TMonitor.Exit(Self);
end;
end;
end;
function TDSSessionManager.RemoveSession(SessionId: string): TDSSession;
var
session: TDSSession;
begin
session := nil;
Synchronized(self, procedure begin
FSessionContainer.TryGetValue(SessionId, session);
if session <> nil then
FSessionContainer.Remove(SessionId);
end);
Result := session;
end;
procedure TDSSessionManager.TerminateAllSessions(const ACreator: TObject; AAllSessions: Boolean);
var
LList: TList<TDSSession>;
LSession: TDSSession;
begin
Assert((ACreator <> nil) or AAllSessions);
LList := TList<TDSSession>.Create;
try
ForEachSession(procedure(const Session: TDSSession) begin
if AAllSessions or (Session.ObjectCreator = ACreator) then
LList.Add(RemoveSession(Session.SessionName));
end);
for LSession in LList do
TerminateSession(LSession);
finally
LList.Free;
end;
end;
procedure TDSSessionManager.TerminateAllSessions(const ACreator: TObject);
begin
TerminateAllSessions(ACreator, False);
end;
procedure TDSSessionManager.TerminateAllSessions;
begin
TerminateAllSessions(nil, True);
end;
procedure TDSSessionManager.ForEachSession(AVisitor: TDSSessionVisitor);
begin
Synchronized(self, procedure
var
valEnumerator: TDictionary<string, TDSSession>.TValueEnumerator;
begin
valEnumerator := FSessionContainer.Values.GetEnumerator;
try
while valEnumerator.MoveNext do
AVisitor(valEnumerator.Current);
finally
valEnumerator.Free
end;
end);
end;
procedure TDSSessionManager.TerminateSession(session: TDSSession);
begin
try
if Assigned(session) then
begin
// Session should have been removed from the list by now
Assert(GetSession(session.SessionName) = nil);
if TDBXScheduler.Instance <> nil then
TDBXScheduler.Instance.CancelEvent(session.Id);
session.Terminate;
NotifyEvents(session, SessionClose);
end;
finally
session.Free;
end;
end;
procedure TDSSessionManager.TerminateSession(const sessionId: string);
var
session: TDSSession;
begin
session := RemoveSession(sessionId);
if Assigned(session) then
TerminateSession(session);
end;
{ TDSAuthSession }
procedure TDSAuthSession.GetAuthRoles(ServerMethod: TDSServerMethod;
out AuthorizedRoles, DeniedRoles: TStrings);
begin
AuthorizedRoles := nil;
DeniedRoles := nil;
if (ServerMethod <> nil) and (ServerMethod.MethodInfo <> nil) then
if (FAuthManager <> nil) then
GetAuthRoleInternal(ServerMethod, FAuthManager, AuthorizedRoles, DeniedRoles);
end;
function TDSAuthSession.Authorize(EventObject: TDSAuthorizeEventObject): Boolean;
begin
if (FAuthManager <> nil) then
begin
exit(FAuthManager.Authorize(EventObject))
end;
exit(True); //return true if no authentication manager is set
end;
{ TDSRESTSession }
function TDSRESTSession.Authenticate(const AuthenticateEventObject: TDSAuthenticateEventObject; connectionProps: TDBXProperties): Boolean;
begin
inherited;
exit(True); //currently, authentication will be done elsewhere for REST
end;
constructor TDSRESTSession.Create(AAuthManager: TDSCustomAuthenticationManager);
begin
FAuthManager := AAuthManager;
inherited Create;
end;
{ TDSSessionCache }
function TDSSessionCache.AddItem(Item: TResultCommandHandler): Integer;
var
LargestId: Integer;
Id: Integer;
begin
if (Item = nil) then
exit(-1);
TMonitor.Enter(FItems);
try
LargestId := -1;
for Id in FItems.Keys do
begin
if FItems.Items[Id] = Item then
exit(Id);
if (Id > LargestId) then
LargestId := Id;
end;
Id := LargestId + 1;
FItems.Add(Id, Item);
Result := Id;
finally
TMonitor.Exit(FItems);
end;
end;
procedure TDSSessionCache.ClearAllItems(InstanceOwner: Boolean);
var
Item: TResultCommandHandler;
begin
if Assigned(FItems) then
begin
TMonitor.Enter(FItems);
try
if InstanceOwner then
begin
for Item in FItems.Values do
try
Item.Free;
except
end;
end;
FItems.Clear;
finally
TMonitor.Exit(FItems);
end;
end;
end;
constructor TDSSessionCache.Create;
begin
FItems := TDictionary<Integer, TResultCommandHandler>.Create;
end;
destructor TDSSessionCache.Destroy;
begin
ClearAllItems(True);
FreeAndNil(FItems);
inherited;
end;
function TDSSessionCache.GetItem(ID: Integer): TResultCommandHandler;
var
Item: TResultCommandHandler;
begin
Result := nil;
if FItems.TryGetValue(ID, Item) then
begin
Result := Item;
end;
end;
function TDSSessionCache.GetItemID(Item: TResultCommandHandler): Integer;
var
Id: Integer;
begin
Result := -1;
if (Item <> nil) and Assigned(FItems) then
begin
TMonitor.Enter(FItems);
try
for Id in FItems.Keys do
begin
if FItems.Items[Id] = Item then
exit(Id);
end;
finally
TMonitor.Exit(FItems);
end;
end;
end;
function TDSSessionCache.GetItemIDs: TDSSessionCacheKeys;
var
Key: Integer;
begin
Result := TDSSessionCacheKeys.Create;
TMonitor.Enter(FItems);
try
for Key in FItems.Keys do
Result.Add(Key);
finally
TMonitor.Exit(FItems);
Result.Sort;
end;
end;
procedure TDSSessionCache.RemoveItem(Item: TResultCommandHandler);
var
Val: TResultCommandHandler;
I: Integer;
IndexToRemove: Integer;
begin
if (Item = nil) or not Assigned(FItems) then
Exit;
IndexToRemove := -1;
TMonitor.Enter(FItems);
try
for I in FItems.Keys do
begin
Val := FItems.Items[I];
if Val = Item then
begin
IndexToRemove := I;
end;
end;
if (IndexToRemove > -1) then
RemoveItem(IndexToRemove, False);
finally
TMonitor.Exit(FItems);
end;
end;
function TDSSessionCache.RemoveItem(ID: Integer; InstanceOwner: Boolean): TResultCommandHandler;
var
Item: TResultCommandHandler;
begin
Result := nil;
TMonitor.Enter(FItems);
try
if FItems.TryGetValue(ID, Item) then
begin
FItems.Remove(ID);
if InstanceOwner then
Item.Free
else
Result := Item;
end;
finally
TMonitor.Exit(FItems);
end;
end;
{ TDSSessionDictionaryData }
constructor TDSSessionDictionaryData.Create;
begin
inherited;
FMetaData := TDictionary<string,string>.Create;
FMetaObjects := TDictionary<string,TObject>.Create;
end;
destructor TDSSessionDictionaryData.Destroy;
var
LObjEnumerator: TDictionary<string, TObject>.TValueEnumerator;
begin
LObjEnumerator := FMetaObjects.Values.GetEnumerator;
try
while LObjEnumerator.MoveNext do
try
LObjEnumerator.Current.Free;
except
end;
finally
LObjEnumerator.Free
end;
FMetaObjects.Free;
FMetaData.Free;
end;
function TDSSessionDictionaryData.HasData(const AKey: string): Boolean;
begin
Result := FMetaData.ContainsKey(AnsiLowerCase(AKey));
end;
function TDSSessionDictionaryData.HasObject(const AKey: string): Boolean;
begin
Result := FMetaObjects.ContainsKey(AnsiLowerCase(AKey));
end;
function TDSSessionDictionaryData.GetData(const AKey: string): string;
var
LValue: string;
begin
if (FMetaData.TryGetValue(AnsiLowerCase(AKey), LValue)) then
exit(LValue);
Result := '';
end;
procedure TDSSessionDictionaryData.CheckTransient;
begin
if Session <> nil then
Session.CheckTransient;
end;
procedure TDSSessionDictionaryData.PutData(const AKey, LValue: string);
var
LLowerKey: string;
begin
CheckTransient;
LLowerKey := AnsiLowerCase(AKey);
FMetaData.Remove(LLowerKey);
FMetaData.Add(LLowerKey, LValue);
end;
function TDSSessionDictionaryData.PutObject(const AKey: string;
AValue: TObject): Boolean;
begin
CheckTransient;
Result := True;
if not HasObject(AKey) then
FMetaObjects.Add(AnsiLowerCase(AKey), AValue)
else
Exit(False);
end;
procedure TDSSessionDictionaryData.RemoveData(const AKey: string);
begin
CheckTransient;
FMetaData.Remove(AnsiLowerCase(AKey));
end;
function TDSSessionDictionaryData.RemoveObject(const AKey: string;
AInstanceOwner: Boolean): TObject;
var
LVal: TObject;
begin
CheckTransient;
Result := nil;
if HasObject(AKey) then
begin
LVal := GetObject(AKey);
FMetaObjects.Remove(AnsiLowerCase(AKey));
if AInstanceOwner then
FreeAndNil(LVal)
else
Result := LVal;
end;
end;
function TDSSessionDictionaryData.GetObject(const AKey: string): TObject;
begin
if (FMetaObjects.TryGetValue(AnsiLowerCase(AKey), Result)) then
Exit;
Result := nil;
end;
{ TDSSessionData }
constructor TDSSessionData.Create;
begin
end;
procedure TDSSessionData.SetSession(const ASession: TDSSession);
begin
if FDSSession <> nil then
FDSSession.FSessionData := nil;
FDSSession := ASession;
if FDSSEssion <> nil then
FDSSession.FSessionData := Self;
end;
initialization
Randomize;
TDSSessionManager.FInstance := TDSSessionManager.Create;
finalization
TDSSessionManager.FInstance.Free;
end.
|
{----------------------------------------------------------------------------}
{ Written by Nguyen Le Quang Duy }
{ Nguyen Quang Dieu High School, An Giang }
{----------------------------------------------------------------------------}
Program TTRIP;
Uses Math;
Const
maxN =100;
maxValue =100000001;
Var
n :ShortInt;
A :Array[1..maxN,1..maxN] of LongInt;
Free :Array[1..maxN] of Boolean;
res :Int64;
procedure Enter;
var
u,v :ShortInt;
c :LongInt;
begin
Read(n);
for u:=1 to n do
for v:=1 to n do
begin
Read(c);
if (c=0) then A[u,v]:=maxValue else A[u,v]:=c;
end;
end;
procedure Optimize;
var
u,v,k :ShortInt;
minV :LongInt;
begin
for k:=1 to n do
for u:=1 to n do
for v:=1 to n do
A[u,v]:=Min(A[u,v],A[u,k]+A[k,v]);
FillChar(Free,n,true); Free[1]:=false;
res:=0; u:=1;
repeat
k:=0; minV:=maxValue;
for v:=2 to n-1 do
if (Free[v]) and (minV>A[u,v]) then
begin
minV:=A[u,v]; k:=v;
end;
if (k=0) then Break;
Inc(res,minV);
u:=k;
Free[u]:=false;
until false;
Inc(res,A[u,n]);
end;
Begin
Assign(Input,''); Reset(Input);
Assign(Output,''); Rewrite(Output);
Enter;
Optimize;
Write(res);
Close(Input); Close(Output);
End. |
unit AMostraBoleto;
{ Autor: Douglas Thomas Jacobsen
Data Criação: 28/02/2000;
Função: TELA BÁSICA
Data Alteração:
Alterado por:
Motivo alteração:
}
interface
uses
Windows, SysUtils, Classes,Controls, Forms, Componentes1, ExtCtrls,
PainelGradiente, Formularios, StdCtrls, Buttons, Tabela, Grids, DBCtrls,
Localizacao, Mask, DBGrids, LabelCorMove, numericos, UnImpressao, Db,
DBTables, ComCtrls, UnClassesImprimir, DBClient;
type
TFMostraBoleto = class(TFormularioPermissao)
PanelFechar: TPanelColor;
BFechar: TBitBtn;
BImprimir: TBitBtn;
PainelTitulo: TPainelGradiente;
Panel: TPanelColor;
Label76: TLabel;
Shape4: TShape;
Label14: TLabel;
Label5: TLabel;
EValorDocumento: Tnumerico;
ELocalPagamento: TEditColor;
PanelModelo: TPanelColor;
Label1: TLabel;
CModelo: TDBLookupComboBoxColor;
CAD_DOC: TSQL;
CAD_DOCI_NRO_DOC: TFMTBCDField;
CAD_DOCI_SEQ_IMP: TFMTBCDField;
CAD_DOCC_NOM_DOC: TWideStringField;
CAD_DOCC_TIP_DOC: TWideStringField;
DATACAD_DOC: TDataSource;
Label3: TLabel;
Label4: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
ECedente: TEditColor;
Label10: TLabel;
Label11: TLabel;
ENumeroDocumento: TEditColor;
Label12: TLabel;
EEspecieDocumento: TEditColor;
EAceite: TEditColor;
Label13: TLabel;
Label15: TLabel;
Label16: TLabel;
ECarteira: TEditColor;
EEspecie: TEditColor;
Label17: TLabel;
EQuantidade: TEditColor;
Label18: TLabel;
Label19: TLabel;
Label20: TLabel;
EAgencia: TEditColor;
Label21: TLabel;
ENossoNumero: TEditColor;
Label22: TLabel;
Label23: TLabel;
Label24: TLabel;
EDesconto: Tnumerico;
Label25: TLabel;
EOutras: Tnumerico;
Label26: TLabel;
EMoraMulta: Tnumerico;
Label27: TLabel;
EAcrescimos: Tnumerico;
Label28: TLabel;
EValoCobrado: Tnumerico;
Label29: TLabel;
Label30: TLabel;
Shape9: TShape;
Shape1: TShape;
Shape2: TShape;
Shape3: TShape;
Shape5: TShape;
Shape6: TShape;
Shape7: TShape;
Shape8: TShape;
Shape10: TShape;
Shape11: TShape;
Shape12: TShape;
Shape13: TShape;
Shape14: TShape;
Shape15: TShape;
Shape16: TShape;
Shape17: TShape;
Shape18: TShape;
Shape19: TShape;
Shape20: TShape;
EInstrucoes: TMemoColorLimite;
ESacado: TMemoColorLimite;
DBText2: TDBText;
CAD_DOCC_NOM_IMP: TWideStringField;
EValor: Tnumerico;
EDataDocumento: TMaskEditColor;
EDataProcessamento: TMaskEditColor;
EVencimento: TMaskEditColor;
BOK: TBitBtn;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BFecharClick(Sender: TObject);
procedure BImprimirClick(Sender: TObject);
procedure CModeloCloseUp(Sender: TObject);
procedure FormShow(Sender: TObject);
private
IMP : TFuncoesImpressao;
procedure DesativaEdits;
public
{ Public declarations }
procedure ImprimeDocumento;
procedure MostraDocumento(Dados: TDadosBoleto);
procedure CarregaDados(Dados: TDadosBoleto);
procedure CarregaEdits(Dados: TDadosBoleto);
end;
var
FMostraBoleto: TFMostraBoleto;
implementation
uses APrincipal, FunSql, FunString, ConstMsg, FunObjeto, Constantes;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFMostraBoleto.FormCreate(Sender: TObject);
begin
EDataDocumento.Text:=DateToStr(Date);
EDataProcessamento.Text:=DateToStr(Date);
EVencimento.Text:=DateToStr(Date);
IMP := TFuncoesImpressao.Criar(self, FPrincipal.BaseDados);
AbreTabela(CAD_DOC);
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFMostraBoleto.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FechaTabela(CAD_DOC);
IMP.Destroy;
Action := CaFree;
end;
procedure TFMostraBoleto.BFecharClick(Sender: TObject);
begin
Close;
end;
procedure TFMostraBoleto.BImprimirClick(Sender: TObject);
begin
ImprimeDocumento;
end;
procedure TFMostraBoleto.ImprimeDocumento;
var
Dados: TDadosBoleto;
begin
if ((not CAD_DOC.EOF) and (CModelo.Text <> '')) then
begin
Dados := TDadosBoleto.Create;
IMP.InicializaImpressao( CAD_DOCI_NRO_DOC.AsInteger, CAD_DOCI_SEQ_IMP.AsInteger);
CarregaDados(Dados);
IMP.ImprimeBoleto(Dados); // Imprime 1 documento.
IMP.FechaImpressao(Config.ImpPorta, 'C:\IMP.TXT');
end
else
Aviso('Não existe modelo de documento para imprimir.');
end;
procedure TFMostraBoleto.MostraDocumento(Dados: TDadosBoleto);
begin
BOK.Visible := True;
ActiveControl := BOK;
CarregaEdits(Dados);
DesativaEdits;
if BImprimir.Visible then
Height := Height - PanelModelo.Height - PanelFechar.Height - PainelTitulo.Height;
BImprimir.Visible := False;
PanelModelo.Visible := False;
PanelFechar.Visible := False;
PainelTitulo.Visible := False;
if BImprimir.Visible then
Height := Height - PanelModelo.Height - PanelFechar.Height - PainelTitulo.Height; DesativaEdits;
FormStyle := fsStayOnTop;
BorderStyle := bsDialog;
Show;
end;
procedure TFMostraBoleto.DesativaEdits;
var
I: Integer;
begin
for I := 0 to (ComponentCount -1) do
begin
if (Components[I] is TEditColor) then
(Components[I] as TEditColor).ReadOnly := True;
if (Components[I] is TNumerico) then
(Components[I] as TNumerico).ReadOnly := True;
end;
end;
procedure TFMostraBoleto.CarregaEdits(Dados: TDadosBoleto);
begin
with Dados do
begin
ELocalPagamento.Text:=LocalPagamento;
ECedente.Text:=Cedente;
EDataDocumento.Text:=DateToStr(DataDocumento);
ENumeroDocumento.Text:=NumeroDocumento;
EEspecieDocumento.Text:=EspecieDocumento;
EAceite.Text:=Aceite;
EDataProcessamento.Text:=DateToStr(DataProcessamento);
ECarteira.Text:=Carteira;
EEspecie.Text:=Especie;
EQuantidade.Text:=Quantidade;
EVencimento.Text:=DateToStr(Vencimento);
EAgencia.Text:=Agencia;
ENossoNumero.Text:=NossoNumero;
EValorDocumento.AValor := ValorDocumento;
EValor.AValor := Valor;
EDesconto.AValor := Desconto;
EOutras.AValor := Outras;
EMoraMulta.AValor := MoraMulta;
EAcrescimos.AValor := Acrescimos;
EValoCobrado.AValor := ValoCobrado;
EInstrucoes.Lines := Instrucoes;
ESacado.Lines :=Sacado;
end;
end;
procedure TFMostraBoleto.CarregaDados(Dados: TDadosBoleto);
var
I : Integer;
begin
with Dados do
begin
LocalPagamento := ELocalPagamento.Text;
Cedente := ECedente.Text;
DataDocumento := StrToDate(EDataDocumento.Text);
NumeroDocumento := ENumeroDocumento.Text;
EspecieDocumento := EEspecieDocumento.Text;
Aceite := EAceite.Text;
DataProcessamento := StrToDate(EDataProcessamento.Text);
Carteira := ECarteira.Text;
Especie := EEspecie.Text;
Quantidade := EQuantidade.Text;
Valor := EValor.AValor;
Vencimento := StrToDate(EVencimento.Text);
Agencia := EAgencia.Text;
NossoNumero := ENossoNumero.Text;
ValorDocumento := EValorDocumento.AValor;
Desconto := EDesconto.AValor;
Outras := EOutras.AValor;
MoraMulta := EMoraMulta.AValor;
Acrescimos := EAcrescimos.AValor;
ValoCobrado := EValoCobrado.AValor;
Instrucoes := TStringList.Create;
Instrucoes.Clear;
for I:=0 to EInstrucoes.Lines.Count -1 do
Instrucoes.Add(EInstrucoes.Lines.Strings[I]);
Sacado := TStringList.Create;
Sacado.Clear;
for I:=0 to ESacado.Lines.Count -1 do
Sacado.Add(ESacado.Lines.Strings[I]);
end;
end;
procedure TFMostraBoleto.CModeloCloseUp(Sender: TObject);
begin
LimpaEdits(FMostraBoleto);
LimpaEditsNumericos(FMostraBoleto);
// Configura e limita os edits.
if (not CAD_DOC.EOF) then
IMP.LimitaTamanhoCampos(FMostraBoleto, CAD_DOCI_NRO_DOC.AsInteger);
end;
procedure TFMostraBoleto.FormShow(Sender: TObject);
begin
CModelo.KeyValue:=CAD_DOCI_NRO_DOC.AsInteger; // Posiciona no Primeiro;
// Configura e limita os edits.
if (not CAD_DOC.EOF) then
IMP.LimitaTamanhoCampos(FMostraBoleto, CAD_DOCI_NRO_DOC.AsInteger);
end;
Initialization
RegisterClasses([TFMostraBoleto]);
end.
|
unit stacks;
interface
const
maxBoardSize = 8;
type
TCell = (cQueen, cUnderAttack, cFree);
TBoard = array[1..maxBoardSize, 1..maxBoardSize] of TCell;
PStack= ^TStack;
TStack = record
x: byte;
CurrAbsBoardPos: integer; //текущее положение ферзя в строке применительно к отрисовке
board: TBoard;
next: PStack;
end;
procedure CreateStack (var top:pStack);
procedure ClearStack (var top: PStack);
procedure PushStack (var top: pStack; x: byte; board: TBoard; CurrAbsBoardPos: integer);
procedure PopStack (var top: pStack; var x: byte; var board: TBoard; var CurrAbsBoardPos: integer);
//function StackElements (var top: pStack): integer;
implementation
procedure CreateStack (var top: pStack);
{создание пустого стека}
begin
if top <> nil then
ClearStack (top)
else
top:= nil;
end;
procedure PushStack (var top: pStack; x: byte; board: TBoard; CurrAbsBoardPos: integer);
{добавление элемента в верх стека}
var
temp: pStack;
begin
new (temp); {выделяем память для нового элемента}
temp^.x:= x; {присваиваем элементу информацию}
temp^.board:= board;
temp^.CurrAbsBoardPos:= CurrAbsBoardPos;
temp^.next:= top; {"ставим" новый элемент в верх стека}
top:= temp; {сохраняем стек с новым элементом}
end;
procedure PopStack (var top: pStack; var x: byte; var board: TBoard; var CurrAbsBoardPos: integer);
{изъятие элемента из вершины стека}
var
temp: pStack;
begin
if top <> nil then {если стек не пуст, то}
begin
temp:= top^.next; {сохраняем стек, начиная со второго элемента от вершины}
x:= top^.x; {считываем информацию}
CurrAbsBoardPos:= top^.CurrAbsBoardPos;
board:= top^.board;
dispose (top); {очищаем память от первого элемента}
top:= temp; {записываем новый стек в top}
end;
end;
procedure ClearStack (var top: PStack);
var
temp: PStack;
begin
while top <> nil do
begin
temp:= top;
top:= top^.next;
dispose (temp);
end;
end;
end.
|
{ Copyright (C) 1998-2006, written by Mike Shkolnik, Scalabium Software
E-Mail: mshkolnik@scalabium
WEB: http://www.scalabium.com
Const strings for localization
freeware SMComponent library
}
unit SMCnst;
interface
{English strings}
const
strMessage = 'Drukuj...';
strSaveChanges = 'Napewno zapisać zmiany w bazie danych?';
strErrSaveChanges = 'Nie mozna zapisac dancyh! Sprawdz połączenie z serwerem i poprawność danych.';
strDeleteWarning = 'Napewno usunąć tabelę %s?';
strEmptyWarning = 'Napewno wyczyścić tabelę %s?';
const
PopUpCaption: array [0..24] of string[33] =
('Dodaj rekord',
'Wpisz rekord',
'Edytuj rekord',
'Usuń rekord',
'-',
'Drukuj ...',
'Exportuj ...',
'Filtry ...',
'Szukaj ...',
'-',
'Zapisz zmiany',
'Cofnij zmiany',
'Odswiez',
'-',
'Zaznacz/Odznacz rekordy',
'Zaznacz rekord',
'Zaznacz wszystkie rekordy',
'-',
'Odznacz rekord',
'Odznacz wszystkie rekordy',
'-',
'Zapisz ustawienia kolumn',
'Przywróć ustawienia kolumn',
'-',
'Ustawienia...');
const //for TSMSetDBGridDialog
SgbTitle = ' Tytuł ';
SgbData = ' Dane ';
STitleCaption = 'Tytuł:';
STitleAlignment = 'Wyrównanie:';
STitleColor = 'Tło:';
STitleFont = 'Font:';
SWidth = 'Szerokość:';
SWidthFix = 'znaki';
SAlignLeft = 'do lewej';
SAlignRight = 'do prawej';
SAlignCenter = 'wyśrodkuj';
const //for TSMDBFilterDialog
strEqual = 'równe';
strNonEqual = 'nie równe';
strNonMore = 'nie większe';
strNonLess = 'nie mniejsze';
strLessThan = 'mniejsze niż';
strLargeThan = 'większe niż';
strExist = 'puste';
strNonExist = 'nie puste';
strIn = 'na liście';
strBetween = 'między';
strLike = 'podobne do';
strOR = 'lub';
strAND = 'i';
strField = 'Pole';
strCondition = 'Warunek';
strValue = 'Wartość';
strAddCondition = ' Zdefiniuj dodatkowy warunek:';
strSelection = ' Zaznacz rekordy zgodne z warunkiem:';
strAddToList = 'Dodaj do listy';
strEditInList = 'Edytuj na liście';
strDeleteFromList = 'Usuń z listy';
strTemplate = 'Przykładowy dialog filtrowania';
strFLoadFrom = 'Otwórz z ...';
strFSaveAs = 'Zapisz jako..';
strFDescription = 'Opis';
strFFileName = 'Nazwa pliku';
strFCreate = 'Utworzono: %s';
strFModify = 'Zmodyfikowano: %s';
strFProtect = 'Tylko do odczytu';
strFProtectErr = 'Plik zabezpieczony przed zapisem!';
const //for SMDBNavigator
SFirstRecord = 'Pierwszy rekord';
SPriorRecord = 'Poprzedni rekord';
SNextRecord = 'Następny rekord';
SLastRecord = 'Ostatni rekord';
SInsertRecord = 'Wpisz rekord';
SCopyRecord = 'Kopiuj rekord';
SDeleteRecord = 'Usuń rekord';
SEditRecord = 'Edytuj rekord';
SFilterRecord = 'Filtry warunków';
SFindRecord = 'Szukaj rekordów';
SPrintRecord = 'Drukuj rekordy';
SExportRecord = 'Exportuj rekordy';
SImportRecord = 'Importuj rekordy';
SPostEdit = 'Zapisz zmiany';
SCancelEdit = 'Anuluj zmiany';
SRefreshRecord = 'Odśwież dane';
SChoice = 'Wybierz rekord';
SClear = 'Wyczyść wybrany rekord';
SDeleteRecordQuestion = 'Usunąć rekord?';
SDeleteMultipleRecordsQuestion = 'Napewno usunąć wybrane rekordy?';
SRecordNotFound = 'Nie znaleziono rekordu';
SFirstName = 'Pierwszy';
SPriorName = 'Poprzedni';
SNextName = 'Następny';
SLastName = 'Ostatni';
SInsertName = 'Wpisz';
SCopyName = 'Kopiuj';
SDeleteName = 'usuń';
SEditName = 'Edytuj';
SFilterName = 'Filtr';
SFindName = 'Znajdź';
SPrintName = 'Drukuj';
SExportName = 'Exportuj';
SImportName = 'Importuj';
SPostName = 'Zapisz';
SCancelName = 'Anuluj';
SRefreshName = 'Odśwież';
SChoiceName = 'Wybierz';
SClearName = 'Wyczyść';
SBtnOk = '&OK';
SBtnCancel = '&Anuluj';
SBtnLoad = 'Otwórz';
SBtnSave = 'Zapisz';
SBtnCopy = 'Kopiuj';
SBtnPaste = 'Wklej';
SBtnClear = 'Wyczyść';
SRecNo = 'rec.';
SRecOf = ' of ';
const //for EditTyped
etValidNumber = 'poprawny numer';
etValidInteger = 'poprawna liczba';
etValidDateTime = 'poprawna data\czas';
etValidDate = 'poprawna data';
etValidTime = 'poprawny czas';
etValid = 'poprawne';
etIsNot = 'nie jest';
etOutOfRange = 'Wartość %s jest z poza zakresu %s..%s';
//by RTS
SPrevYear = 'poprzedni rok';
SPrevMonth = 'poprzedni miesiąc';
SNextMonth = 'następny miesiąc';
SNextYear = 'następny rok';
SApplyAll = 'Zapisz wszystkie';
SNoDataToDisplay = '<Brak danych do wyświetlenia>';
implementation
end.
|
unit BenchmarkClassUnit;
interface
uses Windows;
type
{Benchmark categories}
TBenchmarkCategory = (
bmSingleThreadRealloc, bmMultiThreadRealloc, bmSingleThreadAllocAndFree,
bmMultiThreadAllocAndFree, bmSingleThreadReplay, bmMultiThreadReplay,
bmMemoryAccessSpeed);
TBenchmarkCategorySet = set of TBenchmarkCategory;
const
AllBenchmarkCategories: TBenchmarkCategorySet = [low(TBenchmarkCategory)..high(TBenchmarkCategory)];
type
{The benchmark class}
TFastcodeMMBenchmark = class
protected
{Indicates whether the benchmark can be run - or if a problem was
discovered, possibly during create}
FCanRunBenchmark: Boolean;
{The peak address space usage measured}
FPeakAddressSpaceUsage: Cardinal;
{Gets the memory overhead of the benchmark that should be subtracted}
function GetBenchmarkOverhead: Cardinal; virtual;
public
constructor CreateBenchmark; virtual;
{The tests - should return true if implemented}
procedure RunBenchmark; virtual;
{Resets the peak usage measurement}
procedure ResetUsageStatistics;
{Measures the address space usage and updates the peak value if the current
usage is greater}
procedure UpdateUsageStatistics;
{The name of the benchmark}
class function GetBenchmarkName: string; virtual;
{A description for the benchmark}
class function GetBenchmarkDescription: string; virtual;
{Gets the relative weight of the speed portion of the benchmark vs. the
peak address space usage portion in the calculation of relative
performance. The peak address space weight will be 1 - this value.
Valid range: 0.1 to 0.9, default 0.5}
class function GetSpeedWeight: Double; virtual;
{Gets the weight of this benchmark relative to all other benchmarks.
Valid range: 0 to 1.0, default 1.0}
class function GetBenchmarkWeight: Double; virtual;
{Should this benchmark be run by default?}
class function RunByDefault: boolean; virtual;
{Benchmark Category}
class function GetCategory: TBenchmarkCategory; virtual;
{The peak usage measured since the last reset}
property PeakAddressSpaceUsage: Cardinal read FPeakAddressSpaceUsage;
{Indicates whether the benchmark can be run - or if a problem was
discovered, possibly during create}
property CanRunBenchmark: Boolean read FCanRunBenchmark;
end;
TFastcodeMMBenchmarkClass = class of TFastcodeMMBenchmark;
const
{Benchmark category names}
BenchmarkCategoryNames: array[TBenchmarkCategory] of string = (
'Single Thread ReallocMem', 'Multi-threaded ReallocMem',
'Single Thread GetMem and FreeMem',
'Multi-threaded GetMem and FreeMem',
'Single Thread Replay',
'Multi-threaded Replay',
'Memory Access Speed');
var
{All the benchmarks}
Benchmarks: array of TFastcodeMMBenchmarkClass;
{The global weight for each benchmark}
GlobalBenchmarkWeights: array of double;
{Get the list of benchmarks}
procedure DefineBenchmarks;
{Get the global weights for all benchmarks}
procedure ComputeBenchmarkGlobalWeights;
implementation
uses FragmentationTestUnit, ReallocMemBenchmark, DownsizeTestUnit,
SmallUpsizeBenchmark, AddressSpaceCreepBenchmark,
ArrayUpsizeSingleThread, BlockSizeSpreadBenchmark,
LargeBlockSpreadBenchmark, NexusDBBenchmarkUnit,
RawPerformanceMultiThread, RawPerformanceSingleThread,
ReplayBenchmarkUnit, SmallDownsizeBenchmark, StringThreadTestUnit,
WildThreadsBenchmarkUnit, AddressSpaceCreepBenchmarkLarge,
DoubleFPBenchmark1Unit, DoubleFPBenchmark2Unit, DoubleFPBenchmark3Unit,
MoveBenchmark1Unit, MoveBenchmark2Unit,
SingleFPBenchmark1Unit, SingleFPBenchmark2Unit,
LinkedListBenchmark, BenchmarkUtilities, MemFreeBenchmark1Unit,
MemFreeBenchmark2Unit, FillCharMultiThreadBenchmark1Unit,
SortIntArrayBenchmark1Unit, SortExtendedArrayBenchmark1Unit,
MultiThreadedAllocAndFree, MultiThreadedReallocate,
SingleThreadedAllocAndFree, SingleThreadedReallocate,
SortIntArrayBenchmark2Unit, SortExtendedArrayBenchmark2Unit,
SingleThreadedAllocMem;
{ TFastcodeMMBenchmark }
procedure TFastcodeMMBenchmark.RunBenchmark;
begin
{We want reproducible results, so keep the same sequence of random numbers}
RandSeed := 0;
{Reset the peak usage statistic}
ResetUsageStatistics;
end;
class function TFastcodeMMBenchmark.GetBenchmarkName: string;
begin
Result := '(Unnamed)';
end;
constructor TFastcodeMMBenchmark.CreateBenchmark;
begin
inherited;
FCanRunBenchmark := True;
end;
procedure TFastcodeMMBenchmark.ResetUsageStatistics;
begin
FPeakAddressSpaceUsage := 0;
end;
procedure TFastcodeMMBenchmark.UpdateUsageStatistics;
var
LCurrentUsage: Cardinal;
begin
{Get the usage less the usage at program startup (before the MM was started).
The assumption here is that any static lookup tables used by the MM will be
small.}
LCurrentUsage := GetAddressSpaceUsed - GetBenchmarkOverhead;
{Update the peak usage}
if integer(LCurrentUsage) > integer(FPeakAddressSpaceUsage) then
FPeakAddressSpaceUsage := LCurrentUsage;
end;
class function TFastcodeMMBenchmark.GetBenchmarkDescription: string;
begin
Result := '';
end;
class function TFastcodeMMBenchmark.RunByDefault: boolean;
begin
Result := True;
end;
class function TFastcodeMMBenchmark.GetSpeedWeight: Double;
begin
Result := 0.5;
end;
class function TFastcodeMMBenchmark.GetBenchmarkWeight: Double;
begin
Result := 1;
end;
function TFastcodeMMBenchmark.GetBenchmarkOverhead: Cardinal;
begin
{Return the address space usage on startup}
Result := InitialAddressSpaceUsed;
end;
{---------------------Initialization functions-------------------}
procedure AddBenchMark(ABenchmarkClass: TFastcodeMMBenchmarkClass);
var
i: integer;
begin
i := Length(Benchmarks);
SetLength(Benchmarks, i + 1);
Benchmarks[i] := ABenchmarkClass;
end;
procedure DefineBenchmarks;
begin
// first all single-thread benchmarks that execute in the application's main thread...
AddBenchMark(TFragmentationTest);
AddBenchMark(TReallocBench);
AddBenchMark(TDownsizeTest);
AddBenchMark(TSmallUpsizeBench);
AddBenchMark(TSmallDownsizeBench);
AddBenchMark(TBlockSizeSpreadBench);
AddBenchMark(TRawPerformanceSingleThread);
AddBenchMark(TAddressSpaceCreepBench);
AddBenchMark(TLargeBlockSpreadBench);
AddBenchMark(TArrayUpsizeSingleThread);
AddBenchMark(TAddressSpaceCreepBenchLarge);
AddBenchMark(TSingleThreadReallocateBenchmark);
AddBenchMark(TSingleThreadAllocateAndFreeBenchmark);
AddBenchMark(TReservationsSystemBenchmark);
AddBenchMark(TXMLParserBenchmark);
AddBenchMark(TDocumentClassificationBenchmark);
// ...then all the benchmarks that create TThread descendants
AddBenchMark(TSingleFPThreads);
AddBenchMark(TSingleFPThreads2);
AddBenchMark(TDoubleFPThreads1);
AddBenchMark(TDoubleFPThreads2);
AddBenchMark(TDoubleFPThreads3);
AddBenchMark(TMoveThreads1);
AddBenchMark(TMoveThreads2);
AddBenchMark(TFillCharThreads);
AddBenchMark(TSortIntArrayThreads);
AddBenchMark(TSortExtendedArrayThreads);
AddBenchMark(TMemFreeThreads1);
AddBenchMark(TMemFreeThreads2);
AddBenchMark(TLinkedListBench);
AddBenchMark(TMultiThreadAllocateAndFreeBenchmark);
AddBenchMark(TMultiThreadReallocateBenchmark);
AddBenchMark(TQuickSortIntArrayThreads);
AddBenchMark(TQuickSortExtendedArrayThreads);
//AddBenchMark(TNexusBenchmark1Thread);
//AddBenchMark(TNexusBenchmark2Threads);
//AddBenchMark(TNexusBenchmark4Threads);
//AddBenchMark(TNexusBenchmark8Threads);
//AddBenchMark(TWildThreads);
//AddBenchMark(TRawPerformanceMultiThread);
//AddBenchMark(TManyThreadsTest);
//AddBenchMark(TStringThreadTest);
//AddBenchMark(TeLinkBenchmark);
//AddBenchMark(TeLinkComServerBenchmark);
//AddBenchMark(TWebbrokerReplayBenchmark);
//AddBenchMark(TBeyondCompareBenchmark);
//AddBenchMark(TSingleThreadAllocMemBenchmark);
{End of benchmark list}
AddBenchMark(TReplayBenchmark); // not active by default, added so you can run your own replays
end;
procedure ComputeBenchmarkGlobalWeights;
const
{PLR 6/5/2005 changed weights: Multi-threaded weights were IMO
disproportionately high vs. single threaded. Having multithreaded benchmarks
carry more than 50% more weight than single-threaded benchmarks is not
realistic?! Should it be exactly balanced?}
WeightPerCategory: array[TBenchmarkCategory] of Double = (
{If your application reallocs a lot in speed-critical code then it is badly
written (hence the low weight)}
0.08, //bmSingleThreadRealloc
0.11, //bmMultiThreadRealloc
{Alloc and free is the typical behaviour of most apps}
0.10, //bmSingleThreadAllocAndFree
0.14, //bmMultiThreadAllocAndFree
{Replays count the most (this is the closest to real-world behaviour we've
got at the moment, although memory is not actually "used")}
0.20, //bmSingleThreadReplay
0.29, //bmMultiThreadReplay
{Some anomalies with some of the current speed tests precludes using a
bigger weight.}
0.08 //bmMemoryAccessSpeed
);
var
i: integer;
WeightSumArray: array[TBenchmarkCategory] of Double;
Category: TBenchmarkCategory;
begin
// compute sum of relative weights within each category
FillChar(WeightSumArray, SizeOf(WeightSumArray), 0);
for i := 0 to high(Benchmarks) do begin
if Benchmarks[i].RunByDefault then begin
Category := Benchmarks[i].GetCategory;
WeightSumArray[Category] := WeightSumArray[Category] + Benchmarks[i].GetBenchmarkWeight;
end;
end;
// compute global weight in accordance with array WeightPerCategory
SetLength(GlobalBenchmarkWeights, Length(Benchmarks));
for i := 0 to high(Benchmarks) do begin
Category := Benchmarks[i].GetCategory;
if WeightSumArray[Category] = 0 then
GlobalBenchmarkWeights[i] := 0
else
GlobalBenchmarkWeights[i] := Benchmarks[i].GetBenchmarkWeight * WeightPerCategory[Category] / WeightSumArray[Category];
end;
end;
class function TFastcodeMMBenchmark.GetCategory: TBenchmarkCategory;
begin
Result := bmMemoryAccessSpeed;
end;
initialization
{Get the list of benchmarks}
DefineBenchmarks;
{Get the global weights for all benchmarks}
ComputeBenchmarkGlobalWeights;
end.
|
unit BillContentQry;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ProductsBaseQuery0, 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, DSWrap,
BillContentQuerySimple, SearchStorehouseProduct, BillInterface,
NotifyEvents, StoreHouseListQuery, BillContentInterface;
type
TBillContW = class(TBaseProductsW)
private
FAmount: TFieldWrap;
FBillContentID: TFieldWrap;
FBillID: TFieldWrap;
FSaleCount: TFieldWrap;
FSaleD: TFieldWrap;
FSaleE: TFieldWrap;
FSaleR: TFieldWrap;
protected
procedure InitFields; override;
public const
VirtualIDOffset = -100000;
constructor Create(AOwner: TComponent); override;
function GetStorehouseProductID(AVirtualID: Integer): Integer;
property Amount: TFieldWrap read FAmount;
property BillContentID: TFieldWrap read FBillContentID;
property BillID: TFieldWrap read FBillID;
property SaleCount: TFieldWrap read FSaleCount;
property SaleD: TFieldWrap read FSaleD;
property SaleE: TFieldWrap read FSaleE;
property SaleR: TFieldWrap read FSaleR;
end;
TQueryBillContent = class(TQryProductsBase0, IBillContent)
private
FAfterLoad: TNotifyEventsEx;
FqBillContentSimple: TQueryBillContentSimple;
FqSearchStorehouseProduct: TQuerySearchStorehouseProduct;
FW: TBillContW;
function GetqBillContentSimple: TQueryBillContentSimple;
function GetqSearchStorehouseProduct: TQuerySearchStorehouseProduct;
{ Private declarations }
protected
procedure ApplyDelete(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;
property qBillContentSimple: TQueryBillContentSimple
read GetqBillContentSimple;
property qSearchStorehouseProduct: TQuerySearchStorehouseProduct
read GetqSearchStorehouseProduct;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AfterConstruction; override;
procedure CalcelAllShip;
procedure CancelShip;
procedure LoadContent(ABillID: Integer);
procedure Ship;
procedure ShipAll;
property AfterLoad: TNotifyEventsEx read FAfterLoad;
property W: TBillContW read FW;
{ Public declarations }
end;
implementation
uses
StrHelper, ProjectConst;
{$R *.dfm}
constructor TQueryBillContent.Create(AOwner: TComponent);
begin
inherited;
FW := FDSWrap as TBillContW;
DetailParameterName := W.BillID.FieldName;
FAfterLoad := TNotifyEventsEx.Create(Self);
// Будем сами обновлять запись
FDQuery.OnUpdateRecord := DoOnQueryUpdateRecord;
end;
destructor TQueryBillContent.Destroy;
begin
inherited;
FreeAndNil(FAfterLoad);
end;
procedure TQueryBillContent.AfterConstruction;
begin
// Сохраняем первоначальный SQL
inherited;
// Добавляем в SQL запрос параметр - идентификатор счёта
FDQuery.SQL.Text := ReplaceInSQL(SQL, Format('%s = :%s', [W.BillID.FullName,
W.BillID.FieldName]), 0);
SetParamType(W.BillID.FieldName);
end;
procedure TQueryBillContent.ApplyDelete(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
begin
Assert(ASender = FDQuery);
// Удаление позиции заказа - это отмена позиции заказа, но не удаление товара со склада
// Ищем и удаляем сам контент из счёта
if qBillContentSimple.SearchByID(W.BillContentID.F.AsInteger) = 1 then
qBillContentSimple.FDQuery.Delete;
end;
procedure TQueryBillContent.ApplyUpdate(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
begin
Assert(ASender = FDQuery);
Assert(W.PK.Value < 0);
(*
// Если изменилось кол-во продаж
if W.SaleCount.F.OldValue <> W.SaleCount.F.Value then
begin
// Ищем содержимое счёта
if qBillContentSimple.SearchByID(W.FBillContentID.F.AsInteger) = 0 then
begin
AAction := eaFail;
Exit;
end;
// Обновляем информацию о количестве товаров в контенте счёта
qBillContentSimple.W.TryEdit;
qBillContentSimple.W.SaleCount.F.Value := W.SaleCount.F.AsFloat;
qBillContentSimple.W.TryPost;
end;
*)
// Если изменилось кол-во товара на складе (отгрузили товар)
if W.Amount.F.OldValue <> W.Amount.F.Value then
begin
// Ищем по идентификатору связки склад-продукт
if qSearchStorehouseProduct.SearchByID
(W.GetStorehouseProductID(W.PK.Value)) = 0 then
begin
AAction := eaFail;
Exit;
end;
// Обновляем информацию о количестве товара на складе
qSearchStorehouseProduct.W.TryEdit;
qSearchStorehouseProduct.W.Amount.F.AsFloat := W.Amount.F.AsFloat;
qSearchStorehouseProduct.W.TryPost;
end;
end;
procedure TQueryBillContent.CalcelAllShip;
begin
FDQuery.DisableControls;
try
try
W.SaveBookmark;
FDQuery.First;
while not FDQuery.Eof do
begin
CancelShip;
FDQuery.Next;
end;
W.RestoreBookmark;
ApplyUpdates;
except
CancelUpdates;
raise;
end;
finally
FDQuery.EnableControls;
end;
end;
procedure TQueryBillContent.CancelShip;
begin
if qSearchStorehouseProduct.SearchByID(W.GetStorehouseProductID(W.PK.Value)) = 0
then
raise Exception.Create('Ошибка при поиске товара на складе');
// Увеличиваем кол-во товара на складе в нашем наборе данных
W.TryEdit;
W.Amount.F.AsFloat := qSearchStorehouseProduct.W.Amount.F.AsFloat +
W.SaleCount.F.AsFloat;
W.TryPost;
end;
function TQueryBillContent.CreateDSWrap: TDSWrap;
begin
Result := TBillContW.Create(FDQuery);
end;
function TQueryBillContent.GetqBillContentSimple: TQueryBillContentSimple;
begin
if FqBillContentSimple = nil then
begin
FqBillContentSimple := TQueryBillContentSimple.Create(Self);
end;
Result := FqBillContentSimple;
end;
function TQueryBillContent.GetqSearchStorehouseProduct
: TQuerySearchStorehouseProduct;
begin
if FqSearchStorehouseProduct = nil then
FqSearchStorehouseProduct := TQuerySearchStorehouseProduct.Create(Self);
Result := FqSearchStorehouseProduct;
end;
procedure TQueryBillContent.LoadContent(ABillID: Integer);
begin
if ABillID > 0 then
begin
TryLoad2(ABillID);
FAfterLoad.CallEventHandlers(Self);
end
else
FDQuery.Close;
end;
procedure TQueryBillContent.Ship;
begin
if qSearchStorehouseProduct.SearchByID(W.GetStorehouseProductID(W.PK.Value)) = 0
then
raise Exception.Create('Ошибка при поиске товара на складе');
if qSearchStorehouseProduct.W.Amount.F.AsFloat < W.SaleCount.F.AsFloat then
raise Exception.Create(sIsNotEnoughProductAmount);
// Уменьшаем кол-во товара на складе в нашем наборе данных
W.TryEdit;
W.Amount.F.AsFloat := qSearchStorehouseProduct.W.Amount.F.AsFloat -
W.SaleCount.F.AsFloat;
W.TryPost;
end;
procedure TQueryBillContent.ShipAll;
begin
FDQuery.DisableControls;
try
try
W.SaveBookmark;
FDQuery.First;
while not FDQuery.Eof do
begin
Ship;
FDQuery.Next;
end;
W.RestoreBookmark;
ApplyUpdates;
except
CancelUpdates;
raise;
end;
finally
FDQuery.EnableControls;
end;
end;
constructor TBillContW.Create(AOwner: TComponent);
begin
inherited;
FBillID := TFieldWrap.Create(Self, 'bc.BillID');
FBillContentID := TFieldWrap.Create(Self, 'BillContentID');
FAmount := TFieldWrap.Create(Self, 'sp.Amount');
FSaleCount := TFieldWrap.Create(Self, 'bc.SaleCount');
FSaleR := TFieldWrap.Create(Self, 'SaleR');
FSaleD := TFieldWrap.Create(Self, 'SaleD');
FSaleE := TFieldWrap.Create(Self, 'SaleE');
end;
function TBillContW.GetStorehouseProductID(AVirtualID: Integer): Integer;
begin
Assert(AVirtualID < VirtualIDOffset);
Result := (AVirtualID * -1) + VirtualIDOffset;
end;
procedure TBillContW.InitFields;
begin
inherited;
SetDisplayFormat([SaleR.F, SaleD.F, SaleE.F]);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC wait time user interface }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.VCLUI.Wait;
interface
implementation
uses
System.Classes, System.SysUtils, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls,
FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.Factory,
FireDAC.UI.Intf, FireDAC.UI;
{-------------------------------------------------------------------------------}
{- TFDGUIxVCLWaitCursorImpl -}
{-------------------------------------------------------------------------------}
type
TFDGUIxVCLWaitCursorImpl = class(TFDGUIxVisualWaitCursorImplBase)
private
function CheckGetCursor(out ACrs: TCursor): Boolean;
protected
function CheckCurCursor: Boolean; override;
function InternalHideCursor: Boolean; override;
procedure InternalShowCursor; override;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxVCLWaitCursorImpl.CheckGetCursor(out ACrs: TCursor): Boolean;
begin
case FWaitCursor of
gcrDefault: ACrs := crDefault;
gcrHourGlass: ACrs := crHourGlass;
gcrSQLWait: ACrs := crSQLWait;
gcrAppWait: ACrs := crAppStart;
else ACrs := crNone;
end;
Result := ACrs <> crNone;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxVCLWaitCursorImpl.CheckCurCursor: Boolean;
var
iCrs: TCursor;
begin
Result := (Screen <> nil) and CheckGetCursor(iCrs) and (Screen.Cursor = iCrs);
end;
{-------------------------------------------------------------------------------}
function TFDGUIxVCLWaitCursorImpl.InternalHideCursor: Boolean;
begin
Result := Screen <> nil;
if Result then
Screen.Cursor := crDefault;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxVCLWaitCursorImpl.InternalShowCursor;
var
iCrs: TCursor;
begin
if CheckGetCursor(iCrs) then
Screen.Cursor := iCrs;
end;
{-------------------------------------------------------------------------------}
function CheckGuiRunning: Boolean;
begin
Result := (Application <> nil) and not Application.Terminated;
end;
{-------------------------------------------------------------------------------}
{- TFDGUIxVCLTimerImpl -}
{-------------------------------------------------------------------------------}
type
TFDGUIxVCLTimerImpl = class(TFDGUIxObject, IFDGUIxTimer)
private
FTimer: TTimer;
protected
// IFDGUIxTimer
function GetEnabled: Boolean;
procedure SetEnabled(AValue: Boolean);
procedure SetEvent(AProc: TNotifyEvent; ATimeout: LongWord);
public
procedure Initialize; override;
destructor Destroy; override;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxVCLTimerImpl.Initialize;
begin
inherited Initialize;
FTimer := TTimer.Create(nil);
end;
{-------------------------------------------------------------------------------}
destructor TFDGUIxVCLTimerImpl.Destroy;
begin
FDFreeAndNil(FTimer);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxVCLTimerImpl.GetEnabled: Boolean;
begin
Result := FTimer.Enabled;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxVCLTimerImpl.SetEnabled(AValue: Boolean);
begin
FTimer.Enabled := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxVCLTimerImpl.SetEvent(AProc: TNotifyEvent; ATimeout: LongWord);
begin
FTimer.Interval := ATimeout;
FTimer.OnTimer := AProc;
end;
{-------------------------------------------------------------------------------}
var
oFact1: TFDFactory;
oFact2: TFDFactory;
initialization
oFact1 := TFDSingletonFactory.Create(TFDGUIxVCLWaitCursorImpl, IFDGUIxWaitCursor,
C_FD_GUIxFormsProvider);
oFact2 := TFDMultyInstanceFactory.Create(TFDGUIxVCLTimerImpl, IFDGUIxTimer,
C_FD_GUIxFormsProvider);
GCheckGuiRunning := CheckGuiRunning;
finalization
FDReleaseFactory(oFact1);
FDReleaseFactory(oFact2);
end.
|
unit pVDLogger;
interface
uses
System.SysUtils, System.IOUtils, System.Classes, {fgMemoDisplay,} WinAPI.Windows,
pVDEtc;
type
TLogSource = (lsUtility, lsDiscovery, lsAuthenticate, lsTokenExchange, lsTokenRefresh);
TLogSources = set of TLogSource;
SLogSource = String;
ELogFileError = class(Exception);
ELogFileNoParams = class(ELogFileError);
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
TVDLogger = class(TComponent)
private
FLogFileName: TFileName;
FLogFile: TFileStream;
FLogFilePath: TFileName;
FEtc: TVDEtc;
procedure SetLogFileName(const Value: TFileName);
procedure SetLogFile(const Value: TFileStream);
procedure SetLogFilePath(const Value: TFileName);
procedure SetEtc(const Value: TVDEtc);
procedure CalcLogFileLocs(const AEtc: TVDEtc);
property LogFile: TFileStream read FLogFile write SetLogFile;
protected
function FormatLogHeader(const ATimeStamp: TDateTime; ALogSource: TLogSource): String;
procedure Loaded; override;
public
procedure LogStrings(const ALogSource: TLogSource; const AMsgText: TStringList); overload;
procedure LogStrings(const ALogSource: TLogSource; const AMsgText: TStrings); overload;
procedure LogLine(const ALogSource: TLogSource; const AMsgLine: array of String);
procedure ShowLog;
function CycleLogfile: Boolean;
function GetLogFilePath: TFileName;
function GetLogFileName: TFileName;
property LogFileName: TFileName read GetLogFileName write SetLogFileName;
property LogFilePath: TFileName read GetLogFilePath write SetLogFilePath;
constructor Create(AOwner: TComponent); override;
published
property Etc: TVDEtc read FEtc write SetEtc;
end;
const
SLogSources: array [TLogSource] of String = ('Utility', 'Discovery Document', 'Authenticate', 'Token Exchange', 'Token Refresh');
implementation
uses
System.DateUtils, VCL.Dialogs, VCL.Forms, fmVDLogger;
{ TVDLogger }
{ Application constants are universally specified in the Etc component. This
retrieves the values for the log path and file name for ongoing use. }
procedure TVDLogger.CalcLogFileLocs(const AEtc: TVDEtc);
begin
try
if not Assigned(AEtc) then // be sure Etc component is assigned
raise ELogFileNoParams.Create('Missing reference to Etc component.');
with AEtc do // need Vendor, App and Filename
begin // create the filename and path
LogFilePath := TPath.Combine(TPath.Combine(GetHomePath, Vendor), App);
LogFileName := TPath.Combine(LogFilePath, LogFile);
end;
except
on E: ELogFileNoParams do // missing etc component
MessageDlg(E.Message, mtError, [mbOK], 0); // inform tdhe usere
end;
end;
constructor TVDLogger.Create(AOwner: TComponent);
begin
inherited Create(AOwner); // not much to see here
end;
{ To start a new log file the old file is simply renamed with the current timestamp.
The next attempt to make a log entry will simply create a new log file. }
function TVDLogger.CycleLogfile: Boolean;
var
LNewName: TFileName;
LBasicFilename: TFileName;
LFormatSettings: TFormatSettings;
begin
LBasicFilename := TPath.GetFileNameWithoutExtension(LogFileName);
LFormatSettings := TFormatSettings.Create;
LFormatSettings.DateSeparator := '-';
LFormatSettings.TimeSeparator := '-';
LFormatSettings.ShortDateFormat := 'yyyy-mm-dd';
LFormatSettings.LongTimeFormat := 'hh-nn-ss';
LBasicFilename := DateTimeToStr(Now(), LFormatSettings) + ' ' + LBasicFilename + '.log';
LNewName := TPath.Combine(LogFilePath, LBasicFilename);
if RenameFile(LogFileName, LNewName) then
Result := True
else
Result := False;
end;
{ Formatting the log source converts the enumeration received to a readable string. The
Timestamp is formatted as an ISO8601 date and time. }
function TVDLogger.FormatLogHeader(const ATimeStamp: TDateTime; ALogSource: TLogSource): String;
const
LLogHeaderMask: String = '**** %s; Source: %s'; // format string
begin // is this thread safe?
Result := Format(LLogHeaderMask, [DateToISO8601(ATimeStamp, False), SLogSources[ALogSource]]);
end;
function TVDLogger.GetLogFileName: TFileName;
begin
Result := FLogFileName; // return the log filename already determined
end;
function TVDLogger.GetLogFilePath: TFileName;
begin
Result := FLogFilePath; // return the log path already determined
end;
{ Now that all components have been loaded we can obtain the full path and file
name of the log file from the Etc component. }
procedure TVDLogger.Loaded;
begin
Inherited;
CalcLogFileLocs(Etc); // obtain and save the log file path and file name
end;
{ Logging a series of single lines causes a stringlist to be built. Then the LogText procedure is
invoked that will add a header line and save the completed entry to the log file. }
procedure TVDLogger.LogLine(const ALogSource: TLogSource; const AMsgLine: array of String);
var
LMessageList: TStringList; // work list
LMessageLine: String; // for iteration
begin
LMessageList := TStringList.Create; // create the work list
try
for LMessageLine in AMsgLine do // prdocess each line of the input arrayi
LMessageList.Add(LMessageLine); // add the line to the stringlist
LogStrings(ALogSource, LMessageList); // invoke the log list procedure
finally
LMessageList.Free; // return the resource
end;
end;
{ This overload is intended primarily as a workaround for handling TMemo lines, that
are actually TMemoStrings, not TStrings. TMemoStrings do not handle TrailingLineBreak
correctly (it is completely ignored). Hence we need to build a real TStringList
for submission tdo the LogStrings Routine. }
procedure TVDLogger.LogStrings(const ALogSource: TLogSource;
const AMsgText: TStrings);
var
LStringList: TStringList; // string list to receive input lines
begin
LStringList := TStringList.Create; // create the string list
try
LStringList.Assign(AMsgText); // assign the input lines to the stringlist
LogStrings(ALogSource, LStringList); // invoke the logging routine using the new list
finally
LStringList.Free; // return resources after all done
end;
end;
{ General purpose routine that logs a stringlist. Note that the so-called TStrings of a TMemo
are not suitable for this routine. The overloaded method that accepts TStrings should be used
instead. }
procedure TVDLogger.LogStrings(const ALogSource: TLogSource; const AMsgText: TStringList);
var
LMode: Word; // log file mode
LMsgTimeStamp: String; // time stamp appended as first line
begin
if not FileExists(LogFileName) then // check for presence of existing log file
begin
ForceDirectories(LogFilePath); // if no file, ensure the path exists
LMode := fmCreate; // create the file since none exists
end
else
LMode := fmOpenReadWrite; // if file exists, simply append
LogFile := TFileStream.Create(LogFileName, LMode or fmShareDenyWrite); // create the stream writer
try
LogFile.Seek(0, soFromEnd); // position at the end of the file
LMsgTimeStamp := FormatLogHeader(Now(), ALogSource); // format the timestamp (local time)
AMsgText.Insert(0, LMsgTimeStamp); // insert the timestamp as the first line
AMsgText.SaveToStream(LogFile, TEncoding.UTF8); // write the completed set of lines to the log
finally
LogFile.Free; // return resources
end;
end;
procedure TVDLogger.SetEtc(const Value: TVDEtc);
begin
FEtc := Value;
end;
procedure TVDLogger.SetLogFile(const Value: TFileStream);
begin
FLogFile := Value;
end;
procedure TVDLogger.SetLogFileName(const Value: TFileName);
begin
FLogFileName := Value;
end;
procedure TVDLogger.SetLogFilePath(const Value: TFileName);
begin
FLogFilePath := Value;
end;
{ Display the current log file in a read-only memo box. The current log
file name is stored as a property of the class. }
procedure TVDLogger.ShowLog;
var
LgMemoDisplay: tgLogger; // pointer to the form for display
begin
if FileExists(LogFileName) then // first make sure we actually have a log file
begin
LgMemoDisplay := tgLogger.CreateLog(Self, LogFileName);
// LgMemoDisplay := TgMemoDisplay.CreateAux(Self, LogFileName); // create the window
LgMemoDisplay.Show; // show triggers the log file retrieval
end
else
ShowMessage('There is no current log file.'); // inform the user if there is no current log file
end;
end.
|
unit keccak_n;
{Basic Keccak functions using NIST API}
interface
{$i STD.INC}
(*************************************************************************
DESCRIPTION : Basic Keccak functions using NIST API
REQUIREMENTS : TP5-7, D1-D7/D9-D12, FPC, VP, WDOSX
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : http://keccak.noekeon.org/KeccakReferenceAndOptimized-3.2.zip
http://keccak.noekeon.org/KeccakKAT-3.zip (17MB)
http://csrc.nist.gov/groups/ST/hash/documents/SHA3-C-API.pdf
REMARKS : The current implementation needs little-endian machines
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.01 17.10.12 W.Ehrhardt Initial BP7 version from Keccak-simple32BI.c
0.02 18.10.12 we Fixed buf in xorIntoState
0.03 18.10.12 we Other compilers
0.04 19.10.12 we Separate unit
0.05 20.10.12 we Functions from KeccakSponge
0.06 21.10.12 we Functions from KeccakNISTInterface
0.07 21.10.12 we D2-D6 with ASM RotL function
0.08 22.10.12 we Include files keccperm.i16 and .i32
0.09 22.10.12 we __P2I type casts removed
0.10 22.10.12 we References, comments, remarks
0.11 25.10.12 we Make partialBlock longint
0.12 30.10.12 we Packed arrays, type TKDQueue
0.13 31.10.12 we Partially unrolled 64-bit code from Keccak-inplace.c
0.14 01.11.12 we Compact 64-bit code from Botan
0.15 02.11.12 we 64-bit code about 20% faster with local data
0.16 09.11.12 we KeccakFullBytes, TKeccakMaxDigest
0.17 12.11.12 we USE32BIT forces skipping of 64-bit code
*************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2012 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
---------------------------------------------------------------------------
*NOTE FROM THE DESIGNERS OF KECCAK*
The Keccak sponge function, designed by Guido Bertoni, Joan Daemen,
Michael Peeters and Gilles Van Assche. For more information, feedback or
questions, please refer to our website: http://keccak.noekeon.org/
Implementation by the designers (and Ronny Van Keer), hereby denoted
as "the implementer".
To the extent possible under law, the implementer has waived all copyright
and related or neighboring rights to the source code in this file.
http://creativecommons.org/publicdomain/zero/1.0/
----------------------------------------------------------------------------*)
uses
BTypes;
const
SUCCESS = 0;
FAIL = 1;
BAD_HASHLEN = 2; {Return results}
const
KeccakPermutationSize = 1600;
KeccakMaximumRate = 1536;
KeccakPermutationSizeInBytes = KeccakPermutationSize div 8;
KeccakMaximumRateInBytes = KeccakMaximumRate div 8;
type
TState_B = packed array[0..KeccakPermutationSizeInBytes-1] of byte;
TState_L = packed array[0..(KeccakPermutationSizeInBytes) div 4 - 1] of longint;
TKDQueue = packed array[0..KeccakMaximumRateInBytes-1] of byte;
type
TSpongeState = record
state: TState_B;
dataQueue: TKDQueue;
rate: integer;
capacity: integer;
bitsInQueue: integer;
fixedOutputLength: integer;
bitsAvailableForSqueezing: integer;
squeezing: integer;
end;
type
THashState = TSpongeState; {Hash state context}
type
TKeccakMaxDigest = packed array[0..63] of byte; {Keccak-512 digest}
function Init(var state: THashState; hashbitlen: integer): integer;
{-Initialize the state of the Keccak[r, c] sponge function. The rate r and}
{ capacity c values are determined from hashbitlen = number of digest bits}
{ or 0 for Keccak with default parameters and arbitrarily-long output. The}
{ allowed fixed length values are 224, 256, 384, and 512. Result 0=success}
function Update(var state: THashState; data: pointer; databitlen: longint): integer;
{-Update state with databitlen bits from data. May be called multiple times, }
{ only the last databitlen may be a non-multiple of 8 (the corresponding byte}
{ must be MSB aligned, i.e. in the (databitlen and 7) most significant bits. }
function Final(var state: THashState; hashval: pointer): integer;
{-Compute Keccak hash digest and store into hashval. The hashbitlen from }
{ init is used (If zero, the squeeze function must be must to extract the}
{ the arbitrarily-length output. Result = 0 if successful.}
function Squeeze(var state: THashState; output: pointer; outputLength: longint): integer;
{-Squeeze output data from the sponge function. If the sponge function was }
{ in the absorbing phase, this function switches it to the squeezing phase.}
{ Returns 0 if successful, 1 otherwise. output: pointer to the buffer where}
{ tt store the output data; outputLength: number of output bits desired, }
{ must be a multiple of 8.}
function KeccakFullBytes(HashBitlen: integer; data: pointer; datalen: longint; hashval: pointer): integer;
{-Compute Keccak hash from inlen bytes and store into hashval}
implementation
const
cKeccakNumberOfRounds = 24;
{---------------------------------------------------------------------------}
{Helper types}
{$ifndef BIT16}
type
TBABytes = array[0..MaxLongint-1] of byte;
{$else}
type
TBABytes = array[0..$FFF0-1] of byte;
{$endif}
type
PBA = ^TBABytes;
{$ifndef USE32BIT}
{$ifdef HAS_INT64}
{$ifdef HAS_INLINE}
{$define USE_64BITCODE}
{$endif}
{$endif}
{$endif}
{.$define USE_64BITCODE}
{---------------------------------------------------------------------------}
{$ifndef BIT16}
{$ifdef USE_64BITCODE}
{$i kperm_64.inc}
{$ifdef HAS_MSG}
{$message '* using 64-bit code'}
{$endif}
{$else}
{$i kperm_32.inc}
{$endif}
{$else}
{$i kperm_16.inc}
{$endif}
{---------------------------------------------------------------------------}
procedure KeccakInitialize;
begin
{nothing to do in this implementation}
end;
{---------------------------------------------------------------------------}
procedure KeccakInitializeState(var state: TState_B);
begin
fillchar(state, sizeof(state), 0);
end;
{---------------------------------------------------------------------------}
procedure KeccakF(var state: TState_L; inp: pointer; laneCount: integer);
begin
xorIntoState(state,inp,laneCount);
KeccakPermutation(state);
end;
{---------------------------------------------------------------------------}
procedure KeccakAbsorb(var state: TState_B; data: pointer; laneCount: integer);
begin
KeccakF(TState_L(state), data, laneCount);
end;
{---------------------------------------------------------------------------}
function InitSponge(var state: TSpongeState; rate, capacity: integer): integer;
{-Function to initialize the state of the Keccak sponge function.}
{ The sponge function is set to the absorbing phase. Result=0 if }
{ success, 1 if rate and/or capacity are invalid.}
begin
InitSponge := 1;
if rate+capacity <> 1600 then exit;
if (rate <= 0) or (rate >= 1600) or ((rate and 63) <> 0) then exit;
KeccakInitialize;
state.rate := rate;
state.capacity := capacity;
state.fixedOutputLength := 0;
KeccakInitializeState(state.state);
fillchar(state.dataQueue, KeccakMaximumRateInBytes,0);
state.bitsInQueue := 0;
state.squeezing := 0;
state.bitsAvailableForSqueezing := 0;
InitSponge := 0;
end;
{---------------------------------------------------------------------------}
procedure AbsorbQueue(var state: TSpongeState);
{-Absorb remaining bits from queue}
begin
{state.bitsInQueue is assumed to be equal to state.rate}
KeccakAbsorb(state.state, @state.dataQueue, state.rate div 64);
state.bitsInQueue := 0;
end;
{---------------------------------------------------------------------------}
function Absorb(var state: TSpongeState; data: pointer; databitlen: longint): integer;
{-Function to give input data for the sponge function to absorb}
var
i, j, wholeBlocks, partialBlock: longint;
partialByte: integer;
curData: pByte;
begin
Absorb := 1;
if state.bitsInQueue and 7 <> 0 then exit; {Only the last call may contain a partial byte}
if state.squeezing<>0 then exit; {Too late for additional input}
i := 0;
while i < databitlen do begin
if ((state.bitsInQueue=0) and (databitlen >= state.rate) and (i <= (databitlen-state.rate))) then begin
wholeBlocks := (databitlen-i) div state.rate;
curData := @PBA(data)^[i div 8];
j := 0;
while j<wholeBlocks do begin
KeccakAbsorb(state.state, curData, state.rate div 64);
inc(j);
inc(Ptr2Inc(curData), state.rate div 8);
end;
inc(i, wholeBlocks*state.rate);
end
else begin
partialBlock := databitlen - i;
if partialBlock+state.bitsInQueue > state.rate then begin
partialBlock := state.rate - state.bitsInQueue;
end;
partialByte := partialBlock and 7;
dec(partialBlock, partialByte);
move(PBA(data)^[i div 8], state.dataQueue[state.bitsInQueue div 8], partialBlock div 8);
inc(state.bitsInQueue, partialBlock);
inc(i, partialBlock);
if state.bitsInQueue=state.rate then AbsorbQueue(state);
if partialByte > 0 then begin
state.dataQueue[state.bitsInQueue div 8] := PBA(data)^[i div 8] and ((1 shl partialByte)-1);
inc(state.bitsInQueue, partialByte);
inc(i, partialByte);
end;
end;
end;
Absorb := 0;
end;
{---------------------------------------------------------------------------}
procedure PadAndSwitchToSqueezingPhase(var state: TSpongeState);
var
i: integer;
begin
{Note: the bits are numbered from 0=LSB to 7=MSB}
if (state.bitsInQueue + 1 = state.rate) then begin
i := state.bitsInQueue div 8;
state.dataQueue[i] := state.dataQueue[i] or (1 shl (state.bitsInQueue and 7));
AbsorbQueue(state);
fillchar(state.dataQueue, state.rate div 8, 0);
end
else begin
i := state.bitsInQueue div 8;
fillchar(state.dataQueue[(state.bitsInQueue+7) div 8], state.rate div 8 - (state.bitsInQueue+7) div 8,0);
state.dataQueue[i] := state.dataQueue[i] or (1 shl (state.bitsInQueue and 7));
end;
i := (state.rate-1) div 8;
state.dataQueue[i] := state.dataQueue[i] or (1 shl ((state.rate-1) and 7));
AbsorbQueue(state);
extractFromState(@state.dataQueue, TState_L(state.state), state.rate div 64);
state.bitsAvailableForSqueezing := state.rate;
state.squeezing := 1;
end;
{---------------------------------------------------------------------------}
function Squeeze(var state: THashState; output: pointer; outputLength: longint): integer;
{-Squeeze output data from the sponge function. If the sponge function was }
{ in the absorbing phase, this function switches it to the squeezing phase.}
{ Returns 0 if successful, 1 otherwise. output: pointer to the buffer where}
{ to store the output data; outputLength: number of output bits desired, }
{ must be a multiple of 8.}
var
i: longint;
partialBlock: integer;
begin
Squeeze := 1;
if state.squeezing=0 then PadAndSwitchToSqueezingPhase(state);
if outputLength and 7 <> 0 then exit; {Only multiple of 8 bits are allowed, truncation can be done at user level}
i := 0;
while i < outputLength do begin
if state.bitsAvailableForSqueezing=0 then begin
KeccakPermutation(TState_L(state.state));
extractFromState(@state.dataQueue, TState_L(state.state), state.rate div 64);
state.bitsAvailableForSqueezing := state.rate;
end;
partialBlock := state.bitsAvailableForSqueezing;
if partialBlock > outputLength - i then partialBlock := outputLength - i;
move(state.dataQueue[(state.rate - state.bitsAvailableForSqueezing) div 8], PBA(output)^[i div 8], partialBlock div 8);
dec(state.bitsAvailableForSqueezing, partialBlock);
inc(i,partialBlock);
end;
Squeeze := 0;
end;
{---------------------------------------------------------------------------}
function Init(var state: THashState; hashbitlen: integer): integer;
{-Initialize the state of the Keccak[r, c] sponge function. The rate r and}
{ capacity c values are determined from hashbitlen = number of digest bits}
{ or 0 for Keccak with default parameters and arbitrarily-long output. The}
{ allowed fixed length values are 224, 256, 384, and 512. Result 0=success}
begin
case hashbitlen of
0: Init := InitSponge(state, 1024, 576); {Default parameters, arbitrary length output}
224: Init := InitSponge(state, 1152, 448);
256: Init := InitSponge(state, 1088, 512);
384: Init := InitSponge(state, 832, 768);
512: Init := InitSponge(state, 576, 1024);
else begin
Init := BAD_HASHLEN;
exit;
end;
end;
state.fixedOutputLength := hashbitlen;
end;
{---------------------------------------------------------------------------}
function Update(var state: THashState; data: pointer; databitlen: longint): integer;
{-Update state with databitlen bits from data. May be called multiple times, }
{ only the last databitlen may be a non-multiple of 8 (the corresponding byte}
{ must be MSB aligned, i.e. in the (databitlen and 7) most significant bits. }
var
ret: integer;
lastByte: byte;
begin
if databitlen and 7 = 0 then Update := Absorb(state, data, databitlen)
else begin
ret := Absorb(state, data, databitlen - (databitlen and 7));
if ret=SUCCESS then begin
{Align the last partial byte to the least significant bits}
lastByte := PBA(data)^[databitlen div 8] shr (8 - (databitlen and 7));
Update := Absorb(state, @lastByte, databitlen and 7);
end
else update := ret;
end;
end;
{---------------------------------------------------------------------------}
function Final(var state: THashState; hashval: pointer): integer;
{-Compute Keccak hash digest and store into hashval. The hashbitlen from }
{ init is used (If zero, the squeeze function must be must to extract the}
{ the arbitrarily-length output. Result = 0 if successful.}
begin
Final := Squeeze(state, hashval, state.fixedOutputLength);
end;
{---------------------------------------------------------------------------}
function KeccakFullBytes(HashBitlen: integer; data: pointer; datalen: longint; hashval: pointer): integer;
{-Compute Keccak hash from inlen bytes and store into hashval}
var
state: thashState;
err: integer;
begin
err := Init(state,HashBitlen);
if err=0 then err := Update(state, data, datalen*8);
if err=0 then err := Final(state, hashval);
KeccakFullBytes := err;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: cgPostTransformationShader<p>
A shader that uses a texture to distort the view by adjusting texture
coordinates.
Does not have any practical use, but is fun to play around with.<p>
<b>History : </b><font size=-1><ul>
<li>22/04/10 - Yar - Fixes after GLState revision
<li>05/04/07 - DaStr - Contributed to GLScene
<li>04/11/06 - DaStr - Creation (based on demo by Rick)
}
unit cgPostTransformationShader;
interface
{$I GLScene.inc}
uses
System.Classes,
System.SysUtils,
// GLS
GLTexture, GLCadencer, GLContext, OpenGLTokens, GLScene, GLCustomShader,
GLRenderContextInfo, GLTextureFormat,
// CG Shaders
Cg, CgGL, GLCgShader;
type
TGLCustomCGPostTransformationShader = class(TCustomCGShader, IGLPostShader)
private
FTransformationPower: Single;
FTransformationTexture: TGLTexture;
protected
procedure DoApply(var rci: TRenderContextInfo; Sender: TObject); override;
// Implementing IGLPostShader.
procedure DoUseTempTexture(const TempTexture: TGLTextureHandle; TextureTarget: TGLTextureTarget);
function GetTextureTarget: TGLTextureTarget;
public
constructor Create(AOwner: TComponent); override;
property TransformationPower: Single read FTransformationPower write FTransformationPower;
property TransformationTexture: TGLTexture read FTransformationTexture write FTransformationTexture;
end;
TGLCGPostTransformationShader = class(TGLCustomCGPostTransformationShader)
published
property TransformationPower;
property TransformationTexture;
end;
//------------------------------------------------------------------------
//------------------------------------------------------------------------
//------------------------------------------------------------------------
implementation
//------------------------------------------------------------------------
//------------------------------------------------------------------------
//------------------------------------------------------------------------
{ TGLCustomCGPostTransformationShader }
constructor TGLCustomCGPostTransformationShader.Create(AOwner: TComponent);
begin
inherited;
with VertexProgram.Code do
begin
Add(' ');
Add('void main( ');
Add(' float4 iPos : POSITION, ');
Add(' float2 iTex0 : TEXCOORD0, ');
Add(' out float4 oPos : POSITION, ');
Add(' out float2 oTex0 : TEXCOORD0 ');
Add(' ) ');
Add('{ ');
Add(' oPos = iPos; ');
Add(' oTex0 = iTex0; ');
Add('} ');
end;
with FragmentProgram.Code do
begin
Add('void main( ');
Add(' float2 iTex0 : TEXCOORD0, ');
Add(' out float4 oCol : COLOR, ');
Add(' ');
Add(' uniform samplerRECT snapshotTex, ');
Add(' uniform sampler2D transformTex, ');
Add(' uniform float screenW, ');
Add(' uniform float screenH, ');
Add(' uniform float transformPower ');
Add(' ) ');
Add('{ ');
Add(' ');
Add(' /* Read the offset from the transformation texture ');
Add(' x offset is in the red channel, ');
Add(' y offset is in the green channel ');
Add(' */ ');
Add(' float2 offset = 2 * tex2D( transformTex, iTex0 ).rg -1; ');
Add(' ');
Add(' /* When using NPOT texture RECT, you need to scale up the texcoords with ');
Add(' the screenSize */ ');
Add(' iTex0.x *= screenW; ');
Add(' iTex0.y *= screenH; ');
Add(' ');
Add(' /* Apply offset */ ');
Add(' iTex0 += offset * transformPower; ');
Add(' ');
Add(' /* The result is the pixel from the snapshot, with offset */ ');
Add(' oCol.rgb = texRECT( snapshotTex, iTex0 ).rgb; ');
Add(' oCol.a = 1; ');
Add('} ');
end;
VertexProgram.OnApply := OnApplyVP;
FragmentProgram.OnApply := OnApplyFP;
FragmentProgram.OnUnApply := OnUnApplyFP;
FTransformationPower := 70;
end;
procedure TGLCustomCGPostTransformationShader.DoApply(
var rci: TRenderContextInfo; Sender: TObject);
begin
inherited;
FragmentProgram.ParamByName('screenW').SetAsScalar(rci.viewPortSize.cx);
FragmentProgram.ParamByName('screenH').SetAsScalar(rci.viewPortSize.cy);
FragmentProgram.ParamByName('transformTex').SetAsTexture2D(FTransformationTexture.Handle);
FragmentProgram.ParamByName('transformTex').EnableTexture;
FragmentProgram.ParamByName('transformPower').SetAsScalar(FTransformationPower);
end;
procedure TGLCustomCGPostTransformationShader.DoUseTempTexture(
const TempTexture: TGLTextureHandle; TextureTarget: TGLTextureTarget);
begin
FragmentProgram.ParamByName('snapshotTex').SetAsTextureRECT(TempTexture.Handle);
FragmentProgram.ParamByName('snapshotTex').EnableTexture;
end;
function TGLCustomCGPostTransformationShader.GetTextureTarget: TGLTextureTarget;
begin
Result := ttTextureRect;
end;
end.
|
unit GridViewForm2;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, CustomGridViewForm, GridFrame,
GridView, GridViewEx, Vcl.ExtCtrls, cxGraphics, cxLookAndFeels,
cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, dxSkinBlack, dxSkinBlue,
dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide,
dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis,
dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink,
dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue,
dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray,
dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark,
dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008,
dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine,
dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark,
dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue, Vcl.StdCtrls, cxButtons;
type
TfrmGridView2 = class(TfrmCustomGridView)
cxbtnOK: TcxButton;
private
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
{ Public declarations }
end;
implementation
{$R *.dfm}
constructor TfrmGridView2.Create(AOwner: TComponent);
begin
inherited;
pnlMain.Anchors := [akLeft, akTop, akRight, akBottom];
end;
end.
|
unit frame_Location;
interface
uses
{$WARNINGS OFF} // Useless warning about platform - don't care about it
FileCtrl,
{$WARNINGS ON}
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, SDUFrames, SDUFilenameEdit_U;
type
Tfme_Location = class(TFrame)
rbDrive: TRadioButton;
dcbDrive: TDriveComboBox;
rbDevice: TRadioButton;
edDevice: TEdit;
rbFile: TRadioButton;
SaveDialog1: TSaveDialog;
OpenDialog1: TOpenDialog;
SDUFilenameEdit1: TSDUFilenameEdit;
procedure rbLocationTypeClick(Sender: TObject);
procedure dcbDriveChange(Sender: TObject);
procedure edDeviceChange(Sender: TObject);
procedure SDUFilenameEdit1Change(Sender: TObject);
private
function GetSaveLocation(): TSDUFilenamEditType;
procedure SetSaveLocation(typ: TSDUFilenamEditType);
public
procedure Initialize();
function GetLocation(): string;
procedure EnableDisableControls();
published
property SaveLocation: TSDUFilenamEditType read GetSaveLocation write SetSaveLocation;
end;
implementation
{$R *.dfm}
uses
SDUGeneral,
AppGlobals;
function Tfme_Location.GetLocation(): string;
var
retVal: string;
begin
retVal:= '';
if (rbDrive.checked) then
begin
retVal := '\\.\'+dcbDrive.Drive+':';
end
else if (rbDevice.checked) then
begin
retVal := edDevice.Text;
end
else if (rbFile.checked) then
begin
retVal := SDUFilenameEdit1.Filename;
end;
Result := retVal;
end;
procedure Tfme_Location.rbLocationTypeClick(Sender: TObject);
begin
EnableDisableControls();
end;
procedure Tfme_Location.dcbDriveChange(Sender: TObject);
begin
rbDrive.Checked := TRUE;
end;
procedure Tfme_Location.edDeviceChange(Sender: TObject);
begin
rbDevice.Checked := TRUE;
end;
procedure Tfme_Location.SDUFilenameEdit1Change(Sender: TObject);
begin
rbFile.Checked := TRUE;
end;
procedure Tfme_Location.EnableDisableControls();
begin
SDUFilenameEdit1.Filter := FILE_FILTER_FLT_IMAGES;
SDUFilenameEdit1.DefaultExt := EXTN_IMG_NORMAL;
SDUEnableControl(dcbDrive, rbDrive.checked);
SDUEnableControl(edDevice, rbDevice.checked);
SDUEnableControl(SDUFilenameEdit1, rbFile.checked);
end;
function Tfme_Location.GetSaveLocation(): TSDUFilenamEditType;
begin
Result := SDUFilenameEdit1.FilenameEditType;
end;
procedure Tfme_Location.SetSaveLocation(typ: TSDUFilenamEditType);
begin
SDUFilenameEdit1.FilenameEditType := typ;
end;
procedure Tfme_Location.Initialize();
begin
// Unselect a drive...
dcbDrive.ItemIndex := -1;
// Unselect source/destination
rbDrive.checked := FALSE;
rbDevice.checked := FALSE;
rbFile.checked := FALSE;
EnableDisableControls();
end;
END.
|
namespace RemObjects.SDK.CodeGen4;
{$IF ECHOES}
interface
uses
System.CodeDom,
System.CodeDom.Compiler;
type
EchoesCodeDomRodlCodeGen = public class(RodlCodeGen)
private
method GenerateCodeFromCompileUnit(aUnit: CodeCompileUnit): not nullable String;
method ConvertRodlLibrary(library: RodlLibrary): not nullable RemObjects.SDK.Rodl.RodlLibrary;
begin
result := new RemObjects.SDK.Rodl.RodlLibrary();
result.LoadFromString(library.ToString());
result.FileName := library.Filename;
end;
protected
method GetIncludesNamespace(library: RodlLibrary): String; override;
begin
if assigned(library.Includes) then exit library.Includes.NetModule;
exit inherited GetIncludesNamespace(library);
end;
public
constructor;
property Language: String;
property FullFramework: Boolean := true;
property AsyncSupport: Boolean := true;
property CodeUnitSupport: Boolean := False;override;
method GetCodeDomProviderForLanguage: nullable CodeDomProvider;
method GetGlobalName(library: RodlLibrary): String; override;
method GenerateInterfaceFile(library: RodlLibrary; aTargetNamespace: String; aUnitName: String := nil): not nullable String; override;
method GenerateInvokerFile(library: RodlLibrary; aTargetNamespace: String; aUnitName: String := nil): not nullable String; override;
method GenerateLegacyEventsFile(library: RodlLibrary; aTargetNamespace: String; aUnitName: String := nil): not nullable String;
method GenerateImplementationFiles(library: RodlLibrary; aTargetNamespace: String; aServiceName: String): not nullable Dictionary<String,String>; override;
end;
implementation
uses
RemObjects.SDK.Rodl,
RemObjects.SDK.Rodl.CodeGen;
constructor EchoesCodeDomRodlCodeGen;
begin
end;
method EchoesCodeDomRodlCodeGen.GetGlobalName(library: RodlLibrary): String;
begin
exit library.Name+"_Defines";
end;
method EchoesCodeDomRodlCodeGen.GenerateInterfaceFile(library: RodlLibrary; aTargetNamespace: String; aUnitName: String := nil): not nullable String;
begin
var lCodegen := new CodeGen_Intf();
var lRodl := self.ConvertRodlLibrary(library);
var lUnit := lCodegen.GenerateCompileUnit(lRodl, coalesce(GetIncludesNamespace(library), aTargetNamespace, GetNamespace(library)), FullFramework, AsyncSupport, false);
result := GenerateCodeFromCompileUnit(lUnit);
end;
method EchoesCodeDomRodlCodeGen.GenerateInvokerFile(library: RodlLibrary; aTargetNamespace: String; aUnitName: String): not nullable String;
begin
var lCodegen := new CodeGen_Invk();
var lRodl := self.ConvertRodlLibrary(library);
var lUnit := lCodegen.GenerateCompileUnit(lRodl, coalesce(GetIncludesNamespace(library), aTargetNamespace, GetNamespace(library)), FullFramework, AsyncSupport);
result := GenerateCodeFromCompileUnit(lUnit);
end;
method EchoesCodeDomRodlCodeGen.GenerateLegacyEventsFile(library: RodlLibrary; aTargetNamespace: String; aUnitName: String := nil): not nullable String;
begin
result := '';
end;
method EchoesCodeDomRodlCodeGen.GenerateImplementationFiles(library: RodlLibrary; aTargetNamespace: String; aServiceName: String): not nullable Dictionary<String,String>;
begin
var lCodegen := new CodeGen_Impl();
var lRodl := self.ConvertRodlLibrary(library);
var lService := RemObjects.SDK.Rodl.RodlService(lRodl.Services.FindEntity(aServiceName));
var lUnit: CodeCompileUnit;
if assigned(lService) then
lUnit := lCodegen.GenerateCompileUnit(lService, coalesce(GetIncludesNamespace(library), aTargetNamespace, GetNamespace(library)), FullFramework)
else
lUnit := lCodegen.GenerateCompileUnit(lRodl, aTargetNamespace, FullFramework, AsyncSupport);
var lunitname := aServiceName + '_Impl.'+GetCodeDomProviderForLanguage().FileExtension;
result := new Dictionary<String,String>;
result.Add(lunitname, GenerateCodeFromCompileUnit(lUnit));
end;
method EchoesCodeDomRodlCodeGen.GetCodeDomProviderForLanguage(): nullable CodeDomProvider;
begin
var lLookingForCodeDomName: String;
try
case Language:ToLowerInvariant() of
'oxygene','pas': begin
lLookingForCodeDomName := 'Oxygene';
result := CodeDomProvider.CreateProvider("pas");
end;
'hydrogene','cs','c#', 'standard-c#': begin
result := new Microsoft.CSharp.CSharpCodeProvider();
end;
'silver', 'swift': begin
lLookingForCodeDomName := 'Silver';
result := CodeDomProvider.CreateProvider("Silver");
end;
'iodide', 'java': begin
lLookingForCodeDomName := 'Iodine';
result := CodeDomProvider.CreateProvider("Iodine");
end;
'mercury', 'vb','visualbasic','visual basic', 'standard-vb': begin
result := new Microsoft.VisualBasic.VBCodeProvider();
end;
end;
except
on E: System.Configuration.ConfigurationException do begin
result := nil;
end;
end;
if not assigned(result) then begin
//Console.WriteLine(Language:ToLowerInvariant());
//Console.WriteLine("Known CodeDom providers:");
for each p in CodeDomProvider.GetAllCompilerInfo do begin
//Console.Write(" ");
for each l in p.GetLanguages index i do begin
//if i > 0 then Console.Write(", ");
if (result = nil) and (l = lLookingForCodeDomName) then
result := p.CreateProvider();
//Console.Write(l);
end;
//Console.WriteLine();
end;
end;
end;
method EchoesCodeDomRodlCodeGen.GenerateCodeFromCompileUnit(aUnit: CodeCompileUnit): not nullable String;
begin
var lProvider := GetCodeDomProviderForLanguage();
if not assigned(lProvider) then
raise new Exception("CodeDom Provider for "+Language+" not found");
using lWriter := new System.IO.StringWriter() do begin
lProvider.GenerateCodeFromCompileUnit(aUnit, lWriter, new CodeGeneratorOptions());
lWriter.Flush();
exit lWriter.GetStringBuilder().ToString() as not nullable;
end;
end;
{$ENDIF}
end. |
unit SimpleTCPUnit;
interface
uses
Classes, winsock, windows, dialogs, DateUtils, SysUtils;
type
SimpleTCPClientThread = class(TThread)
private
{ Private declarations }
protected
procedure Execute; override;
public
Sock: TSOCKET;
UseUsDGRProt: Boolean;
ClientID: Integer;
SetR, SetE, SetRW: TFDSet;
Timeout:PTimeVal;
ExBeg: Boolean;
BufSize, SNDBufSize : integer;
BSize: integer;
LastSendindNOHasASK: Boolean;
SendingNoComplete: Boolean;
CurrentReceivedPacket: Widestring;
LastReceivedNoAccept: Boolean;
LastReceivedComplete: Boolean;
ErrorClientSocket: Boolean;
Autorized: Boolean;
UseNonBlockingMode: Boolean;
//SendBufSection: TCriticalSection;
Login: String;
Password: String;
StatusStr: String;
InputDataStringList: TStringList;
ThreadMessagesStringList: TStringList;
WaitAsk, SendAsk: Boolean;
Terminated: Boolean;
useUTF8: Boolean;
notUseJSON: Boolean;
function SendUTFString(data: string;
itsSystemMessage: Boolean=False): Boolean;
procedure TestWinSockError(S:String);
end;
const FTimeOutWrite = 60000;
implementation
{ TCPClientThread }
procedure SimpleTCPClientThread.TestWinSockError(S:String);
var
iErr:Integer;
sFullErr:String;
begin
iErr:=WSAGetLastError();
sFullErr:='Неизвестная ошибка'+IntToStr(iErr);
case iErr of
WSANOTINITIALISED: sFullErr:='Нужно сначала вызвать функцию WSASturtup, а потом создавать сокет';
WSAENETDOWN: sFullErr:='Cвязь нарушена, возможные причины - отошёл кабель или отключились от Интернета';
WSAEADDRINUSE: sFullErr:='Указанный адрес уже используется';
WSAEFAULT: sFullErr:='Параметры name и namelen не соответствуют выбранной адресации. Параметр namelen может быть меньше необходимого значения, а name содержать некорректные данные';
WSAEINPROGRESS: sFullErr:='Выполняется операция в блокирующем режиме. Вы уже запустили на выполнение какую-то функцию и нужно дождаться завершения её работы';
WSAEINVAL: sFullErr:='Сокет уже связан с адресом';
WSAENOBUFS: sFullErr:='Недостаточно буферов, слишком много соединений';
WSAENOTSOCK: sFullErr:='Неверный дескриптор сокета';
WSAEISCONN: sFullErr:='Сокет уже подключён';
WSAEMFILE: sFullErr:='Нет больше доступных дескрипторов';
end;
ThreadMessagesStringList.Add('Ошибка в функции '+S+
' - '+sFullErr);
StatusStr:='Ошибка в функции '+S+
' - '+sFullErr;
end;
procedure SimpleTCPClientThread.Execute;
var
sRecvBuff: array of char;//[0..255] of char;
sSendBuff: array of char;
ret, rcv_size: Integer;
s, SendStr, partial_in_str, modified_str, last_end_part: String;
vSize : integer;
Block:u_long;
mode_succes: Boolean;
begin
modified_str:='';
last_end_part:='';
LastSendindNOHasASK:=False;
WaitAsk:=False;
SendAsk:=False;
useUTF8:=False;
notUseJSON:=False;
SendingNoComplete:=False;
LastReceivedNoAccept:=True;
LastReceivedComplete:=True;
ErrorClientSocket:=False;
CurrentReceivedPacket:='';
ExBeg:=False;
Terminated:=False;
StatusStr:='Инициализация!';
//if setsockopt(sock, SOL_SOCKET, SO_RCVBUF, @BSize, Sizeof(BSize))<>0 then;
//if setsockopt(sock, SOL_SOCKET, SO_SNDBUF, @BSize, Sizeof(BSize))<>0 then;
vSize := sizeOf(BufSize);
GetSockOpt(sock,SOL_SOCKET,SO_RCVBUF,PAnsiChar(@BufSize),vSize);
GetSockOpt(sock,SOL_SOCKET,SO_SNDBUF,PAnsiChar(@SNDBufSize),vSize);
SetLength(sRecvBuff,BufSize);
Timeout := New(PTimeVal);
Timeout.tv_sec:=1;
Timeout.tv_usec:=500000;
InputDataStringList:=TStringList.Create;
ThreadMessagesStringList:=TStringList.Create;
ThreadMessagesStringList.Add('In '+
IntToStr(BufSize)+': Out '+
IntToStr(SNDBufSize));
//Перевод в неблокирующий режим
Block:=1;
mode_succes:=True;
if UseNonBlockingMode then
begin
if IOCtlSocket(Sock,FIONBIO,Block)=0 then
begin
mode_succes:=True;
ThreadMessagesStringList.Add(
'Сокет в неблокирующем режиме!');
StatusStr:='Сокет в неблокирующем режиме!';
end
else
mode_succes:=False;
end
else
ThreadMessagesStringList.Add(
'Сокет в блокирующем режиме!');
if mode_succes then begin
FD_Zero(SetE);
FD_Set(Sock,SetE);
FD_Zero(SetRW);
FD_Set(Sock,SetRW);
Select(Sock,nil,@SetRW,@SetE,nil);
if not FD_IsSet(Sock,SetE) then
//FD_IsSet(Sock,SetW) then
begin
//Цикл проверки входного буфера
while not Terminated and not ErrorClientSocket do
begin
//Проверка размера данных во входном буфере
//2 варианта
//IOCtlSocket(Sock,FIONRead,rcv_size);
StatusStr:='Запуск цикла!';
FD_Zero(SetR);
FD_Set(Sock,SetR);
FD_Zero(SetE);
FD_Set(Sock,SetE);
Select(0,@SetR,nil,@SetE,nil); //Timeout
//Если входной буфер не пуст
//if (rcv_size>0) then
if FD_IsSet(Sock,SetE) then
begin
ThreadMessagesStringList.Add(
'Ошибка сокета при считывании!');
ErrorClientSocket:=True;
StatusStr:='Ошибка сокета при считывании!';
Break;
end
else
if True then//FD_IsSet(Sock,SetR) then
begin
StatusStr:='Проверяем входной буфер!';
ret := Recv(Sock, sRecvBuff[0], BufSize, 0);
//if not(ExBeg) then
//begin
//MessageBox(0, 'Ожидание', 'Внимание!!!', 0);
//end;
ExBeg := True;
if (ret = 0) then
begin
//MessageBox(0, 'ret = 0!', 'Внимание!!!', 0);
if UseNonBlockingMode then
begin
StatusStr:='Пустой входной буфер!';
Continue;
end
else
begin
StatusStr:='Пустой входной буфер в блокирующем режиме! '+
'Возможно клиент отключился!';
//ExchangeError:=True;
//ErrorClientSocket:=True;
Break;
end;
end
else
begin
if (ret = SOCKET_ERROR) then
begin
if WSAGetLastError<>WSAEWouldBlock then
begin
ThreadMessagesStringList.Add('Ошибка получения данных! '+
'Возможно клиент отключился!');
TestWinSockError('Data receiving!');
StatusStr:='Ошибка получения данных! '+
'Возможно клиент отключился!';
//ExchangeError:=True;
ErrorClientSocket:=True;
Break;
end
else
begin
//Требуется блокирование так как переполнен
//буфер передачи
ThreadMessagesStringList.Add(
'Требуется блокирование так как буфер '+
'приема переполнен!');
StatusStr:='Требуется блокирование так как буфер '+
'приема переполнен!';
Continue;
end;
end;
end;
end
else
begin
//Нет данных во входном буфере
//MessageBox(0, 'Нет данных во входном буфере!', 'Внимание!!!', 0);
StatusStr:='Входной буфер не готов!';
Continue;
end;
//s:=sRecvBuff;
SetLength(s,ret+1);//(ret div 2+ret mod 2));
lstrcpyn(@s[1],@sRecvBuff[0],ret+1);
//
if s[Length(s)]=#10 then
s:=Copy(s, 1, Length(s)-1);
//MessageBox(0, PChar('Получил '+s), 'Внимание!!!', 0);
if True then
InputDataStringList.Add(s)
else
begin
s:=last_end_part+s;
partial_in_str:=s;
last_end_part:=s;
//last_end_part
//
//ThreadMessagesStringList.Add('---'+s);
while (Pos('}',partial_in_str)<>0) do
begin
modified_str:=partial_in_str;
if Pos('}',modified_str)<
Length(modified_str) then
Delete(modified_str,
Pos('}',modified_str)+1,
Length(modified_str)-
Pos('}',modified_str));
s:=Trim(modified_str);
//ThreadMessagesStringList.Add('+++'+s);
if Length(s)>0 then
if Pos('"ask":"ok"}',s)<>0 then
begin
LastSendindNOHasASK:=False;
ThreadMessagesStringList.Add('LastSendindHasASK');
end
else if Pos('{"sync":"',s)<>0 then
begin
InputDataStringList.Add(s);
end
else
begin
if Pos('"msg_end":"ok"}', s)<>0 then
begin
if LastReceivedComplete then
InputDataStringList.Add(s)
else
InputDataStringList.Strings[
InputDataStringList.Count-1]:=
InputDataStringList.Strings[
InputDataStringList.Count-1]+s;
LastReceivedComplete:=True;
if self.SendAsk then
SendUTFString('{"ask":"ok"}', True);
end
else
begin
if LastReceivedComplete then
InputDataStringList.Add(s)
else
InputDataStringList.Strings[
InputDataStringList.Count-1]:=
InputDataStringList.Strings[
InputDataStringList.Count-1]+s;
// LastReceivedComplete:=False;
if self.SendAsk then
SendUTFString('{"ask":"ok"}', True);
end;
end;
if Pos('}',partial_in_str)<
Length(partial_in_str) then
begin
Delete(partial_in_str, 1,
Pos('}',partial_in_str));
last_end_part:=partial_in_str;
end
else
begin
last_end_part:='';
Break;
end;
end;
//Конец условия self.notUseJSON
end;
//!!!Рассмотреть случай передачи несколькими итерациями цикла приема
//Конец цикла
end;
end
else if FD_IsSet(Sock,SetE) then
begin
// Соединиться не удалось
ThreadMessagesStringList.Add(
'Неудачное создание неблокирующего сокета!');
StatusStr:=
'Неудачное создание неблокирующего сокета!';
ErrorClientSocket:=True;
end
else
begin
// Произошла ещё какая-то ошибка
ThreadMessagesStringList.Add(
'Неудачное создание неблокирующего сокета!');
StatusStr:=
'Еще какая-то ошибка! Неудачное создание неблокирующего сокета!';
ErrorClientSocket:=True;
end;
//Конец условия с отработкой IOCtlSocket
end
else
begin
ThreadMessagesStringList.Add(
'Неудачное создание неблокирующего сокета, метод IOCtlSocket!');
StatusStr:=
'Неудачное создание неблокирующего сокета, метод IOCtlSocket!';
ErrorClientSocket:=True;
end;
//Перевод в блокирующий режим
Block:=0;
if UseNonBlockingMode then
IOCtlSocket(Sock,FIONBIO,Block);
Shutdown(Sock, SD_Both);
CloseSocket(sock);
ErrorClientSocket:=True;
end;
function SimpleTCPClientThread.SendUTFString(data: string; itsSystemMessage: Boolean=False): Boolean;
var SendStr: string;
ret: Integer;
res: Boolean;
TimeVal: TTimeVal;
SetW, SetWE: TFDSet;
sendUTF8: UTF8String;
begin
res:=False;
if not SendingNoComplete then
SendingNoComplete:=True;
SendStr := data;
//если SendStr больше BufSize то сообщение надо разбить
//ret := Send(sock, sSendBuff[0], sizeof(sSendBuff), 0);
ThreadMessagesStringList.Add(
'Передаю: '+data);
while True do
begin
if Sock=INVALID_SOCKET then
begin
ThreadMessagesStringList.Add(
'INVALID_SOCKET');
ErrorClientSocket:=True;
Break;
end;
FD_Zero(SetWE);
FD_Set(Sock,SetWE);
FD_Zero(SetW);
FD_Set(Sock,SetW);
TimeVal.tv_sec:=FTimeOutWrite div 1000;
TimeVal.tv_usec:=(FTimeOutWrite mod 1000)*1000;
if Select(0,nil,@SetW,@SetWE,nil)= //@TimeVal
SOCKET_ERROR then
begin
ThreadMessagesStringList.Add(
'INVALID_SOCKET_OF_SELECT');
ErrorClientSocket:=True;
Break;
end;
if FD_IsSet(Sock,SetWE) then
begin
ThreadMessagesStringList.Add(
'Ошибка сокета при записи!');
ErrorClientSocket:=True;
Break;
end
else
//Если в выходном буфере есть место
if FD_IsSet(Sock,SetW) then
begin
if (self.useUTF8) then
begin
sendUTF8 := AnsiToUtf8(SendStr+#13#10);
ret := Send(sock,sendUTF8[1],Length(sendUTF8),0);
end
else
ret := Send(sock,SendStr[1],Length(SendStr),0);//Length(SendStr),0);
if (ret = SOCKET_ERROR) then
begin
if WSAGetLastError<>WSAEWouldBlock then
begin
ThreadMessagesStringList.Add(
'Ошибка передачи данных');
ErrorClientSocket:=True;
Break;
end
else
begin
//Требуется блокирование так как переполнен
//буфер передачи
ThreadMessagesStringList.Add(
'Требуется блокирование так как переполнен'+
' буфер передачи!');
Continue;
end;
end
//else if ret<Length(SendStr)*2 then
//begin
// Continue;
//end
else
begin
//Если переполнен буфер передачи
if not itsSystemMessage then
begin
if self.WaitAsk then
begin
LastSendindNOHasASK:=True;
ThreadMessagesStringList.Add('LastSendindNOHasASK');
end;
end;
if (self.useUTF8) then
begin
if Length(sendUtf8)<ret then
begin
Delete(sendUtf8,1,ret);
ThreadMessagesStringList.Add(
'Переполнение исх. буфера (UTF8)!');
Continue;
end
else
begin
res:=True;
Break;
end;
end
else
begin
Delete(SendStr, 1, ret);
if Length(SendStr)>0 then
begin
ThreadMessagesStringList.Add(
'Переполнение исх. буфера (ANSI)!');
Continue;
end
else
begin
res:=True;
Break;
end;
end;
end;
end
else
begin
ThreadMessagesStringList.Add(
'Выходной буфер не готов к считыванию!');
Continue;
end;
end; //Конец цикла
SendingNoComplete:=False;
Result:=res;
end;
end.
|
UNIT Utilidades;
INTERFACE
USES
DT_Especie, DT_TipoElemental;
CONST
MAX_NUMERO_ESPECIES= 1000;
MAX_NUMERO_TIPOS_ELEMENTALES= 20;
TYPE
(***************************************************
* Tipo para manejar el listado de especies pokémon.*
***************************************************)
ListaEspecies= RECORD
lista: ARRAY[1..MAX_NUMERO_ESPECIES] OF Especie;
tope: INTEGER;
end;
(***************************************************
* Tipo para manejar el listado de tipos elementales*
***************************************************)
ListaTiposElementales= RECORD
lista: ARRAY[1..MAX_NUMERO_TIPOS_ELEMENTALES] OF TipoElemental;
tope: INTEGER;
end;
(**********************************************************
* Operaciones para manejar el listado de especies pokémon.*
***********************************************************)
(*Inicia la lista como vacía*)
PROCEDURE IniciarListaEspecies(VAR l: ListaEspecies);
(*Agrega una especie al final de la lista.*)
PROCEDURE AgregarEspecieListaEspecies(e: Especie; VAR l: ListaEspecies);
(*Indica si la lista es vacía.*)
FUNCTION EsVaciaListaEspecies(l: ListaEspecies): BOOLEAN;
(*Retorna la especie del inicio de la lista. La lista no debe esar vacía.*)
FUNCTION PrimeraEspecieListaEspecies(l: ListaEspecies): Especie;
(*Indica si el índice pasado como argumento es válido.*)
FUNCTION EsIndiceValidoListaEspecies(i: INTEGER; l: ListaEspecies): BOOLEAN;
(*Retorna la especie del índice indicado. El índice debe ser válido.*)
FUNCTION EspecieListaEspecies(indice: INTEGER; l: ListaEspecies): Especie;
(**********************************************************
* Operaciones para manejar el listado de tipos elementales*
***********************************************************)
(*Inicia la lista como vacía*)
PROCEDURE IniciarListaTiposElementales(VAR l: ListaTiposElementales);
(*Agrega un tipo al final de la lista.*)
PROCEDURE AgregarTipoListaTiposElementales(t: TipoElemental; VAR l: ListaTiposElementales);
(*Indica si la lista es vacía.*)
FUNCTION EsVaciaListaTiposElementales(l: ListaTiposElementales): BOOLEAN;
(*Retorna el tipo del inicio de la lista. La lista no debe esar vacía.*)
FUNCTION PrimerTipoListaTiposElementales(l: ListaTiposElementales): TipoElemental;
(*Indica si el índice pasado como argumento es válido.*)
FUNCTION EsIndiceValidoListaTiposElementales(i: INTEGER; l: ListaTiposElementales): BOOLEAN;
(*Retorna el tipo del índice indicado. El índice debe ser válido.*)
FUNCTION TipoListaTiposElementales(indice: INTEGER; l: ListaTiposElementales): TipoElemental;
IMPLEMENTATION
(**********************************************************
* Operaciones para manejar el listado de especies pokémon.*
***********************************************************)
(*Inicia la lista como vacía*)
PROCEDURE IniciarListaEspecies(VAR l: ListaEspecies);
Begin
l.tope := 0;
end;
(*Agrega una especie al final de la lista.*)
PROCEDURE AgregarEspecieListaEspecies(e: Especie; VAR l: ListaEspecies);
Begin
l.tope := l.tope + 1;
l.lista[l.tope] := e;
end;
(*Indica si la lista es vacía.*)
FUNCTION EsVaciaListaEspecies(l: ListaEspecies): BOOLEAN;
Begin
EsVaciaListaEspecies := l.tope = 0;
end;
(*Retorna la especie del inicio de la lista. La lista no debe esar vacía.*)
FUNCTION PrimeraEspecieListaEspecies(l: ListaEspecies): Especie;
Begin
PrimeraEspecieListaEspecies := l.lista[1];
end;
(*Indica si el índice pasado como argumento es válido.*)
FUNCTION EsIndiceValidoListaEspecies(i: INTEGER; l: ListaEspecies): BOOLEAN;
Begin
EsIndiceValidoListaEspecies := l.tope >= i;
end;
(*Retorna la especie del índice indicado. El índice debe ser válido.*)
FUNCTION EspecieListaEspecies(indice: INTEGER; l: ListaEspecies): Especie;
BEGIN
EspecieListaEspecies := l.lista[indice];
end;
(**********************************************************
* Operaciones para manejar el listado de tipos elementales*
***********************************************************)
(*Inicia la lista como vacía*)
PROCEDURE IniciarListaTiposElementales(VAR l: ListaTiposElementales); Begin
l.tope := 0;
end;
(*Agrega un tipo al final de la lista.*)
PROCEDURE AgregarTipoListaTiposElementales(t: TipoElemental; VAR l: ListaTiposElementales); Begin
l.tope := l.tope + 1;
l.lista[l.tope] := t;
end;
(*Indica si la lista es vacía.*)
FUNCTION EsVaciaListaTiposElementales(l: ListaTiposElementales): BOOLEAN; Begin
EsVaciaListaTiposElementales := l.tope=0;
end;
(*Retorna el tipo del inicio de la lista. La lista no debe esar vacía.*)
FUNCTION PrimerTipoListaTiposElementales(l: ListaTiposElementales): TipoElemental; Begin
PrimerTipoListaTiposElementales := l.lista[1];
end;
(*Indica si el índice pasado como argumento es válido.*)
FUNCTION EsIndiceValidoListaTiposElementales(i: INTEGER; l: ListaTiposElementales): BOOLEAN; Begin
EsIndiceValidoListaTiposElementales := (i < l.tope);
end;
(*Retorna el tipo del índice indicado. El índice debe ser válido.*)
FUNCTION TipoListaTiposElementales(indice: INTEGER; l: ListaTiposElementales): TipoElemental; Begin
(* Ivana *)
if(indice<l.tope) then
TipoListaTiposElementales := l.lista[indice];
(* TipoListaTiposElementales := l.lista[indice]; *)
end;
end.
|
{
@abstract(Interfaces, base classes and support classes for GMLib.)
@author(Xavier Martinez (cadetill) <cadetill@gmail.com>)
@created(Septembre 30, 2015)
@lastmod(Octobre 1, 2015)
The GMClasses unit provides access to interfaces and base classes used into GMLib.
}
unit GMClasses;
{$I ..\gmlib.inc}
interface
uses
{$IFDEF DELPHIXE2}
System.SysUtils, System.Classes,
{$ELSE}
SysUtils, Classes,
{$ENDIF}
GMSets;
type
{ ************************************************************************** }
{ ************************* Events definition **************************** }
{ ************************************************************************** }
// @include(..\docs\GMClasses.TPropertyChanges.txt)
TPropertyChanges = procedure(Owner: TObject; PropName: string) of object;
{ ************************************************************************** }
{ *********************** Interfaces definition ************************** }
{ ************************************************************************** }
// @include(..\docs\GMClasses.IGMAPIUrl.txt)
IGMAPIUrl = interface(IInterface)
['{BF91F436-B314-4128-ADA3-02147063A90C}']
// @exclude
function GetAPIUrl: string;
// @include(..\docs\GMClasses.IGMAPIUrl.APIUrl.txt)
property APIUrl: string read GetAPIUrl;
end;
// @include(..\docs\GMClasses.IGMToStr.txt)
IGMToStr = interface(IInterface)
['{314C6DAD-B258-4D0C-A275-229491430B65}']
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string;
end;
// @include(..\docs\GMClasses.IGMControlChanges.txt)
IGMControlChanges = interface(IInterface)
['{4731A754-4D4B-4AA2-978E-AF2838925A06}']
// @include(..\docs\GMClasses.IGMControlChanges.PropertyChanged.txt)
procedure PropertyChanged(Prop: TPersistent; PropName: string);
end;
// @include(..\docs\GMClasses.IGMOwnerLang.txt)
IGMOwnerLang = interface(IInterface)
['{98DE1EC1-454C-494A-893A-2B57DC4C341F}']
// @include(..\docs\GMClasses.IGMOwnerLang.GetOwnerLang.txt)
function GetOwnerLang: TGMLang;
end;
// @include(..\docs\GMClasses.IGMExecJS.txt)
IGMExecJS = interface(IInterface)
['{C1C87DC5-BDFD-4AA1-9BF7-C5FF01290339}']
// @include(..\docs\GMClasses.IGMExecJS.ExecuteJavaScript.txt)
procedure ExecuteJavaScript(NameFunct, Params: string);
end;
{ ************************************************************************** }
{ ************************* classes definition *************************** }
{ ************************************************************************** }
// @include(..\docs\GMClasses.EGMException.txt)
EGMException = class(Exception)
public
// @include(..\docs\GMClasses.EGMException.Create_1.txt)
constructor Create(const Msg: string; const Args: array of const; Lang: TGMLang); reintroduce; overload; virtual;
// @include(..\docs\GMClasses.EGMException.Create_2.txt)
constructor Create(const Idx: Integer; const Args: array of const; Lang: TGMLang); reintroduce; overload; virtual;
end;
// @include(..\docs\GMClasses.EGMNotValidRealNumber.txt)
EGMNotValidRealNumber = class(EGMException)
public
// @include(..\docs\GMClasses.EGMNotValidRealNumber.Create.txt)
constructor Create(const Args: array of const; Lang: TGMLang); reintroduce; overload; virtual;
end;
// @include(..\docs\GMClasses.EGMWithoutOwner.txt)
EGMWithoutOwner = class(EGMException)
public
// @include(..\docs\GMClasses.EGMWithoutOwner.Create.txt)
constructor Create(Lang: TGMLang); reintroduce; overload; virtual;
end;
// @include(..\docs\GMClasses.EGMOwnerWithoutJS.txt)
EGMOwnerWithoutJS = class(EGMException)
public
// @include(..\docs\GMClasses.EGMOwnerWithoutJS.Create.txt)
constructor Create(Lang: TGMLang); reintroduce; overload; virtual;
end;
// @include(..\docs\GMClasses.EGMJSError.txt)
EGMJSError = class(EGMException)
public
// @include(..\docs\GMClasses.EGMJSError.Create.txt)
constructor Create(const Args: array of const; Lang: TGMLang); reintroduce; overload; virtual;
end;
// @include(..\docs\GMClasses.EGMUnassignedObject.txt)
EGMUnassignedObject = class(EGMException)
public
// @include(..\docs\GMClasses.EGMUnassignedObject.Create.txt)
constructor Create(const Args: array of const; Lang: TGMLang); reintroduce; overload; virtual;
end;
// @include(..\docs\GMClasses.EGMMapIsActive.txt)
EGMMapIsActive = class(EGMException)
public
// @include(..\docs\GMClasses.EGMMapIsActive.Create.txt)
constructor Create(Lang: TGMLang); reintroduce; overload; virtual;
end;
// @include(..\docs\GMClasses.EGMIncorrectBrowser.txt)
EGMIncorrectBrowser = class(EGMException)
public
// @include(..\docs\GMClasses.EGMIncorrectBrowser.Create.txt)
constructor Create(Lang: TGMLang); reintroduce; overload; virtual;
end;
// @include(..\docs\GMClasses.EGMCanLoadResource.txt)
EGMCanLoadResource = class(EGMException)
public
// @include(..\docs\GMClasses.EGMCanLoadResource.Create.txt)
constructor Create(Lang: TGMLang); reintroduce; overload; virtual;
end;
// @include(..\docs\GMClasses.EGMTimeOut.txt)
EGMTimeOut = class(EGMException)
public
// @include(..\docs\GMClasses.EGMTimeOut.Create.txt)
constructor Create(Lang: TGMLang); reintroduce; overload; virtual;
end;
// @include(..\docs\GMClasses.EGMNotActive.txt)
EGMNotActive = class(EGMException)
public
// @include(..\docs\GMClasses.EGMNotActive.Create.txt)
constructor Create(Lang: TGMLang); reintroduce; overload; virtual;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMClasses.TGMObject.txt)
TGMObject = class(TInterfacedObject, IGMAPIUrl)
protected
// @exclude
function GetAPIUrl: string; virtual;
// @include(..\docs\GMClasses.TGMObject.APIUrl.txt)
property APIUrl: string read GetAPIUrl;
public
// @include(..\docs\GMClasses.TGMObject.Assign.txt)
procedure Assign(Source: TObject); virtual;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMClasses.TGMInterfacedOwnedPersistent.txt)
TGMInterfacedOwnedPersistent = class(TInterfacedPersistent)
private
FOwner: TPersistent;
FOnChange: TNotifyEvent;
protected
// @include(..\docs\GMClasses.TGMInterfacedOwnedPersistent.GetOwner.txt)
function GetOwner: TPersistent; override;
// @exclude
procedure ControlChanges(PropName: string); virtual;
// @include(..\docs\GMClasses.TGMInterfacedOwnedPersistent.OnChange.txt)
property OnChange: TNotifyEvent read FOnChange write FOnChange;
public
// @include(..\docs\GMClasses.TGMInterfacedOwnedPersistent.Create.txt)
constructor Create(AOwner: TPersistent); virtual;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMClasses.TGMPersistent.txt)
TGMPersistent = class(TGMInterfacedOwnedPersistent, IGMAPIUrl)
protected
// @exclude
function GetAPIUrl: string; virtual;
// @include(..\docs\GMClasses.TGMPersistent.APIUrl.txt)
property APIUrl: string read GetAPIUrl;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMClasses.TGMPersistentStr.txt)
TGMPersistentStr = class(TGMPersistent, IGMToStr, IGMOwnerLang)
protected
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; virtual;
// @include(..\docs\GMClasses.TGMPersistentStr.GetOwnerLang.txt)
function GetOwnerLang: TGMLang; virtual;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMClasses.TGMComponent.txt)
TGMComponent = class(TComponent, IGMAPIUrl)
private
FLanguage: TGMLang;
FAboutGMLib: string;
protected
// @exclude
function GetAPIUrl: string; virtual;
// @include(..\docs\GMClasses.TGMComponent.APIUrl.txt)
property APIUrl: string read GetAPIUrl;
// @include(..\docs\GMClasses.TGMComponent.Language.txt)
property Language: TGMLang read FLanguage write FLanguage default lnEnglish;
// @include(..\docs\GMClasses.TGMComponent.AboutGMLib.txt)
property AboutGMLib: string read FAboutGMLib stored False;
public
// @include(..\docs\GMClasses.TGMComponent.Create.txt)
constructor Create(AOwner: TComponent); override;
// @include(..\docs\GMClasses.TGMComponent.Assign.txt)
procedure Assign(Source: TPersistent); override;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMClasses.TGMInterfacedCollectionItem.txt)
TGMInterfacedCollectionItem = class(TCollectionItem, IGMToStr, IGMOwnerLang, IGMAPIUrl)
private
FOnChange: TNotifyEvent;
FFObject: TObject;
FTag: Integer;
FName: string;
protected
// @exclude
function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall;
// @exclude
function _AddRef: Integer; virtual; stdcall;
// @exclude
function _Release: Integer; virtual; stdcall;
// @include(..\docs\GMClasses.TGMInterfacedCollectionItem.GetDisplayName.txt)
function GetDisplayName: string; override;
// @exclude
function GetAPIUrl: string; virtual;
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; virtual;
// @include(..\docs\GMClasses.TGMInterfacedCollectionItem.GetOwnerLang.txt)
function GetOwnerLang: TGMLang; virtual;
// @exclude
procedure ControlChanges(PropName: string); virtual;
// @include(..\docs\GMClasses.TGMInterfacedCollectionItem.OnChange.txt)
property OnChange: TNotifyEvent read FOnChange write FOnChange;
public
// @include(..\docs\GMClasses.TGMInterfacedCollectionItem.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\docs\GMClasses.TGMInterfacedCollectionItem.APIUrl.txt)
property APIUrl: string read GetAPIUrl;
// @include(..\docs\GMClasses.TGMInterfacedCollectionItem.FObject.txt)
property FObject: TObject read FFObject write FFObject;
published
// @include(..\docs\GMClasses.TGMInterfacedCollectionItem.Tag.txt)
property Tag: Integer read FTag write FTag default 0;
// @include(..\docs\GMClasses.TGMInterfacedCollectionItem.Name.txt)
property Name: string read FName write FName;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMClasses.TGMInterfacedCollection.txt)
TGMInterfacedCollection = class(TCollection, IGMControlChanges, IGMOwnerLang, IGMToStr)
private
FOnChange: TNotifyEvent;
FOwner: TPersistent;
protected
// @exclude
function GetItems(I: Integer): TGMInterfacedCollectionItem;
// @exclude
procedure SetItems(I: Integer; const Value: TGMInterfacedCollectionItem);
// @exclude
function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall;
// @exclude
function _AddRef: Integer; virtual; stdcall;
// @exclude
function _Release: Integer; virtual; stdcall;
// @include(..\docs\GMClasses.TGMInterfacedCollection.GetOwnerLang.txt)
function GetOwnerLang: TGMLang; virtual;
// @include(..\docs\GMClasses.TGMInterfacedCollection.GetOwner.txt)
function GetOwner: TPersistent; override;
// @exclude
procedure ControlChanges(PropName: string); virtual;
// @include(..\docs\GMClasses.IGMControlChanges.PropertyChanged.txt)
procedure PropertyChanged(Prop: TPersistent; PropName: string);
// @include(..\docs\GMClasses.TGMInterfacedCollection.Delete.txt)
procedure Delete(Index: Integer);
// @include(..\docs\GMClasses.TGMInterfacedCollection.Move.txt)
procedure Move(CurIndex, NewIndex: Integer);
// @include(..\docs\GMClasses.TGMInterfacedCollection.Clear.txt)
procedure Clear;
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; virtual;
// @include(..\docs\GMClasses.TGMInterfacedCollection.OnChange.txt)
property OnChange: TNotifyEvent read FOnChange write FOnChange;
// @include(..\docs\GMClasses.TGMInterfacedCollection.Items.txt)
property Items[I: Integer]: TGMInterfacedCollectionItem read GetItems write SetItems; default;
public
// @include(..\docs\GMClasses.TGMInterfacedCollection.Create.txt)
constructor Create(AOwner: TPersistent; ItemClass: TCollectionItemClass); virtual;
// @include(..\docs\GMClasses.TGMInterfacedCollection.Assign.txt)
procedure Assign(Source: TPersistent); override;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMClasses.TGMTransform.txt)
TGMTransform = record
public
// @include(..\docs\GMClasses.TGMTransform.GMBoolToStr.txt)
class function GMBoolToStr(B: Boolean; UseBoolStrs: Boolean = False): string; static;
// @include(..\docs\GMClasses.TGMTransform.MapTypeIdsToStr.txt)
class function MapTypeIdsToStr(MapTypeIds: TGMMapTypeIds; Delimiter: Char = ';'): string; static;
// @include(..\docs\GMClasses.TGMTransform.GoogleAPIVerToStr.txt)
class function GoogleAPIVerToStr(GoogleAPIVer: TGoogleAPIVer): string; static;
// @include(..\docs\GMClasses.TGMTransform.APILangToStr.txt)
class function APILangToStr(APILang: TGMAPILang): string; static;
// @include(..\docs\GMClasses.TGMTransform.VisibilityToStr.txt)
class function VisibilityToStr(Visibility: TGMVisibility): string; static;
// @include(..\docs\GMClasses.TGMTransform.StrToVisibility.txt)
class function StrToVisibility(Visibility: string): TGMVisibility; static;
// @include(..\docs\GMClasses.TGMTransform.PositionToStr.txt)
class function PositionToStr(Position: TGMControlPosition): string; static;
// @include(..\docs\GMClasses.TGMTransform.MapTypeControlStyleToStr.txt)
class function MapTypeControlStyleToStr(MapTypeControlStyle: TGMMapTypeControlStyle): string; static;
// @include(..\docs\GMClasses.TGMTransform.ScaleControlStyleToStr.txt)
class function ScaleControlStyleToStr(ScaleControlStyle: TGMScaleControlStyle): string; static;
// @include(..\docs\GMClasses.TGMTransform.ZoomControlStyleToStr.txt)
class function ZoomControlStyleToStr(ZoomControlStyle: TGMZoomControlStyle): string; static;
// @include(..\docs\GMClasses.TGMTransform.MapTypeStyleElementTypeToStr.txt)
class function MapTypeStyleElementTypeToStr(MapTypeStyleElementType: TGMMapTypeStyleElementType): string; static;
// @include(..\docs\GMClasses.TGMTransform.MapTypeStyleFeatureTypeToStr.txt)
class function MapTypeStyleFeatureTypeToStr(MapTypeStyleFeatureType: TGMMapTypeStyleFeatureType): string; static;
// @include(..\docs\GMClasses.TGMTransform.MapTypeIdToStr.txt)
class function MapTypeIdToStr(MapTypeId: TGMMapTypeId): string; static;
// @include(..\docs\GMClasses.TGMTransform.StrToPosition.txt)
class function StrToPosition(Position: string): TGMControlPosition; static;
end;
implementation
uses
{$IFDEF DELPHIXE2}
System.TypInfo,
{$ELSE}
TypInfo,
{$ENDIF}
GMTranslations;
{ TGMObject }
procedure TGMObject.Assign(Source: TObject);
begin
//
end;
function TGMObject.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference';
end;
{ EGMException }
constructor EGMException.Create(const Msg: string; const Args: array of const;
Lang: TGMLang);
begin
inherited Create(GetTranslateText(Msg, Args, Lang));
end;
constructor EGMException.Create(const Idx: Integer; const Args: array of const;
Lang: TGMLang);
begin
inherited Create(GetTranslateText(Idx, Args, Lang));
end;
{ TGMComponent }
procedure TGMComponent.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMComponent then
begin
Language := TGMComponent(Source).Language;
end;
end;
constructor TGMComponent.Create(AOwner: TComponent);
begin
inherited;
FLanguage := lnEnglish;
end;
function TGMComponent.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference';
end;
{ TGMInterfacedOwnedPersistent }
procedure TGMInterfacedOwnedPersistent.ControlChanges(PropName: string);
var
Intf: IGMControlChanges;
begin
if (FOwner <> nil) and Supports(FOwner, IGMControlChanges, Intf) then
Intf.PropertyChanged(Self, PropName)
else
if Assigned(FOnChange) then FOnChange(Self);
end;
constructor TGMInterfacedOwnedPersistent.Create(AOwner: TPersistent);
begin
FOwner := AOwner;
end;
function TGMInterfacedOwnedPersistent.GetOwner: TPersistent;
begin
Result := FOwner;
end;
{ TGMPersistent }
function TGMPersistent.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference';
end;
{ TGMTransform }
class function TGMTransform.APILangToStr(APILang: TGMAPILang): string;
begin
Result := GetEnumName(TypeInfo(TGMAPILang), Ord(APILang));
case APILang of
lArabic: Result := 'ar';
lBulgarian: Result := 'bg';
lBengali: Result := 'bn';
lCatalan: Result := 'ca';
lCzech: Result := 'cs';
lDanish: Result := 'da';
lGerman: Result := 'de';
lGreek: Result := 'el';
lEnglish: Result := 'en';
lEnglish_Aust: Result := 'en-AU';
lEnglish_GB: Result := 'en-GB';
lSpanish: Result := 'es';
lBasque: Result := 'eu';
lFarsi: Result := 'fa';
lFinnish: Result := 'fi';
lFilipino: Result := 'fil';
lFrench: Result := 'fr';
lGalician: Result := 'gl';
lGujarati: Result := 'gu';
lHindi: Result := 'hi';
lCroatian: Result := 'hr';
lHungarian: Result := 'hu';
lIndonesian: Result := 'id';
lItalian: Result := 'it';
lHebrew: Result := 'iw';
lJapanese: Result := 'ja';
lKannada: Result := 'kn';
lKorean: Result := 'ko';
lLithuanian: Result := 'lt';
lLatvian: Result := 'lv';
lMalayalam: Result := 'ml';
lMarathi: Result := 'mr';
lDutch: Result := 'nl';
lNorwegian: Result := 'no';
lPolish: Result := 'pl';
lPortuguese: Result := 'pt';
lPortuguese_Br: Result := 'pt-BR';
lPortuguese_Ptg: Result := 'pt-PT';
lRomanian: Result := 'ro';
lRussian: Result := 'ru';
lSlovak: Result := 'sk';
lSlovenian: Result := 'sl';
lSerbian: Result := 'sr';
lSwedish: Result := 'sv';
lTamil: Result := 'ta';
lTelugu: Result := 'te';
lThai: Result := 'th';
lTagalog: Result := 'tl';
lTurkish: Result := 'tr';
lUkrainian: Result := 'uk';
lVietnamese: Result := 'vi';
lChinese_Simp: Result := 'zh-CN';
lChinese_Trad: Result := 'zh-TW';
lUndefined: Result := '';
end;
end;
class function TGMTransform.GMBoolToStr(B, UseBoolStrs: Boolean): string;
const
cSimpleBoolStrs: array [boolean] of string = ('0', '-1');
begin
if UseBoolStrs then
begin
if B then Result := 'true'
else Result := 'false';
end
else
Result := cSimpleBoolStrs[B];
end;
class function TGMTransform.GoogleAPIVerToStr(
GoogleAPIVer: TGoogleAPIVer): string;
begin
case GoogleAPIVer of
api321: Result := '3.21';
api322: Result := '3.22';
api323: Result := '3.23';
api324: Result := '3.24';
apiNewest: Result := '3.x';
end;
end;
class function TGMTransform.MapTypeControlStyleToStr(
MapTypeControlStyle: TGMMapTypeControlStyle): string;
begin
Result := GetEnumName(TypeInfo(TGMMapTypeControlStyle), Ord(MapTypeControlStyle));
end;
class function TGMTransform.MapTypeIdsToStr(MapTypeIds: TGMMapTypeIds;
Delimiter: Char): string;
begin
Result := '';
if mtHYBRID in MapTypeIds then
Result := Result + 'mtHYBRID';
if mtROADMAP in MapTypeIds then
begin
if Result <> '' then Result := Result + Delimiter;
Result := Result + 'mtROADMAP';
end;
if mtSATELLITE in MapTypeIds then
begin
if Result <> '' then Result := Result + Delimiter;
Result := Result + 'mtSATELLITE';
end;
if mtTERRAIN in MapTypeIds then
begin
if Result <> '' then Result := Result + Delimiter;
Result := Result + 'mtTERRAIN';
end;
if mtOSM in MapTypeIds then
begin
if Result <> '' then Result := Result + Delimiter;
Result := Result + 'mtOSM';
end;
end;
class function TGMTransform.MapTypeIdToStr(MapTypeId: TGMMapTypeId): string;
begin
Result := GetEnumName(TypeInfo(TGMMapTypeId), Ord(MapTypeId));
end;
class function TGMTransform.MapTypeStyleElementTypeToStr(
MapTypeStyleElementType: TGMMapTypeStyleElementType): string;
begin
Result := GetEnumName(TypeInfo(TGMMapTypeStyleElementType), Ord(MapTypeStyleElementType));
end;
class function TGMTransform.MapTypeStyleFeatureTypeToStr(
MapTypeStyleFeatureType: TGMMapTypeStyleFeatureType): string;
begin
Result := GetEnumName(TypeInfo(TGMMapTypeStyleFeatureType), Ord(MapTypeStyleFeatureType));
end;
class function TGMTransform.PositionToStr(Position: TGMControlPosition): string;
begin
Result := GetEnumName(TypeInfo(TGMControlPosition), Ord(Position));
end;
class function TGMTransform.ScaleControlStyleToStr(
ScaleControlStyle: TGMScaleControlStyle): string;
begin
Result := GetEnumName(TypeInfo(TGMScaleControlStyle), Ord(ScaleControlStyle));
end;
class function TGMTransform.StrToPosition(Position: string): TGMControlPosition;
begin
Result := TGMControlPosition(GetEnumValue(TypeInfo(TGMControlPosition), Position));
end;
class function TGMTransform.StrToVisibility(Visibility: string): TGMVisibility;
begin
Result := TGMVisibility(GetEnumValue(TypeInfo(TGMVisibility), Visibility));
end;
class function TGMTransform.VisibilityToStr(Visibility: TGMVisibility): string;
begin
Result := GetEnumName(TypeInfo(TGMVisibility), Ord(Visibility));
end;
class function TGMTransform.ZoomControlStyleToStr(
ZoomControlStyle: TGMZoomControlStyle): string;
begin
Result := GetEnumName(TypeInfo(TGMZoomControlStyle), Ord(ZoomControlStyle));
end;
{ TGMPersistentStr }
function TGMPersistentStr.GetOwnerLang: TGMLang;
var
Intf: IGMOwnerLang;
begin
Result := lnEnglish;
if not Assigned(GetOwner()) then Exit;
if not Supports(GetOwner(), IGMOwnerLang, Intf) then Exit;
Result := Intf.GetOwnerLang;
end;
function TGMPersistentStr.PropToString: string;
begin
Result := '';
end;
{ TGMInterfacedCollectionItem }
procedure TGMInterfacedCollectionItem.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMInterfacedCollectionItem then
begin
Name := TGMInterfacedCollectionItem(Source).Name;
Tag := TGMInterfacedCollectionItem(Source).Tag;
FObject := TGMInterfacedCollectionItem(Source).FObject;
end;
end;
procedure TGMInterfacedCollectionItem.ControlChanges(PropName: string);
var
Intf: IGMControlChanges;
begin
if (GetOwner <> nil) and Supports(GetOwner, IGMControlChanges, Intf) then
Intf.PropertyChanged(Self, PropName)
else
if Assigned(FOnChange) then FOnChange(Self);
end;
function TGMInterfacedCollectionItem.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference';
end;
function TGMInterfacedCollectionItem.GetDisplayName: string;
begin
if Length(FName) > 0 then
begin
if Length(FName) > 15 then
Result := Copy(FName, 0, 15) + '...'
else
Result := FName;
end
else
begin
Result := inherited GetDisplayName;
FName := Result;
end;
end;
function TGMInterfacedCollectionItem.GetOwnerLang: TGMLang;
var
Intf: IGMOwnerLang;
begin
Result := lnEnglish;
if not Assigned(Collection) then Exit;
if not Supports(Collection, IGMOwnerLang, Intf) then Exit;
Result := Intf.GetOwnerLang;
end;
function TGMInterfacedCollectionItem.PropToString: string;
begin
Result := '';
end;
function TGMInterfacedCollectionItem.QueryInterface(const IID: TGUID;
out Obj): HResult;
begin
if GetInterface(IID, Obj) then Result := S_OK
else Result := E_NOINTERFACE;
end;
function TGMInterfacedCollectionItem._AddRef: Integer;
begin
Result := -1;
end;
function TGMInterfacedCollectionItem._Release: Integer;
begin
Result := -1;
end;
{ TGMInterfacedCollection }
procedure TGMInterfacedCollection.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMInterfacedCollection then
FOwner := TGMInterfacedCollection(Source).FOwner;
end;
procedure TGMInterfacedCollection.Clear;
begin
inherited Clear;
ControlChanges('');
end;
procedure TGMInterfacedCollection.ControlChanges(PropName: string);
var
Intf: IGMControlChanges;
begin
if (GetOwner <> nil) and Supports(GetOwner, IGMControlChanges, Intf) then
Intf.PropertyChanged(Self, PropName)
else
if Assigned(FOnChange) then FOnChange(Self);
end;
constructor TGMInterfacedCollection.Create(AOwner: TPersistent;
ItemClass: TCollectionItemClass);
begin
inherited Create(ItemClass);
FOwner := AOwner;
end;
procedure TGMInterfacedCollection.Delete(Index: Integer);
begin
inherited Delete(Index);
ControlChanges('');
end;
function TGMInterfacedCollection.GetItems(
I: Integer): TGMInterfacedCollectionItem;
begin
Result := TGMInterfacedCollectionItem(inherited Items[I]);
end;
function TGMInterfacedCollection.GetOwner: TPersistent;
begin
Result := FOwner;
end;
function TGMInterfacedCollection.GetOwnerLang: TGMLang;
var
Intf: IGMOwnerLang;
begin
Result := lnEnglish;
if not Assigned(FOwner) then Exit;
if not Supports(FOwner, IGMOwnerLang, Intf) then Exit;
Result := Intf.GetOwnerLang;
end;
procedure TGMInterfacedCollection.Move(CurIndex, NewIndex: Integer);
begin
Items[CurIndex].Index := NewIndex;
ControlChanges('');
end;
procedure TGMInterfacedCollection.PropertyChanged(Prop: TPersistent;
PropName: string);
begin
ControlChanges(PropName);
end;
function TGMInterfacedCollection.PropToString: string;
begin
Result := '';
end;
function TGMInterfacedCollection.QueryInterface(const IID: TGUID;
out Obj): HResult;
begin
if GetInterface(IID, Obj) then Result := S_OK
else Result := E_NOINTERFACE;
end;
procedure TGMInterfacedCollection.SetItems(I: Integer;
const Value: TGMInterfacedCollectionItem);
begin
inherited SetItem(I, Value);
end;
function TGMInterfacedCollection._AddRef: Integer;
begin
Result := -1;
end;
function TGMInterfacedCollection._Release: Integer;
begin
Result := -1;
end;
{ EGMNotValidRealNumber }
constructor EGMNotValidRealNumber.Create(const Args: array of const;
Lang: TGMLang);
begin
inherited Create(1, Args, Lang);
end;
{ EGMWithoutOwner }
constructor EGMWithoutOwner.Create(Lang: TGMLang);
begin
inherited Create(2, [], Lang);
end;
{ EGMOwnerWithoutJS }
constructor EGMOwnerWithoutJS.Create(Lang: TGMLang);
begin
inherited Create(3, [], Lang);
end;
{ EGMJSError }
constructor EGMJSError.Create(const Args: array of const; Lang: TGMLang);
begin
inherited Create(4, Args, Lang);
end;
{ EGMUnassignedObject }
constructor EGMUnassignedObject.Create(const Args: array of const;
Lang: TGMLang);
begin
inherited Create(5, Args, Lang);
end;
{ EGMMapIsActive }
constructor EGMMapIsActive.Create(Lang: TGMLang);
begin
inherited Create(6, [], Lang);
end;
{ EGMIncorrectBrowser }
constructor EGMIncorrectBrowser.Create(Lang: TGMLang);
begin
inherited Create(7, [], Lang);
end;
{ EGMCanLoadResource }
constructor EGMCanLoadResource.Create(Lang: TGMLang);
begin
inherited Create(8, [], Lang);
end;
{ EGMTimeOut }
constructor EGMTimeOut.Create(Lang: TGMLang);
begin
inherited Create(9, [], Lang);
end;
{ EGMNotActive }
constructor EGMNotActive.Create(Lang: TGMLang);
begin
inherited Create(10, [], Lang);
end;
end.
|
unit ColumnsBarButtonsHelper;
interface
uses
System.Classes, Vcl.ActnList, dxBar, cxGridDBBandedTableView,
cxGridBandedTableView, System.Generics.Collections, cxVGridViewInfo, cxGrid,
cxDBTL, cxTL;
type
TGroupGVAction = class;
TGVAction = class;
TTLAction = class;
TTLBandAction = class;
TTLColumnAction = class;
TGroupTLAction = class;
TGroupTLActionClass = class of TGroupTLAction;
TGroupGVActionClass = class of TGroupGVAction;
TGVAction = class(TAction)
private
protected
function GetGridView: TcxGridDBBandedTableView; virtual; abstract;
public
property GridView: TcxGridDBBandedTableView read GetGridView;
end;
TGVBandAction = class(TGVAction)
procedure actCustomizeBandExecute(Sender: TObject); virtual;
private
FBand: TcxGridBand;
procedure SetBand(const Value: TcxGridBand);
protected
function GetGridView: TcxGridDBBandedTableView; override;
public
property Band: TcxGridBand read FBand write SetBand;
end;
TGVColumnAction = class(TGVAction)
procedure actCustomizeColumnExecute(Sender: TObject); virtual;
private
FColumn: TcxGridDBBandedColumn;
procedure SetColumn(const Value: TcxGridDBBandedColumn);
protected
function GetGridView: TcxGridDBBandedTableView; override;
public
property Column: TcxGridDBBandedColumn read FColumn write SetColumn;
end;
TGVColumnsBarButtons = class(TComponent)
private
FGroupActions: TList<TGroupGVAction>;
FcxGridDBBandedTableView: TcxGridDBBandedTableView;
FdxBarSubitem: TdxBarSubItem;
protected
function CreateBandAction(ABand: TcxGridBand): TGVBandAction; virtual;
function CreateColumnAction(AColumn: TcxGridDBBandedColumn)
: TGVColumnAction; virtual;
procedure CreateDxBarButton(AAction: TAction;
ABarButtonStyle: TdxBarButtonStyle; ACloseSubMenuOnClick: Boolean);
function CreateGroupAction(AActionClass: TGroupGVActionClass)
: TGroupGVAction;
procedure CreateGroupActions; virtual;
procedure ProcessGridView; virtual;
public
constructor Create(AOwner: TComponent; AdxBarSubitem: TdxBarSubItem;
AcxGridDBBandedTableView: TcxGridDBBandedTableView); reintroduce; virtual;
destructor Destroy; override;
procedure AfterConstruction; override;
end;
TGroupGVAction = class(TAction)
private
FActions: TList<TGVAction>;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Actions: TList<TGVAction> read FActions;
end;
TGVHideAllAction = class(TGroupGVAction)
procedure actHideAllExecute(Sender: TObject);
private
HideAll: Boolean;
public
constructor Create(AOwner: TComponent); override;
end;
TGVColumnsBarButtonsEx = class(TGVColumnsBarButtons)
private
FChildGridView: TcxGridDBBandedTableView;
protected
function CreateBandAction(ABand: TcxGridBand): TGVBandAction; override;
function CreateColumnAction(AColumn: TcxGridDBBandedColumn)
: TGVColumnAction; override;
public
constructor Create(AOwner: TComponent; AdxBarSubitem: TdxBarSubItem;
AcxGridDBBandedTableView, AChildGridView: TcxGridDBBandedTableView);
reintroduce;
end;
TGVColumnActionEx = class(TGVColumnAction)
procedure actCustomizeColumnExecute(Sender: TObject); override;
private
FChildAction: TGVColumnAction;
property ChildAction: TGVColumnAction read FChildAction write FChildAction;
end;
TGVBandActionEx = class(TGVBandAction)
procedure actCustomizeBandExecute(Sender: TObject); override;
private
FChildAction: TGVBandAction;
property ChildAction: TGVBandAction read FChildAction write FChildAction;
end;
TTLColumnsBarButtons = class(TComponent)
private
FcxDBTreeList: TcxDBTreeList;
FdxBarSubitem: TdxBarSubItem;
FGroupActions: TList<TGroupTLAction>;
protected
procedure CreateDxBarButton(AAction: TAction;
ABarButtonStyle: TdxBarButtonStyle; ACloseSubMenuOnClick: Boolean);
function CreateGroupAction(AActionClass: TGroupTLActionClass)
: TGroupTLAction;
procedure CreateGroupActions;
function CreateBandAction(Band: TcxTreeListBand): TTLBandAction;
function CreateColumnAction(AColumn: TcxTreeListColumn): TTLColumnAction;
procedure ProcessTreeList;
public
constructor Create(AOwner: TComponent; AdxBarSubitem: TdxBarSubItem;
AcxDBTreeList: TcxDBTreeList); reintroduce;
destructor Destroy; override;
procedure AfterConstruction; override;
end;
TTLAction = class(TAction)
private
protected
function GetDBTreeList: TcxDBTreeList; virtual; abstract;
public
property DBTreeList: TcxDBTreeList read GetDBTreeList;
end;
TTLBandAction = class(TTLAction)
procedure actHideBandExecute(Sender: TObject); virtual;
private
FcxTreeListBand: TcxTreeListBand;
procedure SetcxTreeListBand(const Value: TcxTreeListBand);
protected
function GetDBTreeList: TcxDBTreeList; override;
public
property cxTreeListBand: TcxTreeListBand read FcxTreeListBand
write SetcxTreeListBand;
end;
TTLColumnAction = class(TTLAction)
procedure actHideColumnExecute(Sender: TObject); virtual;
private
FColumn: TcxTreeListColumn;
procedure SetColumn(const Value: TcxTreeListColumn);
protected
function GetDBTreeList: TcxDBTreeList; override;
public
property Column: TcxTreeListColumn read FColumn write SetColumn;
end;
TGroupTLAction = class(TAction)
private
FActions: TList<TTLAction>;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Actions: TList<TTLAction> read FActions;
end;
TTLHideAllAction = class(TGroupTLAction)
procedure actHideAllExecute(Sender: TObject);
private
HideAll: Boolean;
public
constructor Create(AOwner: TComponent); override;
end;
implementation
uses System.SysUtils, System.Generics.Defaults;
{ TGVColumnsBarButtons }
constructor TGVColumnsBarButtons.Create(AOwner: TComponent;
AdxBarSubitem: TdxBarSubItem;
AcxGridDBBandedTableView: TcxGridDBBandedTableView);
begin
inherited Create(AOwner);
Assert(AdxBarSubitem <> nil);
Assert(AcxGridDBBandedTableView <> nil);
FdxBarSubitem := AdxBarSubitem;
FcxGridDBBandedTableView := AcxGridDBBandedTableView;
FGroupActions := TList<TGroupGVAction>.Create;
end;
destructor TGVColumnsBarButtons.Destroy;
var
i: Integer;
begin
// Удаляем ссылки на все добавленные кнопки
for i := FdxBarSubitem.ItemLinks.Count - 1 downto 0 do
FdxBarSubitem.ItemLinks.Delete(i);
inherited;
FreeAndNil(FGroupActions);
end;
procedure TGVColumnsBarButtons.AfterConstruction;
begin
inherited;
ProcessGridView;
end;
function TGVColumnsBarButtons.CreateBandAction(ABand: TcxGridBand)
: TGVBandAction;
begin
Result := TGVBandAction.Create(Self);
Result.Band := ABand;
end;
function TGVColumnsBarButtons.CreateColumnAction(AColumn: TcxGridDBBandedColumn)
: TGVColumnAction;
begin
Result := TGVColumnAction.Create(Self);
Result.Column := AColumn;
end;
procedure TGVColumnsBarButtons.CreateDxBarButton(AAction: TAction;
ABarButtonStyle: TdxBarButtonStyle; ACloseSubMenuOnClick: Boolean);
var
AdxBarButton: TdxBarButton;
AdxBarItemLink: TdxBarItemLink;
begin
AdxBarButton := TdxBarButton.Create(Self);
AdxBarButton.ButtonStyle := ABarButtonStyle;
AdxBarButton.CloseSubMenuOnClick := ACloseSubMenuOnClick;
AdxBarButton.Action := AAction;
AdxBarItemLink := FdxBarSubitem.ItemLinks.AddButton;
AdxBarItemLink.Item := AdxBarButton;
end;
function TGVColumnsBarButtons.CreateGroupAction(AActionClass
: TGroupGVActionClass): TGroupGVAction;
begin
// Добавляем действие для представления в целом
Result := AActionClass.Create(Self);
CreateDxBarButton(Result, bsDefault, True);
FGroupActions.Add(Result);
end;
procedure TGVColumnsBarButtons.CreateGroupActions;
begin
// Добавляем действие "Спрятать все колонки"
CreateGroupAction(TGVHideAllAction);
end;
procedure TGVColumnsBarButtons.ProcessGridView;
var
AAction: TGVAction;
ABands: TList<TcxGridBand>;
AColumn: TcxGridDBBandedColumn;
i: Integer;
AAllColumns: TList<TcxGridDBBandedColumn>;
AColumns: TList<TcxGridDBBandedColumn>;
ACustomizeGridViewAction: TGroupGVAction;
begin
// Создаём действия для табличного представления в целом
CreateGroupActions;
ABands := TList<TcxGridBand>.Create;
AColumns := TList<TcxGridDBBandedColumn>.Create;
// Список всех колонок cxGrid
AAllColumns := TList<TcxGridDBBandedColumn>.Create;
try
// Добавляем в список все колонки, которые есть у cxGrid
for i := 0 to FcxGridDBBandedTableView.ColumnCount - 1 do
begin
if FcxGridDBBandedTableView.Columns[i].Position.Band <> nil then
begin
Assert(FcxGridDBBandedTableView.Columns[i].Position.Band <> nil);
AAllColumns.Add(FcxGridDBBandedTableView.Columns[i]);
end;
end;
// Сортируем эти столбцы по позиции бэнда и по позиции внутри бэнда
AAllColumns.Sort(TComparer<TcxGridDBBandedColumn>.Construct(
function(const L, R: TcxGridDBBandedColumn): Integer
begin
Result := L.Position.Band.Position.ColIndex -
R.Position.Band.Position.ColIndex;
if Result = 0 then
Result := L.Position.ColIndex - R.Position.ColIndex;
end));
for AColumn in AAllColumns do
begin
// AColumn := FcxGridDBBandedTableView.Columns[i];
Assert(AColumn.Position.Band <> nil);
if (AColumn.VisibleForCustomization) and
(AColumn.Position.Band.VisibleForCustomization) then
begin
AAction := nil;
// Если колонка относится к "пустому" бэнду
if (AColumn.Position.Band.Caption = '') then
begin
// Если этот бэнд не зафиксирован
if AColumn.Position.Band.FixedKind = fkNone then
begin
// если действия для такой колонки ещё не создавали
if AColumns.IndexOf(AColumn) < 0 then
begin
AColumns.Add(AColumn);
AAction := CreateColumnAction(AColumn);
end;
end;
end
else
begin
// Если колонка относится к не пустому бэнду
// Если для такого бэнда действие ещё не создавали
if ABands.IndexOf(AColumn.Position.Band) < 0 then
begin
ABands.Add(AColumn.Position.Band);
AAction := CreateBandAction(AColumn.Position.Band);
end;
end;
if AAction <> nil then
begin
for ACustomizeGridViewAction in FGroupActions do
ACustomizeGridViewAction.Actions.Add(AAction);
CreateDxBarButton(AAction, bsChecked, False);
end;
end;
end;
finally
FreeAndNil(ABands);
FreeAndNil(AColumns);
FreeAndNil(AAllColumns);
end;
end;
procedure TGVBandAction.actCustomizeBandExecute(Sender: TObject);
begin
Assert(FBand <> nil);
Checked := not Checked;
FBand.Visible := Checked;
if FBand.Visible then
FBand.ApplyBestFit();
end;
function TGVBandAction.GetGridView: TcxGridDBBandedTableView;
begin
Result := Band.GridView as TcxGridDBBandedTableView;
end;
procedure TGVBandAction.SetBand(const Value: TcxGridBand);
begin
if FBand <> Value then
begin
FBand := Value;
if FBand <> nil then
begin
Caption := FBand.Caption;
Checked := FBand.Visible;
OnExecute := actCustomizeBandExecute;
end
else
begin
Caption := '';
Checked := False;
OnExecute := nil;
end;
end;
end;
procedure TGVColumnAction.actCustomizeColumnExecute(Sender: TObject);
var
ABand: TcxGridBand;
AnyVisible: Boolean;
i: Integer;
begin
Assert(FColumn <> nil);
Checked := not Checked;
FColumn.Visible := Checked;
if not FColumn.Visible then
begin
AnyVisible := False;
ABand := FColumn.Position.Band;
for i := 0 to ABand.ColumnCount - 1 do
begin
AnyVisible := ABand.Columns[i].Visible;
if AnyVisible then
Break;
end;
// если все колонки в бэнде невидимые
if not AnyVisible then
ABand.Visible := False;
end
else
FColumn.Position.Band.Visible := True;
end;
function TGVColumnAction.GetGridView: TcxGridDBBandedTableView;
begin
Result := FColumn.GridView as TcxGridDBBandedTableView;
end;
procedure TGVColumnAction.SetColumn(const Value: TcxGridDBBandedColumn);
begin
if FColumn <> Value then
begin
FColumn := Value;
if FColumn <> nil then
begin
Caption := FColumn.Caption;
Checked := FColumn.Visible;
OnExecute := actCustomizeColumnExecute;
end
else
begin
Caption := '';
Checked := False;
OnExecute := nil;
end;
end;
end;
constructor TGVHideAllAction.Create(AOwner: TComponent);
begin
inherited;
HideAll := False;
Caption := 'Спрятать все';
OnExecute := actHideAllExecute;
end;
procedure TGVHideAllAction.actHideAllExecute(Sender: TObject);
var
AAction: TAction;
AGridView: TcxGridDBBandedTableView;
begin
if Actions.Count > 0 then
begin
HideAll := not HideAll;
if HideAll then
Caption := 'Показать все'
else
Caption := 'Спрятать все';
AGridView := Actions[0].GridView;
Assert(AGridView <> nil);
AGridView.BeginBestFitUpdate;
try
for AAction in Actions do
begin
if (HideAll and AAction.Checked) or (not HideAll and not AAction.Checked)
then
AAction.Execute;
end;
finally
AGridView.EndBestFitUpdate;
end;
end;
end;
procedure TGVColumnActionEx.actCustomizeColumnExecute(Sender: TObject);
{
var
ABand: TcxGridBand;
ABand2: TcxGridBand;
AWidth: Integer;
}
begin
inherited;
if FChildAction = nil then
Exit;
FChildAction.Execute;
// Всё это не имеет смысла
// Достаточно сделать ширину дочернего бэнда 0
{
ABand := FColumn.Position.Band;
ABand2 := FChildAction.Column.Position.Band;
if (ABand = nil) or (ABand2 = nil) then
Exit;
// Пытаемся выровнять ширину бэндов, к которым относятся колонки
AWidth := FColumn.GridView.ViewInfo.HeaderViewInfo.BandsViewInfo.Items[ABand.VisibleIndex].Width;
ABand2.Width := AWidth;
}
end;
{ TGVColumnsBarButtonsEx }
constructor TGVColumnsBarButtonsEx.Create(AOwner: TComponent;
AdxBarSubitem: TdxBarSubItem; AcxGridDBBandedTableView, AChildGridView
: TcxGridDBBandedTableView);
begin
inherited Create(AOwner, AdxBarSubitem, AcxGridDBBandedTableView);
FChildGridView := AChildGridView;
end;
function TGVColumnsBarButtonsEx.CreateBandAction(ABand: TcxGridBand)
: TGVBandAction;
var
AChildAction: TGVBandAction;
begin
Assert(FChildGridView <> nil);
Result := TGVBandActionEx.Create(Self);
Result.Band := ABand;
AChildAction := TGVBandAction.Create(Self);
AChildAction.Band := FChildGridView.Bands[ABand.Index];
(Result as TGVBandActionEx).ChildAction := AChildAction;
end;
function TGVColumnsBarButtonsEx.CreateColumnAction
(AColumn: TcxGridDBBandedColumn): TGVColumnAction;
var
AChildAction: TGVColumnAction;
begin
Assert(FChildGridView <> nil);
Result := TGVColumnActionEx.Create(Self);
Result.Column := AColumn;
AChildAction := TGVColumnAction.Create(Self);
AChildAction.Column := FChildGridView.Columns[AColumn.Index];
(Result as TGVColumnActionEx).ChildAction := AChildAction;
end;
procedure TGVBandActionEx.actCustomizeBandExecute(Sender: TObject);
begin
inherited;
if FChildAction <> nil then
FChildAction.Execute;
end;
constructor TGroupGVAction.Create(AOwner: TComponent);
begin
inherited;
FActions := TList<TGVAction>.Create;
end;
destructor TGroupGVAction.Destroy;
begin
FreeAndNil(FActions);
inherited;
end;
{ TTLColumnsBarButtons }
constructor TTLColumnsBarButtons.Create(AOwner: TComponent;
AdxBarSubitem: TdxBarSubItem; AcxDBTreeList: TcxDBTreeList);
begin
inherited Create(AOwner);
Assert(AdxBarSubitem <> nil);
Assert(AcxDBTreeList <> nil);
FdxBarSubitem := AdxBarSubitem;
FcxDBTreeList := AcxDBTreeList;
// Действия над всем деревом
FGroupActions := TList<TGroupTLAction>.Create;
end;
destructor TTLColumnsBarButtons.Destroy;
begin
inherited;
FreeAndNil(FGroupActions);
end;
procedure TTLColumnsBarButtons.AfterConstruction;
begin
inherited;
ProcessTreeList;
end;
procedure TTLColumnsBarButtons.CreateDxBarButton(AAction: TAction;
ABarButtonStyle: TdxBarButtonStyle; ACloseSubMenuOnClick: Boolean);
var
AdxBarButton: TdxBarButton;
AdxBarItemLink: TdxBarItemLink;
begin
AdxBarButton := TdxBarButton.Create(Self);
AdxBarButton.ButtonStyle := ABarButtonStyle;
AdxBarButton.CloseSubMenuOnClick := ACloseSubMenuOnClick;
AdxBarButton.Action := AAction;
AdxBarItemLink := FdxBarSubitem.ItemLinks.AddButton;
AdxBarItemLink.Item := AdxBarButton;
end;
function TTLColumnsBarButtons.CreateGroupAction(AActionClass
: TGroupTLActionClass): TGroupTLAction;
begin
// Добавляем действие для представления в целом
Result := AActionClass.Create(Self);
CreateDxBarButton(Result, bsDefault, True);
FGroupActions.Add(Result);
end;
procedure TTLColumnsBarButtons.CreateGroupActions;
begin
// Создаём действие "спрятать всё"
CreateGroupAction(TTLHideAllAction);
end;
function TTLColumnsBarButtons.CreateBandAction(Band: TcxTreeListBand)
: TTLBandAction;
begin
Assert(Band <> nil);
Result := TTLBandAction.Create(Self);
Result.cxTreeListBand := Band;
end;
function TTLColumnsBarButtons.CreateColumnAction(AColumn: TcxTreeListColumn)
: TTLColumnAction;
begin
Assert(AColumn <> nil);
Result := TTLColumnAction.Create(Self);
Result.Column := AColumn;
end;
procedure TTLColumnsBarButtons.ProcessTreeList;
var
AAction: TTLAction;
ABaseTLAction: TGroupTLAction;
ACaptions: TList<String>;
AColumn: TcxTreeListColumn;
AColumns: TList<TcxTreeListColumn>;
i: Integer;
begin
// Создаём действия для табличного представления в целом
CreateGroupActions;
ACaptions := TList<string>.Create;
try
// Список колонок TreeList
AColumns := TList<TcxTreeListColumn>.Create;
try
// Добавляем в список все колонки, которые есть у cxGrid
for i := 0 to FcxDBTreeList.ColumnCount - 1 do
begin
if (FcxDBTreeList.Columns[i] as TcxDBTreeListColumn)
.DataBinding.FieldName = '' then
Continue;
Assert(FcxDBTreeList.Columns[i].Position.Band <> nil);
AColumns.Add(FcxDBTreeList.Columns[i]);
end;
// Сортируем эти столбцы по позиции бэнда и по позиции внутри бэнда
AColumns.Sort(TComparer<TcxTreeListColumn>.Construct(
function(const L, R: TcxTreeListColumn): Integer
begin
Result := L.Position.Band.Position.ColIndex -
R.Position.Band.Position.ColIndex;
if Result = 0 then
Result := L.Position.ColIndex - R.Position.ColIndex;
end));
for AColumn in AColumns do
begin
Assert(AColumn.Position.Band <> nil);
if (AColumn.Options.Customizing) and
(AColumn.Position.Band.Options.Customizing) then
begin
AAction := nil;
// Если колонка относится к "пустому" бэнду
if (AColumn.Position.Band.Caption.Text = '') then
begin
// Если этот бэнд не зафиксирован
if AColumn.Position.Band.FixedKind = tlbfNone then
begin
// если такого заголовка ещё не было
if ACaptions.IndexOf(AColumn.Caption.Text) < 0 then
begin
ACaptions.Add(AColumn.Caption.Text);
AAction := CreateColumnAction(AColumn);
end;
end;
end
else
begin
// Если колонка относится к не пустому бэнду
if AColumn.Position.Band.FixedKind = tlbfNone then
begin
// если такого заголовка бэнда ещё не было
if ACaptions.IndexOf(AColumn.Position.Band.Caption.Text) < 0 then
begin
ACaptions.Add(AColumn.Position.Band.Caption.Text);
AAction := CreateBandAction(AColumn.Position.Band);
end;
end;
end;
if AAction <> nil then
begin
for ABaseTLAction in FGroupActions do
ABaseTLAction.Actions.Add(AAction);
CreateDxBarButton(AAction, bsChecked, False);
end;
end;
end;
finally
FreeAndNil(AColumns)
end;
finally
FreeAndNil(ACaptions);
end;
end;
procedure TTLBandAction.actHideBandExecute(Sender: TObject);
begin
Assert(FcxTreeListBand <> nil);
Checked := not Checked;
FcxTreeListBand.Visible := Checked;
if FcxTreeListBand.Visible then
FcxTreeListBand.ApplyBestFit();
end;
function TTLBandAction.GetDBTreeList: TcxDBTreeList;
begin
Assert(FcxTreeListBand <> nil);
Result := FcxTreeListBand.TreeList as TcxDBTreeList;
end;
procedure TTLBandAction.SetcxTreeListBand(const Value: TcxTreeListBand);
begin
if FcxTreeListBand = Value then
Exit;
FcxTreeListBand := Value;
if FcxTreeListBand <> nil then
begin
Caption := FcxTreeListBand.Caption.Text;
Checked := FcxTreeListBand.Visible;
OnExecute := actHideBandExecute;
end
else
begin
Caption := '';
Checked := False;
OnExecute := nil;
end;
end;
procedure TTLColumnAction.actHideColumnExecute(Sender: TObject);
var
ABand: TcxTreeListBand;
AnyVisible: Boolean;
i: Integer;
begin
Assert(FColumn <> nil);
Checked := not Checked;
FColumn.Visible := Checked;
if not FColumn.Visible then
begin
AnyVisible := False;
ABand := FColumn.Position.Band;
for i := 0 to ABand.ColumnCount - 1 do
begin
AnyVisible := ABand.Columns[i].Visible;
if AnyVisible then
Break;
end;
// если все колонки в бэнде невидимые
if not AnyVisible then
ABand.Visible := False;
end
else
FColumn.Position.Band.Visible := True;
end;
function TTLColumnAction.GetDBTreeList: TcxDBTreeList;
begin
Assert(FColumn <> nil);
Result := FColumn.TreeList as TcxDBTreeList;
end;
procedure TTLColumnAction.SetColumn(const Value: TcxTreeListColumn);
begin
if FColumn = Value then
Exit;
FColumn := Value;
if FColumn <> nil then
begin
Caption := FColumn.Caption.Text;
Checked := FColumn.Visible;
OnExecute := actHideColumnExecute;
end
else
begin
Caption := '';
Checked := False;
OnExecute := nil;
end;
end;
constructor TGroupTLAction.Create(AOwner: TComponent);
begin
inherited;
FActions := TList<TTLAction>.Create;
end;
destructor TGroupTLAction.Destroy;
begin
FreeAndNil(FActions);
inherited;
end;
constructor TTLHideAllAction.Create(AOwner: TComponent);
begin
inherited;
HideAll := False;
Caption := 'Спрятать все';
OnExecute := actHideAllExecute;
end;
procedure TTLHideAllAction.actHideAllExecute(Sender: TObject);
var
AAction: TAction;
ATreeList: TcxDBTreeList;
begin
if Actions.Count > 0 then
begin
HideAll := not HideAll;
if HideAll then
Caption := 'Показать все'
else
Caption := 'Спрятать все';
ATreeList := Actions[0].DBTreeList;
Assert(ATreeList <> nil);
ATreeList.BeginUpdate;
try
for AAction in Actions do
begin
if (HideAll and AAction.Checked) or (not HideAll and not AAction.Checked)
then
AAction.Execute;
end;
finally
ATreeList.EndUpdate;
end;
end;
end;
end.
|
{*********************************************}
{ TeeChart Delphi Component Library }
{ Keyboard Scrolling Demo }
{ Copyright (c) 1996 by David Berneda }
{ All rights reserved }
{*********************************************}
unit Ukeyboa;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Teengine, Series, ExtCtrls, Chart, StdCtrls, Buttons,
TeeProcs;
type
TKeyboardForm = class(TForm)
Chart1: TChart;
LineSeries1: TLineSeries;
Panel1: TPanel;
BitBtn1: TBitBtn;
InvertScroll: TCheckBox;
CheckLimits: TCheckBox;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure CheckLimitsClick(Sender: TObject);
procedure InvertScrollClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.DFM}
procedure TKeyboardForm.FormCreate(Sender: TObject);
begin
LineSeries1.FillSampleValues(500);
AnimatedZoomFactor:=4;
end;
procedure TKeyboardForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
Var XDelta,YDelta,
XRange,YRange:Double;
begin
{ initialize some temporary variables... }
XDelta:=0;
YDelta:=0;
With LineSeries1.GetHorizAxis do XRange:=Maximum-Minimum;
With LineSeries1.GetVertAxis do YRange:=Maximum-Minimum;
{ handle keyboard !!! }
if ssShift in Shift then
begin
Case key of
VK_LEFT,VK_UP : Chart1.ZoomPercent( 110 );
VK_RIGHT,VK_DOWN : Chart1.ZoomPercent( 90 );
end;
exit;
end
else
Case key of
VK_LEFT : XDelta:=-XRange/100;
VK_RIGHT : XDelta:= XRange/100;
VK_UP : YDelta:= YRange/100;
VK_DOWN : YDelta:=-YRange/100;
vk_Next : YDelta:=-YRange/10;
vk_Prior : YDelta:= YRange/10;
VK_SPACE : Begin Chart1.UndoZoom; Exit; End; { <-- reset scrolling }
end;
{ just to make this example a little better... }
if not InvertScroll.Checked then
begin
XDelta:=-XDelta;
YDelta:=-YDelta;
end;
{ apply scrolling !!! }
With Chart1 do
Begin
LeftAxis.Scroll(YDelta,CheckLimits.Checked);
RightAxis.Scroll(YDelta,CheckLimits.Checked);
BottomAxis.Scroll(XDelta,CheckLimits.Checked);
TopAxis.Scroll(XDelta,CheckLimits.Checked);
SetFocus;
End;
end;
procedure TKeyboardForm.CheckLimitsClick(Sender: TObject);
begin
ShowMessage('Please zoom before scrolling.');
Chart1.SetFocus;
end;
procedure TKeyboardForm.InvertScrollClick(Sender: TObject);
begin
Chart1.SetFocus;
end;
end.
|
unit uTesteRemovePrinter;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, LMDCustomComponent, LMDSysInfo, Printers, winspool;
type
TForm33 = class(TForm)
SI: TLMDSysInfo;
Button1: TButton;
Memo1: TMemo;
procedure FormShow(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form33: TForm33;
implementation
{$R *.dfm}
procedure GetPrinterList(List: TStrings);
var
Buffer, PrinterInfo: PChar;
Flags, Count, NumInfo: DWORD;
i: Integer;
Level: Byte;
begin
List.Clear;
if Win32Platform = VER_PLATFORM_WIN32_NT then
begin
Flags := PRINTER_ENUM_LOCAL;
Level := 4;
end
else
begin
Flags := PRINTER_ENUM_LOCAL;
Level := 5;
end;
Count := 0;
EnumPrinters(Flags, nil, Level, nil, 0, Count, NumInfo);
if Count > 0 then
begin
GetMem(Buffer, Count);
try
if not EnumPrinters(Flags, nil, Level, PByte(Buffer), Count, Count, NumInfo) then
Exit;
PrinterInfo := Buffer;
for i := 0 to NumInfo - 1 do
begin
if Level = 4 then
begin
List.Add(PPrinterInfo4(PrinterInfo)^.pPrinterName);
Inc(PrinterInfo, SizeOf(TPrinterInfo4));
end
else
begin
List.Add(PPrinterInfo5(PrinterInfo)^.pPrinterName);
Inc(PrinterInfo, SizeOf(TPrinterInfo5));
end;
end;
finally
FreeMem(Buffer, Count);
end;
end;
end;
procedure TForm33.Button1Click(Sender: TObject);
begin
GetPrinterList(Memo1.Lines);
end;
procedure TForm33.FormShow(Sender: TObject);
begin
// Memo1.Lines.Text := SI.AllPrinters.Text;
end;
end.
|
unit WinampApi;
{
WinAmp API Wrapper for Delphi
Author: C.Small
Date: May 2001
www.sloppycode.net
Winamp API docs:
http://www.winamp.com/nsdn/winamp2x/dev/sdk/api.jhtml
}
interface
uses Windows,Messages,Classes,SysUtils;
type
TWinampApi = class
private
WinampHnd : THandle;
function ConvertTime(n: integer;m : integer): string;
function ConvertTimeTool(n: integer): string;
function split(seperator: Char; text: String; var list: TStringList): Integer;
public
WinampPath : String;
SongLengthParseTime : Boolean;
SongPosParseTime : Boolean;
constructor Create(WPath : String);
function getWhatsPlaying():String;
function getSongState():String;
function getSongPosition():String;
function getSongLength():String;
function getSongSampleRate():String;
function getSongBitRate():String;
function getSongChannels():String;
function getPlayListPosition():String;
function getPlayListLength():String;
procedure getPlayList(var PlayList:TStringList;var FileList:TStringList);
procedure PlaySong(Mp3Name:string);
procedure AddToPlayList(Mp3Name:string);
procedure Play();
procedure Stop();
procedure Pause();
procedure NextTrack();
procedure PreviousTrack();
procedure Forward5Seconds();
procedure Back5Seconds();
procedure StartOfPlayList();
procedure VolumeUp();
procedure VolumeDown();
procedure FadeOutStop();
end;
implementation
{ ----- PUBLIC VOID/NULL RETURN METHODS ---- }
constructor TWinampApi.Create(WPath : String);
begin
SongLengthParseTime := False;
SongPosParseTime := False;
WinampPath := WPath;
WinampHnd := FindWindow(\'Winamp v1.x\', nil);
end;
procedure TWinampApi.PlaySong(Mp3Name:String);
begin
WinExec(PChar(\'\"\'+WinampPath+\'\\winamp.exe\" \"\'+Mp3Name+\'\"\'),SW_SHOW);
end;
procedure TWinampApi.AddToPlayList(Mp3Name:String);
begin
WinExec(PChar(\'\"\'+WinampPath+\'\\winamp.exe\" /ADD \"\'+Mp3Name+\'\"\'),SW_SHOW);
end;
procedure TWinampApi.Play();
begin
SendMessage(WinampHnd, WM_COMMAND, 40045, 0);
end;
procedure TWinampApi.Stop();
begin
SendMessage(WinampHnd, WM_COMMAND, 40047, 0);
end;
procedure TWinampApi.Pause();
begin
SendMessage(WinampHnd, WM_COMMAND, 40046, 0);
end;
procedure TWinampApi.NextTrack();
begin
SendMessage(WinampHnd, WM_COMMAND, 40048, 0);
end;
procedure TWinampApi.PreviousTrack();
begin
SendMessage(WinampHnd, WM_COMMAND, 40044, 0);
end;
procedure TWinampApi.Forward5Seconds();
begin
SendMessage(WinampHnd, WM_COMMAND, 40148, 0);
end;
procedure TWinampApi.Back5Seconds();
begin
SendMessage(WinampHnd, WM_COMMAND, 40144, 0);
end;
procedure TWinampApi.StartOfPlayList();
begin
SendMessage(WinampHnd, WM_COMMAND, 40154, 0);
end;
procedure TWinampApi.VolumeUp();
begin
SendMessage(WinampHnd, WM_COMMAND, 40058, 0);
end;
procedure TWinampApi.VolumeDown();
begin
SendMessage(WinampHnd, WM_COMMAND, 40059, 0);
end;
procedure TWinampApi.FadeOutStop();
begin
SendMessage(WinampHnd, WM_COMMAND, 40147, 0);
end;
function TWinampApi.getWhatsPlaying():String;
var
TitleLen: integer;
TempInt : Integer;
TempStr: String;
begin
TempStr := \'Winamp isn\'\'t running\';
if WinampHnd <> 0 then
begin
// Get wHnd text
TitleLen := GetWindowTextLength(WinampHnd)+2;
SetLength(TempStr,TitleLen);
GetWindowText(WinampHnd,Pchar(TempStr),TitleLen);
SetLength(TempStr,Length(TempStr));
// Remove \'- Winamp\' part
TempInt := Pos(\'- Winamp\',TempStr);
TempStr := Copy(TempStr,0,TempInt -2); // Knock of space and -
end;
result := TempStr;
end;
procedure TWinampApi.getPlayList(var PlayList:TStringList;var FileList:TStringList);
var
Buffer: string;
Stream: TFileStream;
FileStr : String;
TempList : TStringList;
TempListLen : Integer;
TempStr,TempStr2 : String;
TempPos,TempPos2 : Integer;
i : Integer;
begin
SendMessage(WinampHnd,WM_USER,0,120);
Stream := TFileStream.Create(WinampPath+\'\\winamp.m3u\', fmShareDenyNone);
try
SetLength(buffer, Stream.Size);
Stream.Read(Buffer[1], Stream.Size);
FileStr := Buffer;
finally
Stream.Free;
end;
TempList := TStringList.Create;
TempListLen := Split(\'#\',FileStr,TempList);
// Start from 1 to cut out \'#EXTM3U\'. Grab Name and Filename
for i:=2 to TempListLen -1 do
begin
TempPos := Pos(\',\',TempList.Strings[i]);
TempPos2 := Pos(#13,TempList.Strings[i]);
TempStr := Copy(TempList.Strings[i],TempPos +1,(TempPos2 -1) - TempPos);
TempStr2 := Copy(TempList.Strings[i],TempPos2 +2,(Length(TempList.Strings[i]) -1) - (TempPos2 +2));
PlayList.Add(TempStr);
FileList.Add(TempStr2);
end;
TempList.Free;
end;
{ ----- PUBLIC RETURN METHODS ---- }
function TWinampApi.getSongState():String;
var
SongState : Word;
SongStateStr : String;
begin
SongState := SendMessage(WinampHnd,WM_USER,0,104);
case SongState of
1: SongStateStr:= \'playing\';
3: SongStateStr:= \'paused\';
0: SongStateStr:= \'stopped\'
else
SongStateStr := \'unknown\';
end;
Result := SongStateStr;
end;
function TWinampApi.getSongPosition():String;
var
TempInt : Integer;
begin
TempInt := SendMessage(WinampHnd,WM_USER,0,105);
if SongPosParseTime then
Result := ConvertTime(TempInt,1000)
else
Result := IntToStr(TempInt);
end;
function TWinampApi.getSongLength():String;
var
TempInt : Integer;
begin
TempInt := SendMessage(WinampHnd,WM_USER,1,105);
if SongLengthParseTime then
Result := ConvertTime(TempInt,1)
else
Result := IntToStr(TempInt);
end;
function TWinampApi.getSongSampleRate():String;
begin
Result := IntToStr(SendMessage(WinampHnd,WM_USER,0,126));
end;
function TWinampApi.getSongBitRate():String;
begin
Result := IntToStr(SendMessage(WinampHnd,WM_USER,1,126));
end;
function TWinampApi.getSongChannels():String;
begin
Result := IntToStr(SendMessage(WinampHnd,WM_USER,2,126));
end;
function TWinampApi.getPlayListPosition():String;
var
TempInt : Integer;
begin
TempInt := SendMessage(WinampHnd,WM_USER,0,125);
if StrToInt(getPlayListLength()) <1 then
Result := IntToStr(TempInt)
else
Result := IntToStr(TempInt +1);
end;
function TWinampApi.getPlayListLength():String;
begin
Result := IntToStr(SendMessage(WinampHnd,WM_USER,0,124));
end;
{ ----- PRIVATE METHODS ----- }
function TWinampApi.ConvertTime(n: integer;m : integer): string;
begin
n := n div m;
result := ConvertTimeTool(n div 60) + \':\' + ConvertTimeTool(n mod 60);
end;
function TWinampApi.ConvertTimeTool(n: integer): string;
begin
if n < 10 then
result := \'0\' + inttostr(n)
else
result := inttostr(n);
end;
function TWinampApi.split(seperator: Char; text: String; var list: TStringList): Integer;
var
mypos, number: Integer;
begin
number:=0;
if Length(text) > 0 then
begin
if text[Length(text)] <> seperator then
text:=text+seperator;
while(Pos(String(seperator),text))>0 do
begin
mypos:=Pos(String(seperator),text);
list.Add(Copy(text,1,mypos-1));
text:=Copy(text,mypos+1,Length(text)-mypos);
Inc(number);
end;
end;
Result:=number;
end;
end. |
unit VCLSFTPClientComponentMainForm;
interface
{$POINTERMATH ON}
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.FileCtrl, Vcl.Grids, Vcl.ComCtrls,
DateUtils, IOUtils, Registry,
tgputtylib, tgputtysftp, tgputtysftpclient;
type
TVCLSFTPClientComponentDemoForm = class(TForm)
DirectoryListBox1: TDirectoryListBox;
DriveComboBox1: TDriveComboBox;
FileListBox1: TFileListBox;
Label1: TLabel;
Label2: TLabel;
edURL: TEdit;
Label3: TLabel;
edPort: TEdit;
Label4: TLabel;
edUserName: TEdit;
Label5: TLabel;
edPassword: TEdit;
Label6: TLabel;
edFolderPath: TEdit;
Label7: TLabel;
sgRemoteFiles: TStringGrid;
Label8: TLabel;
btConnect: TButton;
btDisconnect: TButton;
Label9: TLabel;
cbVerbose: TCheckBox;
memLog: TMemo;
btUpload: TButton;
btDownload: TButton;
cbSavePassword: TCheckBox;
ProgressBar1: TProgressBar;
btDeleteLocal: TButton;
btDeleteRemote: TButton;
btMkDir: TButton;
btRemoveDir: TButton;
btMove: TButton;
TGPuttySFTPClient1: TTGPuttySFTPClient;
procedure btConnectClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btDisconnectClick(Sender: TObject);
procedure sgRemoteFilesDblClick(Sender: TObject);
procedure btDownloadClick(Sender: TObject);
procedure btUploadClick(Sender: TObject);
procedure edFolderPathExit(Sender: TObject);
procedure btDeleteLocalClick(Sender: TObject);
procedure btDeleteRemoteClick(Sender: TObject);
procedure DirectoryListBox1Change(Sender: TObject);
procedure btMkDirClick(Sender: TObject);
procedure btRemoveDirClick(Sender: TObject);
procedure btMoveClick(Sender: TObject);
procedure cbVerboseClick(Sender: TObject);
function TGPuttySFTPClient1SFTPGetInput(Sender: TObject; var cancel: Boolean): string;
function TGPuttySFTPClient1SFTPListing(Sender: TObject; const Items: TSFTPItems): Boolean;
procedure TGPuttySFTPClient1SFTPMessage(Sender: TObject; const Msg: string; const isstderr: Boolean);
function TGPuttySFTPClient1SFTPProgress(Sender: TObject; const bytescopied: Int64; const isupload: Boolean): Boolean;
function TGPuttySFTPClient1SFTPVerifyHostKey(Sender: TObject; const host: string; const port: Integer;
const fingerprint: string; const verificationstatus: Integer;
var storehostkey: Boolean): Boolean;
private
{ Private declarations }
FTotalToCopy:Int64;
FInLoadSettings:Boolean;
procedure SaveSettings;
procedure LoadSettings;
procedure GetListing;
public
{ Public declarations }
end;
var
VCLSFTPClientComponentDemoForm: TVCLSFTPClientComponentDemoForm;
implementation
{$R *.dfm}
procedure TVCLSFTPClientComponentDemoForm.btConnectClick(Sender: TObject);
begin
SaveSettings;
with TGPuttySFTPClient1 do begin
HostName:=edURL.Text;
UserName:=edUserName.Text;
Password:=edPassword.Text;
Port:=StrToIntDef(edPort.Text,22);
Connect;
if edFolderPath.Text<>'' then
ChangeDir(edFolderPath.Text);
edFolderPath.Text:=WorkDir;
end;
GetListing;
end;
procedure TVCLSFTPClientComponentDemoForm.btDeleteLocalClick(Sender: TObject);
var i,count:Integer;
APath:string;
begin
count:=0;
for i:=0 to FileListBox1.Count-1 do
if FileListBox1.Selected[i] then
Inc(count);
if count=0 then
Exit;
if Application.MessageBox(PWideChar('Please confirm deleting '+IntToStr(count)+' file locally (left side)'),
'Confirm Deletion',
MB_YESNO or MB_ICONQUESTION)=IDYES then begin
for i:=0 to FileListBox1.Count-1 do
if FileListBox1.Selected[i] then begin
APath:=DirectoryListBox1.Directory+PathDelim+FileListBox1.Items[i];
DeleteFile(APath);
end;
FileListBox1.Update;
end;
end;
procedure TVCLSFTPClientComponentDemoForm.btDisconnectClick(Sender: TObject);
begin
TGPuttySFTPClient1.Disconnect;
sgRemoteFiles.RowCount:=0;
sgRemoteFiles.ColCount:=0;
end;
procedure TVCLSFTPClientComponentDemoForm.btDownloadClick(Sender: TObject);
var i:Integer;
DownloadStream:TStream;
APath:UnicodeString;
begin
for i:=sgRemoteFiles.Selection.Top to sgRemoteFiles.Selection.Bottom do begin
if sgRemoteFiles.Cells[2,i]<>'<dir>' then begin
APath:=DirectoryListBox1.Directory+PathDelim+sgRemoteFiles.Cells[0,i];
DownloadStream:=TFileStream.Create(APath,fmCreate);
try
FTotalToCopy:=StrToInt64Def(sgRemoteFiles.Cells[2,i],0);
ProgressBar1.Min:=0;
ProgressBar1.Max:=FTotalToCopy div 1024;
ProgressBar1.Position:=0;
ProgressBar1.Visible:=true;
Application.ProcessMessages;
TGPuttySFTPClient1.DownloadStream(sgRemoteFiles.Cells[0,i],
DownloadStream,
false);
FileListBox1.Update;
finally
ProgressBar1.Visible:=false;
FreeAndNil(DownloadStream);
end;
end;
end;
end;
procedure TVCLSFTPClientComponentDemoForm.btMkDirClick(Sender: TObject);
var AName:string;
begin
AName:=InputBox('Make Directory','Enter new Directory Name:','');
if AName<>'' then begin
TGPuttySFTPClient1.MakeDir(AName);
GetListing;
end;
end;
procedure TVCLSFTPClientComponentDemoForm.btMoveClick(Sender: TObject);
var count,i:Integer;
AName:string;
begin
AName:=InputBox('Rename / Move','Enter new name and/or destination directory:','');
if AName<>'' then begin
count:=sgRemoteFiles.Selection.Bottom-sgRemoteFiles.Selection.Top+1;
if count=0 then
Exit;
if Application.MessageBox(PWideChar('Please confirm moving '+IntToStr(count)+' file(s) remotely (right side)'),
'Confirm Moving',
MB_YESNO or MB_ICONQUESTION)=IDYES then begin
for i:=sgRemoteFiles.Selection.Top to sgRemoteFiles.Selection.Bottom do
if sgRemoteFiles.Cells[2,i]<>'<dir>' then
TGPuttySFTPClient1.Move(sgRemoteFiles.Cells[0,i],AName);
end;
GetListing;
end;
end;
procedure TVCLSFTPClientComponentDemoForm.btUploadClick(Sender: TObject);
var i:Integer;
APath:string;
UploadStream:TStream;
LDateTime:TDateTimeInfoRec;
begin
for i:=0 to FileListBox1.Count-1 do
if FileListBox1.Selected[i] then begin
APath:=DirectoryListBox1.Directory+PathDelim+FileListBox1.Items[i];
FileGetDateTimeInfo(APath,LDateTime);
UploadStream:=TFileStream.Create(APath,fmOpenRead);
try
FTotalToCopy:=UploadStream.Size;
ProgressBar1.Min:=0;
ProgressBar1.Max:=FTotalToCopy div 1024;
ProgressBar1.Position:=0;
ProgressBar1.Visible:=true;
Application.ProcessMessages;
TGPuttySFTPClient1.UploadStream(FileListBox1.Items[i],UploadStream,false);
TGPuttySFTPClient1.SetModifiedDate(FileListBox1.Items[i],LDateTime.TimeStamp,false);
GetListing;
finally
FreeAndNil(UploadStream);
ProgressBar1.Visible:=false;
end;
end;
end;
procedure TVCLSFTPClientComponentDemoForm.cbVerboseClick(Sender: TObject);
begin
TGPuttySFTPClient1.Verbose:=cbVerbose.Checked;
end;
procedure TVCLSFTPClientComponentDemoForm.btRemoveDirClick(Sender: TObject);
var count,i:Integer;
begin
count:=sgRemoteFiles.Selection.Bottom-sgRemoteFiles.Selection.Top+1;
if count=0 then
Exit;
if Application.MessageBox(PWideChar('Please confirm deleting '+IntToStr(count)+' directory/ies remotely (right side)'),
'Confirm Deletion',
MB_YESNO or MB_ICONQUESTION)=IDYES then begin
for i:=sgRemoteFiles.Selection.Top to sgRemoteFiles.Selection.Bottom do
if sgRemoteFiles.Cells[2,i]='<dir>' then
TGPuttySFTPClient1.RemoveDir(sgRemoteFiles.Cells[0,i]);
end;
GetListing;
end;
procedure TVCLSFTPClientComponentDemoForm.DirectoryListBox1Change(Sender: TObject);
begin
if not FInLoadSettings then
SaveSettings;
end;
procedure TVCLSFTPClientComponentDemoForm.btDeleteRemoteClick(Sender: TObject);
var count,i:Integer;
begin
count:=sgRemoteFiles.Selection.Bottom-sgRemoteFiles.Selection.Top+1;
if count=0 then
Exit;
if Application.MessageBox(PWideChar('Please confirm deleting '+IntToStr(count)+' file(s) remotely (right side)'),
'Confirm Deletion',
MB_YESNO or MB_ICONQUESTION)=IDYES then begin
for i:=sgRemoteFiles.Selection.Top to sgRemoteFiles.Selection.Bottom do
if sgRemoteFiles.Cells[2,i]<>'<dir>' then
TGPuttySFTPClient1.DeleteFile(sgRemoteFiles.Cells[0,i]);
end;
GetListing;
end;
procedure TVCLSFTPClientComponentDemoForm.edFolderPathExit(Sender: TObject);
begin
if TGPuttySFTPClient1.Connected then begin
try
if edFolderPath.Text<>'' then
TGPuttySFTPClient1.ChangeDir(edFolderPath.Text);
edFolderPath.Text:=TGPuttySFTPClient1.WorkDir;
GetListing;
except
on E:Exception do
Application.MessageBox(PWideChar(E.Message),'Error');
end;
end;
end;
procedure TVCLSFTPClientComponentDemoForm.FormCreate(Sender: TObject);
begin
// nothing to do
end;
procedure TVCLSFTPClientComponentDemoForm.FormDestroy(Sender: TObject);
begin
// nothing to do
end;
procedure TVCLSFTPClientComponentDemoForm.FormShow(Sender: TObject);
begin
LoadSettings;
ProgressBar1.Visible:=false;
memLog.Lines.Add('Library version: '+TGPuttySFTPClient1.LibVersion);
end;
procedure TVCLSFTPClientComponentDemoForm.GetListing;
begin
sgRemoteFiles.RowCount:=1;
sgRemoteFiles.ColCount:=3;
sgRemoteFiles.ColWidths[0]:=480;
sgRemoteFiles.ColWidths[1]:=300;
sgRemoteFiles.ColWidths[2]:=150;
sgRemoteFiles.Cells[0,0]:='Name';
sgRemoteFiles.Cells[1,0]:='Timestamp';
sgRemoteFiles.Cells[2,0]:='Size';
TGPuttySFTPClient1.ListDir('');
if sgRemoteFiles.RowCount>1 then
sgRemoteFiles.FixedRows:=1;
sgRemoteFiles.FixedCols:=0;
end;
procedure TVCLSFTPClientComponentDemoForm.LoadSettings;
var Reg:TRegistry;
begin
Reg:=TRegistry.Create;
FInLoadSettings:=true;
try
with Reg do begin
RootKey:=HKEY_CURRENT_USER;
if OpenKey('SOFWARE\tgputty',true) then begin
edURL.Text:=ReadString('URL');
edUserName.Text:=ReadString('UserName');
edPassword.Text:=ReadString('Password');
cbSavePassword.Checked:=edPassword.Text<>'';
try
edPort.Text:=IntToStr(ReadInteger('Port'));
except
edPort.Text:='22';
end;
edFolderPath.Text:=ReadString('FolderPath');
DirectoryListBox1.Directory:=ReadString('LocalPath');
end;
end;
finally
FreeAndNil(Reg);
FInLoadSettings:=false;
end;
end;
procedure TVCLSFTPClientComponentDemoForm.SaveSettings;
var Reg:TRegistry;
begin
Reg:=TRegistry.Create;
try
with Reg do begin
RootKey:=HKEY_CURRENT_USER;
if OpenKey('SOFWARE\tgputty',true) then begin
WriteString('URL',edURL.Text);
WriteString('UserName',edUserName.Text);
if cbSavePassword.Checked then
WriteString('Password',edPassword.Text)
else
DeleteValue('Password');
WriteInteger('Port',StrToIntDef(edPort.Text,22));
WriteString('FolderPath',edFolderPath.Text);
WriteString('LocalPath',DirectoryListBox1.Directory);
end;
end;
finally
FreeAndNil(Reg);
end;
end;
procedure TVCLSFTPClientComponentDemoForm.sgRemoteFilesDblClick(Sender: TObject);
begin
if sgRemoteFiles.Selection.Top=sgRemoteFiles.Selection.Bottom then begin
if sgRemoteFiles.Cells[2,sgRemoteFiles.Selection.Top]='<dir>' then begin
TGPuttySFTPClient1.ChangeDir(sgRemoteFiles.Cells[0,sgRemoteFiles.Selection.Top]);
edFolderPath.Text:=TGPuttySFTPClient1.WorkDir;
SaveSettings;
GetListing;
end;
end;
end;
function TVCLSFTPClientComponentDemoForm.TGPuttySFTPClient1SFTPGetInput(Sender: TObject; var cancel: Boolean): string;
begin
Result:=''; // this event will not normally fire
cancel:=false;
memLog.Lines.Add('Replying with empty line.');
end;
function TVCLSFTPClientComponentDemoForm.TGPuttySFTPClient1SFTPListing(Sender: TObject; const Items: TSFTPItems): Boolean;
var StartRow,i:Integer;
begin
StartRow:=sgRemoteFiles.RowCount;
sgRemoteFiles.RowCount:=StartRow+Length(Items);
for i:=0 to Length(Items)-1 do begin
sgRemoteFiles.Cells[0,StartRow+i]:=Items[i].filename;
sgRemoteFiles.Cells[1,StartRow+i]:=DateTimeToStr(TTimeZone.Local.ToLocalTime(UnixToDateTime(Items[i].attrs.mtime)));
if Items[i].attrs.permissions and $F000 = $4000 then
sgRemoteFiles.Cells[2,StartRow+i]:='<dir>'
else
sgRemoteFiles.Cells[2,StartRow+i]:=IntToStr(Items[i].attrs.size);
end;
Result:=true;
end;
procedure TVCLSFTPClientComponentDemoForm.TGPuttySFTPClient1SFTPMessage(Sender: TObject; const Msg: string; const isstderr: Boolean);
begin
if Assigned(memLog) then
memLog.Lines.Add(Msg);
end;
function TVCLSFTPClientComponentDemoForm.TGPuttySFTPClient1SFTPProgress(Sender: TObject; const bytescopied: Int64; const isupload: Boolean): Boolean;
begin
ProgressBar1.Position:=bytescopied div 1024;
Application.ProcessMessages;
Result:=true;
end;
function TVCLSFTPClientComponentDemoForm.TGPuttySFTPClient1SFTPVerifyHostKey(Sender: TObject; const host: string;
const port: Integer;
const fingerprint: string; const verificationstatus: Integer;
var storehostkey: Boolean): Boolean;
begin
if verificationstatus=0 then begin
Result:=true;
Exit;
end;
Result:=Application.MessageBox(PWideChar(WideString(
'Please confirm the SSH host key fingerprint for '+host+
', port '+IntToStr(port)+':'+sLineBreak+
fingerprint)),
'Server Verification',
MB_YESNO or MB_ICONQUESTION) = IDYES;
storehostkey:=Result;
end;
end.
|
unit MainFrm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Variants, System.Classes,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FGX.FlipView, FMX.Ani, FMX.Effects,
FMX.Filter.Effects, FMX.ListView.Types, FMX.ListView, FMX.Edit, FMX.ListBox, FMX.NumberBox, FMX.Controls.Presentation,
FMX.EditBox, FMX.ScrollBox, FMX.Memo, FMX.Gestures, FMX.Layouts, FMX.MultiView;
type
TFormMain = class(TForm)
fgFlipView: TfgFlipView;
nbSlideShowDuration: TNumberBox;
cbMode: TComboBox;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
cbEffectDuration: TNumberBox;
cbEffect: TComboBox;
cbSlideDirection: TComboBox;
nbSlideDuration: TNumberBox;
ListBoxItem3: TListBoxItem;
ListBoxItem4: TListBoxItem;
ListBoxItem7: TListBoxItem;
ListBoxItem8: TListBoxItem;
ListBoxItem9: TListBoxItem;
ListBoxItem10: TListBoxItem;
ListBoxItem11: TListBoxItem;
ListBoxItem12: TListBoxItem;
ListBoxItem13: TListBoxItem;
ListBoxItem14: TListBoxItem;
ListBoxItem15: TListBoxItem;
ListBoxItem16: TListBoxItem;
ListBoxItem17: TListBoxItem;
ListBoxItem18: TListBoxItem;
ListBoxItem19: TListBoxItem;
ListBoxItem20: TListBoxItem;
ListBoxItem21: TListBoxItem;
ListBoxItem22: TListBoxItem;
ListBoxItem23: TListBoxItem;
ListBoxItem24: TListBoxItem;
ListBoxItem25: TListBoxItem;
ListBoxItem26: TListBoxItem;
ListBoxItem27: TListBoxItem;
Memo1: TMemo;
GestureManager1: TGestureManager;
MultiView1: TMultiView;
ListBox1: TListBox;
ListBoxGroupHeader1: TListBoxGroupHeader;
ListBoxItem5: TListBoxItem;
ListBoxItem6: TListBoxItem;
ListBoxItem28: TListBoxItem;
ListBoxItem29: TListBoxItem;
ListBoxGroupHeader2: TListBoxGroupHeader;
ListBoxItem30: TListBoxItem;
ListBoxItem31: TListBoxItem;
ListBoxGroupHeader3: TListBoxGroupHeader;
ListBoxItem32: TListBoxItem;
swSlideShow: TSwitch;
MultiView2: TMultiView;
ListBoxItem33: TListBoxItem;
swShowNavigationButtons: TSwitch;
SpeedButton1: TSpeedButton;
procedure nbSlideShowDurationChange(Sender: TObject);
procedure cbModeChange(Sender: TObject);
procedure cbEffectChange(Sender: TObject);
procedure cbEffectDurationChange(Sender: TObject);
procedure nbSlideDurationChange(Sender: TObject);
procedure cbSlideDirectionChange(Sender: TObject);
procedure fgFlipViewStartChanging(Sender: TObject; const NewItemIndex: Integer);
procedure fgFlipViewFinishChanging(Sender: TObject);
procedure swSlideShowSwitch(Sender: TObject);
procedure MultiView1PresenterChanging(Sender: TObject; var PresenterClass: TMultiViewPresentationClass);
procedure FormCreate(Sender: TObject);
procedure swShowNavigationButtonsSwitch(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure fgFlipViewImageClick(Sender: TObject; const AFlipView: TfgCustomFlipView; const AImageIndex: Integer);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
uses
FGX.FlipView.Types, FMX.MultiView.Presentations;
{$R *.fmx}
procedure TFormMain.cbEffectChange(Sender: TObject);
begin
fgFlipView.EffectOptions.Kind := TfgTransitionEffectKind(cbEffect.ItemIndex);
end;
procedure TFormMain.cbEffectDurationChange(Sender: TObject);
begin
fgFlipView.EffectOptions.Duration := cbEffectDuration.Value;
end;
procedure TFormMain.cbModeChange(Sender: TObject);
begin
fgFlipView.Mode := TfgFlipViewMode(cbMode.ItemIndex);
end;
procedure TFormMain.cbSlideDirectionChange(Sender: TObject);
begin
fgFlipView.SlideOptions.Direction := TfgSlideDirection(cbSlideDirection.ItemIndex);
end;
procedure TFormMain.fgFlipViewFinishChanging(Sender: TObject);
begin
Memo1.Lines.Add('OnFinishChanging');
end;
procedure TFormMain.fgFlipViewImageClick(Sender: TObject; const AFlipView: TfgCustomFlipView;
const AImageIndex: Integer);
var
Message: string;
begin
Message := Format('OnImageClick: Image=%d', [AImageIndex]);
Memo1.Lines.Add(Message);
ShowMessage(Message);
end;
procedure TFormMain.fgFlipViewStartChanging(Sender: TObject; const NewItemIndex: Integer);
begin
Memo1.Lines.Add(Format('OnStartChanging: Image=%d', [NewItemIndex]));
end;
procedure TFormMain.FormCreate(Sender: TObject);
begin
MultiView1.Mode := TMultiViewMode.PlatformBehaviour;
{$IFNDEF MSWINDOWS}
ListBox1.ItemHeight := 0;
{$ENDIF}
end;
procedure TFormMain.MultiView1PresenterChanging(Sender: TObject; var PresenterClass: TMultiViewPresentationClass);
begin
if PresenterClass = TMultiViewNavigationPanePresentation then
PresenterClass := TMultiViewDockedPanelPresentation;
end;
procedure TFormMain.nbSlideShowDurationChange(Sender: TObject);
begin
fgFlipView.SlideShowOptions.Duration := Round(nbSlideShowDuration.Value);
end;
procedure TFormMain.SpeedButton1Click(Sender: TObject);
begin
Memo1.Lines.Clear;
end;
procedure TFormMain.swShowNavigationButtonsSwitch(Sender: TObject);
begin
fgFlipView.ShowNavigationButtons := swShowNavigationButtons.IsChecked;
end;
procedure TFormMain.swSlideShowSwitch(Sender: TObject);
begin
fgFlipView.SlideShowOptions.Enabled := swSlideShow.IsChecked;
end;
procedure TFormMain.nbSlideDurationChange(Sender: TObject);
begin
fgFlipView.SlideOptions.Duration := nbSlideDuration.Value;
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Classes,
Vcl.Graphics, Vcl.Imaging.Jpeg, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
//GLS
GLWin32Viewer, GLScene, GLObjects, GLTexture, GLHudObjects, GLCompositeImage,
GLFileJPEG, GLCadencer, GLBlur, GLCrossPlatform, GLMaterial, GLCoordinates,
GLBaseClasses, GLUtils;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLCamera1: TGLCamera;
GLMaterialLibrary1: TGLMaterialLibrary;
GLCube1: TGLCube;
GLLightSource1: TGLLightSource;
GLSceneViewer1: TGLSceneViewer;
GLCadencer1: TGLCadencer;
GLSphere1: TGLSphere;
Panel1: TPanel;
ComboBox1: TComboBox;
Label1: TLabel;
Label2: TLabel;
ComboBox2: TComboBox;
Timer1: TTimer;
GLDummyCube1: TGLDummyCube;
LabelFPS: TLabel;
procedure FormCreate(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure ComboBox1Click(Sender: TObject);
procedure ComboBox2Change(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
private
{ Private declarations }
oldx, oldy: integer;
public
{ Public declarations }
B: TGLBlur;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
SetGLSceneMediaDir();
// Add GLBlur to scene
B := TGLBlur.Create(self);
GLCube1.AddChild(B);
B.TargetObject := GLCube1;
B.RenderWidth := 256;
B.RenderHeight := 256;
// Load texture for objects
GLMaterialLibrary1.Materials[0].Material.Texture.Image.LoadFromFile('marbletiles.jpg');
ComboBox1.ItemIndex := 2;
ComboBox1Click(self);
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
begin
GLCube1.Turn(deltatime * 10);
GLSphere1.Turn(deltatime * 50);
end;
procedure TForm1.ComboBox1Click(Sender: TObject);
begin
B.Preset := TGLBlurPreset(ComboBox1.itemIndex);
end;
procedure TForm1.ComboBox2Change(Sender: TObject);
begin
B.RenderWidth := StrToInt(ComboBox2.Items[ComboBox2.ItemIndex]);
B.RenderHeight := B.RenderWidth;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
LabelFPS.Caption := FloatToStr(Trunc(GLSceneViewer1.FramesPerSecond))+ ' FPS';
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if ssLeft in Shift then
begin
GLCamera1.MoveAroundTarget(0.2 * (oldy - y), 0.2 * (oldx - x));
end;
oldx := x;
oldy := y;
end;
end.
|
// WebAssembly C API -> Delphi
unit Wasm;
interface
uses
System.SysUtils, Ownership;
type
// vector utility
TWasmVec<T> = record
public type
PT = ^T;
private
size : NativeInt; // ** offset+0:size : Same wasm_xxx_vec_t
data : PT; // ** offset+8:bodies : Same wasm_xxx_vec_t
private
function GetItem(i : Integer) : T;
procedure SetItem(i : Integer; Value : T);
function GetPointers(i : Integer) : Pointer;
public
constructor Create(size : NativeInt; data : PT); overload;
constructor Create(const arry : array of T); overload;
class operator Implicit(const arry : array of T) : TWasmVec<T>;
property Items[i : Integer] : T read GetItem write SetItem; default;
property Pointers[i : Integer] : Pointer read GetPointers;
end;
TWasmMutability = (WASM_CONST, WASM_VAR);
PWasmLimits = ^TWasmLimits;
TWasmLimits = record
public
min : Cardinal;
max : Cardinal;
public
constructor Create(min, max : Cardinal);
end;
TWasmExternKind = (WASM_EXTERN_FUNC, WASM_EXTERN_GLOBAL, WASM_EXTERN_TABLE, WASM_EXTERN_MEMORY);
TWasmValkind = (WASM_I32, WASM_I64, WASM_F32, WASM_F64, WASM_ANYREF=128, WASM_FUNCREF);
TWasmValKindHelper = record helper for TWasmValKind
function IsNum : Boolean;
function IsRef : Boolean;
end;
TWasmByte = Byte;
PWasmByte = ^TWasmByte;
TWasmTableSize = Cardinal;
TWasmMemoryPages = Cardinal;
TWasmUnwrapProc<T> = reference to procedure(data : T);
PWasmByteVec = ^TWasmByteVec;
PPWasmByteVec = ^PWasmByteVec;
PWasmConfig = ^TWasmConfig;
PPWasmConfig = ^PWasmConfig;
PWasmEngine = ^TWasmEngine;
PPWasmEngine = ^PWasmEngine;
PWasmStore = ^TWasmStore;
PPWasmStore = ^PWasmStore;
PWasmValtype = ^TWasmValtype;
PPWasmValtype = ^PWasmValtype;
PWasmValtypeVec = ^TWasmValtypeVec;
PPWasmValtypeVec = ^PWasmValtypeVec;
PWasmFunctype = ^TWasmFunctype;
PPWasmFunctype = ^PWasmFunctype;
PWasmFunctypeVec = ^TWasmFunctypeVec;
PPWasmFunctypeVec = ^PWasmFunctypeVec;
PWasmGlobaltype = ^TWasmGlobaltype;
PPWasmGlobaltype = ^PWasmGlobaltype;
PWasmGlobaltypeVec = ^TWasmGlobaltypeVec;
PPWasmGlobaltypeVec = ^PWasmGlobaltypeVec;
PWasmTabletype = ^TWasmTabletype;
PPWasmTabletype = ^PWasmTabletype;
PWasmTabletypeVec = ^TWasmTabletypeVec;
PPWasmTabletypeVec = ^PWasmTabletypeVec;
PWasmMemorytype = ^TWasmMemorytype;
PPWasmMemorytype = ^PWasmMemorytype;
PWasmMemorytypeVec = ^TWasmMemorytypeVec;
PPWasmMemorytypeVec = ^PWasmMemorytypeVec;
PWasmExterntype = ^TWasmExterntype;
PPWasmExterntype = ^PWasmExterntype;
PWasmExterntypeVec = ^TWasmExterntypeVec;
PPWasmExterntypeVec = ^PWasmExterntypeVec;
PWasmImporttype = ^TWasmImporttype;
PPWasmImporttype = ^PWasmImporttype;
PWasmImporttypeVec = ^TWasmImporttypeVec;
PPWasmImporttypeVec = ^PWasmImporttypeVec;
PWasmExporttype = ^TWasmExporttype;
PPWasmExporttype = ^PWasmExporttype;
PWasmExporttypeVec = ^TWasmExporttypeVec;
PPWasmExporttypeVec = ^PWasmExporttypeVec;
PWasmVal = ^TWasmVal;
PPWasmVal = ^PWasmVal;
PWasmValVec = ^TWasmValVec;
PPWasmValVec = ^PWasmValVec;
PWasmRef = ^TWasmRef;
PPWasmRef = ^PWasmRef;
PWasmFrame = ^TWasmFrame;
PPWasmFrame = ^PWasmFrame;
PWasmFrameVec = ^TWasmFrameVec;
PPWasmFrameVec = ^PWasmFrameVec;
PWasmTrap = ^TWasmTrap;
PPWasmTrap = ^PWasmTrap;
PWasmForeign = ^TWasmForeign;
PPWasmForeign = ^PWasmForeign;
PWasmModule = ^TWasmModule;
PPWasmModule = ^PWasmModule;
PWasmSharedModule = ^TWasmSharedModule;
PPWasmSharedModule = ^PWasmSharedModule;
PWasmFunc = ^TWasmFunc;
PPWasmFunc = ^PWasmFunc;
PWasmGlobal = ^TWasmGlobal;
PPWasmGlobal = ^PWasmGlobal;
PWasmTable = ^TWasmTable;
PPWasmTable = ^PWasmTable;
PWasmMemory = ^TWasmMemory;
PPWasmMemory = ^PWasmMemory;
PWasmExtern = ^TWasmExtern;
PPWasmExtern = ^PWasmExtern;
PWasmExternVec = ^TWasmExternVec;
PPWasmExternVec = ^PWasmExternVec;
PWasmInstance = ^TWasmInstance;
PPWasmInstance = ^PWasmInstance;
TOwnByteVec = record // = TRc<PWasmByteVec>
public
FStrongRef : IRcContainer<PWasmByteVec>;
public
class function Wrap(p : PWasmByteVec; deleter : TRcDeleter) : TOwnByteVec; overload; static; inline;
class function Wrap(p : PWasmByteVec) : TOwnByteVec; overload; static;
class operator Finalize(var Dest: TOwnByteVec);
class operator Implicit(const Src : IRcContainer<PWasmByteVec>) : TOwnByteVec; overload;
class operator Positive(Src : TOwnByteVec) : PWasmByteVec;
class operator Negative(Src : TOwnByteVec) : IRcContainer<PWasmByteVec>;
function Unwrap() : PWasmByteVec;
function IsNone() : Boolean;
end;
TOwnName = TOwnByteVec;
TOwnMessage = TOwnName;
TOwnConfig = record // = TRc<PWasmConfig>
public
FStrongRef : IRcContainer<PWasmConfig>;
public
class function Wrap(p : PWasmConfig; deleter : TRcDeleter) : TOwnConfig; overload; static; inline;
class function Wrap(p : PWasmConfig) : TOwnConfig; overload; static;
class operator Finalize(var Dest: TOwnConfig);
class operator Implicit(const Src : IRcContainer<PWasmConfig>) : TOwnConfig; overload;
class operator Positive(Src : TOwnConfig) : PWasmConfig;
class operator Negative(Src : TOwnConfig) : IRcContainer<PWasmConfig>;
function Unwrap() : PWasmConfig;
function IsNone() : Boolean;
end;
TOwnEngine = record // = TRc<PWasmEngine>
public
FStrongRef : IRcContainer<PWasmEngine>;
public
class function Wrap(p : PWasmEngine; deleter : TRcDeleter) : TOwnEngine; overload; static; inline;
class function Wrap(p : PWasmEngine) : TOwnEngine; overload; static;
class operator Finalize(var Dest: TOwnEngine);
class operator Implicit(const Src : IRcContainer<PWasmEngine>) : TOwnEngine; overload;
class operator Positive(Src : TOwnEngine) : PWasmEngine;
class operator Negative(Src : TOwnEngine) : IRcContainer<PWasmEngine>;
function Unwrap() : PWasmEngine;
function IsNone() : Boolean;
end;
TOwnStore = record // = TRc<PWasmStore>
public
FStrongRef : IRcContainer<PWasmStore>;
public
class function Wrap(p : PWasmStore; deleter : TRcDeleter) : TOwnStore; overload; static; inline;
class function Wrap(p : PWasmStore) : TOwnStore; overload; static;
class operator Finalize(var Dest: TOwnStore);
class operator Implicit(const Src : IRcContainer<PWasmStore>) : TOwnStore; overload;
class operator Positive(Src : TOwnStore) : PWasmStore;
class operator Negative(Src : TOwnStore) : IRcContainer<PWasmStore>;
function Unwrap() : PWasmStore;
function IsNone() : Boolean;
end;
TOwnValtypeVec = record // = TRc<PWasmValtypeVec>
public
FStrongRef : IRcContainer<PWasmValtypeVec>;
public
class function Wrap(p : PWasmValtypeVec; deleter : TRcDeleter) : TOwnValtypeVec; overload; static; inline;
class function Wrap(p : PWasmValtypeVec) : TOwnValtypeVec; overload; static;
class operator Finalize(var Dest: TOwnValtypeVec);
class operator Implicit(const Src : IRcContainer<PWasmValtypeVec>) : TOwnValtypeVec; overload;
class operator Positive(Src : TOwnValtypeVec) : PWasmValtypeVec;
class operator Negative(Src : TOwnValtypeVec) : IRcContainer<PWasmValtypeVec>;
function Unwrap() : PWasmValtypeVec;
function IsNone() : Boolean;
end;
TOwnValtype = record // = TRc<PWasmValtype>
public
FStrongRef : IRcContainer<PWasmValtype>;
public
class function Wrap(p : PWasmValtype; deleter : TRcDeleter) : TOwnValtype; overload; static; inline;
class function Wrap(p : PWasmValtype) : TOwnValtype; overload; static;
class operator Finalize(var Dest: TOwnValtype);
class operator Implicit(const Src : IRcContainer<PWasmValtype>) : TOwnValtype; overload;
class operator Positive(Src : TOwnValtype) : PWasmValtype;
class operator Negative(Src : TOwnValtype) : IRcContainer<PWasmValtype>;
function Unwrap() : PWasmValtype;
function IsNone() : Boolean;
end;
TOwnFunctypeVec = record // = TRc<PWasmFunctypeVec>
public
FStrongRef : IRcContainer<PWasmFunctypeVec>;
public
class function Wrap(p : PWasmFunctypeVec; deleter : TRcDeleter) : TOwnFunctypeVec; overload; static; inline;
class function Wrap(p : PWasmFunctypeVec) : TOwnFunctypeVec; overload; static;
class operator Finalize(var Dest: TOwnFunctypeVec);
class operator Implicit(const Src : IRcContainer<PWasmFunctypeVec>) : TOwnFunctypeVec; overload;
class operator Positive(Src : TOwnFunctypeVec) : PWasmFunctypeVec;
class operator Negative(Src : TOwnFunctypeVec) : IRcContainer<PWasmFunctypeVec>;
function Unwrap() : PWasmFunctypeVec;
function IsNone() : Boolean;
end;
TOwnFunctype = record // = TRc<PWasmFunctype>
public
FStrongRef : IRcContainer<PWasmFunctype>;
public
class function Wrap(p : PWasmFunctype; deleter : TRcDeleter) : TOwnFunctype; overload; static; inline;
class function Wrap(p : PWasmFunctype) : TOwnFunctype; overload; static;
class operator Finalize(var Dest: TOwnFunctype);
class operator Implicit(const Src : IRcContainer<PWasmFunctype>) : TOwnFunctype; overload;
class operator Positive(Src : TOwnFunctype) : PWasmFunctype;
class operator Negative(Src : TOwnFunctype) : IRcContainer<PWasmFunctype>;
function Unwrap() : PWasmFunctype;
function IsNone() : Boolean;
end;
TOwnGlobaltypeVec = record // = TRc<PWasmGlobaltypeVec>
public
FStrongRef : IRcContainer<PWasmGlobaltypeVec>;
public
class function Wrap(p : PWasmGlobaltypeVec; deleter : TRcDeleter) : TOwnGlobaltypeVec; overload; static; inline;
class function Wrap(p : PWasmGlobaltypeVec) : TOwnGlobaltypeVec; overload; static;
class operator Finalize(var Dest: TOwnGlobaltypeVec);
class operator Implicit(const Src : IRcContainer<PWasmGlobaltypeVec>) : TOwnGlobaltypeVec; overload;
class operator Positive(Src : TOwnGlobaltypeVec) : PWasmGlobaltypeVec;
class operator Negative(Src : TOwnGlobaltypeVec) : IRcContainer<PWasmGlobaltypeVec>;
function Unwrap() : PWasmGlobaltypeVec;
function IsNone() : Boolean;
end;
TOwnGlobaltype = record // = TRc<PWasmGlobaltype>
public
FStrongRef : IRcContainer<PWasmGlobaltype>;
public
class function Wrap(p : PWasmGlobaltype; deleter : TRcDeleter) : TOwnGlobaltype; overload; static; inline;
class function Wrap(p : PWasmGlobaltype) : TOwnGlobaltype; overload; static;
class operator Finalize(var Dest: TOwnGlobaltype);
class operator Implicit(const Src : IRcContainer<PWasmGlobaltype>) : TOwnGlobaltype; overload;
class operator Positive(Src : TOwnGlobaltype) : PWasmGlobaltype;
class operator Negative(Src : TOwnGlobaltype) : IRcContainer<PWasmGlobaltype>;
function Unwrap() : PWasmGlobaltype;
function IsNone() : Boolean;
end;
TOwnTabletypeVec = record // = TRc<PWasmTabletypeVec>
public
FStrongRef : IRcContainer<PWasmTabletypeVec>;
public
class function Wrap(p : PWasmTabletypeVec; deleter : TRcDeleter) : TOwnTabletypeVec; overload; static; inline;
class function Wrap(p : PWasmTabletypeVec) : TOwnTabletypeVec; overload; static;
class operator Finalize(var Dest: TOwnTabletypeVec);
class operator Implicit(const Src : IRcContainer<PWasmTabletypeVec>) : TOwnTabletypeVec; overload;
class operator Positive(Src : TOwnTabletypeVec) : PWasmTabletypeVec;
class operator Negative(Src : TOwnTabletypeVec) : IRcContainer<PWasmTabletypeVec>;
function Unwrap() : PWasmTabletypeVec;
function IsNone() : Boolean;
end;
TOwnTabletype = record // = TRc<PWasmTabletype>
public
FStrongRef : IRcContainer<PWasmTabletype>;
public
class function Wrap(p : PWasmTabletype; deleter : TRcDeleter) : TOwnTabletype; overload; static; inline;
class function Wrap(p : PWasmTabletype) : TOwnTabletype; overload; static;
class operator Finalize(var Dest: TOwnTabletype);
class operator Implicit(const Src : IRcContainer<PWasmTabletype>) : TOwnTabletype; overload;
class operator Positive(Src : TOwnTabletype) : PWasmTabletype;
class operator Negative(Src : TOwnTabletype) : IRcContainer<PWasmTabletype>;
function Unwrap() : PWasmTabletype;
function IsNone() : Boolean;
end;
TOwnMemorytypeVec = record // = TRc<PWasmMemorytypeVec>
public
FStrongRef : IRcContainer<PWasmMemorytypeVec>;
public
class function Wrap(p : PWasmMemorytypeVec; deleter : TRcDeleter) : TOwnMemorytypeVec; overload; static; inline;
class function Wrap(p : PWasmMemorytypeVec) : TOwnMemorytypeVec; overload; static;
class operator Finalize(var Dest: TOwnMemorytypeVec);
class operator Implicit(const Src : IRcContainer<PWasmMemorytypeVec>) : TOwnMemorytypeVec; overload;
class operator Positive(Src : TOwnMemorytypeVec) : PWasmMemorytypeVec;
class operator Negative(Src : TOwnMemorytypeVec) : IRcContainer<PWasmMemorytypeVec>;
function Unwrap() : PWasmMemorytypeVec;
function IsNone() : Boolean;
end;
TOwnMemorytype = record // = TRc<PWasmMemorytype>
public
FStrongRef : IRcContainer<PWasmMemorytype>;
public
class function Wrap(p : PWasmMemorytype; deleter : TRcDeleter) : TOwnMemorytype; overload; static; inline;
class function Wrap(p : PWasmMemorytype) : TOwnMemorytype; overload; static;
class operator Finalize(var Dest: TOwnMemorytype);
class operator Implicit(const Src : IRcContainer<PWasmMemorytype>) : TOwnMemorytype; overload;
class operator Positive(Src : TOwnMemorytype) : PWasmMemorytype;
class operator Negative(Src : TOwnMemorytype) : IRcContainer<PWasmMemorytype>;
function Unwrap() : PWasmMemorytype;
function IsNone() : Boolean;
end;
TOwnExterntypeVec = record // = TRc<PWasmExterntypeVec>
public
FStrongRef : IRcContainer<PWasmExterntypeVec>;
public
class function Wrap(p : PWasmExterntypeVec; deleter : TRcDeleter) : TOwnExterntypeVec; overload; static; inline;
class function Wrap(p : PWasmExterntypeVec) : TOwnExterntypeVec; overload; static;
class operator Finalize(var Dest: TOwnExterntypeVec);
class operator Implicit(const Src : IRcContainer<PWasmExterntypeVec>) : TOwnExterntypeVec; overload;
class operator Positive(Src : TOwnExterntypeVec) : PWasmExterntypeVec;
class operator Negative(Src : TOwnExterntypeVec) : IRcContainer<PWasmExterntypeVec>;
function Unwrap() : PWasmExterntypeVec;
function IsNone() : Boolean;
end;
TOwnExterntype = record // = TRc<PWasmExterntype>
public
FStrongRef : IRcContainer<PWasmExterntype>;
public
class function Wrap(p : PWasmExterntype; deleter : TRcDeleter) : TOwnExterntype; overload; static; inline;
class function Wrap(p : PWasmExterntype) : TOwnExterntype; overload; static;
class operator Finalize(var Dest: TOwnExterntype);
class operator Implicit(const Src : IRcContainer<PWasmExterntype>) : TOwnExterntype; overload;
class operator Positive(Src : TOwnExterntype) : PWasmExterntype;
class operator Negative(Src : TOwnExterntype) : IRcContainer<PWasmExterntype>;
function Unwrap() : PWasmExterntype;
function IsNone() : Boolean;
end;
TOwnImporttypeVec = record // = TRc<PWasmImporttypeVec>
public
FStrongRef : IRcContainer<PWasmImporttypeVec>;
public
class function Wrap(p : PWasmImporttypeVec; deleter : TRcDeleter) : TOwnImporttypeVec; overload; static; inline;
class function Wrap(p : PWasmImporttypeVec) : TOwnImporttypeVec; overload; static;
class operator Finalize(var Dest: TOwnImporttypeVec);
class operator Implicit(const Src : IRcContainer<PWasmImporttypeVec>) : TOwnImporttypeVec; overload;
class operator Positive(Src : TOwnImporttypeVec) : PWasmImporttypeVec;
class operator Negative(Src : TOwnImporttypeVec) : IRcContainer<PWasmImporttypeVec>;
function Unwrap() : PWasmImporttypeVec;
function IsNone() : Boolean;
end;
TOwnImporttype = record // = TRc<PWasmImporttype>
public
FStrongRef : IRcContainer<PWasmImporttype>;
public
class function Wrap(p : PWasmImporttype; deleter : TRcDeleter) : TOwnImporttype; overload; static; inline;
class function Wrap(p : PWasmImporttype) : TOwnImporttype; overload; static;
class operator Finalize(var Dest: TOwnImporttype);
class operator Implicit(const Src : IRcContainer<PWasmImporttype>) : TOwnImporttype; overload;
class operator Positive(Src : TOwnImporttype) : PWasmImporttype;
class operator Negative(Src : TOwnImporttype) : IRcContainer<PWasmImporttype>;
function Unwrap() : PWasmImporttype;
function IsNone() : Boolean;
end;
TOwnExporttypeVec = record // = TRc<PWasmExporttypeVec>
public
FStrongRef : IRcContainer<PWasmExporttypeVec>;
public
class function Wrap(p : PWasmExporttypeVec; deleter : TRcDeleter) : TOwnExporttypeVec; overload; static; inline;
class function Wrap(p : PWasmExporttypeVec) : TOwnExporttypeVec; overload; static;
class operator Finalize(var Dest: TOwnExporttypeVec);
class operator Implicit(const Src : IRcContainer<PWasmExporttypeVec>) : TOwnExporttypeVec; overload;
class operator Positive(Src : TOwnExporttypeVec) : PWasmExporttypeVec;
class operator Negative(Src : TOwnExporttypeVec) : IRcContainer<PWasmExporttypeVec>;
function Unwrap() : PWasmExporttypeVec;
function IsNone() : Boolean;
end;
TOwnExporttype = record // = TRc<PWasmExporttype>
public
FStrongRef : IRcContainer<PWasmExporttype>;
public
class function Wrap(p : PWasmExporttype; deleter : TRcDeleter) : TOwnExporttype; overload; static; inline;
class function Wrap(p : PWasmExporttype) : TOwnExporttype; overload; static;
class operator Finalize(var Dest: TOwnExporttype);
class operator Implicit(const Src : IRcContainer<PWasmExporttype>) : TOwnExporttype; overload;
class operator Positive(Src : TOwnExporttype) : PWasmExporttype;
class operator Negative(Src : TOwnExporttype) : IRcContainer<PWasmExporttype>;
function Unwrap() : PWasmExporttype;
function IsNone() : Boolean;
end;
TOwnVal = record // = TRc<PWasmVal>
public
FStrongRef : IRcContainer<PWasmVal>;
public
class function Wrap(p : PWasmVal; deleter : TRcDeleter) : TOwnVal; overload; static; inline;
class function Wrap(p : PWasmVal) : TOwnVal; overload; static;
class operator Finalize(var Dest: TOwnVal);
class operator Implicit(const Src : IRcContainer<PWasmVal>) : TOwnVal; overload;
class operator Positive(Src : TOwnVal) : PWasmVal;
class operator Negative(Src : TOwnVal) : IRcContainer<PWasmVal>;
function Unwrap() : PWasmVal;
function IsNone() : Boolean;
end;
TOwnValVec = record // = TRc<PWasmValVec>
public
FStrongRef : IRcContainer<PWasmValVec>;
public
class function Wrap(p : PWasmValVec; deleter : TRcDeleter) : TOwnValVec; overload; static; inline;
class function Wrap(p : PWasmValVec) : TOwnValVec; overload; static;
class operator Finalize(var Dest: TOwnValVec);
class operator Implicit(const Src : IRcContainer<PWasmValVec>) : TOwnValVec; overload;
class operator Positive(Src : TOwnValVec) : PWasmValVec;
class operator Negative(Src : TOwnValVec) : IRcContainer<PWasmValVec>;
function Unwrap() : PWasmValVec;
function IsNone() : Boolean;
end;
TOwnRef = record // = TRc<PWasmRef>
public
FStrongRef : IRcContainer<PWasmRef>;
public
class function Wrap(p : PWasmRef; deleter : TRcDeleter) : TOwnRef; overload; static; inline;
class function Wrap(p : PWasmRef) : TOwnRef; overload; static;
class operator Finalize(var Dest: TOwnRef);
class operator Implicit(const Src : IRcContainer<PWasmRef>) : TOwnRef; overload;
class operator Positive(Src : TOwnRef) : PWasmRef;
class operator Negative(Src : TOwnRef) : IRcContainer<PWasmRef>;
function Unwrap() : PWasmRef;
function IsNone() : Boolean;
end;
TOwnFrame = record // = TRc<PWasmFrame>
public
FStrongRef : IRcContainer<PWasmFrame>;
public
class function Wrap(p : PWasmFrame; deleter : TRcDeleter) : TOwnFrame; overload; static; inline;
class function Wrap(p : PWasmFrame) : TOwnFrame; overload; static;
class operator Finalize(var Dest: TOwnFrame);
class operator Implicit(const Src : IRcContainer<PWasmFrame>) : TOwnFrame; overload;
class operator Positive(Src : TOwnFrame) : PWasmFrame;
class operator Negative(Src : TOwnFrame) : IRcContainer<PWasmFrame>;
function Unwrap() : PWasmFrame;
function IsNone() : Boolean;
end;
TOwnFrameVec = record // = TRc<PWasmFrameVec>
public
FStrongRef : IRcContainer<PWasmFrameVec>;
public
class function Wrap(p : PWasmFrameVec; deleter : TRcDeleter) : TOwnFrameVec; overload; static; inline;
class function Wrap(p : PWasmFrameVec) : TOwnFrameVec; overload; static;
class operator Finalize(var Dest: TOwnFrameVec);
class operator Implicit(const Src : IRcContainer<PWasmFrameVec>) : TOwnFrameVec; overload;
class operator Positive(Src : TOwnFrameVec) : PWasmFrameVec;
class operator Negative(Src : TOwnFrameVec) : IRcContainer<PWasmFrameVec>;
function Unwrap() : PWasmFrameVec;
function IsNone() : Boolean;
end;
TOwnTrap = record // = TRc<PWasmTrap>
public
FStrongRef : IRcContainer<PWasmTrap>;
public
class function Wrap(p : PWasmTrap; deleter : TRcDeleter) : TOwnTrap; overload; static; inline;
class function Wrap(p : PWasmTrap) : TOwnTrap; overload; static;
class operator Finalize(var Dest: TOwnTrap);
class operator Implicit(const Src : IRcContainer<PWasmTrap>) : TOwnTrap; overload;
class operator Positive(Src : TOwnTrap) : PWasmTrap;
class operator Negative(Src : TOwnTrap) : IRcContainer<PWasmTrap>;
function Unwrap() : PWasmTrap;
function IsNone() : Boolean;
function IsError() : Boolean; overload;
function IsError(proc : TWasmUnwrapProc<PWasmTrap>) : Boolean; overload;
end;
TOwnForeign = record // = TRc<PWasmForeign>
public
FStrongRef : IRcContainer<PWasmForeign>;
public
class function Wrap(p : PWasmForeign; deleter : TRcDeleter) : TOwnForeign; overload; static; inline;
class function Wrap(p : PWasmForeign) : TOwnForeign; overload; static;
class operator Finalize(var Dest: TOwnForeign);
class operator Implicit(const Src : IRcContainer<PWasmForeign>) : TOwnForeign; overload;
class operator Positive(Src : TOwnForeign) : PWasmForeign;
class operator Negative(Src : TOwnForeign) : IRcContainer<PWasmForeign>;
function Unwrap() : PWasmForeign;
function IsNone() : Boolean;
end;
TOwnModule = record // = TRc<PWasmModule>
public
FStrongRef : IRcContainer<PWasmModule>;
public
class function Wrap(p : PWasmModule; deleter : TRcDeleter) : TOwnModule; overload; static; inline;
class function Wrap(p : PWasmModule) : TOwnModule; overload; static;
class operator Finalize(var Dest: TOwnModule);
class operator Implicit(const Src : IRcContainer<PWasmModule>) : TOwnModule; overload;
class operator Positive(Src : TOwnModule) : PWasmModule;
class operator Negative(Src : TOwnModule) : IRcContainer<PWasmModule>;
function Unwrap() : PWasmModule;
function IsNone() : Boolean;
end;
TOwnSharedModule = record // = TRc<PWasmSharedModule>
public
FStrongRef : IRcContainer<PWasmSharedModule>;
public
class function Wrap(p : PWasmSharedModule; deleter : TRcDeleter) : TOwnSharedModule; overload; static; inline;
class function Wrap(p : PWasmSharedModule) : TOwnSharedModule; overload; static;
class operator Finalize(var Dest: TOwnSharedModule);
class operator Implicit(const Src : IRcContainer<PWasmSharedModule>) : TOwnSharedModule; overload;
class operator Positive(Src : TOwnSharedModule) : PWasmSharedModule;
class operator Negative(Src : TOwnSharedModule) : IRcContainer<PWasmSharedModule>;
function Unwrap() : PWasmSharedModule;
function IsNone() : Boolean;
end;
TOwnFunc = record // = TRc<PWasmFunc>
public
FStrongRef : IRcContainer<PWasmFunc>;
public
class function Wrap(p : PWasmFunc; deleter : TRcDeleter) : TOwnFunc; overload; static; inline;
class function Wrap(p : PWasmFunc) : TOwnFunc; overload; static;
class operator Finalize(var Dest: TOwnFunc);
class operator Implicit(const Src : IRcContainer<PWasmFunc>) : TOwnFunc; overload;
class operator Positive(Src : TOwnFunc) : PWasmFunc;
class operator Negative(Src : TOwnFunc) : IRcContainer<PWasmFunc>;
function Unwrap() : PWasmFunc;
function IsNone() : Boolean;
end;
TOwnGlobal = record // = TRc<PWasmGlobal>
public
FStrongRef : IRcContainer<PWasmGlobal>;
public
class function Wrap(p : PWasmGlobal; deleter : TRcDeleter) : TOwnGlobal; overload; static; inline;
class function Wrap(p : PWasmGlobal) : TOwnGlobal; overload; static;
class operator Finalize(var Dest: TOwnGlobal);
class operator Implicit(const Src : IRcContainer<PWasmGlobal>) : TOwnGlobal; overload;
class operator Positive(Src : TOwnGlobal) : PWasmGlobal;
class operator Negative(Src : TOwnGlobal) : IRcContainer<PWasmGlobal>;
function Unwrap() : PWasmGlobal;
function IsNone() : Boolean;
end;
TOwnTable = record // = TRc<PWasmTable>
public
FStrongRef : IRcContainer<PWasmTable>;
public
class function Wrap(p : PWasmTable; deleter : TRcDeleter) : TOwnTable; overload; static; inline;
class function Wrap(p : PWasmTable) : TOwnTable; overload; static;
class operator Finalize(var Dest: TOwnTable);
class operator Implicit(const Src : IRcContainer<PWasmTable>) : TOwnTable; overload;
class operator Positive(Src : TOwnTable) : PWasmTable;
class operator Negative(Src : TOwnTable) : IRcContainer<PWasmTable>;
function Unwrap() : PWasmTable;
function IsNone() : Boolean;
end;
TOwnMemory = record // = TRc<PWasmMemory>
public
FStrongRef : IRcContainer<PWasmMemory>;
public
class function Wrap(p : PWasmMemory; deleter : TRcDeleter) : TOwnMemory; overload; static; inline;
class function Wrap(p : PWasmMemory) : TOwnMemory; overload; static;
class operator Finalize(var Dest: TOwnMemory);
class operator Implicit(const Src : IRcContainer<PWasmMemory>) : TOwnMemory; overload;
class operator Positive(Src : TOwnMemory) : PWasmMemory;
class operator Negative(Src : TOwnMemory) : IRcContainer<PWasmMemory>;
function Unwrap() : PWasmMemory;
function IsNone() : Boolean;
end;
TOwnExtern = record // = TRc<PWasmExtern>
public
FStrongRef : IRcContainer<PWasmExtern>;
public
class function Wrap(p : PWasmExtern; deleter : TRcDeleter) : TOwnExtern; overload; static; inline;
class function Wrap(p : PWasmExtern) : TOwnExtern; overload; static;
class operator Finalize(var Dest: TOwnExtern);
class operator Implicit(const Src : IRcContainer<PWasmExtern>) : TOwnExtern; overload;
class operator Positive(Src : TOwnExtern) : PWasmExtern;
class operator Negative(Src : TOwnExtern) : IRcContainer<PWasmExtern>;
function Unwrap() : PWasmExtern;
function IsNone() : Boolean;
end;
TOwnExternVec = record // = TRc<PWasmExternVec>
public
FStrongRef : IRcContainer<PWasmExternVec>;
public
class function Wrap(p : PWasmExternVec; deleter : TRcDeleter) : TOwnExternVec; overload; static; inline;
class function Wrap(p : PWasmExternVec) : TOwnExternVec; overload; static;
class operator Finalize(var Dest: TOwnExternVec);
class operator Implicit(const Src : IRcContainer<PWasmExternVec>) : TOwnExternVec; overload;
class operator Positive(Src : TOwnExternVec) : PWasmExternVec;
class operator Negative(Src : TOwnExternVec) : IRcContainer<PWasmExternVec>;
function Unwrap() : PWasmExternVec;
function IsNone() : Boolean;
end;
TOwnInstance = record // = TRc<PWasmInstance>
public
FStrongRef : IRcContainer<PWasmInstance>;
public
class function Wrap(p : PWasmInstance; deleter : TRcDeleter) : TOwnInstance; overload; static; inline;
class function Wrap(p : PWasmInstance) : TOwnInstance; overload; static;
class operator Finalize(var Dest: TOwnInstance);
class operator Implicit(const Src : IRcContainer<PWasmInstance>) : TOwnInstance; overload;
class operator Positive(Src : TOwnInstance) : PWasmInstance;
class operator Negative(Src : TOwnInstance) : IRcContainer<PWasmInstance>;
function Unwrap() : PWasmInstance;
function IsNone() : Boolean;
end;
// Byte vectors
TWasmByteVec = record
public
constructor Create(const arry: array of TWasmByte);
class function NewEmpty() : TOwnByteVec; static;
class function NewUninitialized(size : NativeInt) : TOwnByteVec; static;
class function New(const init : array of TWasmByte) : TOwnByteVec; overload; static;
function LoadFromFile(fname : string) : Boolean;
class function NewFromString(s : UTF8String): TOwnName; overload; static;
class function NewFromStringNt(s : UTF8String): TOwnName; overload; static;
class function NewFromString(s : String): TOwnName; overload; static;
class function NewFromStringNt(s : String): TOwnName; overload; static;
function AsUTF8String : UTF8String;
function AsString : string;
function Copy() : TOwnByteVec;
procedure Assign(const Src : TOwnByteVec);
public
case Integer of
0 :(size : NativeInt; data : PWasmByte);
1 :(Items : TWasmVec<TWasmByte>);
end;
TWasmName = TWasmByteVec;
PWasmName = ^TWasmByteVec;
TWasmMessage = TWasmName;
PWasmMessage = ^TWasmByteVec;
TWasmFinalizer = procedure(p : Pointer); cdecl;
TWasmFuncCallBack = function(const args : PWasmValVec; {own} results : PWasmValVec): {own} PWasmTrap; cdecl;
TWasmFuncCallBackWithEnv = function(env : Pointer; const args : PWasmValVec; {own} results : PWasmValVec): {own} PWasmTrap; cdecl;
///////////////////////////////////////////////////////////////////////////////
// Runtime Environment
// Configuration
TWasmConfig = record
public
class function New() : TOwnConfig; overload; static;
end;
// Embedders may provide custom functions for manipulating configs.
// Engine
TWasmEngine = record
public
class function New() : TOwnEngine; overload; static;
class function NewWithConfig(config : TOwnConfig) : TOwnEngine; overload; static;
end;
// Store
TWasmStore = record
public
class function New(engine : PWasmEngine) : TOwnStore; overload; static;
end;
TWasmValtypeVec = record
public
constructor Create(const arry: array of PWasmValtype);
class function NewEmpty() : TOwnValtypeVec; static;
class function NewUninitialized(size : NativeInt) : TOwnValtypeVec; static;
class function New(const init : array of PWasmValtype; elem_release : Boolean) : TOwnValtypeVec; overload; static;
class function New(const arry: array of TWasmValkind): TOwnValtypeVec; overload; static;
class function New(const init: array of TOwnValtype): TOwnValtypeVec; overload; static;
function Copy() : TOwnValtypeVec;
procedure Assign(const Src : TOwnValtypeVec);
public
case Integer of
0 :(size : NativeInt; data : PPWasmValtype);
1 :(Items : TWasmVec<PWasmValtype>);
end;
///////////////////////////////////////////////////////////////////////////////
// Type Representations
// Type attributes
// Generic
// Value Types
TWasmValtype = record
public
function Copy() : TOwnValtype;
class function New(valkind : TWasmValkind) : TOwnValtype; overload; static;
function Kind() : TWasmValkind;
end;
TWasmFunctypeVec = record
public
constructor Create(const arry: array of PWasmFunctype);
class function NewEmpty() : TOwnFunctypeVec; static;
class function NewUninitialized(size : NativeInt) : TOwnFunctypeVec; static;
class function New(const init : array of PWasmFunctype; elem_release : Boolean) : TOwnFunctypeVec; overload; static;
function Copy() : TOwnFunctypeVec;
procedure Assign(const Src : TOwnFunctypeVec);
public
case Integer of
0 :(size : NativeInt; data : PPWasmFunctype);
1 :(Items : TWasmVec<PWasmFunctype>);
end;
// Function Types
TWasmFunctype = record
public
function Copy() : TOwnFunctype;
class function New(const p, r: array of TWasmValkind): TOwnFunctype; overload; static;
class function New(const p, r: array of TOwnValtype): TOwnFunctype; overload; static;
class function New(params : TOwnValtypeVec; results : TOwnValtypeVec) : TOwnFunctype; overload; static;
function Params() : PWasmValtypeVec;
function Results() : PWasmValtypeVec;
function AsExterntype() : PWasmExterntype;
function AsExterntypeConst() : PWasmExterntype;
end;
TWasmGlobaltypeVec = record
public
constructor Create(const arry: array of PWasmGlobaltype);
class function NewEmpty() : TOwnGlobaltypeVec; static;
class function NewUninitialized(size : NativeInt) : TOwnGlobaltypeVec; static;
class function New(const init : array of PWasmGlobaltype; elem_release : Boolean) : TOwnGlobaltypeVec; overload; static;
function Copy() : TOwnGlobaltypeVec;
procedure Assign(const Src : TOwnGlobaltypeVec);
public
case Integer of
0 :(size : NativeInt; data : PPWasmGlobaltype);
1 :(Items : TWasmVec<PWasmGlobaltype>);
end;
// Global Types
TWasmGlobaltype = record
public
function Copy() : TOwnGlobaltype;
class function New(valkind : TWasmValKind; mutability : TWasmMutability) : TOwnGlobaltype; overload; static;
class function New(valtype : TOwnValtype; mutability : TWasmMutability) : TOwnGlobaltype; overload; static;
function Content() : PWasmValtype;
function Mutability() : TWasmMutability;
function AsExterntype() : PWasmExterntype;
function AsExterntypeConst() : PWasmExterntype;
end;
TWasmTabletypeVec = record
public
constructor Create(const arry: array of PWasmTabletype);
class function NewEmpty() : TOwnTabletypeVec; static;
class function NewUninitialized(size : NativeInt) : TOwnTabletypeVec; static;
class function New(const init : array of PWasmTabletype; elem_release : Boolean) : TOwnTabletypeVec; overload; static;
function Copy() : TOwnTabletypeVec;
procedure Assign(const Src : TOwnTabletypeVec);
public
case Integer of
0 :(size : NativeInt; data : PPWasmTabletype);
1 :(Items : TWasmVec<PWasmTabletype>);
end;
// Table Types
TWasmTabletype = record
public
function Copy() : TOwnTabletype;
class function New(valtype : TOwnValtype; const limits : PWasmLimits) : TOwnTabletype; overload; static;
function Element() : PWasmValtype;
function Limits() : PWasmLimits;
function AsExterntype() : PWasmExterntype;
function AsExterntypeConst() : PWasmExterntype;
end;
TWasmMemorytypeVec = record
public
constructor Create(const arry: array of PWasmMemorytype);
class function NewEmpty() : TOwnMemorytypeVec; static;
class function NewUninitialized(size : NativeInt) : TOwnMemorytypeVec; static;
class function New(const init : array of PWasmMemorytype; elem_release : Boolean) : TOwnMemorytypeVec; overload; static;
function Copy() : TOwnMemorytypeVec;
procedure Assign(const Src : TOwnMemorytypeVec);
public
case Integer of
0 :(size : NativeInt; data : PPWasmMemorytype);
1 :(Items : TWasmVec<PWasmMemorytype>);
end;
// Memory Types
TWasmMemorytype = record
public
function Copy() : TOwnMemorytype;
class function New( const limits : PWasmLimits) : TOwnMemorytype; overload; static;
function Limits() : PWasmLimits;
function AsExterntype() : PWasmExterntype;
function AsExterntypeConst() : PWasmExterntype;
end;
TWasmExterntypeVec = record
public
constructor Create(const arry: array of PWasmExterntype);
class function NewEmpty() : TOwnExterntypeVec; static;
class function NewUninitialized(size : NativeInt) : TOwnExterntypeVec; static;
class function New(const init : array of PWasmExterntype; elem_release : Boolean) : TOwnExterntypeVec; overload; static;
function Copy() : TOwnExterntypeVec;
procedure Assign(const Src : TOwnExterntypeVec);
public
case Integer of
0 :(size : NativeInt; data : PPWasmExterntype);
1 :(Items : TWasmVec<PWasmExterntype>);
end;
// Extern Types
TWasmExterntype = record
public
function Copy() : TOwnExterntype;
function Kind() : TWasmExternkind;
function AsFunctype() : PWasmFunctype;
function AsGlobaltype() : PWasmGlobaltype;
function AsTabletype() : PWasmTabletype;
function AsMemorytype() : PWasmMemorytype;
function AsFunctypeConst() : PWasmFunctype;
function AsGlobaltypeConst() : PWasmGlobaltype;
function AsTabletypeConst() : PWasmTabletype;
function AsMemorytypeConst() : PWasmMemorytype;
end;
TWasmImporttypeVec = record
public
constructor Create(const arry: array of PWasmImporttype);
class function NewEmpty() : TOwnImporttypeVec; static;
class function NewUninitialized(size : NativeInt) : TOwnImporttypeVec; static;
class function New(const init : array of PWasmImporttype; elem_release : Boolean) : TOwnImporttypeVec; overload; static;
function Copy() : TOwnImporttypeVec;
procedure Assign(const Src : TOwnImporttypeVec);
public
case Integer of
0 :(size : NativeInt; data : PPWasmImporttype);
1 :(Items : TWasmVec<PWasmImporttype>);
end;
// Import Types
TWasmImporttype = record
public
function Copy() : TOwnImporttype;
class function New(module : string; name : string; externtype : TOwnExterntype) : TOwnImporttype; overload; static;
function Module() : string;
function Name() : string;
function GetType() : PWasmExterntype;
end;
TWasmExporttypeVec = record
public
constructor Create(const arry: array of PWasmExporttype);
class function NewEmpty() : TOwnExporttypeVec; static;
class function NewUninitialized(size : NativeInt) : TOwnExporttypeVec; static;
class function New(const init : array of PWasmExporttype; elem_release : Boolean) : TOwnExporttypeVec; overload; static;
function Copy() : TOwnExporttypeVec;
procedure Assign(const Src : TOwnExporttypeVec);
public
case Integer of
0 :(size : NativeInt; data : PPWasmExporttype);
1 :(Items : TWasmVec<PWasmExporttype>);
end;
// Export Types
TWasmExporttype = record
public
function Copy() : TOwnExporttype;
class function New(name : string; externtype : TOwnExterntype) : TOwnExporttype; overload; static;
function Name() : string;
function GetType() : PWasmExterntype;
end;
TWasmVal = record
public
constructor Create(val:Integer); overload;
constructor Create(val:Int64); overload;
constructor Create(val:Single); overload;
constructor Create(val:Double); overload;
constructor Create(val:PWasmRef); overload;
class operator Implicit(val:Integer) : TWasmVal; overload;
class operator Implicit(val:Int64) : TWasmVal; overload;
class operator Implicit(val:Single) : TWasmVal; overload;
class operator Implicit(val:Double) : TWasmVal; overload;
class operator Implicit(val:PWasmRef) : TWasmVal; overload;
public
kind : TWasmValkind;
case Integer of
0 : (i32 : Integer);
1 : (i64 : Int64);
2 : (f32 : Single);
3 : (f64 : Double);
4 : (ref : PWasmRef);
end;
///////////////////////////////////////////////////////////////////////////////
// Runtime Objects
// Values
TWasmValVec = record
public
constructor Create(const arry: array of TWasmVal);
class function NewEmpty() : TOwnValVec; static;
class function NewUninitialized(size : NativeInt) : TOwnValVec; static;
class function New(const init : array of TWasmVal) : TOwnValVec; overload; static;
function Copy() : TOwnValVec;
procedure Assign(const Src : TOwnValVec);
public
case Integer of
0 :(size : NativeInt; data : PWasmVal);
1 :(Items : TWasmVec<TWasmVal>);
end;
// References
TWasmRef = record
public
function Copy() : TOwnRef;
function Same(const p : PWasmRef) : Boolean;
function GetHostInfo : Pointer;
procedure SetHostInfo(info : Pointer);
procedure SetHostInfoWithFinalizer(info : Pointer ;finalizer : TWasmFinalizer);
function AsTrapConst() : PWasmTrap;
function AsTrap() : PWasmTrap;
function AsForeignConst() : PWasmForeign;
function AsForeign() : PWasmForeign;
function AsModuleConst() : PWasmModule;
function AsModule() : PWasmModule;
function AsFuncConst() : PWasmFunc;
function AsFunc() : PWasmFunc;
function AsGlobalConst() : PWasmGlobal;
function AsGlobal() : PWasmGlobal;
function AsTableConst() : PWasmTable;
function AsTable() : PWasmTable;
function AsMemoryConst() : PWasmMemory;
function AsMemory() : PWasmMemory;
function AsExternConst() : PWasmExtern;
function AsExtern() : PWasmExtern;
function AsInstanceConst() : PWasmInstance;
function AsInstance() : PWasmInstance;
end;
// Frames
TWasmFrame = record
public
function Copy() : TOwnFrame;
function Instance() : PWasmInstance;
function FuncIndex() : Cardinal;
function FuncOffset() : NativeInt;
function ModuleOffset() : NativeInt;
end;
TWasmFrameVec = record
public
constructor Create(const arry: array of PWasmFrame);
class function NewEmpty() : TOwnFrameVec; static;
class function NewUninitialized(size : NativeInt) : TOwnFrameVec; static;
class function New(const init : array of PWasmFrame; elem_release : Boolean) : TOwnFrameVec; overload; static;
function Copy() : TOwnFrameVec;
procedure Assign(const Src : TOwnFrameVec);
public
case Integer of
0 :(size : NativeInt; data : PPWasmFrame);
1 :(Items : TWasmVec<PWasmFrame>);
end;
// Traps
// null terminated
TWasmTrap = record
public
function Copy() : TOwnTrap;
function Same(const p : PWasmTrap) : Boolean;
function GetHostInfo : Pointer;
procedure SetHostInfo(info : Pointer);
procedure SetHostInfoWithFinalizer(info : Pointer ;finalizer : TWasmFinalizer);
function AsRef : PWasmRef;
function AsRefConst : PWasmRef;
class function New(store : PWasmStore; const message : PWasmMessage) : TOwnTrap; overload; static;
function GetMessage() : string;
function Origin() : TOwnFrame;
function Trace() : TOwnFrameVec;
end;
// Foreign Objects
TWasmForeign = record
public
function Copy() : TOwnForeign;
function Same(const p : PWasmForeign) : Boolean;
function GetHostInfo : Pointer;
procedure SetHostInfo(info : Pointer);
procedure SetHostInfoWithFinalizer(info : Pointer ;finalizer : TWasmFinalizer);
function AsRef : PWasmRef;
function AsRefConst : PWasmRef;
class function New(store : PWasmStore) : TOwnForeign; overload; static;
end;
TWasmModule = record
public
function Copy() : TOwnModule;
function Same(const p : PWasmModule) : Boolean;
function GetHostInfo : Pointer;
procedure SetHostInfo(info : Pointer);
procedure SetHostInfoWithFinalizer(info : Pointer ;finalizer : TWasmFinalizer);
function Share() : TOwnSharedModule;
function AsRef : PWasmRef;
function AsRefConst : PWasmRef;
class function New(store : PWasmStore; const binary : PWasmByteVec) : TOwnModule; overload; static;
function Validate(store : PWasmStore; const binary : PWasmByteVec) : Boolean;
function Imports() : TOwnImporttypeVec;
function GetExports() : TOwnExporttypeVec;
function Serialize() : TOwnByteVec;
class function Deserialize(store : PWasmStore; const byte_vec : PWasmByteVec) : TOwnModule; overload; static;
end;
// Modules
TWasmSharedModule = record
public
function Obtain(store : PWasmStore) : TOwnModule;
end;
// Function Instances
TWasmFunc = record
public
function Copy() : TOwnFunc;
function Same(const p : PWasmFunc) : Boolean;
function GetHostInfo : Pointer;
procedure SetHostInfo(info : Pointer);
procedure SetHostInfoWithFinalizer(info : Pointer ;finalizer : TWasmFinalizer);
function AsRef : PWasmRef;
function AsRefConst : PWasmRef;
class function New(store : PWasmStore; const functype : PWasmFunctype; func_callback : TWasmFuncCallback) : TOwnFunc; overload; static;
class function NewWithEnv(store : PWasmStore; const typ : PWasmFunctype; func_callback_with_env : TWasmFuncCallbackWithEnv; env : Pointer; finalizer : TWasmFinalizer) : TOwnFunc; overload; static;
function GetType() : TOwnFunctype;
function ParamArity() : NativeInt;
function ResultArity() : NativeInt;
function Call( const args : PWasmValVec; results : PWasmValVec) : TOwnTrap;
function AsExtern() : PWasmExtern;
function AsExternConst() : PWasmExtern;
end;
// Global Instances
TWasmGlobal = record
public
function Copy() : TOwnGlobal;
function Same(const p : PWasmGlobal) : Boolean;
function GetHostInfo : Pointer;
procedure SetHostInfo(info : Pointer);
procedure SetHostInfoWithFinalizer(info : Pointer ;finalizer : TWasmFinalizer);
function AsRef : PWasmRef;
function AsRefConst : PWasmRef;
class function New(store : PWasmStore; const globaltype : PWasmGlobaltype; const val : PWasmVal) : TOwnGlobal; overload; static;
function GetType() : TOwnGlobaltype;
function GetVal() : TOwnVal;
procedure SetVal( const val : PWasmVal);
function AsExtern() : PWasmExtern;
function AsExternConst() : PWasmExtern;
end;
// Table Instances
TWasmTable = record
public
function Copy() : TOwnTable;
function Same(const p : PWasmTable) : Boolean;
function GetHostInfo : Pointer;
procedure SetHostInfo(info : Pointer);
procedure SetHostInfoWithFinalizer(info : Pointer ;finalizer : TWasmFinalizer);
function AsRef : PWasmRef;
function AsRefConst : PWasmRef;
class function New(store : PWasmStore; const tabletype : PWasmTabletype; init : PWasmRef) : TOwnTable; overload; static;
function GetType() : TOwnTabletype;
function GetRef(index : TWasmTableSize) : TOwnRef;
function SetRef(index : TWasmTableSize; ref : PWasmRef) : Boolean;
function Size() : TWasmTableSize;
function Grow(delta : TWasmTableSize; init : PWasmRef) : Boolean;
function AsExtern() : PWasmExtern;
function AsExternConst() : PWasmExtern;
end;
// Memory Instances
TWasmMemory = record
public
function Copy() : TOwnMemory;
function Same(const p : PWasmMemory) : Boolean;
function GetHostInfo : Pointer;
procedure SetHostInfo(info : Pointer);
procedure SetHostInfoWithFinalizer(info : Pointer ;finalizer : TWasmFinalizer);
function AsRef : PWasmRef;
function AsRefConst : PWasmRef;
class function New(store : PWasmStore; const memorytype : PWasmMemorytype) : TOwnMemory; overload; static;
function GetType() : TOwnMemorytype;
function Data() : PByte;
function DataSize() : NativeInt;
function Size() : TWasmMemoryPages;
function Grow(delta : TWasmMemoryPages) : Boolean;
function AsExtern() : PWasmExtern;
function AsExternConst() : PWasmExtern;
end;
// Externals
TWasmExtern = record
public
function Copy() : TOwnExtern;
function Same(const p : PWasmExtern) : Boolean;
function GetHostInfo : Pointer;
procedure SetHostInfo(info : Pointer);
procedure SetHostInfoWithFinalizer(info : Pointer ;finalizer : TWasmFinalizer);
function AsRef : PWasmRef;
function AsRefConst : PWasmRef;
function Kind() : TWasmExternkind;
function GetType() : TOwnExterntype;
function AsFunc() : PWasmFunc;
function AsGlobal() : PWasmGlobal;
function AsTable() : PWasmTable;
function AsMemory() : PWasmMemory;
function AsFuncConst() : PWasmFunc;
function AsGlobalConst() : PWasmGlobal;
function AsTableConst() : PWasmTable;
function AsMemoryConst() : PWasmMemory;
end;
TWasmExternVec = record
public
constructor Create(const arry: array of PWasmExtern);
class function NewEmpty() : TOwnExternVec; static;
class function NewUninitialized(size : NativeInt) : TOwnExternVec; static;
class function New(const init : array of PWasmExtern; elem_release : Boolean) : TOwnExternVec; overload; static;
function Copy() : TOwnExternVec;
procedure Assign(const Src : TOwnExternVec);
public
case Integer of
0 :(size : NativeInt; data : PPWasmExtern);
1 :(Items : TWasmVec<PWasmExtern>);
end;
// Module Instances
TWasmInstance = record
public
class function New(store : PWasmStore; const module : PWasmModule; const imports : array of PWasmExtern) : TOwnInstance; overload; static;
class function New(store : PWasmStore; const module : PWasmModule; const imports : array of PWasmExtern; var trap : TOwnTrap) : TOwnInstance; overload; static;
class function New(store : PWasmStore; const module : PWasmModule; const imports : PWasmExternVec) : TOwnInstance; overload; static;
function Copy() : TOwnInstance;
function Same(const p : PWasmInstance) : Boolean;
function GetHostInfo : Pointer;
procedure SetHostInfo(info : Pointer);
procedure SetHostInfoWithFinalizer(info : Pointer ;finalizer : TWasmFinalizer);
function AsRef : PWasmRef;
function AsRefConst : PWasmRef;
class function New(store : PWasmStore; const module : PWasmModule; const imports : PWasmExternVec; var {own} trap : TOwnTrap) : TOwnInstance; overload; static;
function GetExports() : TOwnExternVec;
end;
TWasmByteVecNewEmptyAPI = procedure({own} out_ : PWasmByteVec); cdecl;
TWasmByteVecNewUninitializedAPI = procedure({own} out_ : PWasmByteVec; size : NativeInt); cdecl;
TWasmByteVecNewAPI = procedure({own} out_ : PWasmByteVec; size : NativeInt; {own} const init : PWasmByte); cdecl;
TWasmByteVecCopyAPI = procedure({own} out_ : PWasmByteVec; src : PWasmByteVec); cdecl;
TWasmByteVecDeleteAPI = procedure(p : PWasmByteVec); cdecl;
TWasmConfigDeleteAPI = procedure(p : PWasmConfig); cdecl;
TWasmConfigNewAPI = function () : {own} PWasmConfig; cdecl;
TWasmEngineDeleteAPI = procedure(p : PWasmEngine); cdecl;
TWasmEngineNewAPI = function () : {own} PWasmEngine; cdecl;
TWasmEngineNewWithConfigAPI = function ({own} config : PWasmConfig) : {own} PWasmEngine; cdecl;
TWasmStoreDeleteAPI = procedure(p : PWasmStore); cdecl;
TWasmStoreNewAPI = function (engine : PWasmEngine) : {own} PWasmStore; cdecl;
TWasmValtypeDeleteAPI = procedure(p : PWasmValtype); cdecl;
TWasmValtypeCopyAPI = function(const {own} self : PWasmValtype) : PWasmValtype; cdecl;
TWasmValtypeVecNewEmptyAPI = procedure({own} out_ : PWasmValtypeVec); cdecl;
TWasmValtypeVecNewUninitializedAPI = procedure({own} out_ : PWasmValtypeVec; size : NativeInt); cdecl;
TWasmValtypeVecNewAPI = procedure({own} out_ : PWasmValtypeVec; size : NativeInt; {own} const init : PPWasmValtype); cdecl;
TWasmValtypeVecCopyAPI = procedure({own} out_ : PWasmValtypeVec; src : PWasmValtypeVec); cdecl;
TWasmValtypeVecDeleteAPI = procedure(p : PWasmValtypeVec); cdecl;
TWasmValtypeNewAPI = function (valkind : TWasmValkind) : {own} PWasmValtype; cdecl;
TWasmValtypeKindAPI = function (const valtype : PWasmValtype) : TWasmValkind; cdecl;
TWasmFunctypeDeleteAPI = procedure(p : PWasmFunctype); cdecl;
TWasmFunctypeCopyAPI = function(const {own} self : PWasmFunctype) : PWasmFunctype; cdecl;
TWasmFunctypeVecNewEmptyAPI = procedure({own} out_ : PWasmFunctypeVec); cdecl;
TWasmFunctypeVecNewUninitializedAPI = procedure({own} out_ : PWasmFunctypeVec; size : NativeInt); cdecl;
TWasmFunctypeVecNewAPI = procedure({own} out_ : PWasmFunctypeVec; size : NativeInt; {own} const init : PPWasmFunctype); cdecl;
TWasmFunctypeVecCopyAPI = procedure({own} out_ : PWasmFunctypeVec; src : PWasmFunctypeVec); cdecl;
TWasmFunctypeVecDeleteAPI = procedure(p : PWasmFunctypeVec); cdecl;
TWasmFunctypeNewAPI = function ({own} params : PWasmValtypeVec; {own} results : PWasmValtypeVec) : {own} PWasmFunctype; cdecl;
TWasmFunctypeParamsAPI = function (const functype : PWasmFunctype) : PWasmValtypeVec; cdecl;
TWasmFunctypeResultsAPI = function (const functype : PWasmFunctype) : PWasmValtypeVec; cdecl;
TWasmGlobaltypeDeleteAPI = procedure(p : PWasmGlobaltype); cdecl;
TWasmGlobaltypeCopyAPI = function(const {own} self : PWasmGlobaltype) : PWasmGlobaltype; cdecl;
TWasmGlobaltypeVecNewEmptyAPI = procedure({own} out_ : PWasmGlobaltypeVec); cdecl;
TWasmGlobaltypeVecNewUninitializedAPI = procedure({own} out_ : PWasmGlobaltypeVec; size : NativeInt); cdecl;
TWasmGlobaltypeVecNewAPI = procedure({own} out_ : PWasmGlobaltypeVec; size : NativeInt; {own} const init : PPWasmGlobaltype); cdecl;
TWasmGlobaltypeVecCopyAPI = procedure({own} out_ : PWasmGlobaltypeVec; src : PWasmGlobaltypeVec); cdecl;
TWasmGlobaltypeVecDeleteAPI = procedure(p : PWasmGlobaltypeVec); cdecl;
TWasmGlobaltypeNewAPI = function ({own} valtype : PWasmValtype; mutability : TWasmMutability) : {own} PWasmGlobaltype; cdecl;
TWasmGlobaltypeContentAPI = function (const globaltype : PWasmGlobaltype) : PWasmValtype; cdecl;
TWasmGlobaltypeMutabilityAPI = function (const globaltype : PWasmGlobaltype) : TWasmMutability; cdecl;
TWasmTabletypeDeleteAPI = procedure(p : PWasmTabletype); cdecl;
TWasmTabletypeCopyAPI = function(const {own} self : PWasmTabletype) : PWasmTabletype; cdecl;
TWasmTabletypeVecNewEmptyAPI = procedure({own} out_ : PWasmTabletypeVec); cdecl;
TWasmTabletypeVecNewUninitializedAPI = procedure({own} out_ : PWasmTabletypeVec; size : NativeInt); cdecl;
TWasmTabletypeVecNewAPI = procedure({own} out_ : PWasmTabletypeVec; size : NativeInt; {own} const init : PPWasmTabletype); cdecl;
TWasmTabletypeVecCopyAPI = procedure({own} out_ : PWasmTabletypeVec; src : PWasmTabletypeVec); cdecl;
TWasmTabletypeVecDeleteAPI = procedure(p : PWasmTabletypeVec); cdecl;
TWasmTabletypeNewAPI = function ({own} valtype : PWasmValtype; const limits : PWasmLimits) : {own} PWasmTabletype; cdecl;
TWasmTabletypeElementAPI = function (const tabletype : PWasmTabletype) : PWasmValtype; cdecl;
TWasmTabletypeLimitsAPI = function (const tabletype : PWasmTabletype) : PWasmLimits; cdecl;
TWasmMemorytypeDeleteAPI = procedure(p : PWasmMemorytype); cdecl;
TWasmMemorytypeCopyAPI = function(const {own} self : PWasmMemorytype) : PWasmMemorytype; cdecl;
TWasmMemorytypeVecNewEmptyAPI = procedure({own} out_ : PWasmMemorytypeVec); cdecl;
TWasmMemorytypeVecNewUninitializedAPI = procedure({own} out_ : PWasmMemorytypeVec; size : NativeInt); cdecl;
TWasmMemorytypeVecNewAPI = procedure({own} out_ : PWasmMemorytypeVec; size : NativeInt; {own} const init : PPWasmMemorytype); cdecl;
TWasmMemorytypeVecCopyAPI = procedure({own} out_ : PWasmMemorytypeVec; src : PWasmMemorytypeVec); cdecl;
TWasmMemorytypeVecDeleteAPI = procedure(p : PWasmMemorytypeVec); cdecl;
TWasmMemorytypeNewAPI = function (const limits : PWasmLimits) : {own} PWasmMemorytype; cdecl;
TWasmMemorytypeLimitsAPI = function (const memorytype : PWasmMemorytype) : PWasmLimits; cdecl;
TWasmExterntypeDeleteAPI = procedure(p : PWasmExterntype); cdecl;
TWasmExterntypeCopyAPI = function(const {own} self : PWasmExterntype) : PWasmExterntype; cdecl;
TWasmExterntypeVecNewEmptyAPI = procedure({own} out_ : PWasmExterntypeVec); cdecl;
TWasmExterntypeVecNewUninitializedAPI = procedure({own} out_ : PWasmExterntypeVec; size : NativeInt); cdecl;
TWasmExterntypeVecNewAPI = procedure({own} out_ : PWasmExterntypeVec; size : NativeInt; {own} const init : PPWasmExterntype); cdecl;
TWasmExterntypeVecCopyAPI = procedure({own} out_ : PWasmExterntypeVec; src : PWasmExterntypeVec); cdecl;
TWasmExterntypeVecDeleteAPI = procedure(p : PWasmExterntypeVec); cdecl;
TWasmExterntypeKindAPI = function (const externtype : PWasmExterntype) : TWasmExternkind; cdecl;
TWasmFunctypeAsExterntypeAPI = function (functype : PWasmFunctype) : PWasmExterntype; cdecl;
TWasmGlobaltypeAsExterntypeAPI = function (globaltype : PWasmGlobaltype) : PWasmExterntype; cdecl;
TWasmTabletypeAsExterntypeAPI = function (tabletype : PWasmTabletype) : PWasmExterntype; cdecl;
TWasmMemorytypeAsExterntypeAPI = function (memorytype : PWasmMemorytype) : PWasmExterntype; cdecl;
TWasmExterntypeAsFunctypeAPI = function (externtype : PWasmExterntype) : PWasmFunctype; cdecl;
TWasmExterntypeAsGlobaltypeAPI = function (externtype : PWasmExterntype) : PWasmGlobaltype; cdecl;
TWasmExterntypeAsTabletypeAPI = function (externtype : PWasmExterntype) : PWasmTabletype; cdecl;
TWasmExterntypeAsMemorytypeAPI = function (externtype : PWasmExterntype) : PWasmMemorytype; cdecl;
TWasmFunctypeAsExterntypeConstAPI = function (const functype : PWasmFunctype) : PWasmExterntype; cdecl;
TWasmGlobaltypeAsExterntypeConstAPI = function (const globaltype : PWasmGlobaltype) : PWasmExterntype; cdecl;
TWasmTabletypeAsExterntypeConstAPI = function (const tabletype : PWasmTabletype) : PWasmExterntype; cdecl;
TWasmMemorytypeAsExterntypeConstAPI = function (const memorytype : PWasmMemorytype) : PWasmExterntype; cdecl;
TWasmExterntypeAsFunctypeConstAPI = function (const externtype : PWasmExterntype) : PWasmFunctype; cdecl;
TWasmExterntypeAsGlobaltypeConstAPI = function (const externtype : PWasmExterntype) : PWasmGlobaltype; cdecl;
TWasmExterntypeAsTabletypeConstAPI = function (const externtype : PWasmExterntype) : PWasmTabletype; cdecl;
TWasmExterntypeAsMemorytypeConstAPI = function (const externtype : PWasmExterntype) : PWasmMemorytype; cdecl;
TWasmImporttypeDeleteAPI = procedure(p : PWasmImporttype); cdecl;
TWasmImporttypeCopyAPI = function(const {own} self : PWasmImporttype) : PWasmImporttype; cdecl;
TWasmImporttypeVecNewEmptyAPI = procedure({own} out_ : PWasmImporttypeVec); cdecl;
TWasmImporttypeVecNewUninitializedAPI = procedure({own} out_ : PWasmImporttypeVec; size : NativeInt); cdecl;
TWasmImporttypeVecNewAPI = procedure({own} out_ : PWasmImporttypeVec; size : NativeInt; {own} const init : PPWasmImporttype); cdecl;
TWasmImporttypeVecCopyAPI = procedure({own} out_ : PWasmImporttypeVec; src : PWasmImporttypeVec); cdecl;
TWasmImporttypeVecDeleteAPI = procedure(p : PWasmImporttypeVec); cdecl;
TWasmImporttypeNewAPI = function ({own} module : PWasmName; {own} name : PWasmName; {own} externtype : PWasmExterntype) : {own} PWasmImporttype; cdecl;
TWasmImporttypeModuleAPI = function (const importtype : PWasmImporttype) : PWasmName; cdecl;
TWasmImporttypeNameAPI = function (const importtype : PWasmImporttype) : PWasmName; cdecl;
TWasmImporttypeTypeAPI = function (const importtype : PWasmImporttype) : PWasmExterntype; cdecl;
TWasmExporttypeDeleteAPI = procedure(p : PWasmExporttype); cdecl;
TWasmExporttypeCopyAPI = function(const {own} self : PWasmExporttype) : PWasmExporttype; cdecl;
TWasmExporttypeVecNewEmptyAPI = procedure({own} out_ : PWasmExporttypeVec); cdecl;
TWasmExporttypeVecNewUninitializedAPI = procedure({own} out_ : PWasmExporttypeVec; size : NativeInt); cdecl;
TWasmExporttypeVecNewAPI = procedure({own} out_ : PWasmExporttypeVec; size : NativeInt; {own} const init : PPWasmExporttype); cdecl;
TWasmExporttypeVecCopyAPI = procedure({own} out_ : PWasmExporttypeVec; src : PWasmExporttypeVec); cdecl;
TWasmExporttypeVecDeleteAPI = procedure(p : PWasmExporttypeVec); cdecl;
TWasmExporttypeNewAPI = function ({own} name : PWasmName; {own} externtype : PWasmExterntype) : {own} PWasmExporttype; cdecl;
TWasmExporttypeNameAPI = function (const exporttype : PWasmExporttype) : PWasmName; cdecl;
TWasmExporttypeTypeAPI = function (const exporttype : PWasmExporttype) : PWasmExterntype; cdecl;
TWasmValDeleteAPI = procedure ({own} v : PWasmVal); cdecl;
TWasmValCopyAPI = procedure ({own} out_ : PWasmVal; const val1 : PWasmVal); cdecl;
TWasmValVecNewEmptyAPI = procedure({own} out_ : PWasmValVec); cdecl;
TWasmValVecNewUninitializedAPI = procedure({own} out_ : PWasmValVec; size : NativeInt); cdecl;
TWasmValVecNewAPI = procedure({own} out_ : PWasmValVec; size : NativeInt; {own} const init : PWasmVal); cdecl;
TWasmValVecCopyAPI = procedure({own} out_ : PWasmValVec; src : PWasmValVec); cdecl;
TWasmValVecDeleteAPI = procedure(p : PWasmValVec); cdecl;
TWasmRefDeleteAPI = procedure(p : PWasmRef); cdecl;
TWasmRefCopyAPI = function(const {own} self : PWasmRef) : PWasmRef; cdecl;
TWasmRefSameAPI = function(const {own} self : PWasmRef; target : PWasmRef) : Boolean; cdecl;
TWasmRefGetHostInfoAPI = function(const {own} self : PWasmRef) : Pointer; cdecl;
TWasmRefSetHostInfoAPI = procedure(const {own} self : PWasmRef; info : Pointer); cdecl;
TWasmRefSetHostInfoWithFinalizerAPI = procedure(const {own} self : PWasmRef; info : Pointer; finalizer : TWasmFinalizer); cdecl;
TWasmFrameDeleteAPI = procedure(p : PWasmFrame); cdecl;
TWasmFrameVecNewEmptyAPI = procedure({own} out_ : PWasmFrameVec); cdecl;
TWasmFrameVecNewUninitializedAPI = procedure({own} out_ : PWasmFrameVec; size : NativeInt); cdecl;
TWasmFrameVecNewAPI = procedure({own} out_ : PWasmFrameVec; size : NativeInt; {own} const init : PPWasmFrame); cdecl;
TWasmFrameVecCopyAPI = procedure({own} out_ : PWasmFrameVec; src : PWasmFrameVec); cdecl;
TWasmFrameVecDeleteAPI = procedure(p : PWasmFrameVec); cdecl;
TWasmFrameCopyAPI = function (const frame : PWasmFrame) : {own} PWasmFrame; cdecl;
TWasmFrameInstanceAPI = function (const frame : PWasmFrame) : PWasmInstance; cdecl;
TWasmFrameFuncIndexAPI = function (const frame : PWasmFrame) : Cardinal; cdecl;
TWasmFrameFuncOffsetAPI = function (const frame : PWasmFrame) : NativeInt; cdecl;
TWasmFrameModuleOffsetAPI = function (const frame : PWasmFrame) : NativeInt; cdecl;
TWasmTrapDeleteAPI = procedure(p : PWasmTrap); cdecl;
TWasmTrapCopyAPI = function(const {own} self : PWasmTrap) : PWasmTrap; cdecl;
TWasmTrapSameAPI = function(const {own} self : PWasmTrap; target : PWasmTrap) : Boolean; cdecl;
TWasmTrapGetHostInfoAPI = function(const {own} self : PWasmTrap) : Pointer; cdecl;
TWasmTrapSetHostInfoAPI = procedure(const {own} self : PWasmTrap; info : Pointer); cdecl;
TWasmTrapSetHostInfoWithFinalizerAPI = procedure(const {own} self : PWasmTrap; info : Pointer; finalizer : TWasmFinalizer); cdecl;
TWasmTrapAsRefAPI = function({own} self : PWasmTrap) : PWasmRef; cdecl;
TWasmTrapAsRefConstAPI = function(const {own} self : PWasmTrap) : PWasmRef; cdecl;
TWasmRefAsTrapAPI= function({own} self : PWasmRef) : PWasmTrap; cdecl;
TWasmRefAsTrapConstAPI = function(const {own} self : PWasmRef) : PWasmTrap; cdecl;
TWasmTrapNewAPI = function (store : PWasmStore; const message : PWasmMessage) : {own} PWasmTrap; cdecl;
TWasmTrapMessageAPI = procedure (const trap : PWasmTrap; {own} out_ : PWasmMessage); cdecl;
TWasmTrapOriginAPI = function (const trap : PWasmTrap) : {own} PWasmFrame; cdecl;
TWasmTrapTraceAPI = procedure (const trap : PWasmTrap; {own} out_ : PWasmFrameVec); cdecl;
TWasmForeignDeleteAPI = procedure(p : PWasmForeign); cdecl;
TWasmForeignCopyAPI = function(const {own} self : PWasmForeign) : PWasmForeign; cdecl;
TWasmForeignSameAPI = function(const {own} self : PWasmForeign; target : PWasmForeign) : Boolean; cdecl;
TWasmForeignGetHostInfoAPI = function(const {own} self : PWasmForeign) : Pointer; cdecl;
TWasmForeignSetHostInfoAPI = procedure(const {own} self : PWasmForeign; info : Pointer); cdecl;
TWasmForeignSetHostInfoWithFinalizerAPI = procedure(const {own} self : PWasmForeign; info : Pointer; finalizer : TWasmFinalizer); cdecl;
TWasmForeignAsRefAPI = function({own} self : PWasmForeign) : PWasmRef; cdecl;
TWasmForeignAsRefConstAPI = function(const {own} self : PWasmForeign) : PWasmRef; cdecl;
TWasmRefAsForeignAPI= function({own} self : PWasmRef) : PWasmForeign; cdecl;
TWasmRefAsForeignConstAPI = function(const {own} self : PWasmRef) : PWasmForeign; cdecl;
TWasmForeignNewAPI = function (store : PWasmStore) : {own} PWasmForeign; cdecl;
TWasmModuleDeleteAPI = procedure(p : PWasmModule); cdecl;
TWasmModuleCopyAPI = function(const {own} self : PWasmModule) : PWasmModule; cdecl;
TWasmModuleSameAPI = function(const {own} self : PWasmModule; target : PWasmModule) : Boolean; cdecl;
TWasmModuleGetHostInfoAPI = function(const {own} self : PWasmModule) : Pointer; cdecl;
TWasmModuleSetHostInfoAPI = procedure(const {own} self : PWasmModule; info : Pointer); cdecl;
TWasmModuleSetHostInfoWithFinalizerAPI = procedure(const {own} self : PWasmModule; info : Pointer; finalizer : TWasmFinalizer); cdecl;
TWasmModuleAsRefAPI = function({own} self : PWasmModule) : PWasmRef; cdecl;
TWasmModuleAsRefConstAPI = function(const {own} self : PWasmModule) : PWasmRef; cdecl;
TWasmRefAsModuleAPI= function({own} self : PWasmRef) : PWasmModule; cdecl;
TWasmRefAsModuleConstAPI = function(const {own} self : PWasmRef) : PWasmModule; cdecl;
TWasmSharedModuleDeleteAPI = procedure(p : PWasmSharedModule); cdecl;
TWasmSharedModuleCopyAPI = function(const {own} self : PWasmSharedModule) : PWasmSharedModule; cdecl;
TWasmSharedModuleSameAPI = function(const {own} self : PWasmSharedModule; target : PWasmSharedModule) : Boolean; cdecl;
TWasmSharedModuleGetHostInfoAPI = function(const {own} self : PWasmSharedModule) : Pointer; cdecl;
TWasmSharedModuleSetHostInfoAPI = procedure(const {own} self : PWasmSharedModule; info : Pointer); cdecl;
TWasmSharedModuleSetHostInfoWithFinalizerAPI = procedure(const {own} self : PWasmSharedModule; info : Pointer; finalizer : TWasmFinalizer); cdecl;
TWasmSharedModuleAsRefAPI = function({own} self : PWasmSharedModule) : PWasmRef; cdecl;
TWasmSharedModuleAsRefConstAPI = function(const {own} self : PWasmSharedModule) : PWasmRef; cdecl;
TWasmRefAsSharedModuleAPI= function({own} self : PWasmRef) : PWasmSharedModule; cdecl;
TWasmRefAsSharedModuleConstAPI = function(const {own} self : PWasmRef) : PWasmSharedModule; cdecl;
TWasmModuleShareAPI = function(const {own} self : PWasmModule) : {own} PWasmSharedModule; cdecl;
TWasmModuleObtainAPI = function(store : PWasmStore; const {own} self : PWasmSharedModule) : {own} PWasmModule; cdecl;
TWasmModuleNewAPI = function (store : PWasmStore; const binary : PWasmByteVec) : {own} PWasmModule; cdecl;
TWasmModuleValidateAPI = function (store : PWasmStore; const binary : PWasmByteVec) : Boolean; cdecl;
TWasmModuleImportsAPI = procedure (const module : PWasmModule; {own} out_ : PWasmImporttypeVec); cdecl;
TWasmModuleExportsAPI = procedure (const module : PWasmModule; {own} out_ : PWasmExporttypeVec); cdecl;
TWasmModuleSerializeAPI = procedure (const module : PWasmModule; {own} out_ : PWasmByteVec); cdecl;
TWasmModuleDeserializeAPI = function (store : PWasmStore; const byte_vec : PWasmByteVec) : {own} PWasmModule; cdecl;
TWasmFuncDeleteAPI = procedure(p : PWasmFunc); cdecl;
TWasmFuncCopyAPI = function(const {own} self : PWasmFunc) : PWasmFunc; cdecl;
TWasmFuncSameAPI = function(const {own} self : PWasmFunc; target : PWasmFunc) : Boolean; cdecl;
TWasmFuncGetHostInfoAPI = function(const {own} self : PWasmFunc) : Pointer; cdecl;
TWasmFuncSetHostInfoAPI = procedure(const {own} self : PWasmFunc; info : Pointer); cdecl;
TWasmFuncSetHostInfoWithFinalizerAPI = procedure(const {own} self : PWasmFunc; info : Pointer; finalizer : TWasmFinalizer); cdecl;
TWasmFuncAsRefAPI = function({own} self : PWasmFunc) : PWasmRef; cdecl;
TWasmFuncAsRefConstAPI = function(const {own} self : PWasmFunc) : PWasmRef; cdecl;
TWasmRefAsFuncAPI= function({own} self : PWasmRef) : PWasmFunc; cdecl;
TWasmRefAsFuncConstAPI = function(const {own} self : PWasmRef) : PWasmFunc; cdecl;
TWasmFuncNewAPI = function (store : PWasmStore; const functype : PWasmFunctype; func_callback : TWasmFuncCallback) : {own} PWasmFunc; cdecl;
TWasmFuncNewWithEnvAPI = function (store : PWasmStore; const typ : PWasmFunctype; func_callback_with_env : TWasmFuncCallbackWithEnv; env : Pointer; finalizer : TWasmFinalizer) : {own} PWasmFunc; cdecl;
TWasmFuncTypeAPI = function (const func : PWasmFunc) : {own} PWasmFunctype; cdecl;
TWasmFuncParamArityAPI = function (const func : PWasmFunc) : NativeInt; cdecl;
TWasmFuncResultArityAPI = function (const func : PWasmFunc) : NativeInt; cdecl;
TWasmFuncCallAPI = function (const func : PWasmFunc; const args : PWasmValVec; results : PWasmValVec) : {own} PWasmTrap; cdecl;
TWasmGlobalDeleteAPI = procedure(p : PWasmGlobal); cdecl;
TWasmGlobalCopyAPI = function(const {own} self : PWasmGlobal) : PWasmGlobal; cdecl;
TWasmGlobalSameAPI = function(const {own} self : PWasmGlobal; target : PWasmGlobal) : Boolean; cdecl;
TWasmGlobalGetHostInfoAPI = function(const {own} self : PWasmGlobal) : Pointer; cdecl;
TWasmGlobalSetHostInfoAPI = procedure(const {own} self : PWasmGlobal; info : Pointer); cdecl;
TWasmGlobalSetHostInfoWithFinalizerAPI = procedure(const {own} self : PWasmGlobal; info : Pointer; finalizer : TWasmFinalizer); cdecl;
TWasmGlobalAsRefAPI = function({own} self : PWasmGlobal) : PWasmRef; cdecl;
TWasmGlobalAsRefConstAPI = function(const {own} self : PWasmGlobal) : PWasmRef; cdecl;
TWasmRefAsGlobalAPI= function({own} self : PWasmRef) : PWasmGlobal; cdecl;
TWasmRefAsGlobalConstAPI = function(const {own} self : PWasmRef) : PWasmGlobal; cdecl;
TWasmGlobalNewAPI = function (store : PWasmStore; const globaltype : PWasmGlobaltype; const val : PWasmVal) : {own} PWasmGlobal; cdecl;
TWasmGlobalTypeAPI = function (const global : PWasmGlobal) : {own} PWasmGlobaltype; cdecl;
TWasmGlobalGetAPI = procedure (const global : PWasmGlobal; {own} out_ : PWasmVal); cdecl;
TWasmGlobalSetAPI = procedure (global : PWasmGlobal; const val : PWasmVal); cdecl;
TWasmTableDeleteAPI = procedure(p : PWasmTable); cdecl;
TWasmTableCopyAPI = function(const {own} self : PWasmTable) : PWasmTable; cdecl;
TWasmTableSameAPI = function(const {own} self : PWasmTable; target : PWasmTable) : Boolean; cdecl;
TWasmTableGetHostInfoAPI = function(const {own} self : PWasmTable) : Pointer; cdecl;
TWasmTableSetHostInfoAPI = procedure(const {own} self : PWasmTable; info : Pointer); cdecl;
TWasmTableSetHostInfoWithFinalizerAPI = procedure(const {own} self : PWasmTable; info : Pointer; finalizer : TWasmFinalizer); cdecl;
TWasmTableAsRefAPI = function({own} self : PWasmTable) : PWasmRef; cdecl;
TWasmTableAsRefConstAPI = function(const {own} self : PWasmTable) : PWasmRef; cdecl;
TWasmRefAsTableAPI= function({own} self : PWasmRef) : PWasmTable; cdecl;
TWasmRefAsTableConstAPI = function(const {own} self : PWasmRef) : PWasmTable; cdecl;
TWasmTableNewAPI = function (store : PWasmStore; const tabletype : PWasmTabletype; init : PWasmRef) : {own} PWasmTable; cdecl;
TWasmTableTypeAPI = function (const table : PWasmTable) : {own} PWasmTabletype; cdecl;
TWasmTableGetAPI = function (const table : PWasmTable; index : TWasmTableSize) : {own} PWasmRef; cdecl;
TWasmTableSetAPI = function (table : PWasmTable; index : TWasmTableSize; ref : PWasmRef) : Boolean; cdecl;
TWasmTableSizeAPI = function (const table : PWasmTable) : TWasmTableSize; cdecl;
TWasmTableGrowAPI = function (table : PWasmTable; delta : TWasmTableSize; init : PWasmRef) : Boolean; cdecl;
TWasmMemoryDeleteAPI = procedure(p : PWasmMemory); cdecl;
TWasmMemoryCopyAPI = function(const {own} self : PWasmMemory) : PWasmMemory; cdecl;
TWasmMemorySameAPI = function(const {own} self : PWasmMemory; target : PWasmMemory) : Boolean; cdecl;
TWasmMemoryGetHostInfoAPI = function(const {own} self : PWasmMemory) : Pointer; cdecl;
TWasmMemorySetHostInfoAPI = procedure(const {own} self : PWasmMemory; info : Pointer); cdecl;
TWasmMemorySetHostInfoWithFinalizerAPI = procedure(const {own} self : PWasmMemory; info : Pointer; finalizer : TWasmFinalizer); cdecl;
TWasmMemoryAsRefAPI = function({own} self : PWasmMemory) : PWasmRef; cdecl;
TWasmMemoryAsRefConstAPI = function(const {own} self : PWasmMemory) : PWasmRef; cdecl;
TWasmRefAsMemoryAPI= function({own} self : PWasmRef) : PWasmMemory; cdecl;
TWasmRefAsMemoryConstAPI = function(const {own} self : PWasmRef) : PWasmMemory; cdecl;
TWasmMemoryNewAPI = function (store : PWasmStore; const memorytype : PWasmMemorytype) : {own} PWasmMemory; cdecl;
TWasmMemoryTypeAPI = function (const memory : PWasmMemory) : {own} PWasmMemorytype; cdecl;
TWasmMemoryDataAPI = function (memory : PWasmMemory) : PByte; cdecl;
TWasmMemoryDataSizeAPI = function (const memory : PWasmMemory) : NativeInt; cdecl;
TWasmMemorySizeAPI = function (const memory : PWasmMemory) : TWasmMemoryPages; cdecl;
TWasmMemoryGrowAPI = function (memory : PWasmMemory; delta : TWasmMemoryPages) : Boolean; cdecl;
TWasmExternDeleteAPI = procedure(p : PWasmExtern); cdecl;
TWasmExternCopyAPI = function(const {own} self : PWasmExtern) : PWasmExtern; cdecl;
TWasmExternSameAPI = function(const {own} self : PWasmExtern; target : PWasmExtern) : Boolean; cdecl;
TWasmExternGetHostInfoAPI = function(const {own} self : PWasmExtern) : Pointer; cdecl;
TWasmExternSetHostInfoAPI = procedure(const {own} self : PWasmExtern; info : Pointer); cdecl;
TWasmExternSetHostInfoWithFinalizerAPI = procedure(const {own} self : PWasmExtern; info : Pointer; finalizer : TWasmFinalizer); cdecl;
TWasmExternAsRefAPI = function({own} self : PWasmExtern) : PWasmRef; cdecl;
TWasmExternAsRefConstAPI = function(const {own} self : PWasmExtern) : PWasmRef; cdecl;
TWasmRefAsExternAPI= function({own} self : PWasmRef) : PWasmExtern; cdecl;
TWasmRefAsExternConstAPI = function(const {own} self : PWasmRef) : PWasmExtern; cdecl;
TWasmExternVecNewEmptyAPI = procedure({own} out_ : PWasmExternVec); cdecl;
TWasmExternVecNewUninitializedAPI = procedure({own} out_ : PWasmExternVec; size : NativeInt); cdecl;
TWasmExternVecNewAPI = procedure({own} out_ : PWasmExternVec; size : NativeInt; {own} const init : PPWasmExtern); cdecl;
TWasmExternVecCopyAPI = procedure({own} out_ : PWasmExternVec; src : PWasmExternVec); cdecl;
TWasmExternVecDeleteAPI = procedure(p : PWasmExternVec); cdecl;
TWasmExternKindAPI = function (const extern : PWasmExtern) : TWasmExternkind; cdecl;
TWasmExternTypeAPI = function (const extern : PWasmExtern) : {own} PWasmExterntype; cdecl;
TWasmFuncAsExternAPI = function (func : PWasmFunc) : PWasmExtern; cdecl;
TWasmGlobalAsExternAPI = function (global : PWasmGlobal) : PWasmExtern; cdecl;
TWasmTableAsExternAPI = function (table : PWasmTable) : PWasmExtern; cdecl;
TWasmMemoryAsExternAPI = function (memory : PWasmMemory) : PWasmExtern; cdecl;
TWasmExternAsFuncAPI = function (extern : PWasmExtern) : PWasmFunc; cdecl;
TWasmExternAsGlobalAPI = function (extern : PWasmExtern) : PWasmGlobal; cdecl;
TWasmExternAsTableAPI = function (extern : PWasmExtern) : PWasmTable; cdecl;
TWasmExternAsMemoryAPI = function (extern : PWasmExtern) : PWasmMemory; cdecl;
TWasmFuncAsExternConstAPI = function (const func : PWasmFunc) : PWasmExtern; cdecl;
TWasmGlobalAsExternConstAPI = function (const global : PWasmGlobal) : PWasmExtern; cdecl;
TWasmTableAsExternConstAPI = function (const table : PWasmTable) : PWasmExtern; cdecl;
TWasmMemoryAsExternConstAPI = function (const memory : PWasmMemory) : PWasmExtern; cdecl;
TWasmExternAsFuncConstAPI = function (const extern : PWasmExtern) : PWasmFunc; cdecl;
TWasmExternAsGlobalConstAPI = function (const extern : PWasmExtern) : PWasmGlobal; cdecl;
TWasmExternAsTableConstAPI = function (const extern : PWasmExtern) : PWasmTable; cdecl;
TWasmExternAsMemoryConstAPI = function (const extern : PWasmExtern) : PWasmMemory; cdecl;
TWasmInstanceDeleteAPI = procedure(p : PWasmInstance); cdecl;
TWasmInstanceCopyAPI = function(const {own} self : PWasmInstance) : PWasmInstance; cdecl;
TWasmInstanceSameAPI = function(const {own} self : PWasmInstance; target : PWasmInstance) : Boolean; cdecl;
TWasmInstanceGetHostInfoAPI = function(const {own} self : PWasmInstance) : Pointer; cdecl;
TWasmInstanceSetHostInfoAPI = procedure(const {own} self : PWasmInstance; info : Pointer); cdecl;
TWasmInstanceSetHostInfoWithFinalizerAPI = procedure(const {own} self : PWasmInstance; info : Pointer; finalizer : TWasmFinalizer); cdecl;
TWasmInstanceAsRefAPI = function({own} self : PWasmInstance) : PWasmRef; cdecl;
TWasmInstanceAsRefConstAPI = function(const {own} self : PWasmInstance) : PWasmRef; cdecl;
TWasmRefAsInstanceAPI= function({own} self : PWasmRef) : PWasmInstance; cdecl;
TWasmRefAsInstanceConstAPI = function(const {own} self : PWasmRef) : PWasmInstance; cdecl;
TWasmInstanceNewAPI = function (store : PWasmStore; const module : PWasmModule; const imports : PWasmExternVec; {own} trap : PPWasmTrap) : {own} PWasmInstance; cdecl;
TWasmInstanceExportsAPI = procedure (const instance : PWasmInstance; {own} out_ : PWasmExternVec); cdecl;
TWasm = record
public class var
byte_vec_new_empty : TWasmByteVecNewEmptyAPI;
byte_vec_new_uninitialized : TWasmByteVecNewUninitializedAPI;
byte_vec_new : TWasmByteVecNewAPI;
byte_vec_copy : TWasmByteVecCopyAPI;
byte_vec_delete : TWasmByteVecDeleteAPI;
config_delete : TWasmConfigDeleteAPI;
config_new : TWasmConfigNewAPI;
engine_delete : TWasmEngineDeleteAPI;
engine_new : TWasmEngineNewAPI;
engine_new_with_config : TWasmEngineNewWithConfigAPI;
store_delete : TWasmStoreDeleteAPI;
store_new : TWasmStoreNewAPI;
valtype_delete : TWasmValtypeDeleteAPI;
valtype_copy : TWasmValtypeCopyAPI;
valtype_vec_new_empty : TWasmValtypeVecNewEmptyAPI;
valtype_vec_new_uninitialized : TWasmValtypeVecNewUninitializedAPI;
valtype_vec_new : TWasmValtypeVecNewAPI;
valtype_vec_copy : TWasmValtypeVecCopyAPI;
valtype_vec_delete : TWasmValtypeVecDeleteAPI;
valtype_new : TWasmValtypeNewAPI;
valtype_kind : TWasmValtypeKindAPI;
functype_delete : TWasmFunctypeDeleteAPI;
functype_copy : TWasmFunctypeCopyAPI;
functype_vec_new_empty : TWasmFunctypeVecNewEmptyAPI;
functype_vec_new_uninitialized : TWasmFunctypeVecNewUninitializedAPI;
functype_vec_new : TWasmFunctypeVecNewAPI;
functype_vec_copy : TWasmFunctypeVecCopyAPI;
functype_vec_delete : TWasmFunctypeVecDeleteAPI;
functype_new : TWasmFunctypeNewAPI;
functype_params : TWasmFunctypeParamsAPI;
functype_results : TWasmFunctypeResultsAPI;
globaltype_delete : TWasmGlobaltypeDeleteAPI;
globaltype_copy : TWasmGlobaltypeCopyAPI;
globaltype_vec_new_empty : TWasmGlobaltypeVecNewEmptyAPI;
globaltype_vec_new_uninitialized : TWasmGlobaltypeVecNewUninitializedAPI;
globaltype_vec_new : TWasmGlobaltypeVecNewAPI;
globaltype_vec_copy : TWasmGlobaltypeVecCopyAPI;
globaltype_vec_delete : TWasmGlobaltypeVecDeleteAPI;
globaltype_new : TWasmGlobaltypeNewAPI;
globaltype_content : TWasmGlobaltypeContentAPI;
globaltype_mutability : TWasmGlobaltypeMutabilityAPI;
tabletype_delete : TWasmTabletypeDeleteAPI;
tabletype_copy : TWasmTabletypeCopyAPI;
tabletype_vec_new_empty : TWasmTabletypeVecNewEmptyAPI;
tabletype_vec_new_uninitialized : TWasmTabletypeVecNewUninitializedAPI;
tabletype_vec_new : TWasmTabletypeVecNewAPI;
tabletype_vec_copy : TWasmTabletypeVecCopyAPI;
tabletype_vec_delete : TWasmTabletypeVecDeleteAPI;
tabletype_new : TWasmTabletypeNewAPI;
tabletype_element : TWasmTabletypeElementAPI;
tabletype_limits : TWasmTabletypeLimitsAPI;
memorytype_delete : TWasmMemorytypeDeleteAPI;
memorytype_copy : TWasmMemorytypeCopyAPI;
memorytype_vec_new_empty : TWasmMemorytypeVecNewEmptyAPI;
memorytype_vec_new_uninitialized : TWasmMemorytypeVecNewUninitializedAPI;
memorytype_vec_new : TWasmMemorytypeVecNewAPI;
memorytype_vec_copy : TWasmMemorytypeVecCopyAPI;
memorytype_vec_delete : TWasmMemorytypeVecDeleteAPI;
memorytype_new : TWasmMemorytypeNewAPI;
memorytype_limits : TWasmMemorytypeLimitsAPI;
externtype_delete : TWasmExterntypeDeleteAPI;
externtype_copy : TWasmExterntypeCopyAPI;
externtype_vec_new_empty : TWasmExterntypeVecNewEmptyAPI;
externtype_vec_new_uninitialized : TWasmExterntypeVecNewUninitializedAPI;
externtype_vec_new : TWasmExterntypeVecNewAPI;
externtype_vec_copy : TWasmExterntypeVecCopyAPI;
externtype_vec_delete : TWasmExterntypeVecDeleteAPI;
externtype_kind : TWasmExterntypeKindAPI;
functype_as_externtype : TWasmFunctypeAsExterntypeAPI;
globaltype_as_externtype : TWasmGlobaltypeAsExterntypeAPI;
tabletype_as_externtype : TWasmTabletypeAsExterntypeAPI;
memorytype_as_externtype : TWasmMemorytypeAsExterntypeAPI;
externtype_as_functype : TWasmExterntypeAsFunctypeAPI;
externtype_as_globaltype : TWasmExterntypeAsGlobaltypeAPI;
externtype_as_tabletype : TWasmExterntypeAsTabletypeAPI;
externtype_as_memorytype : TWasmExterntypeAsMemorytypeAPI;
functype_as_externtype_const : TWasmFunctypeAsExterntypeConstAPI;
globaltype_as_externtype_const : TWasmGlobaltypeAsExterntypeConstAPI;
tabletype_as_externtype_const : TWasmTabletypeAsExterntypeConstAPI;
memorytype_as_externtype_const : TWasmMemorytypeAsExterntypeConstAPI;
externtype_as_functype_const : TWasmExterntypeAsFunctypeConstAPI;
externtype_as_globaltype_const : TWasmExterntypeAsGlobaltypeConstAPI;
externtype_as_tabletype_const : TWasmExterntypeAsTabletypeConstAPI;
externtype_as_memorytype_const : TWasmExterntypeAsMemorytypeConstAPI;
importtype_delete : TWasmImporttypeDeleteAPI;
importtype_copy : TWasmImporttypeCopyAPI;
importtype_vec_new_empty : TWasmImporttypeVecNewEmptyAPI;
importtype_vec_new_uninitialized : TWasmImporttypeVecNewUninitializedAPI;
importtype_vec_new : TWasmImporttypeVecNewAPI;
importtype_vec_copy : TWasmImporttypeVecCopyAPI;
importtype_vec_delete : TWasmImporttypeVecDeleteAPI;
importtype_new : TWasmImporttypeNewAPI;
importtype_module : TWasmImporttypeModuleAPI;
importtype_name : TWasmImporttypeNameAPI;
importtype_type : TWasmImporttypeTypeAPI;
exporttype_delete : TWasmExporttypeDeleteAPI;
exporttype_copy : TWasmExporttypeCopyAPI;
exporttype_vec_new_empty : TWasmExporttypeVecNewEmptyAPI;
exporttype_vec_new_uninitialized : TWasmExporttypeVecNewUninitializedAPI;
exporttype_vec_new : TWasmExporttypeVecNewAPI;
exporttype_vec_copy : TWasmExporttypeVecCopyAPI;
exporttype_vec_delete : TWasmExporttypeVecDeleteAPI;
exporttype_new : TWasmExporttypeNewAPI;
exporttype_name : TWasmExporttypeNameAPI;
exporttype_type : TWasmExporttypeTypeAPI;
val_delete : TWasmValDeleteAPI;
val_copy : TWasmValCopyAPI;
val_vec_new_empty : TWasmValVecNewEmptyAPI;
val_vec_new_uninitialized : TWasmValVecNewUninitializedAPI;
val_vec_new : TWasmValVecNewAPI;
val_vec_copy : TWasmValVecCopyAPI;
val_vec_delete : TWasmValVecDeleteAPI;
ref_delete : TWasmRefDeleteAPI;
ref_copy : TWasmRefCopyAPI;
ref_same : TWasmRefSameAPI;
ref_get_host_info : TWasmRefGetHostInfoAPI;
ref_set_host_info : TWasmRefSetHostInfoAPI;
ref_set_host_info_with_finalizer : TWasmRefSetHostInfoWithFinalizerAPI;
frame_delete : TWasmFrameDeleteAPI;
frame_vec_new_empty : TWasmFrameVecNewEmptyAPI;
frame_vec_new_uninitialized : TWasmFrameVecNewUninitializedAPI;
frame_vec_new : TWasmFrameVecNewAPI;
frame_vec_copy : TWasmFrameVecCopyAPI;
frame_vec_delete : TWasmFrameVecDeleteAPI;
frame_copy : TWasmFrameCopyAPI;
frame_instance : TWasmFrameInstanceAPI;
frame_func_index : TWasmFrameFuncIndexAPI;
frame_func_offset : TWasmFrameFuncOffsetAPI;
frame_module_offset : TWasmFrameModuleOffsetAPI;
trap_delete : TWasmTrapDeleteAPI;
trap_copy : TWasmTrapCopyAPI;
trap_same : TWasmTrapSameAPI;
trap_get_host_info : TWasmTrapGetHostInfoAPI;
trap_set_host_info : TWasmTrapSetHostInfoAPI;
trap_set_host_info_with_finalizer : TWasmTrapSetHostInfoWithFinalizerAPI;
trap_as_ref : TWasmTrapAsRefAPI;
trap_as_ref_const : TWasmTrapAsRefAPI;
ref_as_trap : TWasmRefAsTrapAPI;
ref_as_trap_const : TWasmRefAsTrapConstAPI;
trap_new : TWasmTrapNewAPI;
trap_message : TWasmTrapMessageAPI;
trap_origin : TWasmTrapOriginAPI;
trap_trace : TWasmTrapTraceAPI;
foreign_delete : TWasmForeignDeleteAPI;
foreign_copy : TWasmForeignCopyAPI;
foreign_same : TWasmForeignSameAPI;
foreign_get_host_info : TWasmForeignGetHostInfoAPI;
foreign_set_host_info : TWasmForeignSetHostInfoAPI;
foreign_set_host_info_with_finalizer : TWasmForeignSetHostInfoWithFinalizerAPI;
foreign_as_ref : TWasmForeignAsRefAPI;
foreign_as_ref_const : TWasmForeignAsRefAPI;
ref_as_foreign : TWasmRefAsForeignAPI;
ref_as_foreign_const : TWasmRefAsForeignConstAPI;
foreign_new : TWasmForeignNewAPI;
module_delete : TWasmModuleDeleteAPI;
module_copy : TWasmModuleCopyAPI;
module_same : TWasmModuleSameAPI;
module_get_host_info : TWasmModuleGetHostInfoAPI;
module_set_host_info : TWasmModuleSetHostInfoAPI;
module_set_host_info_with_finalizer : TWasmModuleSetHostInfoWithFinalizerAPI;
module_as_ref : TWasmModuleAsRefAPI;
module_as_ref_const : TWasmModuleAsRefAPI;
ref_as_module : TWasmRefAsModuleAPI;
ref_as_module_const : TWasmRefAsModuleConstAPI;
shared_module_delete : TWasmSharedModuleDeleteAPI;
shared_module_copy : TWasmSharedModuleCopyAPI;
shared_module_same : TWasmSharedModuleSameAPI;
shared_module_get_host_info : TWasmSharedModuleGetHostInfoAPI;
shared_module_set_host_info : TWasmSharedModuleSetHostInfoAPI;
shared_module_set_host_info_with_finalizer : TWasmSharedModuleSetHostInfoWithFinalizerAPI;
shared_module_as_ref : TWasmSharedModuleAsRefAPI;
shared_module_as_ref_const : TWasmSharedModuleAsRefAPI;
ref_as_shared_module : TWasmRefAsSharedModuleAPI;
ref_as_shared_module_const : TWasmRefAsSharedModuleConstAPI;
module_share : TWasmModuleShareAPI;
module_obtain : TWasmModuleObtainAPI;
module_new : TWasmModuleNewAPI;
module_validate : TWasmModuleValidateAPI;
module_imports : TWasmModuleImportsAPI;
module_exports : TWasmModuleExportsAPI;
module_serialize : TWasmModuleSerializeAPI;
module_deserialize : TWasmModuleDeserializeAPI;
func_delete : TWasmFuncDeleteAPI;
func_copy : TWasmFuncCopyAPI;
func_same : TWasmFuncSameAPI;
func_get_host_info : TWasmFuncGetHostInfoAPI;
func_set_host_info : TWasmFuncSetHostInfoAPI;
func_set_host_info_with_finalizer : TWasmFuncSetHostInfoWithFinalizerAPI;
func_as_ref : TWasmFuncAsRefAPI;
func_as_ref_const : TWasmFuncAsRefAPI;
ref_as_func : TWasmRefAsFuncAPI;
ref_as_func_const : TWasmRefAsFuncConstAPI;
func_new : TWasmFuncNewAPI;
func_new_with_env : TWasmFuncNewWithEnvAPI;
func_type : TWasmFuncTypeAPI;
func_param_arity : TWasmFuncParamArityAPI;
func_result_arity : TWasmFuncResultArityAPI;
func_call : TWasmFuncCallAPI;
global_delete : TWasmGlobalDeleteAPI;
global_copy : TWasmGlobalCopyAPI;
global_same : TWasmGlobalSameAPI;
global_get_host_info : TWasmGlobalGetHostInfoAPI;
global_set_host_info : TWasmGlobalSetHostInfoAPI;
global_set_host_info_with_finalizer : TWasmGlobalSetHostInfoWithFinalizerAPI;
global_as_ref : TWasmGlobalAsRefAPI;
global_as_ref_const : TWasmGlobalAsRefAPI;
ref_as_global : TWasmRefAsGlobalAPI;
ref_as_global_const : TWasmRefAsGlobalConstAPI;
global_new : TWasmGlobalNewAPI;
global_type : TWasmGlobalTypeAPI;
global_get : TWasmGlobalGetAPI;
global_set : TWasmGlobalSetAPI;
table_delete : TWasmTableDeleteAPI;
table_copy : TWasmTableCopyAPI;
table_same : TWasmTableSameAPI;
table_get_host_info : TWasmTableGetHostInfoAPI;
table_set_host_info : TWasmTableSetHostInfoAPI;
table_set_host_info_with_finalizer : TWasmTableSetHostInfoWithFinalizerAPI;
table_as_ref : TWasmTableAsRefAPI;
table_as_ref_const : TWasmTableAsRefAPI;
ref_as_table : TWasmRefAsTableAPI;
ref_as_table_const : TWasmRefAsTableConstAPI;
table_new : TWasmTableNewAPI;
table_type : TWasmTableTypeAPI;
table_get : TWasmTableGetAPI;
table_set : TWasmTableSetAPI;
table_size : TWasmTableSizeAPI;
table_grow : TWasmTableGrowAPI;
memory_delete : TWasmMemoryDeleteAPI;
memory_copy : TWasmMemoryCopyAPI;
memory_same : TWasmMemorySameAPI;
memory_get_host_info : TWasmMemoryGetHostInfoAPI;
memory_set_host_info : TWasmMemorySetHostInfoAPI;
memory_set_host_info_with_finalizer : TWasmMemorySetHostInfoWithFinalizerAPI;
memory_as_ref : TWasmMemoryAsRefAPI;
memory_as_ref_const : TWasmMemoryAsRefAPI;
ref_as_memory : TWasmRefAsMemoryAPI;
ref_as_memory_const : TWasmRefAsMemoryConstAPI;
memory_new : TWasmMemoryNewAPI;
memory_type : TWasmMemoryTypeAPI;
memory_data : TWasmMemoryDataAPI;
memory_data_size : TWasmMemoryDataSizeAPI;
memory_size : TWasmMemorySizeAPI;
memory_grow : TWasmMemoryGrowAPI;
extern_delete : TWasmExternDeleteAPI;
extern_copy : TWasmExternCopyAPI;
extern_same : TWasmExternSameAPI;
extern_get_host_info : TWasmExternGetHostInfoAPI;
extern_set_host_info : TWasmExternSetHostInfoAPI;
extern_set_host_info_with_finalizer : TWasmExternSetHostInfoWithFinalizerAPI;
extern_as_ref : TWasmExternAsRefAPI;
extern_as_ref_const : TWasmExternAsRefAPI;
ref_as_extern : TWasmRefAsExternAPI;
ref_as_extern_const : TWasmRefAsExternConstAPI;
extern_vec_new_empty : TWasmExternVecNewEmptyAPI;
extern_vec_new_uninitialized : TWasmExternVecNewUninitializedAPI;
extern_vec_new : TWasmExternVecNewAPI;
extern_vec_copy : TWasmExternVecCopyAPI;
extern_vec_delete : TWasmExternVecDeleteAPI;
extern_kind : TWasmExternKindAPI;
extern_type : TWasmExternTypeAPI;
func_as_extern : TWasmFuncAsExternAPI;
global_as_extern : TWasmGlobalAsExternAPI;
table_as_extern : TWasmTableAsExternAPI;
memory_as_extern : TWasmMemoryAsExternAPI;
extern_as_func : TWasmExternAsFuncAPI;
extern_as_global : TWasmExternAsGlobalAPI;
extern_as_table : TWasmExternAsTableAPI;
extern_as_memory : TWasmExternAsMemoryAPI;
func_as_extern_const : TWasmFuncAsExternConstAPI;
global_as_extern_const : TWasmGlobalAsExternConstAPI;
table_as_extern_const : TWasmTableAsExternConstAPI;
memory_as_extern_const : TWasmMemoryAsExternConstAPI;
extern_as_func_const : TWasmExternAsFuncConstAPI;
extern_as_global_const : TWasmExternAsGlobalConstAPI;
extern_as_table_const : TWasmExternAsTableConstAPI;
extern_as_memory_const : TWasmExternAsMemoryConstAPI;
instance_delete : TWasmInstanceDeleteAPI;
instance_copy : TWasmInstanceCopyAPI;
instance_same : TWasmInstanceSameAPI;
instance_get_host_info : TWasmInstanceGetHostInfoAPI;
instance_set_host_info : TWasmInstanceSetHostInfoAPI;
instance_set_host_info_with_finalizer : TWasmInstanceSetHostInfoWithFinalizerAPI;
instance_as_ref : TWasmInstanceAsRefAPI;
instance_as_ref_const : TWasmInstanceAsRefAPI;
ref_as_instance : TWasmRefAsInstanceAPI;
ref_as_instance_const : TWasmRefAsInstanceConstAPI;
instance_new : TWasmInstanceNewAPI;
instance_exports : TWasmInstanceExportsAPI;
class procedure name_new_from_string({own} out_ : PWasmName; const s : UTF8String); inline; static;
class procedure name_new_from_string_nt({own} out_ : PWasmName; const s : UTF8String); inline; static;
class function valkind_is_num(k : TWasmValkind) : Boolean; inline; static;
class function valkind_is_ref(k : TWasmValkind) : Boolean; inline; static;
class function valtype_is_num(const t : PWasmValType) : Boolean; inline; static;
class function valtype_is_ref(const t : PWasmValType) : Boolean; inline; static;
class function valtype_new_i32() : PWasmValType; inline; static;
class function valtype_new_i64() : PWasmValType; inline; static;
class function valtype_new_f32() : PWasmValType; inline; static;
class function valtype_new_f64() : PWasmValType; inline; static;
class function valtype_new_anyref() : PWasmValType; inline; static;
class function valtype_new_funcref() : PWasmValType; inline; static;
class function functype_new_0_0() : PWasmFunctype; inline; static;
class function functype_new_1_0(p : PWasmValType) : PWasmFunctype; inline; static;
class function functype_new_2_0({own}p1,p2 : PWasmValType) : PWasmFunctype; inline; static;
class function functype_new_3_0({own}p1,p2,p3 : PWasmValType) : PWasmFunctype; inline; static;
class function functype_new_0_1({own} r : PWasmValType) : PWasmFunctype; inline; static;
class function functype_new_1_1({own} p, r : PWasmValType) : PWasmFunctype; inline; static;
class function functype_new_2_1({own} p1,p2, r : PWasmValType) : PWasmFunctype; inline; static;
class function functype_new_3_1({own} p1,p2,p3, r : PWasmValType) : PWasmFunctype; inline; static;
class function functype_new_0_2({own} r1,r2 : PWasmValType) : PWasmFunctype; inline; static;
class function functype_new_1_2({own} p, r1,r2 : PWasmValType) : PWasmFunctype; inline; static;
class function functype_new_2_2({own} p1,p2, r1,r2 : PWasmValType) : PWasmFunctype; inline; static;
class function functype_new_3_2({own} p1,p2,p3, r1,r2 : PWasmValType) : PWasmFunctype; inline; static;
class function functype_new_array(const p : array of PWasmValType; const r : array of PWasmValType) : PWasmFunctype; static;
public
class procedure Init(dll_name : string); static;
class procedure InitAPIs(runtime : HMODULE); static;
end;
function WASM_I32_VAL(val : Integer) : TWasmVal; inline;
function WASM_I64_VAL(val : Int64) : TWasmVal; inline;
function WASM_F32_VAL(val : Single) : TWasmVal; inline;
function WASM_F64_VAL(val : Double) : TWasmVal; inline;
function WASM_REF_VAL(val : PWasmRef) : TWasmVal; inline;
function WASM_INIT_VAL() : TWasmVal; inline;
implementation
uses
Windows, System.Classes;
const
wasm_limits_max_default = $ffffffff;
MEMORY_PAGE_SIZE = $10000;
{ TWasm }
var
wasm_runtime : HMODULE;
class procedure TWasm.Init(dll_name: string);
begin
wasm_runtime := LoadLibrary(PWideChar(dll_name));
InitAPIs(wasm_runtime);
end;
class procedure TWasm.InitAPIs(runtime : HMODULE);
function ProcAddress(name : string) : Pointer;
begin
result := GetProcAddress(runtime, PWideChar(name));
end;
begin
if runtime <> 0 then
begin
byte_vec_new_empty := ProcAddress('wasm_byte_vec_new_empty');
byte_vec_new_uninitialized := ProcAddress('wasm_byte_vec_new_uninitialized');
byte_vec_new := ProcAddress('wasm_byte_vec_new');
byte_vec_copy := ProcAddress('wasm_byte_vec_copy');
byte_vec_delete := ProcAddress('wasm_byte_vec_delete');
config_delete := ProcAddress('wasm_config_delete');
config_new := ProcAddress('wasm_config_new');
engine_delete := ProcAddress('wasm_engine_delete');
engine_new := ProcAddress('wasm_engine_new');
engine_new_with_config := ProcAddress('wasm_engine_new_with_config');
store_delete := ProcAddress('wasm_store_delete');
store_new := ProcAddress('wasm_store_new');
valtype_delete := ProcAddress('wasm_valtype_delete');
valtype_copy := ProcAddress('wasm_valtype_copy');
valtype_vec_new_empty := ProcAddress('wasm_valtype_vec_new_empty');
valtype_vec_new_uninitialized := ProcAddress('wasm_valtype_vec_new_uninitialized');
valtype_vec_new := ProcAddress('wasm_valtype_vec_new');
valtype_vec_copy := ProcAddress('wasm_valtype_vec_copy');
valtype_vec_delete := ProcAddress('wasm_valtype_vec_delete');
valtype_new := ProcAddress('wasm_valtype_new');
valtype_kind := ProcAddress('wasm_valtype_kind');
functype_delete := ProcAddress('wasm_functype_delete');
functype_copy := ProcAddress('wasm_functype_copy');
functype_vec_new_empty := ProcAddress('wasm_functype_vec_new_empty');
functype_vec_new_uninitialized := ProcAddress('wasm_functype_vec_new_uninitialized');
functype_vec_new := ProcAddress('wasm_functype_vec_new');
functype_vec_copy := ProcAddress('wasm_functype_vec_copy');
functype_vec_delete := ProcAddress('wasm_functype_vec_delete');
functype_new := ProcAddress('wasm_functype_new');
functype_params := ProcAddress('wasm_functype_params');
functype_results := ProcAddress('wasm_functype_results');
globaltype_delete := ProcAddress('wasm_globaltype_delete');
globaltype_copy := ProcAddress('wasm_globaltype_copy');
globaltype_vec_new_empty := ProcAddress('wasm_globaltype_vec_new_empty');
globaltype_vec_new_uninitialized := ProcAddress('wasm_globaltype_vec_new_uninitialized');
globaltype_vec_new := ProcAddress('wasm_globaltype_vec_new');
globaltype_vec_copy := ProcAddress('wasm_globaltype_vec_copy');
globaltype_vec_delete := ProcAddress('wasm_globaltype_vec_delete');
globaltype_new := ProcAddress('wasm_globaltype_new');
globaltype_content := ProcAddress('wasm_globaltype_content');
globaltype_mutability := ProcAddress('wasm_globaltype_mutability');
tabletype_delete := ProcAddress('wasm_tabletype_delete');
tabletype_copy := ProcAddress('wasm_tabletype_copy');
tabletype_vec_new_empty := ProcAddress('wasm_tabletype_vec_new_empty');
tabletype_vec_new_uninitialized := ProcAddress('wasm_tabletype_vec_new_uninitialized');
tabletype_vec_new := ProcAddress('wasm_tabletype_vec_new');
tabletype_vec_copy := ProcAddress('wasm_tabletype_vec_copy');
tabletype_vec_delete := ProcAddress('wasm_tabletype_vec_delete');
tabletype_new := ProcAddress('wasm_tabletype_new');
tabletype_element := ProcAddress('wasm_tabletype_element');
tabletype_limits := ProcAddress('wasm_tabletype_limits');
memorytype_delete := ProcAddress('wasm_memorytype_delete');
memorytype_copy := ProcAddress('wasm_memorytype_copy');
memorytype_vec_new_empty := ProcAddress('wasm_memorytype_vec_new_empty');
memorytype_vec_new_uninitialized := ProcAddress('wasm_memorytype_vec_new_uninitialized');
memorytype_vec_new := ProcAddress('wasm_memorytype_vec_new');
memorytype_vec_copy := ProcAddress('wasm_memorytype_vec_copy');
memorytype_vec_delete := ProcAddress('wasm_memorytype_vec_delete');
memorytype_new := ProcAddress('wasm_memorytype_new');
memorytype_limits := ProcAddress('wasm_memorytype_limits');
externtype_delete := ProcAddress('wasm_externtype_delete');
externtype_copy := ProcAddress('wasm_externtype_copy');
externtype_vec_new_empty := ProcAddress('wasm_externtype_vec_new_empty');
externtype_vec_new_uninitialized := ProcAddress('wasm_externtype_vec_new_uninitialized');
externtype_vec_new := ProcAddress('wasm_externtype_vec_new');
externtype_vec_copy := ProcAddress('wasm_externtype_vec_copy');
externtype_vec_delete := ProcAddress('wasm_externtype_vec_delete');
externtype_kind := ProcAddress('wasm_externtype_kind');
functype_as_externtype := ProcAddress('wasm_functype_as_externtype');
globaltype_as_externtype := ProcAddress('wasm_globaltype_as_externtype');
tabletype_as_externtype := ProcAddress('wasm_tabletype_as_externtype');
memorytype_as_externtype := ProcAddress('wasm_memorytype_as_externtype');
externtype_as_functype := ProcAddress('wasm_externtype_as_functype');
externtype_as_globaltype := ProcAddress('wasm_externtype_as_globaltype');
externtype_as_tabletype := ProcAddress('wasm_externtype_as_tabletype');
externtype_as_memorytype := ProcAddress('wasm_externtype_as_memorytype');
functype_as_externtype_const := ProcAddress('wasm_functype_as_externtype_const');
globaltype_as_externtype_const := ProcAddress('wasm_globaltype_as_externtype_const');
tabletype_as_externtype_const := ProcAddress('wasm_tabletype_as_externtype_const');
memorytype_as_externtype_const := ProcAddress('wasm_memorytype_as_externtype_const');
externtype_as_functype_const := ProcAddress('wasm_externtype_as_functype_const');
externtype_as_globaltype_const := ProcAddress('wasm_externtype_as_globaltype_const');
externtype_as_tabletype_const := ProcAddress('wasm_externtype_as_tabletype_const');
externtype_as_memorytype_const := ProcAddress('wasm_externtype_as_memorytype_const');
importtype_delete := ProcAddress('wasm_importtype_delete');
importtype_copy := ProcAddress('wasm_importtype_copy');
importtype_vec_new_empty := ProcAddress('wasm_importtype_vec_new_empty');
importtype_vec_new_uninitialized := ProcAddress('wasm_importtype_vec_new_uninitialized');
importtype_vec_new := ProcAddress('wasm_importtype_vec_new');
importtype_vec_copy := ProcAddress('wasm_importtype_vec_copy');
importtype_vec_delete := ProcAddress('wasm_importtype_vec_delete');
importtype_new := ProcAddress('wasm_importtype_new');
importtype_module := ProcAddress('wasm_importtype_module');
importtype_name := ProcAddress('wasm_importtype_name');
importtype_type := ProcAddress('wasm_importtype_type');
exporttype_delete := ProcAddress('wasm_exporttype_delete');
exporttype_copy := ProcAddress('wasm_exporttype_copy');
exporttype_vec_new_empty := ProcAddress('wasm_exporttype_vec_new_empty');
exporttype_vec_new_uninitialized := ProcAddress('wasm_exporttype_vec_new_uninitialized');
exporttype_vec_new := ProcAddress('wasm_exporttype_vec_new');
exporttype_vec_copy := ProcAddress('wasm_exporttype_vec_copy');
exporttype_vec_delete := ProcAddress('wasm_exporttype_vec_delete');
exporttype_new := ProcAddress('wasm_exporttype_new');
exporttype_name := ProcAddress('wasm_exporttype_name');
exporttype_type := ProcAddress('wasm_exporttype_type');
val_delete := ProcAddress('wasm_val_delete');
val_copy := ProcAddress('wasm_val_copy');
val_vec_new_empty := ProcAddress('wasm_val_vec_new_empty');
val_vec_new_uninitialized := ProcAddress('wasm_val_vec_new_uninitialized');
val_vec_new := ProcAddress('wasm_val_vec_new');
val_vec_copy := ProcAddress('wasm_val_vec_copy');
val_vec_delete := ProcAddress('wasm_val_vec_delete');
ref_delete := ProcAddress('wasm_ref_delete');
ref_copy := ProcAddress('wasm_ref_copy');
ref_same := ProcAddress('wasm_ref_same');
ref_get_host_info := ProcAddress('wasm_ref_same');
ref_set_host_info := ProcAddress('wasm_ref_set_host_info');
ref_set_host_info_with_finalizer := ProcAddress('wasm_ref_set_host_info_with_finalizer');
frame_delete := ProcAddress('wasm_frame_delete');
frame_vec_new_empty := ProcAddress('wasm_frame_vec_new_empty');
frame_vec_new_uninitialized := ProcAddress('wasm_frame_vec_new_uninitialized');
frame_vec_new := ProcAddress('wasm_frame_vec_new');
frame_vec_copy := ProcAddress('wasm_frame_vec_copy');
frame_vec_delete := ProcAddress('wasm_frame_vec_delete');
frame_copy := ProcAddress('wasm_frame_copy');
frame_instance := ProcAddress('wasm_frame_instance');
frame_func_index := ProcAddress('wasm_frame_func_index');
frame_func_offset := ProcAddress('wasm_frame_func_offset');
frame_module_offset := ProcAddress('wasm_frame_module_offset');
trap_delete := ProcAddress('wasm_trap_delete');
trap_copy := ProcAddress('wasm_trap_copy');
trap_same := ProcAddress('wasm_trap_same');
trap_get_host_info := ProcAddress('wasm_trap_same');
trap_set_host_info := ProcAddress('wasm_trap_set_host_info');
trap_set_host_info_with_finalizer := ProcAddress('wasm_trap_set_host_info_with_finalizer');
trap_as_ref := ProcAddress('wasm_trap_as_ref');
trap_as_ref_const := ProcAddress('wasm_trap_as_ref_const');
ref_as_trap := ProcAddress('wasm_ref_as_trap');
ref_as_trap_const := ProcAddress('wasm_ref_as_trap_const');
trap_new := ProcAddress('wasm_trap_new');
trap_message := ProcAddress('wasm_trap_message');
trap_origin := ProcAddress('wasm_trap_origin');
trap_trace := ProcAddress('wasm_trap_trace');
foreign_delete := ProcAddress('wasm_foreign_delete');
foreign_copy := ProcAddress('wasm_foreign_copy');
foreign_same := ProcAddress('wasm_foreign_same');
foreign_get_host_info := ProcAddress('wasm_foreign_same');
foreign_set_host_info := ProcAddress('wasm_foreign_set_host_info');
foreign_set_host_info_with_finalizer := ProcAddress('wasm_foreign_set_host_info_with_finalizer');
foreign_as_ref := ProcAddress('wasm_foreign_as_ref');
foreign_as_ref_const := ProcAddress('wasm_foreign_as_ref_const');
ref_as_foreign := ProcAddress('wasm_ref_as_foreign');
ref_as_foreign_const := ProcAddress('wasm_ref_as_foreign_const');
foreign_new := ProcAddress('wasm_foreign_new');
module_delete := ProcAddress('wasm_module_delete');
module_copy := ProcAddress('wasm_module_copy');
module_same := ProcAddress('wasm_module_same');
module_get_host_info := ProcAddress('wasm_module_same');
module_set_host_info := ProcAddress('wasm_module_set_host_info');
module_set_host_info_with_finalizer := ProcAddress('wasm_module_set_host_info_with_finalizer');
module_as_ref := ProcAddress('wasm_module_as_ref');
module_as_ref_const := ProcAddress('wasm_module_as_ref_const');
ref_as_module := ProcAddress('wasm_ref_as_module');
ref_as_module_const := ProcAddress('wasm_ref_as_module_const');
shared_module_delete := ProcAddress('wasm_shared_module_delete');
shared_module_copy := ProcAddress('wasm_shared_module_copy');
shared_module_same := ProcAddress('wasm_shared_module_same');
shared_module_get_host_info := ProcAddress('wasm_shared_module_same');
shared_module_set_host_info := ProcAddress('wasm_shared_module_set_host_info');
shared_module_set_host_info_with_finalizer := ProcAddress('wasm_shared_module_set_host_info_with_finalizer');
shared_module_as_ref := ProcAddress('wasm_shared_module_as_ref');
shared_module_as_ref_const := ProcAddress('wasm_shared_module_as_ref_const');
ref_as_shared_module := ProcAddress('wasm_ref_as_shared_module');
ref_as_shared_module_const := ProcAddress('wasm_ref_as_shared_module_const');
module_share := ProcAddress('wasm_module_share');
module_obtain := ProcAddress('wasm_module_obtain');
module_new := ProcAddress('wasm_module_new');
module_validate := ProcAddress('wasm_module_validate');
module_imports := ProcAddress('wasm_module_imports');
module_exports := ProcAddress('wasm_module_exports');
module_serialize := ProcAddress('wasm_module_serialize');
module_deserialize := ProcAddress('wasm_module_deserialize');
func_delete := ProcAddress('wasm_func_delete');
func_copy := ProcAddress('wasm_func_copy');
func_same := ProcAddress('wasm_func_same');
func_get_host_info := ProcAddress('wasm_func_same');
func_set_host_info := ProcAddress('wasm_func_set_host_info');
func_set_host_info_with_finalizer := ProcAddress('wasm_func_set_host_info_with_finalizer');
func_as_ref := ProcAddress('wasm_func_as_ref');
func_as_ref_const := ProcAddress('wasm_func_as_ref_const');
ref_as_func := ProcAddress('wasm_ref_as_func');
ref_as_func_const := ProcAddress('wasm_ref_as_func_const');
func_new := ProcAddress('wasm_func_new');
func_new_with_env := ProcAddress('wasm_func_new_with_env');
func_type := ProcAddress('wasm_func_type');
func_param_arity := ProcAddress('wasm_func_param_arity');
func_result_arity := ProcAddress('wasm_func_result_arity');
func_call := ProcAddress('wasm_func_call');
global_delete := ProcAddress('wasm_global_delete');
global_copy := ProcAddress('wasm_global_copy');
global_same := ProcAddress('wasm_global_same');
global_get_host_info := ProcAddress('wasm_global_same');
global_set_host_info := ProcAddress('wasm_global_set_host_info');
global_set_host_info_with_finalizer := ProcAddress('wasm_global_set_host_info_with_finalizer');
global_as_ref := ProcAddress('wasm_global_as_ref');
global_as_ref_const := ProcAddress('wasm_global_as_ref_const');
ref_as_global := ProcAddress('wasm_ref_as_global');
ref_as_global_const := ProcAddress('wasm_ref_as_global_const');
global_new := ProcAddress('wasm_global_new');
global_type := ProcAddress('wasm_global_type');
global_get := ProcAddress('wasm_global_get');
global_set := ProcAddress('wasm_global_set');
table_delete := ProcAddress('wasm_table_delete');
table_copy := ProcAddress('wasm_table_copy');
table_same := ProcAddress('wasm_table_same');
table_get_host_info := ProcAddress('wasm_table_same');
table_set_host_info := ProcAddress('wasm_table_set_host_info');
table_set_host_info_with_finalizer := ProcAddress('wasm_table_set_host_info_with_finalizer');
table_as_ref := ProcAddress('wasm_table_as_ref');
table_as_ref_const := ProcAddress('wasm_table_as_ref_const');
ref_as_table := ProcAddress('wasm_ref_as_table');
ref_as_table_const := ProcAddress('wasm_ref_as_table_const');
table_new := ProcAddress('wasm_table_new');
table_type := ProcAddress('wasm_table_type');
table_get := ProcAddress('wasm_table_get');
table_set := ProcAddress('wasm_table_set');
table_size := ProcAddress('wasm_table_size');
table_grow := ProcAddress('wasm_table_grow');
memory_delete := ProcAddress('wasm_memory_delete');
memory_copy := ProcAddress('wasm_memory_copy');
memory_same := ProcAddress('wasm_memory_same');
memory_get_host_info := ProcAddress('wasm_memory_same');
memory_set_host_info := ProcAddress('wasm_memory_set_host_info');
memory_set_host_info_with_finalizer := ProcAddress('wasm_memory_set_host_info_with_finalizer');
memory_as_ref := ProcAddress('wasm_memory_as_ref');
memory_as_ref_const := ProcAddress('wasm_memory_as_ref_const');
ref_as_memory := ProcAddress('wasm_ref_as_memory');
ref_as_memory_const := ProcAddress('wasm_ref_as_memory_const');
memory_new := ProcAddress('wasm_memory_new');
memory_type := ProcAddress('wasm_memory_type');
memory_data := ProcAddress('wasm_memory_data');
memory_data_size := ProcAddress('wasm_memory_data_size');
memory_size := ProcAddress('wasm_memory_size');
memory_grow := ProcAddress('wasm_memory_grow');
extern_delete := ProcAddress('wasm_extern_delete');
extern_copy := ProcAddress('wasm_extern_copy');
extern_same := ProcAddress('wasm_extern_same');
extern_get_host_info := ProcAddress('wasm_extern_same');
extern_set_host_info := ProcAddress('wasm_extern_set_host_info');
extern_set_host_info_with_finalizer := ProcAddress('wasm_extern_set_host_info_with_finalizer');
extern_as_ref := ProcAddress('wasm_extern_as_ref');
extern_as_ref_const := ProcAddress('wasm_extern_as_ref_const');
ref_as_extern := ProcAddress('wasm_ref_as_extern');
ref_as_extern_const := ProcAddress('wasm_ref_as_extern_const');
extern_vec_new_empty := ProcAddress('wasm_extern_vec_new_empty');
extern_vec_new_uninitialized := ProcAddress('wasm_extern_vec_new_uninitialized');
extern_vec_new := ProcAddress('wasm_extern_vec_new');
extern_vec_copy := ProcAddress('wasm_extern_vec_copy');
extern_vec_delete := ProcAddress('wasm_extern_vec_delete');
extern_kind := ProcAddress('wasm_extern_kind');
extern_type := ProcAddress('wasm_extern_type');
func_as_extern := ProcAddress('wasm_func_as_extern');
global_as_extern := ProcAddress('wasm_global_as_extern');
table_as_extern := ProcAddress('wasm_table_as_extern');
memory_as_extern := ProcAddress('wasm_memory_as_extern');
extern_as_func := ProcAddress('wasm_extern_as_func');
extern_as_global := ProcAddress('wasm_extern_as_global');
extern_as_table := ProcAddress('wasm_extern_as_table');
extern_as_memory := ProcAddress('wasm_extern_as_memory');
func_as_extern_const := ProcAddress('wasm_func_as_extern_const');
global_as_extern_const := ProcAddress('wasm_global_as_extern_const');
table_as_extern_const := ProcAddress('wasm_table_as_extern_const');
memory_as_extern_const := ProcAddress('wasm_memory_as_extern_const');
extern_as_func_const := ProcAddress('wasm_extern_as_func_const');
extern_as_global_const := ProcAddress('wasm_extern_as_global_const');
extern_as_table_const := ProcAddress('wasm_extern_as_table_const');
extern_as_memory_const := ProcAddress('wasm_extern_as_memory_const');
instance_delete := ProcAddress('wasm_instance_delete');
instance_copy := ProcAddress('wasm_instance_copy');
instance_same := ProcAddress('wasm_instance_same');
instance_get_host_info := ProcAddress('wasm_instance_same');
instance_set_host_info := ProcAddress('wasm_instance_set_host_info');
instance_set_host_info_with_finalizer := ProcAddress('wasm_instance_set_host_info_with_finalizer');
instance_as_ref := ProcAddress('wasm_instance_as_ref');
instance_as_ref_const := ProcAddress('wasm_instance_as_ref_const');
ref_as_instance := ProcAddress('wasm_ref_as_instance');
ref_as_instance_const := ProcAddress('wasm_ref_as_instance_const');
instance_new := ProcAddress('wasm_instance_new');
instance_exports := ProcAddress('wasm_instance_exports');
end;
end;
class procedure TWasm.name_new_from_string(out_: PWasmName; const s: UTF8String);
begin
TWasm.byte_vec_new(PWasmByteVec(out_), Length(s), @s[1]);
end;
class procedure TWasm.name_new_from_string_nt(out_: PWasmName; const s: UTF8String);
begin
TWasm.byte_vec_new(PWasmByteVec(out_), Length(s)+1, @s[1]);
end;
class function TWasm.valkind_is_num(k : TWasmValkind) : Boolean;
begin
result := k < WASM_ANYREF;
end;
class function TWasm.valkind_is_ref(k : TWasmValkind) : Boolean;
begin
result := k >= WASM_ANYREF;
end;
class function TWasm.valtype_is_num(const t : PWasmValType) : Boolean;
begin
result := TWasm.valkind_is_num(TWasm.valtype_kind(t));
end;
class function TWasm.valtype_is_ref(const t : PWasmValType) : Boolean;
begin
result := TWasm.valkind_is_ref(TWasm.valtype_kind(t));
end;
// Value Type construction short-hands
class function TWasm.valtype_new_i32() : PWasmValType;
begin
result := TWasm.valtype_new(WASM_I32);
end;
class function TWasm.valtype_new_i64() : PWasmValType;
begin
result := TWasm.valtype_new(WASM_I64);
end;
class function TWasm.valtype_new_f32() : PWasmValType;
begin
result := TWasm.valtype_new(WASM_F32);
end;
class function TWasm.valtype_new_f64() : PWasmValType;
begin
result := TWasm.valtype_new(WASM_F64);
end;
class function TWasm.valtype_new_anyref() : PWasmValType;
begin
result := TWasm.valtype_new(WASM_ANYREF);
end;
class function TWasm.valtype_new_funcref() : PWasmValType;
begin
result := TWasm.valtype_new(WASM_FUNCREF);
end;
// Function Types construction short-hands
class function TWasm.functype_new_0_0() : PWasmFunctype;
var
params, results : TWasmValtypeVec;
begin
TWasm.valtype_vec_new_empty(@params);
TWasm.valtype_vec_new_empty(@results);
result := TWasm.functype_new(@params, @results);
end;
class function TWasm.functype_new_1_0(p : PWasmValType) : PWasmFunctype;
var
params, results : TWasmValtypeVec;
ps : array[0..0] of PWasmValType;
begin
ps[0] := p;
TWasm.valtype_vec_new(@params, 1, @ps[0]);
TWasm.valtype_vec_new_empty(@results);
result := TWasm.functype_new(@params, @results);
end;
class function TWasm.functype_new_2_0({own}p1,p2 : PWasmValType) : PWasmFunctype;
var
params, results : TWasmValtypeVec;
ps : array[0..1] of PWasmValType;
begin
ps[0] := p1;
ps[1] := p2;
TWasm.valtype_vec_new(@params, 2, @ps[0]);
TWasm.valtype_vec_new_empty(@results);
result := TWasm.functype_new(@params, @results);
end;
class function TWasm.functype_new_3_0({own}p1,p2,p3 : PWasmValType) : PWasmFunctype;
var
params, results : TWasmValtypeVec;
ps : array[0..2] of PWasmValType;
begin
ps[0] := p1;
ps[1] := p2;
ps[2] := p3;
TWasm.valtype_vec_new(@params, 3, @ps[0]);
TWasm.valtype_vec_new_empty(@results);
result := TWasm.functype_new(@params, @results);
end;
class function TWasm.functype_new_0_1({own} r : PWasmValType) : PWasmFunctype;
var
params, results : TWasmValtypeVec;
rs : array[0..0] of PWasmValType;
begin
rs[0] := r;
TWasm.valtype_vec_new_empty(@params);
TWasm.valtype_vec_new(@results, 1, @rs[0]);
result := TWasm.functype_new(@params, @results);
end;
class function TWasm.functype_new_1_1({own} p, r : PWasmValType) : PWasmFunctype;
var
params, results : TWasmValtypeVec;
ps : array[0..0] of PWasmValType;
rs : array[0..0] of PWasmValType;
begin
ps[0] := p;
rs[0] := r;
TWasm.valtype_vec_new(@params, 1, @ps[0]);
TWasm.valtype_vec_new(@results, 1, @rs[0]);
result := TWasm.functype_new(@params, @results);
end;
class function TWasm.functype_new_2_1({own} p1,p2, r : PWasmValType) : PWasmFunctype;
var
params, results : TWasmValtypeVec;
ps : array[0..1] of PWasmValType;
rs : array[0..0] of PWasmValType;
begin
ps[0] := p1;
ps[1] := p2;
rs[0] := r;
TWasm.valtype_vec_new(@params, 2, @ps[0]);
TWasm.valtype_vec_new(@results, 1, @rs[0]);
result := TWasm.functype_new(@params, @results);
end;
class function TWasm.functype_new_3_1({own} p1,p2,p3, r : PWasmValType) : PWasmFunctype;
var
params, results : TWasmValtypeVec;
ps : array[0..2] of PWasmValType;
rs : array[0..0] of PWasmValType;
begin
ps[0] := p1;
ps[1] := p2;
ps[2] := p3;
rs[0] := r;
TWasm.valtype_vec_new(@params, 3, @ps[0]);
TWasm.valtype_vec_new(@results, 1, @rs[0]);
result := TWasm.functype_new(@params, @results);
end;
class function TWasm.functype_new_0_2({own} r1,r2 : PWasmValType) : PWasmFunctype;
var
params, results : TWasmValtypeVec;
rs : array[0..1] of PWasmValType;
begin
rs[0] := r1;
rs[1] := r2;
TWasm.valtype_vec_new_empty(@params);
TWasm.valtype_vec_new(@results, 2, @rs[0]);
result := TWasm.functype_new(@params, @results);
end;
class function TWasm.functype_new_1_2({own} p, r1,r2 : PWasmValType) : PWasmFunctype;
var
params, results : TWasmValtypeVec;
ps : array[0..0] of PWasmValType;
rs : array[0..1] of PWasmValType;
begin
ps[0] := p;
rs[0] := r1;
rs[1] := r2;
TWasm.valtype_vec_new(@params, 1, @ps[0]);
TWasm.valtype_vec_new(@results, 2, @rs[0]);
result := TWasm.functype_new(@params, @results);
end;
class function TWasm.functype_new_2_2({own} p1,p2, r1,r2 : PWasmValType) : PWasmFunctype;
var
params, results : TWasmValtypeVec;
ps : array[0..1] of PWasmValType;
rs : array[0..1] of PWasmValType;
begin
ps[0] := p1;
ps[1] := p2;
rs[0] := r1;
rs[1] := r2;
TWasm.valtype_vec_new(@params, 2, @ps[0]);
TWasm.valtype_vec_new(@results, 2, @rs[0]);
result := TWasm.functype_new(@params, @results);
end;
class function TWasm.functype_new_3_2({own} p1,p2,p3, r1,r2 : PWasmValType) : PWasmFunctype;
var
params, results : TWasmValtypeVec;
ps : array[0..2] of PWasmValType;
rs : array[0..1] of PWasmValType;
begin
ps[0] := p1;
ps[1] := p2;
ps[2] := p3;
rs[0] := r1;
rs[1] := r2;
TWasm.valtype_vec_new(@params, 3, @ps[0]);
TWasm.valtype_vec_new(@results, 2, @rs[0]);
result := TWasm.functype_new(@params, @results);
end;
class function TWasm.functype_new_array(const p : array of PWasmValType; const r : array of PWasmValType) : PWasmFunctype;
var
params, results : TWasmValtypeVec;
begin
TWasm.valtype_vec_new(@params, Length(p), @p[0]);
TWasm.valtype_vec_new(@results, Length(r), @r[0]);
result := TWasm.functype_new(@params, @results);
end;
// Value construction short-hands
procedure WasmValInitPtr({own} out_ : PWasmVal; p : Pointer);
begin
{$ifdef CPU64BITS}
out_.kind := WASM_I64;
out_.i64 := Int64(p);
{$else}
out_.kind := WASM_I32;
out_.i32 := Ord(p);
{$endif}
end;
function WasmValPtr(const val : PWasmVal) : Pointer;
begin
{$ifdef CPU64BITS}
result := Pointer(val.i64);
{$else}
result := Pointer(val.i32);
{$endif}
end;
{ TWasmVec<T> }
constructor TWasmVec<T>.Create(const arry: array of T);
begin
self.size := Length(arry);
self.data := @arry[0];
end;
function TWasmVec<T>.GetItem(i: Integer): T;
begin
var p := self.data;
Inc(p, i);
result := p^;
end;
function TWasmVec<T>.GetPointers(i : Integer) : Pointer;
begin
var p := self.data;
Inc(p, i);
result := p;
end;
class operator TWasmVec<T>.Implicit(const arry: array of T): TWasmVec<T>;
begin
result.Create(arry);
end;
procedure TWasmVec<T>.SetItem(i: Integer; Value: T);
begin
var p := self.data;
Inc(p, i);
p^ := Value;
end;
constructor TWasmVec<T>.Create(size: NativeInt; data: PT);
begin
self.size := size;
self.data := data;
end;
{ TWasmLimits }
constructor TWasmLimits.Create(min, max: Cardinal);
begin
self.min := min;
self.max := max;
end;
{ TWasmValKindHelper }
function TWasmValKindHelper.IsNum: Boolean;
begin
result := self < WASM_ANYREF;
end;
function TWasmValKindHelper.IsRef: Boolean;
begin
result := self >= WASM_ANYREF;
end;
procedure byte_vec_disposer(p : Pointer);
begin
TWasm.byte_vec_delete(p);
end;
procedure byte_vec_disposer_host_only(p : Pointer);
begin
Dispose(p);
end;
procedure byte_vec_disposer_host(p : Pointer);
begin
TWasm.byte_vec_delete(p);
Dispose(p);
end;
procedure config_disposer(p : Pointer);
begin
TWasm.config_delete(p);
end;
procedure engine_disposer(p : Pointer);
begin
TWasm.engine_delete(p);
end;
procedure store_disposer(p : Pointer);
begin
TWasm.store_delete(p);
end;
procedure valtype_disposer(p : Pointer);
begin
TWasm.valtype_delete(p);
end;
procedure valtype_vec_disposer(p : Pointer);
begin
TWasm.valtype_vec_delete(p);
end;
procedure valtype_vec_disposer_host_only(p : Pointer);
begin
Dispose(p);
end;
procedure valtype_vec_disposer_host(p : Pointer);
begin
TWasm.valtype_vec_delete(p);
Dispose(p);
end;
procedure functype_disposer(p : Pointer);
begin
TWasm.functype_delete(p);
end;
procedure functype_vec_disposer(p : Pointer);
begin
TWasm.functype_vec_delete(p);
end;
procedure functype_vec_disposer_host_only(p : Pointer);
begin
Dispose(p);
end;
procedure functype_vec_disposer_host(p : Pointer);
begin
TWasm.functype_vec_delete(p);
Dispose(p);
end;
procedure globaltype_disposer(p : Pointer);
begin
TWasm.globaltype_delete(p);
end;
procedure globaltype_vec_disposer(p : Pointer);
begin
TWasm.globaltype_vec_delete(p);
end;
procedure globaltype_vec_disposer_host_only(p : Pointer);
begin
Dispose(p);
end;
procedure globaltype_vec_disposer_host(p : Pointer);
begin
TWasm.globaltype_vec_delete(p);
Dispose(p);
end;
procedure tabletype_disposer(p : Pointer);
begin
TWasm.tabletype_delete(p);
end;
procedure tabletype_vec_disposer(p : Pointer);
begin
TWasm.tabletype_vec_delete(p);
end;
procedure tabletype_vec_disposer_host_only(p : Pointer);
begin
Dispose(p);
end;
procedure tabletype_vec_disposer_host(p : Pointer);
begin
TWasm.tabletype_vec_delete(p);
Dispose(p);
end;
procedure memorytype_disposer(p : Pointer);
begin
TWasm.memorytype_delete(p);
end;
procedure memorytype_vec_disposer(p : Pointer);
begin
TWasm.memorytype_vec_delete(p);
end;
procedure memorytype_vec_disposer_host_only(p : Pointer);
begin
Dispose(p);
end;
procedure memorytype_vec_disposer_host(p : Pointer);
begin
TWasm.memorytype_vec_delete(p);
Dispose(p);
end;
procedure externtype_disposer(p : Pointer);
begin
TWasm.externtype_delete(p);
end;
procedure externtype_vec_disposer(p : Pointer);
begin
TWasm.externtype_vec_delete(p);
end;
procedure externtype_vec_disposer_host_only(p : Pointer);
begin
Dispose(p);
end;
procedure externtype_vec_disposer_host(p : Pointer);
begin
TWasm.externtype_vec_delete(p);
Dispose(p);
end;
procedure importtype_disposer(p : Pointer);
begin
TWasm.importtype_delete(p);
end;
procedure importtype_vec_disposer(p : Pointer);
begin
TWasm.importtype_vec_delete(p);
end;
procedure importtype_vec_disposer_host_only(p : Pointer);
begin
Dispose(p);
end;
procedure importtype_vec_disposer_host(p : Pointer);
begin
TWasm.importtype_vec_delete(p);
Dispose(p);
end;
procedure exporttype_disposer(p : Pointer);
begin
TWasm.exporttype_delete(p);
end;
procedure exporttype_vec_disposer(p : Pointer);
begin
TWasm.exporttype_vec_delete(p);
end;
procedure exporttype_vec_disposer_host_only(p : Pointer);
begin
Dispose(p);
end;
procedure exporttype_vec_disposer_host(p : Pointer);
begin
TWasm.exporttype_vec_delete(p);
Dispose(p);
end;
procedure val_disposer(p : Pointer);
begin
TWasm.val_delete(p);
end;
procedure val_disposer_host(p : Pointer);
begin
TWasm.val_delete(p);
Dispose(p);
end;
procedure val_vec_disposer(p : Pointer);
begin
TWasm.val_vec_delete(p);
end;
procedure val_vec_disposer_host_only(p : Pointer);
begin
Dispose(p);
end;
procedure val_vec_disposer_host(p : Pointer);
begin
TWasm.val_vec_delete(p);
Dispose(p);
end;
procedure ref_disposer(p : Pointer);
begin
TWasm.ref_delete(p);
end;
procedure frame_disposer(p : Pointer);
begin
TWasm.frame_delete(p);
end;
procedure frame_vec_disposer(p : Pointer);
begin
TWasm.frame_vec_delete(p);
end;
procedure frame_vec_disposer_host_only(p : Pointer);
begin
Dispose(p);
end;
procedure frame_vec_disposer_host(p : Pointer);
begin
TWasm.frame_vec_delete(p);
Dispose(p);
end;
procedure trap_disposer(p : Pointer);
begin
TWasm.trap_delete(p);
end;
procedure foreign_disposer(p : Pointer);
begin
TWasm.foreign_delete(p);
end;
procedure module_disposer(p : Pointer);
begin
TWasm.module_delete(p);
end;
procedure shared_module_disposer(p : Pointer);
begin
TWasm.shared_module_delete(p);
end;
procedure func_disposer(p : Pointer);
begin
TWasm.func_delete(p);
end;
procedure global_disposer(p : Pointer);
begin
TWasm.global_delete(p);
end;
procedure table_disposer(p : Pointer);
begin
TWasm.table_delete(p);
end;
procedure memory_disposer(p : Pointer);
begin
TWasm.memory_delete(p);
end;
procedure extern_disposer(p : Pointer);
begin
TWasm.extern_delete(p);
end;
procedure extern_vec_disposer(p : Pointer);
begin
TWasm.extern_vec_delete(p);
end;
procedure extern_vec_disposer_host_only(p : Pointer);
begin
Dispose(p);
end;
procedure extern_vec_disposer_host(p : Pointer);
begin
TWasm.extern_vec_delete(p);
Dispose(p);
end;
procedure instance_disposer(p : Pointer);
begin
TWasm.instance_delete(p);
end;
{ TOwnByteVec }
class function TOwnByteVec.Wrap(p: PWasmByteVec; deleter : TRcDeleter): TOwnByteVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmByteVec>.Create(p, deleter);
end;
class function TOwnByteVec.Wrap(p: PWasmByteVec): TOwnByteVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmByteVec>.Create(p, byte_vec_disposer);
end;
class operator TOwnByteVec.Finalize(var Dest: TOwnByteVec);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnByteVec.Implicit(const Src: IRcContainer<PWasmByteVec>): TOwnByteVec;
begin
result.FStrongRef := Src;
end;
class operator TOwnByteVec.Negative(Src: TOwnByteVec): IRcContainer<PWasmByteVec>;
begin
result := Src.FStrongRef;
end;
class operator TOwnByteVec.Positive(Src: TOwnByteVec): PWasmByteVec;
begin
result := Src.Unwrap;
end;
function TOwnByteVec.Unwrap: PWasmByteVec;
begin
result := FStrongRef.Unwrap;
end;
function TOwnByteVec.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmByteVec }
constructor TWasmByteVec.Create(const arry: array of TWasmByte);
begin
size := Length(arry);
if size = 0 then data := nil
else data := @arry[0];
end;
class function TWasmByteVec.New(const init: array of TWasmByte): TOwnByteVec;
var
prec : PWasmByteVec;
begin
System.New(prec);
TWasm.byte_vec_new(prec, Length(init), @init[0]);
result.FStrongRef := TRcContainer<PWasmByteVec>.Create(prec, byte_vec_disposer_host);
end;
class function TWasmByteVec.NewEmpty: TOwnByteVec;
var
prec : PWasmByteVec;
begin
System.New(prec);
TWasm.byte_vec_new_empty(prec);
result.FStrongRef := TRcContainer<PWasmByteVec>.Create(prec, byte_vec_disposer_host);
end;
class function TWasmByteVec.NewUninitialized(size: NativeInt): TOwnByteVec;
var
prec : PWasmByteVec;
begin
System.New(prec);
TWasm.byte_vec_new_uninitialized(prec, size);
result.FStrongRef := TRcContainer<PWasmByteVec>.Create(prec, byte_vec_disposer_host);
end;
function TWasmByteVec.Copy: TOwnByteVec;
var
prec : PWasmByteVec;
begin
System.New(prec);
TWasm.byte_vec_copy(prec, @self);
result.FStrongRef := TRcContainer<PWasmByteVec>.Create(prec, byte_vec_disposer_host);
end;
procedure TWasmByteVec.Assign(const Src :TOwnByteVec);
begin
TWasm.byte_vec_copy(@self, Src.Unwrap);
end;
function TWasmByteVec.LoadFromFile(fname: string): Boolean;
begin
var stream := TRc.Wrap(TFileStream.Create(fname, fmOpenRead));
var file_size := (+stream).Size;
var binary := TWasmByteVec.NewUninitialized(file_size);
if (+stream).ReadData(binary.Unwrap.data, file_size) <> file_size then
begin
exit(false);
end;
Assign(binary);
result := true;
end;
function TWasmByteVec.AsUTF8String: UTF8String;
begin
var buf := TArray<Byte>.Create();
SetLength(buf, size+1);
Move(data^, buf[0], size);
result := UTF8String(PAnsiChar(@buf[0]));
end;
function TWasmByteVec.AsString: string;
begin
var buf := TArray<Byte>.Create();
SetLength(buf, size+1);
Move(data^, buf[0], size);
result := string(PAnsiChar(@buf[0]));
end;
class function TWasmByteVec.NewFromString(s : UTF8String): TOwnName;
begin
var ret : PWasmByteVec;
System.New(ret);
TWasm.byte_vec_new(ret, Length(s), @s[1]);
result.FStrongRef := TRcContainer<PWasmByteVec>.Create(ret, byte_vec_disposer); // ref ++
end;
class function TWasmByteVec.NewFromStringNt(s : UTF8String): TOwnName;
begin
var ret : PWasmByteVec;
System.New(ret);
TWasm.byte_vec_new(ret, Length(s)+1, @s[1]);
result.FStrongRef := TRcContainer<PWasmByteVec>.Create(ret, byte_vec_disposer); // ref ++
end;
class function TWasmByteVec.NewFromStringNt(s : string): TOwnName;
begin
var ret : PWasmByteVec;
System.New(ret);
var s8 := UTF8String(s);
TWasm.byte_vec_new(ret, Length(s8)+1, @s8[1]);
result.FStrongRef := TRcContainer<PWasmByteVec>.Create(ret, byte_vec_disposer); // ref ++
end;
class function TWasmByteVec.NewFromString(s : string): TOwnName;
begin
var ret : PWasmByteVec;
System.New(ret);
var s8 := UTF8String(s);
TWasm.byte_vec_new(ret, Length(s8), @s8[1]);
result.FStrongRef := TRcContainer<PWasmByteVec>.Create(ret, byte_vec_disposer); // ref ++
end;
{ TOwnConfig }
class function TOwnConfig.Wrap(p: PWasmConfig; deleter : TRcDeleter): TOwnConfig;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmConfig>.Create(p, deleter);
end;
class function TOwnConfig.Wrap(p: PWasmConfig): TOwnConfig;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmConfig>.Create(p, config_disposer);
end;
class operator TOwnConfig.Finalize(var Dest: TOwnConfig);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnConfig.Implicit(const Src: IRcContainer<PWasmConfig>): TOwnConfig;
begin
result.FStrongRef := Src;
end;
class operator TOwnConfig.Negative(Src: TOwnConfig): IRcContainer<PWasmConfig>;
begin
result := Src.FStrongRef;
end;
class operator TOwnConfig.Positive(Src: TOwnConfig): PWasmConfig;
begin
result := Src.Unwrap;
end;
function TOwnConfig.Unwrap: PWasmConfig;
begin
result := FStrongRef.Unwrap;
end;
function TOwnConfig.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmConfig }
class function TWasmConfig.New() : TOwnConfig;
begin
var p := TWasm.config_new();
result := TOwnConfig.Wrap(p, config_disposer); // ref ++
end;
{ TOwnEngine }
class function TOwnEngine.Wrap(p: PWasmEngine; deleter : TRcDeleter): TOwnEngine;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmEngine>.Create(p, deleter);
end;
class function TOwnEngine.Wrap(p: PWasmEngine): TOwnEngine;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmEngine>.Create(p, engine_disposer);
end;
class operator TOwnEngine.Finalize(var Dest: TOwnEngine);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnEngine.Implicit(const Src: IRcContainer<PWasmEngine>): TOwnEngine;
begin
result.FStrongRef := Src;
end;
class operator TOwnEngine.Negative(Src: TOwnEngine): IRcContainer<PWasmEngine>;
begin
result := Src.FStrongRef;
end;
class operator TOwnEngine.Positive(Src: TOwnEngine): PWasmEngine;
begin
result := Src.Unwrap;
end;
function TOwnEngine.Unwrap: PWasmEngine;
begin
result := FStrongRef.Unwrap;
end;
function TOwnEngine.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmEngine }
class function TWasmEngine.New() : TOwnEngine;
begin
var p := TWasm.engine_new();
result := TOwnEngine.Wrap(p, engine_disposer); // ref ++
end;
class function TWasmEngine.NewWithConfig(config : TOwnConfig) : TOwnEngine;
begin
var p := TWasm.engine_new_with_config((-config).Move);
result := TOwnEngine.Wrap(p, engine_disposer); // ref ++
end;
{ TOwnStore }
class function TOwnStore.Wrap(p: PWasmStore; deleter : TRcDeleter): TOwnStore;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmStore>.Create(p, deleter);
end;
class function TOwnStore.Wrap(p: PWasmStore): TOwnStore;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmStore>.Create(p, store_disposer);
end;
class operator TOwnStore.Finalize(var Dest: TOwnStore);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnStore.Implicit(const Src: IRcContainer<PWasmStore>): TOwnStore;
begin
result.FStrongRef := Src;
end;
class operator TOwnStore.Negative(Src: TOwnStore): IRcContainer<PWasmStore>;
begin
result := Src.FStrongRef;
end;
class operator TOwnStore.Positive(Src: TOwnStore): PWasmStore;
begin
result := Src.Unwrap;
end;
function TOwnStore.Unwrap: PWasmStore;
begin
result := FStrongRef.Unwrap;
end;
function TOwnStore.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmStore }
class function TWasmStore.New(engine : PWasmEngine) : TOwnStore;
begin
var p := TWasm.store_new(engine);
result := TOwnStore.Wrap(p, store_disposer); // ref ++
end;
{ TOwnValtypeVec }
class function TOwnValtypeVec.Wrap(p: PWasmValtypeVec; deleter : TRcDeleter): TOwnValtypeVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmValtypeVec>.Create(p, deleter);
end;
class function TOwnValtypeVec.Wrap(p: PWasmValtypeVec): TOwnValtypeVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmValtypeVec>.Create(p, valtype_vec_disposer);
end;
class operator TOwnValtypeVec.Finalize(var Dest: TOwnValtypeVec);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnValtypeVec.Implicit(const Src: IRcContainer<PWasmValtypeVec>): TOwnValtypeVec;
begin
result.FStrongRef := Src;
end;
class operator TOwnValtypeVec.Negative(Src: TOwnValtypeVec): IRcContainer<PWasmValtypeVec>;
begin
result := Src.FStrongRef;
end;
class operator TOwnValtypeVec.Positive(Src: TOwnValtypeVec): PWasmValtypeVec;
begin
result := Src.Unwrap;
end;
function TOwnValtypeVec.Unwrap: PWasmValtypeVec;
begin
result := FStrongRef.Unwrap;
end;
function TOwnValtypeVec.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmValtypeVec }
constructor TWasmValtypeVec.Create(const arry: array of PWasmValtype);
begin
size := Length(arry);
if size = 0 then data := nil
else data := @arry[0];
end;
class function TWasmValtypeVec.New(const init: array of PWasmValtype; elem_release : Boolean): TOwnValtypeVec;
var
prec : PWasmValtypeVec;
begin
System.New(prec);
TWasm.valtype_vec_new(prec, Length(init), @init[0]);
if elem_release then
result.FStrongRef := TRcContainer<PWasmValtypeVec>.Create(prec, valtype_vec_disposer_host)
else
result.FStrongRef := TRcContainer<PWasmValtypeVec>.Create(prec, valtype_vec_disposer_host_only);
end;
class function TWasmValtypeVec.NewEmpty: TOwnValtypeVec;
var
prec : PWasmValtypeVec;
begin
System.New(prec);
TWasm.valtype_vec_new_empty(prec);
result.FStrongRef := TRcContainer<PWasmValtypeVec>.Create(prec, valtype_vec_disposer_host);
end;
class function TWasmValtypeVec.NewUninitialized(size: NativeInt): TOwnValtypeVec;
var
prec : PWasmValtypeVec;
begin
System.New(prec);
TWasm.valtype_vec_new_uninitialized(prec, size);
result.FStrongRef := TRcContainer<PWasmValtypeVec>.Create(prec, valtype_vec_disposer_host);
end;
class function TWasmValtypeVec.New(const arry: array of TWasmValkind): TOwnValtypeVec;
begin
var pw : TArray<PWasmValType>;
SetLength(pw, Length(arry));
for var i := 0 to Length(arry)-1 do
begin
var v := TWasmValtype.New(arry[i]);
pw[i] := v.FStrongRef.Move;
end;
result := TWasmValtypeVec.New(pw, true);
end;
class function TWasmValtypeVec.New(const init : array of TOwnValtype) : TOwnValtypeVec;
begin
var pw : TArray<PWasmValType>;
SetLength(pw, Length(init));
for var i := 0 to Length(init)-1 do
begin
pw[i] := init[i].FStrongRef.Move;
end;
result := New(pw, true);
end;
function TWasmValtypeVec.Copy: TOwnValtypeVec;
var
prec : PWasmValtypeVec;
begin
System.New(prec);
TWasm.valtype_vec_copy(prec, @self);
result.FStrongRef := TRcContainer<PWasmValtypeVec>.Create(prec, valtype_vec_disposer_host);
end;
procedure TWasmValtypeVec.Assign(const Src :TOwnValtypeVec);
begin
TWasm.valtype_vec_copy(@self, Src.Unwrap);
end;
{ TOwnValtype }
class function TOwnValtype.Wrap(p: PWasmValtype; deleter : TRcDeleter): TOwnValtype;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmValtype>.Create(p, deleter);
end;
class function TOwnValtype.Wrap(p: PWasmValtype): TOwnValtype;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmValtype>.Create(p, valtype_disposer);
end;
class operator TOwnValtype.Finalize(var Dest: TOwnValtype);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnValtype.Implicit(const Src: IRcContainer<PWasmValtype>): TOwnValtype;
begin
result.FStrongRef := Src;
end;
class operator TOwnValtype.Negative(Src: TOwnValtype): IRcContainer<PWasmValtype>;
begin
result := Src.FStrongRef;
end;
class operator TOwnValtype.Positive(Src: TOwnValtype): PWasmValtype;
begin
result := Src.Unwrap;
end;
function TOwnValtype.Unwrap: PWasmValtype;
begin
result := FStrongRef.Unwrap;
end;
function TOwnValtype.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmValtype }
function TWasmValtype.Copy: TOwnValtype;
begin
var p := TWasm.valtype_copy(@self);
result.FStrongRef := TRcContainer<PWasmValtype>.Create(p, valtype_disposer);
end;
class function TWasmValtype.New(valkind : TWasmValkind) : TOwnValtype;
begin
var p := TWasm.valtype_new(valkind);
result := TOwnValtype.Wrap(p, valtype_disposer); // ref ++
end;
function TWasmValtype.Kind() : TWasmValkind;
begin
result := TWasm.valtype_kind(@self);
end;
{ TOwnFunctypeVec }
class function TOwnFunctypeVec.Wrap(p: PWasmFunctypeVec; deleter : TRcDeleter): TOwnFunctypeVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmFunctypeVec>.Create(p, deleter);
end;
class function TOwnFunctypeVec.Wrap(p: PWasmFunctypeVec): TOwnFunctypeVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmFunctypeVec>.Create(p, functype_vec_disposer);
end;
class operator TOwnFunctypeVec.Finalize(var Dest: TOwnFunctypeVec);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnFunctypeVec.Implicit(const Src: IRcContainer<PWasmFunctypeVec>): TOwnFunctypeVec;
begin
result.FStrongRef := Src;
end;
class operator TOwnFunctypeVec.Negative(Src: TOwnFunctypeVec): IRcContainer<PWasmFunctypeVec>;
begin
result := Src.FStrongRef;
end;
class operator TOwnFunctypeVec.Positive(Src: TOwnFunctypeVec): PWasmFunctypeVec;
begin
result := Src.Unwrap;
end;
function TOwnFunctypeVec.Unwrap: PWasmFunctypeVec;
begin
result := FStrongRef.Unwrap;
end;
function TOwnFunctypeVec.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmFunctypeVec }
constructor TWasmFunctypeVec.Create(const arry: array of PWasmFunctype);
begin
size := Length(arry);
if size = 0 then data := nil
else data := @arry[0];
end;
class function TWasmFunctypeVec.New(const init: array of PWasmFunctype; elem_release : Boolean): TOwnFunctypeVec;
var
prec : PWasmFunctypeVec;
begin
System.New(prec);
TWasm.functype_vec_new(prec, Length(init), @init[0]);
if elem_release then
result.FStrongRef := TRcContainer<PWasmFunctypeVec>.Create(prec, functype_vec_disposer_host)
else
result.FStrongRef := TRcContainer<PWasmFunctypeVec>.Create(prec, functype_vec_disposer_host_only);
end;
class function TWasmFunctypeVec.NewEmpty: TOwnFunctypeVec;
var
prec : PWasmFunctypeVec;
begin
System.New(prec);
TWasm.functype_vec_new_empty(prec);
result.FStrongRef := TRcContainer<PWasmFunctypeVec>.Create(prec, functype_vec_disposer_host);
end;
class function TWasmFunctypeVec.NewUninitialized(size: NativeInt): TOwnFunctypeVec;
var
prec : PWasmFunctypeVec;
begin
System.New(prec);
TWasm.functype_vec_new_uninitialized(prec, size);
result.FStrongRef := TRcContainer<PWasmFunctypeVec>.Create(prec, functype_vec_disposer_host);
end;
function TWasmFunctypeVec.Copy: TOwnFunctypeVec;
var
prec : PWasmFunctypeVec;
begin
System.New(prec);
TWasm.functype_vec_copy(prec, @self);
result.FStrongRef := TRcContainer<PWasmFunctypeVec>.Create(prec, functype_vec_disposer_host);
end;
procedure TWasmFunctypeVec.Assign(const Src :TOwnFunctypeVec);
begin
TWasm.functype_vec_copy(@self, Src.Unwrap);
end;
{ TOwnFunctype }
class function TOwnFunctype.Wrap(p: PWasmFunctype; deleter : TRcDeleter): TOwnFunctype;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmFunctype>.Create(p, deleter);
end;
class function TOwnFunctype.Wrap(p: PWasmFunctype): TOwnFunctype;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmFunctype>.Create(p, functype_disposer);
end;
class operator TOwnFunctype.Finalize(var Dest: TOwnFunctype);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnFunctype.Implicit(const Src: IRcContainer<PWasmFunctype>): TOwnFunctype;
begin
result.FStrongRef := Src;
end;
class operator TOwnFunctype.Negative(Src: TOwnFunctype): IRcContainer<PWasmFunctype>;
begin
result := Src.FStrongRef;
end;
class operator TOwnFunctype.Positive(Src: TOwnFunctype): PWasmFunctype;
begin
result := Src.Unwrap;
end;
function TOwnFunctype.Unwrap: PWasmFunctype;
begin
result := FStrongRef.Unwrap;
end;
function TOwnFunctype.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmFunctype }
function TWasmFunctype.Copy: TOwnFunctype;
begin
var p := TWasm.functype_copy(@self);
result.FStrongRef := TRcContainer<PWasmFunctype>.Create(p, functype_disposer);
end;
class function TWasmFuncType.New(const p, r: array of TWasmValkind): TOwnFunctype;
begin
var pa := TWasmValtypeVec.New(p);
var ra := TWasmValtypeVec.New(r);
var func := TWasm.functype_new(pa.Unwrap, ra.Unwrap);
if func <> nil then
begin
result.FStrongRef := TRcContainer<PWasmFunctype>.Create(func, functype_disposer);
end else result.FStrongRef := nil;
end;
class function TWasmFuncType.New(const p, r: array of TOwnValtype): TOwnFunctype;
begin
var pa := TWasmValtypeVec.New(p);
var ra := TWasmValtypeVec.New(r);
var func := TWasm.functype_new(pa.Unwrap, ra.Unwrap);
if func <> nil then result.FStrongRef := TRcContainer<PWasmFunctype>.Create(func, functype_disposer)
else result.FStrongRef := nil;
end;
class function TWasmFunctype.New(params : TOwnValtypeVec; results : TOwnValtypeVec) : TOwnFunctype;
begin
var p := TWasm.functype_new((-params).Move, (-results).Move);
result := TOwnFunctype.Wrap(p, functype_disposer); // ref ++
end;
function TWasmFunctype.Params() : PWasmValtypeVec;
begin
result := TWasm.functype_params(@self);
end;
function TWasmFunctype.Results() : PWasmValtypeVec;
begin
result := TWasm.functype_results(@self);
end;
function TWasmFunctype.AsExterntype() : PWasmExterntype;
begin
result := TWasm.functype_as_externtype(@self);
end;
function TWasmFunctype.AsExterntypeConst() : PWasmExterntype;
begin
result := TWasm.functype_as_externtype_const(@self);
end;
{ TOwnGlobaltypeVec }
class function TOwnGlobaltypeVec.Wrap(p: PWasmGlobaltypeVec; deleter : TRcDeleter): TOwnGlobaltypeVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmGlobaltypeVec>.Create(p, deleter);
end;
class function TOwnGlobaltypeVec.Wrap(p: PWasmGlobaltypeVec): TOwnGlobaltypeVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmGlobaltypeVec>.Create(p, globaltype_vec_disposer);
end;
class operator TOwnGlobaltypeVec.Finalize(var Dest: TOwnGlobaltypeVec);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnGlobaltypeVec.Implicit(const Src: IRcContainer<PWasmGlobaltypeVec>): TOwnGlobaltypeVec;
begin
result.FStrongRef := Src;
end;
class operator TOwnGlobaltypeVec.Negative(Src: TOwnGlobaltypeVec): IRcContainer<PWasmGlobaltypeVec>;
begin
result := Src.FStrongRef;
end;
class operator TOwnGlobaltypeVec.Positive(Src: TOwnGlobaltypeVec): PWasmGlobaltypeVec;
begin
result := Src.Unwrap;
end;
function TOwnGlobaltypeVec.Unwrap: PWasmGlobaltypeVec;
begin
result := FStrongRef.Unwrap;
end;
function TOwnGlobaltypeVec.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmGlobaltypeVec }
constructor TWasmGlobaltypeVec.Create(const arry: array of PWasmGlobaltype);
begin
size := Length(arry);
if size = 0 then data := nil
else data := @arry[0];
end;
class function TWasmGlobaltypeVec.New(const init: array of PWasmGlobaltype; elem_release : Boolean): TOwnGlobaltypeVec;
var
prec : PWasmGlobaltypeVec;
begin
System.New(prec);
TWasm.globaltype_vec_new(prec, Length(init), @init[0]);
if elem_release then
result.FStrongRef := TRcContainer<PWasmGlobaltypeVec>.Create(prec, globaltype_vec_disposer_host)
else
result.FStrongRef := TRcContainer<PWasmGlobaltypeVec>.Create(prec, globaltype_vec_disposer_host_only);
end;
class function TWasmGlobaltypeVec.NewEmpty: TOwnGlobaltypeVec;
var
prec : PWasmGlobaltypeVec;
begin
System.New(prec);
TWasm.globaltype_vec_new_empty(prec);
result.FStrongRef := TRcContainer<PWasmGlobaltypeVec>.Create(prec, globaltype_vec_disposer_host);
end;
class function TWasmGlobaltypeVec.NewUninitialized(size: NativeInt): TOwnGlobaltypeVec;
var
prec : PWasmGlobaltypeVec;
begin
System.New(prec);
TWasm.globaltype_vec_new_uninitialized(prec, size);
result.FStrongRef := TRcContainer<PWasmGlobaltypeVec>.Create(prec, globaltype_vec_disposer_host);
end;
function TWasmGlobaltypeVec.Copy: TOwnGlobaltypeVec;
var
prec : PWasmGlobaltypeVec;
begin
System.New(prec);
TWasm.globaltype_vec_copy(prec, @self);
result.FStrongRef := TRcContainer<PWasmGlobaltypeVec>.Create(prec, globaltype_vec_disposer_host);
end;
procedure TWasmGlobaltypeVec.Assign(const Src :TOwnGlobaltypeVec);
begin
TWasm.globaltype_vec_copy(@self, Src.Unwrap);
end;
{ TOwnGlobaltype }
class function TOwnGlobaltype.Wrap(p: PWasmGlobaltype; deleter : TRcDeleter): TOwnGlobaltype;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmGlobaltype>.Create(p, deleter);
end;
class function TOwnGlobaltype.Wrap(p: PWasmGlobaltype): TOwnGlobaltype;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmGlobaltype>.Create(p, globaltype_disposer);
end;
class operator TOwnGlobaltype.Finalize(var Dest: TOwnGlobaltype);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnGlobaltype.Implicit(const Src: IRcContainer<PWasmGlobaltype>): TOwnGlobaltype;
begin
result.FStrongRef := Src;
end;
class operator TOwnGlobaltype.Negative(Src: TOwnGlobaltype): IRcContainer<PWasmGlobaltype>;
begin
result := Src.FStrongRef;
end;
class operator TOwnGlobaltype.Positive(Src: TOwnGlobaltype): PWasmGlobaltype;
begin
result := Src.Unwrap;
end;
function TOwnGlobaltype.Unwrap: PWasmGlobaltype;
begin
result := FStrongRef.Unwrap;
end;
function TOwnGlobaltype.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmGlobaltype }
function TWasmGlobaltype.Copy: TOwnGlobaltype;
begin
var p := TWasm.globaltype_copy(@self);
result.FStrongRef := TRcContainer<PWasmGlobaltype>.Create(p, globaltype_disposer);
end;
class function TWasmGlobaltype.New(valkind : TWasmValKind; mutability : TWasmMutability) : TOwnGlobaltype;
begin
var valtype := TWasmValtype.New(valkind);
var p := TWasm.globaltype_new((-valtype).Move, mutability);
result := TOwnGlobaltype.Wrap(p, globaltype_disposer); // ref ++
end;
class function TWasmGlobaltype.New(valtype : TOwnValtype; mutability : TWasmMutability) : TOwnGlobaltype;
begin
var p := TWasm.globaltype_new((-valtype).Move, mutability);
result := TOwnGlobaltype.Wrap(p, globaltype_disposer); // ref ++
end;
function TWasmGlobaltype.Content() : PWasmValtype;
begin
result := TWasm.globaltype_content(@self);
end;
function TWasmGlobaltype.Mutability() : TWasmMutability;
begin
result := TWasm.globaltype_mutability(@self);
end;
function TWasmGlobaltype.AsExterntype() : PWasmExterntype;
begin
result := TWasm.globaltype_as_externtype(@self);
end;
function TWasmGlobaltype.AsExterntypeConst() : PWasmExterntype;
begin
result := TWasm.globaltype_as_externtype_const(@self);
end;
{ TOwnTabletypeVec }
class function TOwnTabletypeVec.Wrap(p: PWasmTabletypeVec; deleter : TRcDeleter): TOwnTabletypeVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmTabletypeVec>.Create(p, deleter);
end;
class function TOwnTabletypeVec.Wrap(p: PWasmTabletypeVec): TOwnTabletypeVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmTabletypeVec>.Create(p, tabletype_vec_disposer);
end;
class operator TOwnTabletypeVec.Finalize(var Dest: TOwnTabletypeVec);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnTabletypeVec.Implicit(const Src: IRcContainer<PWasmTabletypeVec>): TOwnTabletypeVec;
begin
result.FStrongRef := Src;
end;
class operator TOwnTabletypeVec.Negative(Src: TOwnTabletypeVec): IRcContainer<PWasmTabletypeVec>;
begin
result := Src.FStrongRef;
end;
class operator TOwnTabletypeVec.Positive(Src: TOwnTabletypeVec): PWasmTabletypeVec;
begin
result := Src.Unwrap;
end;
function TOwnTabletypeVec.Unwrap: PWasmTabletypeVec;
begin
result := FStrongRef.Unwrap;
end;
function TOwnTabletypeVec.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmTabletypeVec }
constructor TWasmTabletypeVec.Create(const arry: array of PWasmTabletype);
begin
size := Length(arry);
if size = 0 then data := nil
else data := @arry[0];
end;
class function TWasmTabletypeVec.New(const init: array of PWasmTabletype; elem_release : Boolean): TOwnTabletypeVec;
var
prec : PWasmTabletypeVec;
begin
System.New(prec);
TWasm.tabletype_vec_new(prec, Length(init), @init[0]);
if elem_release then
result.FStrongRef := TRcContainer<PWasmTabletypeVec>.Create(prec, tabletype_vec_disposer_host)
else
result.FStrongRef := TRcContainer<PWasmTabletypeVec>.Create(prec, tabletype_vec_disposer_host_only);
end;
class function TWasmTabletypeVec.NewEmpty: TOwnTabletypeVec;
var
prec : PWasmTabletypeVec;
begin
System.New(prec);
TWasm.tabletype_vec_new_empty(prec);
result.FStrongRef := TRcContainer<PWasmTabletypeVec>.Create(prec, tabletype_vec_disposer_host);
end;
class function TWasmTabletypeVec.NewUninitialized(size: NativeInt): TOwnTabletypeVec;
var
prec : PWasmTabletypeVec;
begin
System.New(prec);
TWasm.tabletype_vec_new_uninitialized(prec, size);
result.FStrongRef := TRcContainer<PWasmTabletypeVec>.Create(prec, tabletype_vec_disposer_host);
end;
function TWasmTabletypeVec.Copy: TOwnTabletypeVec;
var
prec : PWasmTabletypeVec;
begin
System.New(prec);
TWasm.tabletype_vec_copy(prec, @self);
result.FStrongRef := TRcContainer<PWasmTabletypeVec>.Create(prec, tabletype_vec_disposer_host);
end;
procedure TWasmTabletypeVec.Assign(const Src :TOwnTabletypeVec);
begin
TWasm.tabletype_vec_copy(@self, Src.Unwrap);
end;
{ TOwnTabletype }
class function TOwnTabletype.Wrap(p: PWasmTabletype; deleter : TRcDeleter): TOwnTabletype;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmTabletype>.Create(p, deleter);
end;
class function TOwnTabletype.Wrap(p: PWasmTabletype): TOwnTabletype;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmTabletype>.Create(p, tabletype_disposer);
end;
class operator TOwnTabletype.Finalize(var Dest: TOwnTabletype);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnTabletype.Implicit(const Src: IRcContainer<PWasmTabletype>): TOwnTabletype;
begin
result.FStrongRef := Src;
end;
class operator TOwnTabletype.Negative(Src: TOwnTabletype): IRcContainer<PWasmTabletype>;
begin
result := Src.FStrongRef;
end;
class operator TOwnTabletype.Positive(Src: TOwnTabletype): PWasmTabletype;
begin
result := Src.Unwrap;
end;
function TOwnTabletype.Unwrap: PWasmTabletype;
begin
result := FStrongRef.Unwrap;
end;
function TOwnTabletype.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmTabletype }
function TWasmTabletype.Copy: TOwnTabletype;
begin
var p := TWasm.tabletype_copy(@self);
result.FStrongRef := TRcContainer<PWasmTabletype>.Create(p, tabletype_disposer);
end;
class function TWasmTabletype.New(valtype : TOwnValtype; const limits : PWasmLimits) : TOwnTabletype;
begin
var p := TWasm.tabletype_new((-valtype).Move, limits);
result := TOwnTabletype.Wrap(p, tabletype_disposer); // ref ++
end;
function TWasmTabletype.Element() : PWasmValtype;
begin
result := TWasm.tabletype_element(@self);
end;
function TWasmTabletype.Limits() : PWasmLimits;
begin
result := TWasm.tabletype_limits(@self);
end;
function TWasmTabletype.AsExterntype() : PWasmExterntype;
begin
result := TWasm.tabletype_as_externtype(@self);
end;
function TWasmTabletype.AsExterntypeConst() : PWasmExterntype;
begin
result := TWasm.tabletype_as_externtype_const(@self);
end;
{ TOwnMemorytypeVec }
class function TOwnMemorytypeVec.Wrap(p: PWasmMemorytypeVec; deleter : TRcDeleter): TOwnMemorytypeVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmMemorytypeVec>.Create(p, deleter);
end;
class function TOwnMemorytypeVec.Wrap(p: PWasmMemorytypeVec): TOwnMemorytypeVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmMemorytypeVec>.Create(p, memorytype_vec_disposer);
end;
class operator TOwnMemorytypeVec.Finalize(var Dest: TOwnMemorytypeVec);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnMemorytypeVec.Implicit(const Src: IRcContainer<PWasmMemorytypeVec>): TOwnMemorytypeVec;
begin
result.FStrongRef := Src;
end;
class operator TOwnMemorytypeVec.Negative(Src: TOwnMemorytypeVec): IRcContainer<PWasmMemorytypeVec>;
begin
result := Src.FStrongRef;
end;
class operator TOwnMemorytypeVec.Positive(Src: TOwnMemorytypeVec): PWasmMemorytypeVec;
begin
result := Src.Unwrap;
end;
function TOwnMemorytypeVec.Unwrap: PWasmMemorytypeVec;
begin
result := FStrongRef.Unwrap;
end;
function TOwnMemorytypeVec.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmMemorytypeVec }
constructor TWasmMemorytypeVec.Create(const arry: array of PWasmMemorytype);
begin
size := Length(arry);
if size = 0 then data := nil
else data := @arry[0];
end;
class function TWasmMemorytypeVec.New(const init: array of PWasmMemorytype; elem_release : Boolean): TOwnMemorytypeVec;
var
prec : PWasmMemorytypeVec;
begin
System.New(prec);
TWasm.memorytype_vec_new(prec, Length(init), @init[0]);
if elem_release then
result.FStrongRef := TRcContainer<PWasmMemorytypeVec>.Create(prec, memorytype_vec_disposer_host)
else
result.FStrongRef := TRcContainer<PWasmMemorytypeVec>.Create(prec, memorytype_vec_disposer_host_only);
end;
class function TWasmMemorytypeVec.NewEmpty: TOwnMemorytypeVec;
var
prec : PWasmMemorytypeVec;
begin
System.New(prec);
TWasm.memorytype_vec_new_empty(prec);
result.FStrongRef := TRcContainer<PWasmMemorytypeVec>.Create(prec, memorytype_vec_disposer_host);
end;
class function TWasmMemorytypeVec.NewUninitialized(size: NativeInt): TOwnMemorytypeVec;
var
prec : PWasmMemorytypeVec;
begin
System.New(prec);
TWasm.memorytype_vec_new_uninitialized(prec, size);
result.FStrongRef := TRcContainer<PWasmMemorytypeVec>.Create(prec, memorytype_vec_disposer_host);
end;
function TWasmMemorytypeVec.Copy: TOwnMemorytypeVec;
var
prec : PWasmMemorytypeVec;
begin
System.New(prec);
TWasm.memorytype_vec_copy(prec, @self);
result.FStrongRef := TRcContainer<PWasmMemorytypeVec>.Create(prec, memorytype_vec_disposer_host);
end;
procedure TWasmMemorytypeVec.Assign(const Src :TOwnMemorytypeVec);
begin
TWasm.memorytype_vec_copy(@self, Src.Unwrap);
end;
{ TOwnMemorytype }
class function TOwnMemorytype.Wrap(p: PWasmMemorytype; deleter : TRcDeleter): TOwnMemorytype;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmMemorytype>.Create(p, deleter);
end;
class function TOwnMemorytype.Wrap(p: PWasmMemorytype): TOwnMemorytype;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmMemorytype>.Create(p, memorytype_disposer);
end;
class operator TOwnMemorytype.Finalize(var Dest: TOwnMemorytype);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnMemorytype.Implicit(const Src: IRcContainer<PWasmMemorytype>): TOwnMemorytype;
begin
result.FStrongRef := Src;
end;
class operator TOwnMemorytype.Negative(Src: TOwnMemorytype): IRcContainer<PWasmMemorytype>;
begin
result := Src.FStrongRef;
end;
class operator TOwnMemorytype.Positive(Src: TOwnMemorytype): PWasmMemorytype;
begin
result := Src.Unwrap;
end;
function TOwnMemorytype.Unwrap: PWasmMemorytype;
begin
result := FStrongRef.Unwrap;
end;
function TOwnMemorytype.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmMemorytype }
function TWasmMemorytype.Copy: TOwnMemorytype;
begin
var p := TWasm.memorytype_copy(@self);
result.FStrongRef := TRcContainer<PWasmMemorytype>.Create(p, memorytype_disposer);
end;
class function TWasmMemorytype.New( const limits : PWasmLimits) : TOwnMemorytype;
begin
var p := TWasm.memorytype_new(limits);
result := TOwnMemorytype.Wrap(p, memorytype_disposer); // ref ++
end;
function TWasmMemorytype.Limits() : PWasmLimits;
begin
result := TWasm.memorytype_limits(@self);
end;
function TWasmMemorytype.AsExterntype() : PWasmExterntype;
begin
result := TWasm.memorytype_as_externtype(@self);
end;
function TWasmMemorytype.AsExterntypeConst() : PWasmExterntype;
begin
result := TWasm.memorytype_as_externtype_const(@self);
end;
{ TOwnExterntypeVec }
class function TOwnExterntypeVec.Wrap(p: PWasmExterntypeVec; deleter : TRcDeleter): TOwnExterntypeVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmExterntypeVec>.Create(p, deleter);
end;
class function TOwnExterntypeVec.Wrap(p: PWasmExterntypeVec): TOwnExterntypeVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmExterntypeVec>.Create(p, externtype_vec_disposer);
end;
class operator TOwnExterntypeVec.Finalize(var Dest: TOwnExterntypeVec);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnExterntypeVec.Implicit(const Src: IRcContainer<PWasmExterntypeVec>): TOwnExterntypeVec;
begin
result.FStrongRef := Src;
end;
class operator TOwnExterntypeVec.Negative(Src: TOwnExterntypeVec): IRcContainer<PWasmExterntypeVec>;
begin
result := Src.FStrongRef;
end;
class operator TOwnExterntypeVec.Positive(Src: TOwnExterntypeVec): PWasmExterntypeVec;
begin
result := Src.Unwrap;
end;
function TOwnExterntypeVec.Unwrap: PWasmExterntypeVec;
begin
result := FStrongRef.Unwrap;
end;
function TOwnExterntypeVec.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmExterntypeVec }
constructor TWasmExterntypeVec.Create(const arry: array of PWasmExterntype);
begin
size := Length(arry);
if size = 0 then data := nil
else data := @arry[0];
end;
class function TWasmExterntypeVec.New(const init: array of PWasmExterntype; elem_release : Boolean): TOwnExterntypeVec;
var
prec : PWasmExterntypeVec;
begin
System.New(prec);
TWasm.externtype_vec_new(prec, Length(init), @init[0]);
if elem_release then
result.FStrongRef := TRcContainer<PWasmExterntypeVec>.Create(prec, externtype_vec_disposer_host)
else
result.FStrongRef := TRcContainer<PWasmExterntypeVec>.Create(prec, externtype_vec_disposer_host_only);
end;
class function TWasmExterntypeVec.NewEmpty: TOwnExterntypeVec;
var
prec : PWasmExterntypeVec;
begin
System.New(prec);
TWasm.externtype_vec_new_empty(prec);
result.FStrongRef := TRcContainer<PWasmExterntypeVec>.Create(prec, externtype_vec_disposer_host);
end;
class function TWasmExterntypeVec.NewUninitialized(size: NativeInt): TOwnExterntypeVec;
var
prec : PWasmExterntypeVec;
begin
System.New(prec);
TWasm.externtype_vec_new_uninitialized(prec, size);
result.FStrongRef := TRcContainer<PWasmExterntypeVec>.Create(prec, externtype_vec_disposer_host);
end;
function TWasmExterntypeVec.Copy: TOwnExterntypeVec;
var
prec : PWasmExterntypeVec;
begin
System.New(prec);
TWasm.externtype_vec_copy(prec, @self);
result.FStrongRef := TRcContainer<PWasmExterntypeVec>.Create(prec, externtype_vec_disposer_host);
end;
procedure TWasmExterntypeVec.Assign(const Src :TOwnExterntypeVec);
begin
TWasm.externtype_vec_copy(@self, Src.Unwrap);
end;
{ TOwnExterntype }
class function TOwnExterntype.Wrap(p: PWasmExterntype; deleter : TRcDeleter): TOwnExterntype;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmExterntype>.Create(p, deleter);
end;
class function TOwnExterntype.Wrap(p: PWasmExterntype): TOwnExterntype;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmExterntype>.Create(p, externtype_disposer);
end;
class operator TOwnExterntype.Finalize(var Dest: TOwnExterntype);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnExterntype.Implicit(const Src: IRcContainer<PWasmExterntype>): TOwnExterntype;
begin
result.FStrongRef := Src;
end;
class operator TOwnExterntype.Negative(Src: TOwnExterntype): IRcContainer<PWasmExterntype>;
begin
result := Src.FStrongRef;
end;
class operator TOwnExterntype.Positive(Src: TOwnExterntype): PWasmExterntype;
begin
result := Src.Unwrap;
end;
function TOwnExterntype.Unwrap: PWasmExterntype;
begin
result := FStrongRef.Unwrap;
end;
function TOwnExterntype.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmExterntype }
function TWasmExterntype.Copy: TOwnExterntype;
begin
var p := TWasm.externtype_copy(@self);
result.FStrongRef := TRcContainer<PWasmExterntype>.Create(p, externtype_disposer);
end;
function TWasmExterntype.Kind() : TWasmExternkind;
begin
result := TWasm.externtype_kind(@self);
end;
function TWasmExterntype.AsFunctype() : PWasmFunctype;
begin
result := TWasm.externtype_as_functype(@self);
end;
function TWasmExterntype.AsGlobaltype() : PWasmGlobaltype;
begin
result := TWasm.externtype_as_globaltype(@self);
end;
function TWasmExterntype.AsTabletype() : PWasmTabletype;
begin
result := TWasm.externtype_as_tabletype(@self);
end;
function TWasmExterntype.AsMemorytype() : PWasmMemorytype;
begin
result := TWasm.externtype_as_memorytype(@self);
end;
function TWasmExterntype.AsFunctypeConst() : PWasmFunctype;
begin
result := TWasm.externtype_as_functype_const(@self);
end;
function TWasmExterntype.AsGlobaltypeConst() : PWasmGlobaltype;
begin
result := TWasm.externtype_as_globaltype_const(@self);
end;
function TWasmExterntype.AsTabletypeConst() : PWasmTabletype;
begin
result := TWasm.externtype_as_tabletype_const(@self);
end;
function TWasmExterntype.AsMemorytypeConst() : PWasmMemorytype;
begin
result := TWasm.externtype_as_memorytype_const(@self);
end;
{ TOwnImporttypeVec }
class function TOwnImporttypeVec.Wrap(p: PWasmImporttypeVec; deleter : TRcDeleter): TOwnImporttypeVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmImporttypeVec>.Create(p, deleter);
end;
class function TOwnImporttypeVec.Wrap(p: PWasmImporttypeVec): TOwnImporttypeVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmImporttypeVec>.Create(p, importtype_vec_disposer);
end;
class operator TOwnImporttypeVec.Finalize(var Dest: TOwnImporttypeVec);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnImporttypeVec.Implicit(const Src: IRcContainer<PWasmImporttypeVec>): TOwnImporttypeVec;
begin
result.FStrongRef := Src;
end;
class operator TOwnImporttypeVec.Negative(Src: TOwnImporttypeVec): IRcContainer<PWasmImporttypeVec>;
begin
result := Src.FStrongRef;
end;
class operator TOwnImporttypeVec.Positive(Src: TOwnImporttypeVec): PWasmImporttypeVec;
begin
result := Src.Unwrap;
end;
function TOwnImporttypeVec.Unwrap: PWasmImporttypeVec;
begin
result := FStrongRef.Unwrap;
end;
function TOwnImporttypeVec.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmImporttypeVec }
constructor TWasmImporttypeVec.Create(const arry: array of PWasmImporttype);
begin
size := Length(arry);
if size = 0 then data := nil
else data := @arry[0];
end;
class function TWasmImporttypeVec.New(const init: array of PWasmImporttype; elem_release : Boolean): TOwnImporttypeVec;
var
prec : PWasmImporttypeVec;
begin
System.New(prec);
TWasm.importtype_vec_new(prec, Length(init), @init[0]);
if elem_release then
result.FStrongRef := TRcContainer<PWasmImporttypeVec>.Create(prec, importtype_vec_disposer_host)
else
result.FStrongRef := TRcContainer<PWasmImporttypeVec>.Create(prec, importtype_vec_disposer_host_only);
end;
class function TWasmImporttypeVec.NewEmpty: TOwnImporttypeVec;
var
prec : PWasmImporttypeVec;
begin
System.New(prec);
TWasm.importtype_vec_new_empty(prec);
result.FStrongRef := TRcContainer<PWasmImporttypeVec>.Create(prec, importtype_vec_disposer_host);
end;
class function TWasmImporttypeVec.NewUninitialized(size: NativeInt): TOwnImporttypeVec;
var
prec : PWasmImporttypeVec;
begin
System.New(prec);
TWasm.importtype_vec_new_uninitialized(prec, size);
result.FStrongRef := TRcContainer<PWasmImporttypeVec>.Create(prec, importtype_vec_disposer_host);
end;
function TWasmImporttypeVec.Copy: TOwnImporttypeVec;
var
prec : PWasmImporttypeVec;
begin
System.New(prec);
TWasm.importtype_vec_copy(prec, @self);
result.FStrongRef := TRcContainer<PWasmImporttypeVec>.Create(prec, importtype_vec_disposer_host);
end;
procedure TWasmImporttypeVec.Assign(const Src :TOwnImporttypeVec);
begin
TWasm.importtype_vec_copy(@self, Src.Unwrap);
end;
{ TOwnImporttype }
class function TOwnImporttype.Wrap(p: PWasmImporttype; deleter : TRcDeleter): TOwnImporttype;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmImporttype>.Create(p, deleter);
end;
class function TOwnImporttype.Wrap(p: PWasmImporttype): TOwnImporttype;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmImporttype>.Create(p, importtype_disposer);
end;
class operator TOwnImporttype.Finalize(var Dest: TOwnImporttype);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnImporttype.Implicit(const Src: IRcContainer<PWasmImporttype>): TOwnImporttype;
begin
result.FStrongRef := Src;
end;
class operator TOwnImporttype.Negative(Src: TOwnImporttype): IRcContainer<PWasmImporttype>;
begin
result := Src.FStrongRef;
end;
class operator TOwnImporttype.Positive(Src: TOwnImporttype): PWasmImporttype;
begin
result := Src.Unwrap;
end;
function TOwnImporttype.Unwrap: PWasmImporttype;
begin
result := FStrongRef.Unwrap;
end;
function TOwnImporttype.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmImporttype }
function TWasmImporttype.Copy: TOwnImporttype;
begin
var p := TWasm.importtype_copy(@self);
result.FStrongRef := TRcContainer<PWasmImporttype>.Create(p, importtype_disposer);
end;
class function TWasmImporttype.New(module : string; name : string; externtype : TOwnExterntype) : TOwnImporttype;
begin
var p := TWasm.importtype_new(PWasmName((-TWasmName.NewFromString(module)).Move), PWasmName((-TWasmName.NewFromString(name)).Move), (-externtype).Move);
result := TOwnImporttype.Wrap(p, importtype_disposer); // ref ++
end;
function TWasmImporttype.Module() : string;
begin
var p := TWasm.importtype_module(@self);
result := p.AsString;
end;
function TWasmImporttype.Name() : string;
begin
var p := TWasm.importtype_name(@self);
result := p.AsString;
end;
function TWasmImporttype.GetType() : PWasmExterntype;
begin
result := TWasm.importtype_type(@self);
end;
{ TOwnExporttypeVec }
class function TOwnExporttypeVec.Wrap(p: PWasmExporttypeVec; deleter : TRcDeleter): TOwnExporttypeVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmExporttypeVec>.Create(p, deleter);
end;
class function TOwnExporttypeVec.Wrap(p: PWasmExporttypeVec): TOwnExporttypeVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmExporttypeVec>.Create(p, exporttype_vec_disposer);
end;
class operator TOwnExporttypeVec.Finalize(var Dest: TOwnExporttypeVec);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnExporttypeVec.Implicit(const Src: IRcContainer<PWasmExporttypeVec>): TOwnExporttypeVec;
begin
result.FStrongRef := Src;
end;
class operator TOwnExporttypeVec.Negative(Src: TOwnExporttypeVec): IRcContainer<PWasmExporttypeVec>;
begin
result := Src.FStrongRef;
end;
class operator TOwnExporttypeVec.Positive(Src: TOwnExporttypeVec): PWasmExporttypeVec;
begin
result := Src.Unwrap;
end;
function TOwnExporttypeVec.Unwrap: PWasmExporttypeVec;
begin
result := FStrongRef.Unwrap;
end;
function TOwnExporttypeVec.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmExporttypeVec }
constructor TWasmExporttypeVec.Create(const arry: array of PWasmExporttype);
begin
size := Length(arry);
if size = 0 then data := nil
else data := @arry[0];
end;
class function TWasmExporttypeVec.New(const init: array of PWasmExporttype; elem_release : Boolean): TOwnExporttypeVec;
var
prec : PWasmExporttypeVec;
begin
System.New(prec);
TWasm.exporttype_vec_new(prec, Length(init), @init[0]);
if elem_release then
result.FStrongRef := TRcContainer<PWasmExporttypeVec>.Create(prec, exporttype_vec_disposer_host)
else
result.FStrongRef := TRcContainer<PWasmExporttypeVec>.Create(prec, exporttype_vec_disposer_host_only);
end;
class function TWasmExporttypeVec.NewEmpty: TOwnExporttypeVec;
var
prec : PWasmExporttypeVec;
begin
System.New(prec);
TWasm.exporttype_vec_new_empty(prec);
result.FStrongRef := TRcContainer<PWasmExporttypeVec>.Create(prec, exporttype_vec_disposer_host);
end;
class function TWasmExporttypeVec.NewUninitialized(size: NativeInt): TOwnExporttypeVec;
var
prec : PWasmExporttypeVec;
begin
System.New(prec);
TWasm.exporttype_vec_new_uninitialized(prec, size);
result.FStrongRef := TRcContainer<PWasmExporttypeVec>.Create(prec, exporttype_vec_disposer_host);
end;
function TWasmExporttypeVec.Copy: TOwnExporttypeVec;
var
prec : PWasmExporttypeVec;
begin
System.New(prec);
TWasm.exporttype_vec_copy(prec, @self);
result.FStrongRef := TRcContainer<PWasmExporttypeVec>.Create(prec, exporttype_vec_disposer_host);
end;
procedure TWasmExporttypeVec.Assign(const Src :TOwnExporttypeVec);
begin
TWasm.exporttype_vec_copy(@self, Src.Unwrap);
end;
{ TOwnExporttype }
class function TOwnExporttype.Wrap(p: PWasmExporttype; deleter : TRcDeleter): TOwnExporttype;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmExporttype>.Create(p, deleter);
end;
class function TOwnExporttype.Wrap(p: PWasmExporttype): TOwnExporttype;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmExporttype>.Create(p, exporttype_disposer);
end;
class operator TOwnExporttype.Finalize(var Dest: TOwnExporttype);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnExporttype.Implicit(const Src: IRcContainer<PWasmExporttype>): TOwnExporttype;
begin
result.FStrongRef := Src;
end;
class operator TOwnExporttype.Negative(Src: TOwnExporttype): IRcContainer<PWasmExporttype>;
begin
result := Src.FStrongRef;
end;
class operator TOwnExporttype.Positive(Src: TOwnExporttype): PWasmExporttype;
begin
result := Src.Unwrap;
end;
function TOwnExporttype.Unwrap: PWasmExporttype;
begin
result := FStrongRef.Unwrap;
end;
function TOwnExporttype.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmExporttype }
function TWasmExporttype.Copy: TOwnExporttype;
begin
var p := TWasm.exporttype_copy(@self);
result.FStrongRef := TRcContainer<PWasmExporttype>.Create(p, exporttype_disposer);
end;
class function TWasmExporttype.New(name : string; externtype : TOwnExterntype) : TOwnExporttype;
begin
var p := TWasm.exporttype_new(PWasmName((-TWasmName.NewFromString(name)).Move), (-externtype).Move);
result := TOwnExporttype.Wrap(p, exporttype_disposer); // ref ++
end;
function TWasmExporttype.Name() : string;
begin
var p := TWasm.exporttype_name(@self);
result := p.AsString;
end;
function TWasmExporttype.GetType() : PWasmExterntype;
begin
result := TWasm.exporttype_type(@self);
end;
{ TOwnVal }
class function TOwnVal.Wrap(p: PWasmVal; deleter : TRcDeleter): TOwnVal;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmVal>.Create(p, deleter);
end;
class function TOwnVal.Wrap(p: PWasmVal): TOwnVal;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmVal>.Create(p, val_disposer);
end;
class operator TOwnVal.Finalize(var Dest: TOwnVal);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnVal.Implicit(const Src: IRcContainer<PWasmVal>): TOwnVal;
begin
result.FStrongRef := Src;
end;
class operator TOwnVal.Negative(Src: TOwnVal): IRcContainer<PWasmVal>;
begin
result := Src.FStrongRef;
end;
class operator TOwnVal.Positive(Src: TOwnVal): PWasmVal;
begin
result := Src.Unwrap;
end;
function TOwnVal.Unwrap: PWasmVal;
begin
result := FStrongRef.Unwrap;
end;
function TOwnVal.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmVal }
constructor TWasmVal.Create(val : Integer);
begin
kind := WASM_I32;
i32 := val;
end;
constructor TWasmVal.Create(val : Int64);
begin
kind := WASM_I64;
i64 := val;
end;
constructor TWasmVal.Create(val : Single);
begin
kind := WASM_F32;
f32 := val;
end;
constructor TWasmVal.Create(val : Double);
begin
kind := WASM_F64;
f64 := val;
end;
constructor TWasmVal.Create(val : PWasmRef);
begin
kind := WASM_ANYREF;
ref := val;
end;
class operator TWasmVal.Implicit (val : Integer) : TWasmVal;
begin
result.kind := WASM_I32;
result.i32 := val;
end;
class operator TWasmVal.Implicit (val : Int64) : TWasmVal;
begin
result.kind := WASM_I64;
result.i64 := val;
end;
class operator TWasmVal.Implicit (val : Single) : TWasmVal;
begin
result.kind := WASM_F32;
result.f32 := val;
end;
class operator TWasmVal.Implicit (val : Double) : TWasmVal;
begin
result.kind := WASM_F64;
result.f64 := val;
end;
class operator TWasmVal.Implicit (val : PWasmRef) : TWasmVal;
begin
result.kind := WASM_ANYREF;
result.ref := val;
end;
function WASM_I32_VAL(val : Integer) : TWasmVal;
begin
result.kind := WASM_I32;
result.i32 := val;
end;
function WASM_I64_VAL(val : Int64) : TWasmVal;
begin
result.kind := WASM_I64;
result.i64 := val;
end;
function WASM_F32_VAL(val : Single) : TWasmVal;
begin
result.kind := WASM_F32;
result.f32 := val;
end;
function WASM_F64_VAL(val : Double) : TWasmVal;
begin
result.kind := WASM_F64;
result.f64 := val;
end;
function WASM_REF_VAL(val : PWasmRef) : TWasmVal;
begin
result.kind := WASM_ANYREF;
result.ref := val;
end;
function WASM_INIT_VAL() : TWasmVal;
begin
result.kind := WASM_ANYREF;
result.ref := nil;
end;
{ TOwnValVec }
class function TOwnValVec.Wrap(p: PWasmValVec; deleter : TRcDeleter): TOwnValVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmValVec>.Create(p, deleter);
end;
class function TOwnValVec.Wrap(p: PWasmValVec): TOwnValVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmValVec>.Create(p, val_vec_disposer);
end;
class operator TOwnValVec.Finalize(var Dest: TOwnValVec);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnValVec.Implicit(const Src: IRcContainer<PWasmValVec>): TOwnValVec;
begin
result.FStrongRef := Src;
end;
class operator TOwnValVec.Negative(Src: TOwnValVec): IRcContainer<PWasmValVec>;
begin
result := Src.FStrongRef;
end;
class operator TOwnValVec.Positive(Src: TOwnValVec): PWasmValVec;
begin
result := Src.Unwrap;
end;
function TOwnValVec.Unwrap: PWasmValVec;
begin
result := FStrongRef.Unwrap;
end;
function TOwnValVec.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmValVec }
constructor TWasmValVec.Create(const arry: array of TWasmVal);
begin
size := Length(arry);
if size = 0 then data := nil
else data := @arry[0];
end;
class function TWasmValVec.New(const init: array of TWasmVal): TOwnValVec;
var
prec : PWasmValVec;
begin
System.New(prec);
TWasm.val_vec_new(prec, Length(init), @init[0]);
result.FStrongRef := TRcContainer<PWasmValVec>.Create(prec, val_vec_disposer_host);
end;
class function TWasmValVec.NewEmpty: TOwnValVec;
var
prec : PWasmValVec;
begin
System.New(prec);
TWasm.val_vec_new_empty(prec);
result.FStrongRef := TRcContainer<PWasmValVec>.Create(prec, val_vec_disposer_host);
end;
class function TWasmValVec.NewUninitialized(size: NativeInt): TOwnValVec;
var
prec : PWasmValVec;
begin
System.New(prec);
TWasm.val_vec_new_uninitialized(prec, size);
result.FStrongRef := TRcContainer<PWasmValVec>.Create(prec, val_vec_disposer_host);
end;
function TWasmValVec.Copy: TOwnValVec;
var
prec : PWasmValVec;
begin
System.New(prec);
TWasm.val_vec_copy(prec, @self);
result.FStrongRef := TRcContainer<PWasmValVec>.Create(prec, val_vec_disposer_host);
end;
procedure TWasmValVec.Assign(const Src :TOwnValVec);
begin
TWasm.val_vec_copy(@self, Src.Unwrap);
end;
{ TOwnRef }
class function TOwnRef.Wrap(p: PWasmRef; deleter : TRcDeleter): TOwnRef;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmRef>.Create(p, deleter);
end;
class function TOwnRef.Wrap(p: PWasmRef): TOwnRef;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmRef>.Create(p, ref_disposer);
end;
class operator TOwnRef.Finalize(var Dest: TOwnRef);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnRef.Implicit(const Src: IRcContainer<PWasmRef>): TOwnRef;
begin
result.FStrongRef := Src;
end;
class operator TOwnRef.Negative(Src: TOwnRef): IRcContainer<PWasmRef>;
begin
result := Src.FStrongRef;
end;
class operator TOwnRef.Positive(Src: TOwnRef): PWasmRef;
begin
result := Src.Unwrap;
end;
function TOwnRef.Unwrap: PWasmRef;
begin
result := FStrongRef.Unwrap;
end;
function TOwnRef.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmRef }
function TWasmRef.Copy: TOwnRef;
begin
var p := TWasm.ref_copy(@self);
result.FStrongRef := TRcContainer<PWasmRef>.Create(p, ref_disposer);
end;
function TWasmRef.GetHostInfo: Pointer;
begin
result := TWasm.ref_get_host_info(@self);
end;
function TWasmRef.Same(const p: PWasmRef): Boolean;
begin
result := TWasm.ref_same(@self, p);
end;
procedure TWasmRef.SetHostInfo(info: Pointer);
begin
TWasm.ref_set_host_info(@self, info);
end;
procedure TWasmRef.SetHostInfoWithFinalizer(info: Pointer; finalizer: TWasmFinalizer);
begin
TWasm.ref_set_host_info_with_finalizer(@self, info, finalizer);
end;
function TWasmRef.AsTrap() : PWasmTrap;
begin
result := TWasm.ref_as_trap(@self);
end;
function TWasmRef.AsTrapConst() : PWasmTrap;
begin
result := TWasm.ref_as_trap_const(@self);
end;
function TWasmRef.AsForeign() : PWasmForeign;
begin
result := TWasm.ref_as_foreign(@self);
end;
function TWasmRef.AsForeignConst() : PWasmForeign;
begin
result := TWasm.ref_as_foreign_const(@self);
end;
function TWasmRef.AsModule() : PWasmModule;
begin
result := TWasm.ref_as_module(@self);
end;
function TWasmRef.AsModuleConst() : PWasmModule;
begin
result := TWasm.ref_as_module_const(@self);
end;
function TWasmRef.AsFunc() : PWasmFunc;
begin
result := TWasm.ref_as_func(@self);
end;
function TWasmRef.AsFuncConst() : PWasmFunc;
begin
result := TWasm.ref_as_func_const(@self);
end;
function TWasmRef.AsGlobal() : PWasmGlobal;
begin
result := TWasm.ref_as_global(@self);
end;
function TWasmRef.AsGlobalConst() : PWasmGlobal;
begin
result := TWasm.ref_as_global_const(@self);
end;
function TWasmRef.AsTable() : PWasmTable;
begin
result := TWasm.ref_as_table(@self);
end;
function TWasmRef.AsTableConst() : PWasmTable;
begin
result := TWasm.ref_as_table_const(@self);
end;
function TWasmRef.AsMemory() : PWasmMemory;
begin
result := TWasm.ref_as_memory(@self);
end;
function TWasmRef.AsMemoryConst() : PWasmMemory;
begin
result := TWasm.ref_as_memory_const(@self);
end;
function TWasmRef.AsExtern() : PWasmExtern;
begin
result := TWasm.ref_as_extern(@self);
end;
function TWasmRef.AsExternConst() : PWasmExtern;
begin
result := TWasm.ref_as_extern_const(@self);
end;
function TWasmRef.AsInstance() : PWasmInstance;
begin
result := TWasm.ref_as_instance(@self);
end;
function TWasmRef.AsInstanceConst() : PWasmInstance;
begin
result := TWasm.ref_as_instance_const(@self);
end;
{ TOwnFrame }
class function TOwnFrame.Wrap(p: PWasmFrame; deleter : TRcDeleter): TOwnFrame;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmFrame>.Create(p, deleter);
end;
class function TOwnFrame.Wrap(p: PWasmFrame): TOwnFrame;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmFrame>.Create(p, frame_disposer);
end;
class operator TOwnFrame.Finalize(var Dest: TOwnFrame);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnFrame.Implicit(const Src: IRcContainer<PWasmFrame>): TOwnFrame;
begin
result.FStrongRef := Src;
end;
class operator TOwnFrame.Negative(Src: TOwnFrame): IRcContainer<PWasmFrame>;
begin
result := Src.FStrongRef;
end;
class operator TOwnFrame.Positive(Src: TOwnFrame): PWasmFrame;
begin
result := Src.Unwrap;
end;
function TOwnFrame.Unwrap: PWasmFrame;
begin
result := FStrongRef.Unwrap;
end;
function TOwnFrame.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmFrame }
function TWasmFrame.Copy() : TOwnFrame;
begin
var p := TWasm.frame_copy(@self);
result := TOwnFrame.Wrap(p, frame_disposer); // ref ++
end;
function TWasmFrame.Instance() : PWasmInstance;
begin
result := TWasm.frame_instance(@self);
end;
function TWasmFrame.FuncIndex() : Cardinal;
begin
result := TWasm.frame_func_index(@self);
end;
function TWasmFrame.FuncOffset() : NativeInt;
begin
result := TWasm.frame_func_offset(@self);
end;
function TWasmFrame.ModuleOffset() : NativeInt;
begin
result := TWasm.frame_module_offset(@self);
end;
{ TOwnFrameVec }
class function TOwnFrameVec.Wrap(p: PWasmFrameVec; deleter : TRcDeleter): TOwnFrameVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmFrameVec>.Create(p, deleter);
end;
class function TOwnFrameVec.Wrap(p: PWasmFrameVec): TOwnFrameVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmFrameVec>.Create(p, frame_vec_disposer);
end;
class operator TOwnFrameVec.Finalize(var Dest: TOwnFrameVec);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnFrameVec.Implicit(const Src: IRcContainer<PWasmFrameVec>): TOwnFrameVec;
begin
result.FStrongRef := Src;
end;
class operator TOwnFrameVec.Negative(Src: TOwnFrameVec): IRcContainer<PWasmFrameVec>;
begin
result := Src.FStrongRef;
end;
class operator TOwnFrameVec.Positive(Src: TOwnFrameVec): PWasmFrameVec;
begin
result := Src.Unwrap;
end;
function TOwnFrameVec.Unwrap: PWasmFrameVec;
begin
result := FStrongRef.Unwrap;
end;
function TOwnFrameVec.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmFrameVec }
constructor TWasmFrameVec.Create(const arry: array of PWasmFrame);
begin
size := Length(arry);
if size = 0 then data := nil
else data := @arry[0];
end;
class function TWasmFrameVec.New(const init: array of PWasmFrame; elem_release : Boolean): TOwnFrameVec;
var
prec : PWasmFrameVec;
begin
System.New(prec);
TWasm.frame_vec_new(prec, Length(init), @init[0]);
if elem_release then
result.FStrongRef := TRcContainer<PWasmFrameVec>.Create(prec, frame_vec_disposer_host)
else
result.FStrongRef := TRcContainer<PWasmFrameVec>.Create(prec, frame_vec_disposer_host_only);
end;
class function TWasmFrameVec.NewEmpty: TOwnFrameVec;
var
prec : PWasmFrameVec;
begin
System.New(prec);
TWasm.frame_vec_new_empty(prec);
result.FStrongRef := TRcContainer<PWasmFrameVec>.Create(prec, frame_vec_disposer_host);
end;
class function TWasmFrameVec.NewUninitialized(size: NativeInt): TOwnFrameVec;
var
prec : PWasmFrameVec;
begin
System.New(prec);
TWasm.frame_vec_new_uninitialized(prec, size);
result.FStrongRef := TRcContainer<PWasmFrameVec>.Create(prec, frame_vec_disposer_host);
end;
function TWasmFrameVec.Copy: TOwnFrameVec;
var
prec : PWasmFrameVec;
begin
System.New(prec);
TWasm.frame_vec_copy(prec, @self);
result.FStrongRef := TRcContainer<PWasmFrameVec>.Create(prec, frame_vec_disposer_host);
end;
procedure TWasmFrameVec.Assign(const Src :TOwnFrameVec);
begin
TWasm.frame_vec_copy(@self, Src.Unwrap);
end;
{ TOwnTrap }
class function TOwnTrap.Wrap(p: PWasmTrap; deleter : TRcDeleter): TOwnTrap;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmTrap>.Create(p, deleter);
end;
class function TOwnTrap.Wrap(p: PWasmTrap): TOwnTrap;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmTrap>.Create(p, trap_disposer);
end;
class operator TOwnTrap.Finalize(var Dest: TOwnTrap);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnTrap.Implicit(const Src: IRcContainer<PWasmTrap>): TOwnTrap;
begin
result.FStrongRef := Src;
end;
class operator TOwnTrap.Negative(Src: TOwnTrap): IRcContainer<PWasmTrap>;
begin
result := Src.FStrongRef;
end;
class operator TOwnTrap.Positive(Src: TOwnTrap): PWasmTrap;
begin
result := Src.Unwrap;
end;
function TOwnTrap.Unwrap: PWasmTrap;
begin
result := FStrongRef.Unwrap;
end;
function TOwnTrap.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
function TOwnTrap.IsError() : Boolean;
begin
result := FStrongRef <> nil;
end;
function TOwnTrap.IsError(proc : TWasmUnwrapProc<PWasmTrap>) : Boolean;
begin
result := FStrongRef <> nil;
if result then proc(Unwrap);
end;
{ TWasmTrap }
function TWasmTrap.Copy: TOwnTrap;
begin
var p := TWasm.trap_copy(@self);
result.FStrongRef := TRcContainer<PWasmTrap>.Create(p, trap_disposer);
end;
function TWasmTrap.GetHostInfo: Pointer;
begin
result := TWasm.trap_get_host_info(@self);
end;
function TWasmTrap.Same(const p: PWasmTrap): Boolean;
begin
result := TWasm.trap_same(@self, p);
end;
procedure TWasmTrap.SetHostInfo(info: Pointer);
begin
TWasm.trap_set_host_info(@self, info);
end;
procedure TWasmTrap.SetHostInfoWithFinalizer(info: Pointer; finalizer: TWasmFinalizer);
begin
TWasm.trap_set_host_info_with_finalizer(@self, info, finalizer);
end;
function TWasmTrap.AsRef: PWasmRef;
begin
result := TWasm.trap_as_ref(@self);
end;
function TWasmTrap.AsRefConst: PWasmRef;
begin
result := TWasm.trap_as_ref_const(@self);
end;
class function TWasmTrap.New(store : PWasmStore; const message : PWasmMessage) : TOwnTrap;
begin
var p := TWasm.trap_new(store, message);
result := TOwnTrap.Wrap(p, trap_disposer); // ref ++
end;
function TWasmTrap.GetMessage() : string;
begin
var vec : TWasmByteVec;
var out_ := @vec;
TWasm.trap_message(@self, out_);
try
result := vec.AsString();
finally
TWasm.byte_vec_delete(out_);
end;
end;
function TWasmTrap.Origin() : TOwnFrame;
begin
var p := TWasm.trap_origin(@self);
result := TOwnFrame.Wrap(p, frame_disposer); // ref ++
end;
function TWasmTrap.Trace() : TOwnFrameVec;
begin
var out_ : PWasmFrameVec;
System.New(out_);
TWasm.trap_trace(@self, out_);
result := TOwnFrameVec.Wrap(out_, frame_vec_disposer_host); // ref ++
end;
{ TOwnForeign }
class function TOwnForeign.Wrap(p: PWasmForeign; deleter : TRcDeleter): TOwnForeign;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmForeign>.Create(p, deleter);
end;
class function TOwnForeign.Wrap(p: PWasmForeign): TOwnForeign;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmForeign>.Create(p, foreign_disposer);
end;
class operator TOwnForeign.Finalize(var Dest: TOwnForeign);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnForeign.Implicit(const Src: IRcContainer<PWasmForeign>): TOwnForeign;
begin
result.FStrongRef := Src;
end;
class operator TOwnForeign.Negative(Src: TOwnForeign): IRcContainer<PWasmForeign>;
begin
result := Src.FStrongRef;
end;
class operator TOwnForeign.Positive(Src: TOwnForeign): PWasmForeign;
begin
result := Src.Unwrap;
end;
function TOwnForeign.Unwrap: PWasmForeign;
begin
result := FStrongRef.Unwrap;
end;
function TOwnForeign.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmForeign }
function TWasmForeign.Copy: TOwnForeign;
begin
var p := TWasm.foreign_copy(@self);
result.FStrongRef := TRcContainer<PWasmForeign>.Create(p, foreign_disposer);
end;
function TWasmForeign.GetHostInfo: Pointer;
begin
result := TWasm.foreign_get_host_info(@self);
end;
function TWasmForeign.Same(const p: PWasmForeign): Boolean;
begin
result := TWasm.foreign_same(@self, p);
end;
procedure TWasmForeign.SetHostInfo(info: Pointer);
begin
TWasm.foreign_set_host_info(@self, info);
end;
procedure TWasmForeign.SetHostInfoWithFinalizer(info: Pointer; finalizer: TWasmFinalizer);
begin
TWasm.foreign_set_host_info_with_finalizer(@self, info, finalizer);
end;
function TWasmForeign.AsRef: PWasmRef;
begin
result := TWasm.foreign_as_ref(@self);
end;
function TWasmForeign.AsRefConst: PWasmRef;
begin
result := TWasm.foreign_as_ref_const(@self);
end;
class function TWasmForeign.New(store : PWasmStore) : TOwnForeign;
begin
var p := TWasm.foreign_new(store);
result := TOwnForeign.Wrap(p, foreign_disposer); // ref ++
end;
{ TOwnModule }
class function TOwnModule.Wrap(p: PWasmModule; deleter : TRcDeleter): TOwnModule;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmModule>.Create(p, deleter);
end;
class function TOwnModule.Wrap(p: PWasmModule): TOwnModule;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmModule>.Create(p, module_disposer);
end;
class operator TOwnModule.Finalize(var Dest: TOwnModule);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnModule.Implicit(const Src: IRcContainer<PWasmModule>): TOwnModule;
begin
result.FStrongRef := Src;
end;
class operator TOwnModule.Negative(Src: TOwnModule): IRcContainer<PWasmModule>;
begin
result := Src.FStrongRef;
end;
class operator TOwnModule.Positive(Src: TOwnModule): PWasmModule;
begin
result := Src.Unwrap;
end;
function TOwnModule.Unwrap: PWasmModule;
begin
result := FStrongRef.Unwrap;
end;
function TOwnModule.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmModule }
function TWasmModule.Copy: TOwnModule;
begin
var p := TWasm.module_copy(@self);
result.FStrongRef := TRcContainer<PWasmModule>.Create(p, module_disposer);
end;
function TWasmModule.GetHostInfo: Pointer;
begin
result := TWasm.module_get_host_info(@self);
end;
function TWasmModule.Same(const p: PWasmModule): Boolean;
begin
result := TWasm.module_same(@self, p);
end;
procedure TWasmModule.SetHostInfo(info: Pointer);
begin
TWasm.module_set_host_info(@self, info);
end;
procedure TWasmModule.SetHostInfoWithFinalizer(info: Pointer; finalizer: TWasmFinalizer);
begin
TWasm.module_set_host_info_with_finalizer(@self, info, finalizer);
end;
function TWasmModule.AsRef: PWasmRef;
begin
result := TWasm.module_as_ref(@self);
end;
function TWasmModule.AsRefConst: PWasmRef;
begin
result := TWasm.module_as_ref_const(@self);
end;
function TWasmModule.Share() : TOwnSharedModule;
begin
var p := TWasm.module_share(@self);
result := TOwnSharedModule.Wrap(p, shared_module_disposer);
end;
class function TWasmModule.New(store : PWasmStore; const binary : PWasmByteVec) : TOwnModule;
begin
var p := TWasm.module_new(store, binary);
result := TOwnModule.Wrap(p, module_disposer); // ref ++
end;
function TWasmModule.Validate(store : PWasmStore; const binary : PWasmByteVec) : Boolean;
begin
result := TWasm.module_validate(store, binary);
end;
function TWasmModule.Imports() : TOwnImporttypeVec;
begin
var out_ : PWasmImporttypeVec;
System.New(out_);
TWasm.module_imports(@self, out_);
result := TOwnImporttypeVec.Wrap(out_, importtype_vec_disposer_host); // ref ++
end;
function TWasmModule.GetExports() : TOwnExporttypeVec;
begin
var out_ : PWasmExporttypeVec;
System.New(out_);
TWasm.module_exports(@self, out_);
result := TOwnExporttypeVec.Wrap(out_, exporttype_vec_disposer_host); // ref ++
end;
function TWasmModule.Serialize() : TOwnByteVec;
begin
var out_ : PWasmByteVec;
System.New(out_);
TWasm.module_serialize(@self, out_);
result := TOwnByteVec.Wrap(out_, byte_vec_disposer_host); // ref ++
end;
class function TWasmModule.Deserialize(store : PWasmStore; const byte_vec : PWasmByteVec) : TOwnModule;
begin
var p := TWasm.module_deserialize(store, byte_vec);
result := TOwnModule.Wrap(p, module_disposer); // ref ++
end;
{ TOwnSharedModule }
class function TOwnSharedModule.Wrap(p: PWasmSharedModule; deleter : TRcDeleter): TOwnSharedModule;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmSharedModule>.Create(p, deleter);
end;
class function TOwnSharedModule.Wrap(p: PWasmSharedModule): TOwnSharedModule;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmSharedModule>.Create(p, shared_module_disposer);
end;
class operator TOwnSharedModule.Finalize(var Dest: TOwnSharedModule);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnSharedModule.Implicit(const Src: IRcContainer<PWasmSharedModule>): TOwnSharedModule;
begin
result.FStrongRef := Src;
end;
class operator TOwnSharedModule.Negative(Src: TOwnSharedModule): IRcContainer<PWasmSharedModule>;
begin
result := Src.FStrongRef;
end;
class operator TOwnSharedModule.Positive(Src: TOwnSharedModule): PWasmSharedModule;
begin
result := Src.Unwrap;
end;
function TOwnSharedModule.Unwrap: PWasmSharedModule;
begin
result := FStrongRef.Unwrap;
end;
function TOwnSharedModule.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmSharedModule }
function TWasmSharedModule.Obtain(store : PWasmStore): TOwnModule;
begin
var p := TWasm.module_obtain(store, @self);
result.FStrongRef := TRcContainer<PWasmModule>.Create(p, module_disposer);
end;
{ TOwnFunc }
class function TOwnFunc.Wrap(p: PWasmFunc; deleter : TRcDeleter): TOwnFunc;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmFunc>.Create(p, deleter);
end;
class function TOwnFunc.Wrap(p: PWasmFunc): TOwnFunc;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmFunc>.Create(p, func_disposer);
end;
class operator TOwnFunc.Finalize(var Dest: TOwnFunc);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnFunc.Implicit(const Src: IRcContainer<PWasmFunc>): TOwnFunc;
begin
result.FStrongRef := Src;
end;
class operator TOwnFunc.Negative(Src: TOwnFunc): IRcContainer<PWasmFunc>;
begin
result := Src.FStrongRef;
end;
class operator TOwnFunc.Positive(Src: TOwnFunc): PWasmFunc;
begin
result := Src.Unwrap;
end;
function TOwnFunc.Unwrap: PWasmFunc;
begin
result := FStrongRef.Unwrap;
end;
function TOwnFunc.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmFunc }
function TWasmFunc.Copy: TOwnFunc;
begin
var p := TWasm.func_copy(@self);
result.FStrongRef := TRcContainer<PWasmFunc>.Create(p, func_disposer);
end;
function TWasmFunc.GetHostInfo: Pointer;
begin
result := TWasm.func_get_host_info(@self);
end;
function TWasmFunc.Same(const p: PWasmFunc): Boolean;
begin
result := TWasm.func_same(@self, p);
end;
procedure TWasmFunc.SetHostInfo(info: Pointer);
begin
TWasm.func_set_host_info(@self, info);
end;
procedure TWasmFunc.SetHostInfoWithFinalizer(info: Pointer; finalizer: TWasmFinalizer);
begin
TWasm.func_set_host_info_with_finalizer(@self, info, finalizer);
end;
function TWasmFunc.AsRef: PWasmRef;
begin
result := TWasm.func_as_ref(@self);
end;
function TWasmFunc.AsRefConst: PWasmRef;
begin
result := TWasm.func_as_ref_const(@self);
end;
class function TWasmFunc.New(store : PWasmStore; const functype : PWasmFunctype; func_callback : TWasmFuncCallback) : TOwnFunc;
begin
var p := TWasm.func_new(store, functype, func_callback);
result := TOwnFunc.Wrap(p, func_disposer); // ref ++
end;
class function TWasmFunc.NewWithEnv(store : PWasmStore; const typ : PWasmFunctype; func_callback_with_env : TWasmFuncCallbackWithEnv; env : Pointer; finalizer : TWasmFinalizer) : TOwnFunc;
begin
var p := TWasm.func_new_with_env(store, typ, func_callback_with_env, env, finalizer);
result := TOwnFunc.Wrap(p, func_disposer); // ref ++
end;
function TWasmFunc.GetType() : TOwnFunctype;
begin
var p := TWasm.func_type(@self);
result := TOwnFunctype.Wrap(p, functype_disposer); // ref ++
end;
function TWasmFunc.ParamArity() : NativeInt;
begin
result := TWasm.func_param_arity(@self);
end;
function TWasmFunc.ResultArity() : NativeInt;
begin
result := TWasm.func_result_arity(@self);
end;
function TWasmFunc.Call( const args : PWasmValVec; results : PWasmValVec) : TOwnTrap;
begin
var p := TWasm.func_call(@self, args, results);
result := TOwnTrap.Wrap(p, trap_disposer); // ref ++
end;
function TWasmFunc.AsExtern() : PWasmExtern;
begin
result := TWasm.func_as_extern(@self);
end;
function TWasmFunc.AsExternConst() : PWasmExtern;
begin
result := TWasm.func_as_extern_const(@self);
end;
{ TOwnGlobal }
class function TOwnGlobal.Wrap(p: PWasmGlobal; deleter : TRcDeleter): TOwnGlobal;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmGlobal>.Create(p, deleter);
end;
class function TOwnGlobal.Wrap(p: PWasmGlobal): TOwnGlobal;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmGlobal>.Create(p, global_disposer);
end;
class operator TOwnGlobal.Finalize(var Dest: TOwnGlobal);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnGlobal.Implicit(const Src: IRcContainer<PWasmGlobal>): TOwnGlobal;
begin
result.FStrongRef := Src;
end;
class operator TOwnGlobal.Negative(Src: TOwnGlobal): IRcContainer<PWasmGlobal>;
begin
result := Src.FStrongRef;
end;
class operator TOwnGlobal.Positive(Src: TOwnGlobal): PWasmGlobal;
begin
result := Src.Unwrap;
end;
function TOwnGlobal.Unwrap: PWasmGlobal;
begin
result := FStrongRef.Unwrap;
end;
function TOwnGlobal.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmGlobal }
function TWasmGlobal.Copy: TOwnGlobal;
begin
var p := TWasm.global_copy(@self);
result.FStrongRef := TRcContainer<PWasmGlobal>.Create(p, global_disposer);
end;
function TWasmGlobal.GetHostInfo: Pointer;
begin
result := TWasm.global_get_host_info(@self);
end;
function TWasmGlobal.Same(const p: PWasmGlobal): Boolean;
begin
result := TWasm.global_same(@self, p);
end;
procedure TWasmGlobal.SetHostInfo(info: Pointer);
begin
TWasm.global_set_host_info(@self, info);
end;
procedure TWasmGlobal.SetHostInfoWithFinalizer(info: Pointer; finalizer: TWasmFinalizer);
begin
TWasm.global_set_host_info_with_finalizer(@self, info, finalizer);
end;
function TWasmGlobal.AsRef: PWasmRef;
begin
result := TWasm.global_as_ref(@self);
end;
function TWasmGlobal.AsRefConst: PWasmRef;
begin
result := TWasm.global_as_ref_const(@self);
end;
class function TWasmGlobal.New(store : PWasmStore; const globaltype : PWasmGlobaltype; const val : PWasmVal) : TOwnGlobal;
begin
var p := TWasm.global_new(store, globaltype, val);
result := TOwnGlobal.Wrap(p, global_disposer); // ref ++
end;
function TWasmGlobal.GetType() : TOwnGlobaltype;
begin
var p := TWasm.global_type(@self);
result := TOwnGlobaltype.Wrap(p, globaltype_disposer); // ref ++
end;
function TWasmGlobal.GetVal() : TOwnVal;
begin
var out_ : PWasmVal;
System.New(out_);
TWasm.global_get(@self, out_);
result := TOwnVal.Wrap(out_, val_disposer_host); // ref ++
end;
procedure TWasmGlobal.SetVal( const val : PWasmVal);
begin
TWasm.global_set(@self, val);
end;
function TWasmGlobal.AsExtern() : PWasmExtern;
begin
result := TWasm.global_as_extern(@self);
end;
function TWasmGlobal.AsExternConst() : PWasmExtern;
begin
result := TWasm.global_as_extern_const(@self);
end;
{ TOwnTable }
class function TOwnTable.Wrap(p: PWasmTable; deleter : TRcDeleter): TOwnTable;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmTable>.Create(p, deleter);
end;
class function TOwnTable.Wrap(p: PWasmTable): TOwnTable;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmTable>.Create(p, table_disposer);
end;
class operator TOwnTable.Finalize(var Dest: TOwnTable);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnTable.Implicit(const Src: IRcContainer<PWasmTable>): TOwnTable;
begin
result.FStrongRef := Src;
end;
class operator TOwnTable.Negative(Src: TOwnTable): IRcContainer<PWasmTable>;
begin
result := Src.FStrongRef;
end;
class operator TOwnTable.Positive(Src: TOwnTable): PWasmTable;
begin
result := Src.Unwrap;
end;
function TOwnTable.Unwrap: PWasmTable;
begin
result := FStrongRef.Unwrap;
end;
function TOwnTable.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmTable }
function TWasmTable.Copy: TOwnTable;
begin
var p := TWasm.table_copy(@self);
result.FStrongRef := TRcContainer<PWasmTable>.Create(p, table_disposer);
end;
function TWasmTable.GetHostInfo: Pointer;
begin
result := TWasm.table_get_host_info(@self);
end;
function TWasmTable.Same(const p: PWasmTable): Boolean;
begin
result := TWasm.table_same(@self, p);
end;
procedure TWasmTable.SetHostInfo(info: Pointer);
begin
TWasm.table_set_host_info(@self, info);
end;
procedure TWasmTable.SetHostInfoWithFinalizer(info: Pointer; finalizer: TWasmFinalizer);
begin
TWasm.table_set_host_info_with_finalizer(@self, info, finalizer);
end;
function TWasmTable.AsRef: PWasmRef;
begin
result := TWasm.table_as_ref(@self);
end;
function TWasmTable.AsRefConst: PWasmRef;
begin
result := TWasm.table_as_ref_const(@self);
end;
class function TWasmTable.New(store : PWasmStore; const tabletype : PWasmTabletype; init : PWasmRef) : TOwnTable;
begin
var p := TWasm.table_new(store, tabletype, init);
result := TOwnTable.Wrap(p, table_disposer); // ref ++
end;
function TWasmTable.GetType() : TOwnTabletype;
begin
var p := TWasm.table_type(@self);
result := TOwnTabletype.Wrap(p, tabletype_disposer); // ref ++
end;
function TWasmTable.GetRef(index : TWasmTableSize) : TOwnRef;
begin
var p := TWasm.table_get(@self, index);
result := TOwnRef.Wrap(p, ref_disposer); // ref ++
end;
function TWasmTable.SetRef(index : TWasmTableSize; ref : PWasmRef) : Boolean;
begin
result := TWasm.table_set(@self, index, ref);
end;
function TWasmTable.Size() : TWasmTableSize;
begin
result := TWasm.table_size(@self);
end;
function TWasmTable.Grow(delta : TWasmTableSize; init : PWasmRef) : Boolean;
begin
result := TWasm.table_grow(@self, delta, init);
end;
function TWasmTable.AsExtern() : PWasmExtern;
begin
result := TWasm.table_as_extern(@self);
end;
function TWasmTable.AsExternConst() : PWasmExtern;
begin
result := TWasm.table_as_extern_const(@self);
end;
{ TOwnMemory }
class function TOwnMemory.Wrap(p: PWasmMemory; deleter : TRcDeleter): TOwnMemory;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmMemory>.Create(p, deleter);
end;
class function TOwnMemory.Wrap(p: PWasmMemory): TOwnMemory;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmMemory>.Create(p, memory_disposer);
end;
class operator TOwnMemory.Finalize(var Dest: TOwnMemory);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnMemory.Implicit(const Src: IRcContainer<PWasmMemory>): TOwnMemory;
begin
result.FStrongRef := Src;
end;
class operator TOwnMemory.Negative(Src: TOwnMemory): IRcContainer<PWasmMemory>;
begin
result := Src.FStrongRef;
end;
class operator TOwnMemory.Positive(Src: TOwnMemory): PWasmMemory;
begin
result := Src.Unwrap;
end;
function TOwnMemory.Unwrap: PWasmMemory;
begin
result := FStrongRef.Unwrap;
end;
function TOwnMemory.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmMemory }
function TWasmMemory.Copy: TOwnMemory;
begin
var p := TWasm.memory_copy(@self);
result.FStrongRef := TRcContainer<PWasmMemory>.Create(p, memory_disposer);
end;
function TWasmMemory.GetHostInfo: Pointer;
begin
result := TWasm.memory_get_host_info(@self);
end;
function TWasmMemory.Same(const p: PWasmMemory): Boolean;
begin
result := TWasm.memory_same(@self, p);
end;
procedure TWasmMemory.SetHostInfo(info: Pointer);
begin
TWasm.memory_set_host_info(@self, info);
end;
procedure TWasmMemory.SetHostInfoWithFinalizer(info: Pointer; finalizer: TWasmFinalizer);
begin
TWasm.memory_set_host_info_with_finalizer(@self, info, finalizer);
end;
function TWasmMemory.AsRef: PWasmRef;
begin
result := TWasm.memory_as_ref(@self);
end;
function TWasmMemory.AsRefConst: PWasmRef;
begin
result := TWasm.memory_as_ref_const(@self);
end;
class function TWasmMemory.New(store : PWasmStore; const memorytype : PWasmMemorytype) : TOwnMemory;
begin
var p := TWasm.memory_new(store, memorytype);
result := TOwnMemory.Wrap(p, memory_disposer); // ref ++
end;
function TWasmMemory.GetType() : TOwnMemorytype;
begin
var p := TWasm.memory_type(@self);
result := TOwnMemorytype.Wrap(p, memorytype_disposer); // ref ++
end;
function TWasmMemory.Data() : PByte;
begin
result := TWasm.memory_data(@self);
end;
function TWasmMemory.DataSize() : NativeInt;
begin
result := TWasm.memory_data_size(@self);
end;
function TWasmMemory.Size() : TWasmMemoryPages;
begin
result := TWasm.memory_size(@self);
end;
function TWasmMemory.Grow(delta : TWasmMemoryPages) : Boolean;
begin
result := TWasm.memory_grow(@self, delta);
end;
function TWasmMemory.AsExtern() : PWasmExtern;
begin
result := TWasm.memory_as_extern(@self);
end;
function TWasmMemory.AsExternConst() : PWasmExtern;
begin
result := TWasm.memory_as_extern_const(@self);
end;
{ TOwnExtern }
class function TOwnExtern.Wrap(p: PWasmExtern; deleter : TRcDeleter): TOwnExtern;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmExtern>.Create(p, deleter);
end;
class function TOwnExtern.Wrap(p: PWasmExtern): TOwnExtern;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmExtern>.Create(p, extern_disposer);
end;
class operator TOwnExtern.Finalize(var Dest: TOwnExtern);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnExtern.Implicit(const Src: IRcContainer<PWasmExtern>): TOwnExtern;
begin
result.FStrongRef := Src;
end;
class operator TOwnExtern.Negative(Src: TOwnExtern): IRcContainer<PWasmExtern>;
begin
result := Src.FStrongRef;
end;
class operator TOwnExtern.Positive(Src: TOwnExtern): PWasmExtern;
begin
result := Src.Unwrap;
end;
function TOwnExtern.Unwrap: PWasmExtern;
begin
result := FStrongRef.Unwrap;
end;
function TOwnExtern.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmExtern }
function TWasmExtern.Copy: TOwnExtern;
begin
var p := TWasm.extern_copy(@self);
result.FStrongRef := TRcContainer<PWasmExtern>.Create(p, extern_disposer);
end;
function TWasmExtern.GetHostInfo: Pointer;
begin
result := TWasm.extern_get_host_info(@self);
end;
function TWasmExtern.Same(const p: PWasmExtern): Boolean;
begin
result := TWasm.extern_same(@self, p);
end;
procedure TWasmExtern.SetHostInfo(info: Pointer);
begin
TWasm.extern_set_host_info(@self, info);
end;
procedure TWasmExtern.SetHostInfoWithFinalizer(info: Pointer; finalizer: TWasmFinalizer);
begin
TWasm.extern_set_host_info_with_finalizer(@self, info, finalizer);
end;
function TWasmExtern.AsRef: PWasmRef;
begin
result := TWasm.extern_as_ref(@self);
end;
function TWasmExtern.AsRefConst: PWasmRef;
begin
result := TWasm.extern_as_ref_const(@self);
end;
function TWasmExtern.Kind() : TWasmExternkind;
begin
result := TWasm.extern_kind(@self);
end;
function TWasmExtern.GetType() : TOwnExterntype;
begin
var p := TWasm.extern_type(@self);
result := TOwnExterntype.Wrap(p, externtype_disposer); // ref ++
end;
function TWasmExtern.AsFunc() : PWasmFunc;
begin
result := TWasm.extern_as_func(@self);
end;
function TWasmExtern.AsGlobal() : PWasmGlobal;
begin
result := TWasm.extern_as_global(@self);
end;
function TWasmExtern.AsTable() : PWasmTable;
begin
result := TWasm.extern_as_table(@self);
end;
function TWasmExtern.AsMemory() : PWasmMemory;
begin
result := TWasm.extern_as_memory(@self);
end;
function TWasmExtern.AsFuncConst() : PWasmFunc;
begin
result := TWasm.extern_as_func_const(@self);
end;
function TWasmExtern.AsGlobalConst() : PWasmGlobal;
begin
result := TWasm.extern_as_global_const(@self);
end;
function TWasmExtern.AsTableConst() : PWasmTable;
begin
result := TWasm.extern_as_table_const(@self);
end;
function TWasmExtern.AsMemoryConst() : PWasmMemory;
begin
result := TWasm.extern_as_memory_const(@self);
end;
{ TOwnExternVec }
class function TOwnExternVec.Wrap(p: PWasmExternVec; deleter : TRcDeleter): TOwnExternVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmExternVec>.Create(p, deleter);
end;
class function TOwnExternVec.Wrap(p: PWasmExternVec): TOwnExternVec;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmExternVec>.Create(p, extern_vec_disposer);
end;
class operator TOwnExternVec.Finalize(var Dest: TOwnExternVec);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnExternVec.Implicit(const Src: IRcContainer<PWasmExternVec>): TOwnExternVec;
begin
result.FStrongRef := Src;
end;
class operator TOwnExternVec.Negative(Src: TOwnExternVec): IRcContainer<PWasmExternVec>;
begin
result := Src.FStrongRef;
end;
class operator TOwnExternVec.Positive(Src: TOwnExternVec): PWasmExternVec;
begin
result := Src.Unwrap;
end;
function TOwnExternVec.Unwrap: PWasmExternVec;
begin
result := FStrongRef.Unwrap;
end;
function TOwnExternVec.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmExternVec }
constructor TWasmExternVec.Create(const arry: array of PWasmExtern);
begin
size := Length(arry);
if size = 0 then data := nil
else data := @arry[0];
end;
class function TWasmExternVec.New(const init: array of PWasmExtern; elem_release : Boolean): TOwnExternVec;
var
prec : PWasmExternVec;
begin
System.New(prec);
TWasm.extern_vec_new(prec, Length(init), @init[0]);
if elem_release then
result.FStrongRef := TRcContainer<PWasmExternVec>.Create(prec, extern_vec_disposer_host)
else
result.FStrongRef := TRcContainer<PWasmExternVec>.Create(prec, extern_vec_disposer_host_only);
end;
class function TWasmExternVec.NewEmpty: TOwnExternVec;
var
prec : PWasmExternVec;
begin
System.New(prec);
TWasm.extern_vec_new_empty(prec);
result.FStrongRef := TRcContainer<PWasmExternVec>.Create(prec, extern_vec_disposer_host);
end;
class function TWasmExternVec.NewUninitialized(size: NativeInt): TOwnExternVec;
var
prec : PWasmExternVec;
begin
System.New(prec);
TWasm.extern_vec_new_uninitialized(prec, size);
result.FStrongRef := TRcContainer<PWasmExternVec>.Create(prec, extern_vec_disposer_host);
end;
function TWasmExternVec.Copy: TOwnExternVec;
var
prec : PWasmExternVec;
begin
System.New(prec);
TWasm.extern_vec_copy(prec, @self);
result.FStrongRef := TRcContainer<PWasmExternVec>.Create(prec, extern_vec_disposer_host);
end;
procedure TWasmExternVec.Assign(const Src :TOwnExternVec);
begin
TWasm.extern_vec_copy(@self, Src.Unwrap);
end;
{ TOwnInstance }
class function TOwnInstance.Wrap(p: PWasmInstance; deleter : TRcDeleter): TOwnInstance;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmInstance>.Create(p, deleter);
end;
class function TOwnInstance.Wrap(p: PWasmInstance): TOwnInstance;
begin
if p = nil then result.FStrongRef := nil
else result.FStrongRef := TRcContainer<PWasmInstance>.Create(p, instance_disposer);
end;
class operator TOwnInstance.Finalize(var Dest: TOwnInstance);
begin
Dest.FStrongRef := nil;
end;
class operator TOwnInstance.Implicit(const Src: IRcContainer<PWasmInstance>): TOwnInstance;
begin
result.FStrongRef := Src;
end;
class operator TOwnInstance.Negative(Src: TOwnInstance): IRcContainer<PWasmInstance>;
begin
result := Src.FStrongRef;
end;
class operator TOwnInstance.Positive(Src: TOwnInstance): PWasmInstance;
begin
result := Src.Unwrap;
end;
function TOwnInstance.Unwrap: PWasmInstance;
begin
result := FStrongRef.Unwrap;
end;
function TOwnInstance.IsNone() : Boolean;
begin
result := FStrongRef = nil;
end;
{ TWasmInstance }
class function TWasmInstance.New(store: PWasmStore; const module: PWasmModule; const imports: array of PWasmExtern): TOwnInstance;
begin
var imps := TWasmExternVec.Create(imports);
var instance := TWasm.instance_new(store, module, @imps, nil);
result := TOwnInstance.Wrap(instance, instance_disposer)
end;
class function TWasmInstance.New(store: PWasmStore; const module: PWasmModule; const imports: array of PWasmExtern; var trap: TOwnTrap): TOwnInstance;
begin
var imps := TWasmExternVec.Create(imports);
var tmp_trap : PWasmTrap;
var instance := TWasm.instance_new(store, module, @imps, @tmp_trap);
trap := TOwnTrap.Wrap(tmp_trap);
result := TOwnInstance.Wrap(instance, instance_disposer)
end;
class function TWasmInstance.New(store : PWasmStore; const module : PWasmModule; const imports : PWasmExternVec) : TOwnInstance;
begin
var p := TWasm.instance_new(store, module, imports, nil);
result := TOwnInstance.Wrap(p, instance_disposer); // ref ++
end;
function TWasmInstance.Copy: TOwnInstance;
begin
var p := TWasm.instance_copy(@self);
result.FStrongRef := TRcContainer<PWasmInstance>.Create(p, instance_disposer);
end;
function TWasmInstance.GetHostInfo: Pointer;
begin
result := TWasm.instance_get_host_info(@self);
end;
function TWasmInstance.Same(const p: PWasmInstance): Boolean;
begin
result := TWasm.instance_same(@self, p);
end;
procedure TWasmInstance.SetHostInfo(info: Pointer);
begin
TWasm.instance_set_host_info(@self, info);
end;
procedure TWasmInstance.SetHostInfoWithFinalizer(info: Pointer; finalizer: TWasmFinalizer);
begin
TWasm.instance_set_host_info_with_finalizer(@self, info, finalizer);
end;
function TWasmInstance.AsRef: PWasmRef;
begin
result := TWasm.instance_as_ref(@self);
end;
function TWasmInstance.AsRefConst: PWasmRef;
begin
result := TWasm.instance_as_ref_const(@self);
end;
class function TWasmInstance.New(store : PWasmStore; const module : PWasmModule; const imports : PWasmExternVec; var {own} trap : TOwnTrap) : TOwnInstance;
begin
var tmp_trap : PWasmTrap;
var p := TWasm.instance_new(store, module, imports, @tmp_trap);
trap := TOwnTrap.Wrap(tmp_trap);
result := TOwnInstance.Wrap(p, instance_disposer); // ref ++
end;
function TWasmInstance.GetExports() : TOwnExternVec;
begin
var out_ : PWasmExternVec;
System.New(out_);
TWasm.instance_exports(@self, out_);
result := TOwnExternVec.Wrap(out_, extern_vec_disposer_host); // ref ++
end;
end.
|
unit LTConst;
interface
const
AUTH_STUDENT_BEGIN = 2; // 학생 ?
AUTH_STUDENT_END = 3; // 학생 ?
AUTH_TEACHER = 4; // 강사
AUTH_ACADEMY = 5; // 학원장
AUTH_BRANCH = 6; // 지사장
implementation
end.
|
unit caStats;
{$INCLUDE ca.inc}
interface
uses
// Standard Delphi units
Classes,
Sysutils,
Math,
Contnrs,
// ca units
caClasses,
caTypes,
caUtils,
caLog,
caStatsBase;
type
{$IFDEF D5}
IInvokable = IUnknown;
{$ENDIF}
//----------------------------------------------------------------------------
// IcaRegression
//----------------------------------------------------------------------------
IcaRegression = interface(IInvokable)
['{6B636796-F4B8-4F19-9BB2-9EFF853BCA9D}']
// Interface methods
function Correlation: TcaStatsFloat;
function CoVariance: TcaStatsFloat;
function N: Integer;
function ResidualSumSqr: TcaStatsFloat;
function RSquared: TcaStatsFloat;
function S2: TcaStatsFloat;
function Slope: TcaStatsFloat;
function StdErrSlope: TcaStatsFloat;
function StdErrY: TcaStatsFloat;
function STEYX: TcaStatsFloat;
function SumOfProducts: TcaStatsFloat;
function Sxx: TcaStatsFloat;
function Sxy: TcaStatsFloat;
function Syy: TcaStatsFloat;
function T_Ratio: TcaStatsFloat;
function X: TcaStatsVector;
function Y: TcaStatsVector;
procedure AddXY(AX, AY: Double);
procedure Clear;
end;
//----------------------------------------------------------------------------
// TcaRegression
//----------------------------------------------------------------------------
{$M+}
TcaRegression = class(TInterfacedObject, IcaRegression, IcaStatsAsString)
private
// Private fields
FMathUtils: IcaMathUtils;
FX: TcaStatsVector;
FY: TcaStatsVector;
// Private methods
function CheckReset: Boolean;
function Divide(ANumerator, ADenominator: TcaStatsFloat): TcaStatsFloat;
public
// Create/Destroy
constructor Create;
destructor Destroy; override;
// Abstract virtual methods
function GetS2: TcaStatsFloat; virtual; abstract;
function GetSlope: TcaStatsFloat; virtual; abstract;
function GetStdErrSlope: TcaStatsFloat; virtual; abstract;
function GetYIntercept: TcaStatsFloat; virtual; abstract;
// Interface methods - IcaRegression
function X: TcaStatsVector;
function Y: TcaStatsVector;
procedure AddXY(AX, AY: Double);
procedure Clear;
// Interface methods - IcaStatsAsString
function AsString: string;
published
// Interface methods - IcaRegression
function Correlation: TcaStatsFloat;
function CoVariance: TcaStatsFloat;
function YIntercept: TcaStatsFloat;
function N: Integer;
function ResidualSumSqr: TcaStatsFloat;
function RSquared: TcaStatsFloat;
function S2: TcaStatsFloat;
function Slope: TcaStatsFloat;
function StdErrSlope: TcaStatsFloat;
function StdErrY: TcaStatsFloat;
function STEYX: TcaStatsFloat;
function SumOfProducts: TcaStatsFloat;
function Sxx: TcaStatsFloat;
function Sxy: TcaStatsFloat;
function Syy: TcaStatsFloat;
function T_Ratio: TcaStatsFloat;
end;
{$M-}
//----------------------------------------------------------------------------
// TcaForcedOriginRegression
//----------------------------------------------------------------------------
TcaForcedOriginRegression = class(TcaRegression)
public
function GetS2: TcaStatsFloat; override;
function GetSlope: TcaStatsFloat; override;
function GetStdErrSlope: TcaStatsFloat; override;
function GetYIntercept: TcaStatsFloat; override;
end;
//----------------------------------------------------------------------------
// TcaInterceptRegression
//----------------------------------------------------------------------------
TcaInterceptRegression = class(TcaRegression)
public
function GetS2: TcaStatsFloat; override;
function GetSlope: TcaStatsFloat; override;
function GetStdErrSlope: TcaStatsFloat; override;
function GetYIntercept: TcaStatsFloat; override;
end;
implementation
//----------------------------------------------------------------------------
// TcaRegression
//----------------------------------------------------------------------------
// Create/Destroy
constructor TcaRegression.Create;
begin
inherited Create;
FMathUtils := Utils as IcaMathUtils;
FX := TcaStatsVector.Create;
FY := TcaStatsVector.Create;
end;
destructor TcaRegression.Destroy;
begin
FX.Free;
FY.Free;
FMathUtils := nil;
inherited;
end;
// Interface methods - IcaRegression
function TcaRegression.Correlation: TcaStatsFloat; // EXCEL.CORREL(X, Y)
begin
Result := CoVariance / Sqrt(FX.Variance * FY.Variance) * N;
end;
function TcaRegression.CoVariance: TcaStatsFloat; // EXCEL.COVAR(X, Y)
begin
Result := Sxy / N;
end;
function TcaRegression.N: Integer;
begin
Result := Min(FX.N, FY.N);
end;
function TcaRegression.ResidualSumSqr: TcaStatsFloat;
begin
Result := (1 - RSquared) * FY.SumSqrDev;
end;
function TcaRegression.RSquared: TcaStatsFloat;
begin
Result := Sqr(Correlation);
end;
function TcaRegression.S2: TcaStatsFloat;
begin
Result := GetS2;
end;
function TcaRegression.Slope: TcaStatsFloat;
begin
Result := GetSlope;
end;
function TcaRegression.StdErrSlope: TcaStatsFloat;
begin
Result := GetStdErrSlope;
end;
function TcaRegression.StdErrY: TcaStatsFloat;
begin
Result := Sqrt(S2);
end;
function TcaRegression.STEYX: TcaStatsFloat; // EXCEL.STEYX(X, Y)
begin
Result := StdErrY;
end;
function TcaRegression.SumOfProducts: TcaStatsFloat;
begin
Result := 0;
if CheckReset then
while FX.HasMore and FY.HasMore do
Result := Result + (FX.Next * FY.Next);
end;
function TcaRegression.Sxx: TcaStatsFloat;
begin
Result := FX.SumOfSquares - (Sqr(FX.Sum) / N);
end;
function TcaRegression.Sxy: TcaStatsFloat;
begin
Result := SumOfProducts - FX.Sum * FY.Sum / N;
end;
function TcaRegression.Syy: TcaStatsFloat;
begin
Result := FY.SumOfSquares - (Sqr(FY.Sum) / N);
end;
function TcaRegression.T_Ratio: TcaStatsFloat;
begin
Result := Divide(Slope, StdErrSlope);
end;
function TcaRegression.X: TcaStatsVector;
begin
Result := FX;
end;
function TcaRegression.Y: TcaStatsVector;
begin
Result := FY;
end;
function TcaRegression.YIntercept: TcaStatsFloat;
begin
Result := GetYIntercept;
end;
procedure TcaRegression.AddXY(AX, AY: Double);
begin
FX.Add(AX);
FY.Add(AY);
end;
procedure TcaRegression.Clear;
begin
FX.Clear;
FY.Clear;
end;
// Interface methods - IcaStatsAsString
function TcaRegression.AsString: string;
var
FunctionEnumerator: TcaStatsFloatFunctionEnumerator;
begin
FunctionEnumerator := Auto(TcaStatsFloatFunctionEnumerator.Create(Self)).Instance;
Result := FunctionEnumerator.AsString;
end;
// Private methods
function TcaRegression.CheckReset: Boolean;
begin
FX.Reset;
FY.Reset;
Result := FX.N = FY.N;
end;
function TcaRegression.Divide(ANumerator, ADenominator: TcaStatsFloat): TcaStatsFloat;
begin
Result := FMathUtils.FloatDiv(ANumerator, ADenominator, 0);
end;
//----------------------------------------------------------------------------
// TcaForcedOriginRegression
//----------------------------------------------------------------------------
function TcaForcedOriginRegression.GetS2: TcaStatsFloat;
begin
Result := (FY.SumOfSquares - Sqr(SumOfProducts) / FX.SumOfSquares) / (N - 1);
end;
function TcaForcedOriginRegression.GetSlope: TcaStatsFloat;
begin
Result := Divide(SumOfProducts, FX.SumOfSquares)
end;
function TcaForcedOriginRegression.GetStdErrSlope: TcaStatsFloat;
begin
Result := Sqrt(Divide(S2, FX.SumOfSquares));
end;
function TcaForcedOriginRegression.GetYIntercept: TcaStatsFloat;
begin
Result := 0;
end;
//----------------------------------------------------------------------------
// TcaInterceptRegression
//----------------------------------------------------------------------------
function TcaInterceptRegression.GetS2: TcaStatsFloat;
begin
Result := (Syy - (Sqr(Sxy) / Sxx)) / (N - 2);
end;
function TcaInterceptRegression.GetSlope: TcaStatsFloat;
begin
Result := Divide(Sxy, Sxx);
end;
function TcaInterceptRegression.GetStdErrSlope: TcaStatsFloat;
begin
Result := Sqrt(Divide(S2, Sxx));
end;
function TcaInterceptRegression.GetYIntercept: TcaStatsFloat;
begin
Result := FY.Avg - Slope * FX.Avg;
end;
end.
|
{
System of Linear Equations
Deletion Method O(N3)
Input:
M: Number of Equations
N: Number of Xs
Dij: 1<=i<=M 1<=j<=N Coefficient of Xj in Equation i
Di(n+1): Equation i's constant value
Output:
NoAnswer: System does not have unique answer
XFound[i]: Xi is unique
X[i]: Xi (has mean iff XFound[i])
XFounds: Number of unique Xs (== N => System has unique solution)
By Behdad
}
program
EquationsSystem;
const
MaxM = 100 + 2;
MaxN = 100 + 2;
Epsilon = 1E-6;
var
M, N : Integer;
D : array [1 .. MaxM, 1 .. MaxN + 1] of Real;
X : array [1 .. MaxN + 1] of Extended;
XFound : array [1 .. MaxN] of Boolean;
XFounds : Integer;
NoAnswer : Boolean;
function CheckZero (X : Real) : Real;
begin
if Abs(X) <= Epsilon then
CheckZero := 0
else
CheckZero := X;
end;
procedure IncreaseZeroCoefficients;
var
I, J, P, Q: Integer;
R: Real;
begin
for I := 1 to M do
begin
for J := 1 to N + 1 do
if not XFound[J] and (D[I, J] <> 0) then
Break;
if J <= N then
begin
for P := 1 to M do
if (P <> I) and (D[P, J] <> 0) then
begin
R := CheckZero(D[P, J] / D[I, J]);
if R <> 0 then
for Q := 1 to N + 1 do
if Q <> J then
D[P, Q] := CheckZero(D[P, Q] - (D[I, Q] * R));
D[P, J] := 0;
end;
XFound[J] := True;
end;
end;
end;
procedure ExtractUniques;
var
I, J, P, Q : Integer;
begin
for I := 1 to M do
begin
P := 0;
for J := 1 to N do
if (D[I, J] <> 0) then
begin
Inc(P);
Q := J;
end;
if (P = 0) and (D[I, N + 1] <> 0) then
begin
NoAnswer := True;
Exit;
end
else
if P = 1 then
begin
X[Q] := D[I, N + 1] / D[I, Q];
XFound[Q] := True;
Inc(XFounds);
end;
end;
end;
procedure SolveSystem;
begin
NoAnswer := False;
XFounds := 0;
FillChar(XFound, Sizeof(XFound), 0);
IncreaseZeroCoefficients;
FillChar(XFound, Sizeof(XFound), 0);
ExtractUniques;
end;
begin
SolveSystem;
end.
|
unit Test_FIToolkit.Logger.Utils;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework,
FIToolkit.Logger.Utils;
type
TestFIToolkitLoggerUtils = class (TGenericTestCase)
published
procedure TestInferLogMsgType;
end;
implementation
uses
FIToolkit.Logger.Types, FIToolkit.Logger.Consts;
{ TestFIToolkitLoggerUtils }
procedure TestFIToolkitLoggerUtils.TestInferLogMsgType;
begin
CheckEquals<TLogMsgType>(Low(TLogMsgType), InferLogMsgType(SEVERITY_NONE), 'SEVERITY_NONE -> Low(TLogMsgType)');
CheckEquals<TLogMsgType>(High(TLogMsgType), InferLogMsgType(SEVERITY_MAX), 'SEVERITY_MAX -> High(TLogMsgType)');
CheckEquals<TLogMsgType>(lmNone, InferLogMsgType(SEVERITY_NONE), 'SEVERITY_NONE -> lmNone');
CheckEquals<TLogMsgType>(lmDebug, InferLogMsgType(SEVERITY_DEBUG), 'SEVERITY_DEBUG -> lmDebug');
CheckEquals<TLogMsgType>(lmInfo, InferLogMsgType(SEVERITY_INFO), 'SEVERITY_INFO -> lmInfo');
CheckEquals<TLogMsgType>(lmWarning, InferLogMsgType(SEVERITY_WARNING), 'SEVERITY_WARNING -> lmWarning');
CheckEquals<TLogMsgType>(lmError, InferLogMsgType(SEVERITY_ERROR), 'SEVERITY_ERROR -> lmError');
CheckEquals<TLogMsgType>(lmFatal, InferLogMsgType(SEVERITY_FATAL), 'SEVERITY_FATAL -> lmFatal');
CheckEquals<TLogMsgType>(lmDebug, InferLogMsgType(SEVERITY_DEBUG + 1), 'SEVERITY_DEBUG + 1 -> lmDebug');
CheckEquals<TLogMsgType>(Pred(lmFatal), InferLogMsgType(SEVERITY_FATAL - 1), 'SEVERITY_FATAL - 1 -> Pred(lmFatal)');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestFIToolkitLoggerUtils.Suite);
end.
|
unit basefrm;
interface
uses Windows,SysUtils,Messages,Classes,Controls,Forms;
const
APP_MESSAGE = WM_USER+1;
msgWaitView = '∆дите! »дет загрузка данных ...';
//application event types
appCancel=0;
appLoading=1;
appRefresh=2;
appStatus=3;
appClear=4;
appChange=5;
appConfig=6;
appUser=7;
type
TAppAlert = record
id:integer;
time:TDateTime;
msg:string;
end;
TBaseFormClass = class of TBaseForm;
TBaseForm = class(TForm)
private
procedure AppMessage(var Message:TMessage); message APP_MESSAGE;
procedure WMTimer(var Message:TWMTimer); message WM_TIMER;
protected
State:set of (fsLock,fsCreate,fsInactive,fsRefresh);
DestroyTimerID:integer;
Key:string;
procedure CreateParams(var Params: TCreateParams); override;
function MessageBox(Text, Caption:PChar; Flags:Longint):Integer;
procedure DestroyTimeout(timeout:integer=0);
procedure DestroyCancel; virtual;
procedure appEvent(Sender:TObject; var Event:word; Data:pointer); virtual;
public
class function getKey:string;
class function load(ClassType:TBaseFormClass):TBaseForm;
class procedure appEventPost(Sender:TObject; Event:word; Data:pointer=nil);
class function appEventSend(Sender:TObject; Event:word; Data:pointer=nil):boolean;
class procedure msgStatus(const Value:string; id:integer=0);
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
end;
var
DisplayPanel:TWinControl;
DestroyTime:integer=0;
CurrentForm:TForm;
implementation
uses Config;
class function TBaseForm.getKey:string;
begin
result:='forms.'+ClassName;
end;
class procedure TBaseForm.AppEventPost(Sender:TObject; Event:word; Data:pointer=nil);
var
i:integer;
begin
with Application do for i:=ComponentCount-1 downto 0 do
if (Components[i] is TBaseForm) and (Components[i]<>Sender) then begin
PostMessage(TBaseForm(Components[i]).Handle,APP_MESSAGE,integer(Event),integer(Data));
end;
end;
class function TBaseForm.AppEventSend(Sender:TObject; Event:word; Data:pointer=nil):boolean;
var i:integer;
begin
Result:=true;
with Application do for i:=ComponentCount-1 downto 0 do
if (Components[i] is TBaseForm) and (Components[i]<>Sender) then try
TBaseForm(Components[i]).AppEvent(Sender,Event,Data);
if Event=appCancel then begin
Result:=false;
break;
end;
except
on E:Exception do begin
Application.ShowException(E);
Result:=false;
Break;
end;
end;
end;
class procedure TBaseForm.msgStatus(const value:string; id:integer=0);
var alert:TAppAlert;
begin
alert.id:=id;
alert.time:=now;
alert.msg:=value;
AppEventSend(nil,appStatus,@alert);
end;
class function TBaseForm.Load(ClassType:TBaseFormClass):TBaseForm;
var
notInPlace:boolean;
F:TForm;
i:integer;
begin
Result:=nil;
notInPlace:=(GetKeyState(VK_SHIFT) and $80<>0);
if not notInPlace and (CurrentForm<>nil) and (CurrentForm.ClassType=ClassType) then begin
result:=TBaseForm(CurrentForm);
Exit;
end;
if not notInPlace and (CurrentForm<>nil) and not CurrentForm.CloseQuery then Exit;
Application.ProcessMessages;
if ClassType<>nil then try
Screen.Cursor:=crHourGlass;
MsgStatus(MsgWaitView);
F:=nil;
for i:=0 to Application.ComponentCount-1 do if Application.Components[i] is ClassType then begin
if notInPlace then begin
if (fsInactive in TBaseForm(Application.Components[i]).State) then begin
F:=TBaseForm(Application.Components[i]);
break;
end;
end else begin
F:=TBaseForm(Application.Components[i]);
if not (fsInactive in TBaseForm(F).State) then break;
end;
end;
try
if F=nil then begin
Result:=ClassType.Create(Application);
end else begin
Result:=TBaseForm(F);
if notInPlace then with Result do begin
Result.DestroyCancel;
Parent:=nil;
BorderStyle:=bsSizeable;
Align:=alNone;
Position:=poDesigned;
CurrentConfig.readBounds(Key,Result);
end else begin
notInPlace:=(Result.Parent=nil) and not (fsInactive in Result.State);
Result.DestroyCancel;
end;
end;
if notInPlace then begin
if Result.WindowState=wsMinimized then Result.WindowState:=wsNormal;
end else with Result do begin
Parent:=DisplayPanel;
BorderStyle:=bsNone;
Position:=poDefault;
BoundsRect:=Rect(0,0,DisplayPanel.ClientWidth,DisplayPanel.ClientHeight);
Align:=alClient;
end;
Result.Show;
Result.SetFocus;
except
Result.Free;
raise;
end;
finally
Screen.Cursor:=crDefault;
MsgStatus('');
end;
if not notInPlace then begin
F:=CurrentForm;
CurrentForm:=Result;
if F<>nil then try
F.Close;
except
on E:Exception do Application.ShowException(E)
end;
end;
AppEventSend(Result,appRefresh,nil);
end;
constructor TBaseForm.Create(AOwner:TComponent);
begin
Key:=getKey;
DestroyTimerID:=$FFFF;
include(State,fsCreate);
inherited;
Name:='';
exclude(State,fsCreate);
CurrentConfig.readBounds(Key,self);
end;
destructor TBaseForm.Destroy;
begin
if CurrentForm=self then CurrentForm:=nil;
if Parent=nil then CurrentConfig.writeBounds(Key,self);
inherited;
end;
procedure TBaseForm.CreateParams(var Params: TCreateParams);
begin
inherited;
with Params do begin
//if Parent=nil then Params.WndParent:=0;
if (self<>Application.MainForm) and (Application.MainForm<>nil) then ExStyle:=ExStyle or WS_EX_APPWINDOW;
end;
end;
procedure TBaseForm.AppMessage(var Message:TMessage);
begin
AppEvent(nil,Message.WParamLo,pointer(Message.LParam));
end;
procedure TBaseForm.AppEvent(Sender:TObject; var Event:word; Data:pointer);
begin
case Event of
appClear: if CloseQuery then Destroy else Event:=appCancel;
end;
end;
function TBaseForm.MessageBox(Text, Caption:PChar; Flags:Longint):Integer;
begin
if Visible and not Focused then SetFocus;
Result:=Application.MessageBox(Text,Caption,Flags+MB_TOPMOST);
end;
procedure TBaseForm.DestroyTimeout(timeout:integer=0);
begin
if timeout=0 then timeout:=basefrm.DestroyTime;
SetTimer(Handle,DestroyTimerID,timeout*1000,nil);
Hide;
Include(State,fsInactive);
end;
procedure TBaseForm.DestroyCancel;
begin
KillTimer(Handle,DestroyTimerID);
Exclude(State,fsInactive);
end;
procedure TBaseForm.WMTimer(var Message:TWMTimer);
begin
inherited;
if Message.TimerID<>DestroyTimerID then exit;
KillTimer(Handle,DestroyTimerID);
Destroy;
end;
initialization
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.JSON;
/// <summary>
/// System.JSON implements a TJson class that offers several convenience methods:
/// - converting Objects to Json and vice versa
/// - formating Json </summary>
interface
{$SCOPEDENUMS ON}
uses
System.SysUtils, System.Rtti, System.TypInfo, System.Generics.Collections;
type
TJSONByteReader = class;
TJSONValue = class;
/// <summary> Base class for all JSON exception</summary>
EJSONException = class(Exception);
/// <summary> JSON exception generated by JSON path parser code</summary>
EJSONPathException = class(EJSONException);
/// <summary> JSON exception generated by JSON parser code</summary>
EJSONParseException = class(EJSONException)
private
FPath: string;
FOffset: Integer;
FLine, FPosition: Integer;
constructor Create(AOffset: Integer; ABr: TJSONByteReader; AValue: TJSONValue;
AIdent: PResStringRec; const AArgs: array of const); overload;
constructor Create(AOffset: Integer; ABr: TJSONByteReader; AValue: TJSONValue); overload;
public
property Path: string read FPath;
property Offset: Integer read FOffset;
property Line: Integer read FLine;
property Position: Integer read FPosition;
end;
/// <summary> Parses a JSON path with names and indexes.</summary>
/// <remarks>
/// The syntax to write paths is similar to XPath but in a Json way.
/// The following XPath expression:
/// /entities/urls[0]/indices[1]
/// would look like
/// entities.urls[0].indices[1] (dot notation)
/// or
/// entities["urls"][0]["indices"][1] (bracket notation)
///
/// The dot (.) token is used to access the object elements:
/// ex: object.key
///
/// The bracket ([]) token is used to access array or object elements:
/// In array: cities[0]
/// In object: city["name"] or city['name']
/// In object: ["city"]["name"] or ['city']['name']
///
/// The quote (" or ') is used to introduce a literal when the element is being written in bracket notation:
/// ex:["first"]["second"] or ['first']['second']
///
/// To escape the quote in a literal use backslash (\): \"
/// ex: ["quotes(\").should.be.escaped"] or ['quotes(\').should.be.escaped']
///
/// Note: The backslash will only escape quotes within a literal. Bracket notation can be useful when
/// names can not be written in dot notation, like the objects keys with dot characters:
/// ex: object["key.with.dots"] or object['key.with.dots']
///
/// </remarks>
TJSONPathParser = record
public type
TToken = (Undefined, Name, ArrayIndex, Eof, Error);
private
FPathPtr: PChar;
FPtr: PChar;
FEndPtr: PChar;
FTokenArrayIndex: Integer;
FTokenName: string;
FToken: TToken;
function GetIsEof: Boolean; inline;
procedure RaiseError(AMsg: PResStringRec);
procedure RaiseErrorFmt(AMsg: PResStringRec; const AParams: array of const);
procedure ParseName;
procedure ParseQuotedName(AQuote: Char);
procedure ParseArrayIndex;
procedure ParseIndexer;
function EnsureLength(ALength: Integer): Boolean; inline;
procedure FrontTrim(var APtr: PChar); inline;
procedure BackTrim(var APtr: PChar); inline;
public
constructor Create(const APath: string); overload;
constructor Create(const APathPtr: PChar; ALen: Integer); overload;
function NextToken: TToken;
property IsEof: Boolean read GetIsEof;
property Token: TToken read FToken;
property TokenName: string read FTokenName;
property TokenArrayIndex: Integer read FTokenArrayIndex;
end;
/// <summary> JSON top level class. All specific classes are descendant of it.</summary>
/// <remarks> All specific classes are descendant of it. More on JSON can be found on www.json.org </remarks>
TJSONAncestor = class abstract
private
/// <summary> True if the instance is own by the container</summary>
FOwned: Boolean;
protected
/// <summary> Returns true if the instance represent JSON null value </summary>
/// <returns>true if the instance represents JSON null value</returns>
function IsNull: Boolean; virtual;
/// <summary> Method used by parser to re-constitute the JSON object structure </summary>
/// <param name="descendent">descendant to be added</param>
procedure AddDescendant(const Descendent: TJSONAncestor); virtual;
procedure Format(Builder: TStringBuilder; const ParentIdent, Ident: string); overload; virtual;
public
/// <summary> Default constructor, sets owned flag to true </summary>
constructor Create;
/// <summary> Where appropriate, returns the instance representation as String </summary>
/// <returns>string representation, can be null</returns>
function Value: string; virtual;
/// <summary> Returns estimated byte size of current JSON object. The actual size is smaller</summary>
/// <remarks> The actual size is smaller</remarks>
/// <returns>integer - the byte size</returns>
function EstimatedByteSize: Integer; virtual; abstract;
/// <summary> Serializes the JSON object content into bytes. Returns the actual used size.
/// It assumes the byte container has sufficient capacity to store it. </summary>
/// <remarks> Returns the actual used size. It assumes the byte container has sufficient capacity to store it.
/// It is recommended that the container capacity is given by estimatedByteSize </remarks>
/// <param name="data">- byte container</param>
/// <param name="offset">- offset from which the object is serialized</param>
/// <returns>integer - the actual size used</returns>
function ToBytes(const Data: TArray<Byte>; Offset: Integer): Integer; virtual; abstract;
procedure ToChars(Builder: TStringBuilder); virtual; abstract;
function ToJSON: string;
function ToString: string; override;
function Format(Indentation: Integer = 4): string; overload;
/// <summary> Perform deep clone on current value</summary>
/// <returns>an exact copy of current instance</returns>
function Clone: TJSONAncestor; virtual; abstract;
/// <summary> Returns true if the instance represent JSON null value </summary>
/// <returns>true if the instance represents JSON null value</returns>
property Null: Boolean read IsNull;
property Owned: Boolean read FOwned write FOwned;
end;
/// <summary> Generalizes byte consumption of JSON parser. It accommodates UTF8, default it</summary>
/// <remarks> It accommodates UTF8, default it assumes the content is generated by JSON toBytes method. </remarks>
TJSONByteReader = class
private
FData: PByte;
FDataStart: PByte;
FDataEnd: PByte;
FIsUTF8: Boolean;
FUtf8data: TArray<Byte>;
FUtf8offset: Integer;
FUtf8length: Integer;
FStringCache: TDictionary<Cardinal, String>;
FCharData: TArray<Char>;
FCharPos: Integer;
FCharLen: Integer;
FCache: Boolean;
FLevel: Integer;
procedure Init(const Data: PByte; const Offset, Range: Integer);
function GetOffset: Integer; inline;
/// <summary> Consumes byte-order mark if any is present in the byte data </summary>
procedure ConsumeBOM;
procedure MoveOffset; inline;
procedure ProcessMBCS;
procedure EnterLevel; inline;
procedure ExitLevel; inline;
public
constructor Create(const Data: PByte; const Offset: Integer; const Range: Integer); overload;
constructor Create(const Data: PByte; const Offset: Integer; const Range: Integer; const IsUTF8: Boolean); overload;
destructor Destroy; override;
function ConsumeByte: Byte;
function PeekRawByte: Byte; inline;
function PeekByte: Byte;
procedure SkipByte; inline;
procedure SkipWhitespaces;
function IsEof: Boolean; inline;
function HasMore(const Size: Integer): Boolean;
procedure AddChar(Ch: Char);
procedure ResetString; inline;
procedure FlushString(var ADest: string; ACache: Boolean);
procedure OffsetToPos(AOffset: Integer; var ALine, APos: Integer);
property Offset: Integer read GetOffset;
end;
/// <summary> Groups string, number, object, array, true, false, null </summary>
TJSONValue = class abstract(TJSONAncestor)
private
function GetValueP(const APath: string): TJSONValue;
function GetValueA(const AIndex: Integer): TJSONValue; virtual;
protected
function AsTValue(ATypeInfo: PTypeInfo; var AValue: TValue): Boolean; virtual;
public
/// <summary>Finds a JSON value and returns reference to it. </summary>
/// <remarks> Returns nil when a JSON value could not be found. </remarks>
function FindValue(const APath: string): TJSONValue;
/// <summary>Converts a JSON value to a specified type. </summary>
/// <remarks> Returns False when the JSON value could not be converted. </remarks>
function TryGetValue<T>(out AValue: T): Boolean; overload;
/// <summary>Finds a JSON value and converts to a specified type. </summary>
/// <remarks> Returns False when a JSON value could not be found or could not be converted. </remarks>
function TryGetValue<T>(const APath: string; out AValue: T): Boolean; overload;
/// <summary>Finds a JSON value and converts to a specified type. </summary>
/// <remarks> Raises an exception when a JSON value could not be found or the JSON value could not be converted. </remarks>
function GetValue<T>(const APath: string = ''): T; overload;
/// <summary>Finds a JSON value if possible. If found, the JSON value is converted to a specified type.
/// If not found or if the JSON value is null, then returns a default value. </summary>
/// <remarks>Raises an exception when a JSON value is found but can't be converted. </remarks>
function GetValue<T>(const APath: string; ADefaultValue: T): T; overload;
/// <summary>Converts a JSON value to a specified type. </summary>
/// <remarks>Raises an exception when a JSON value can't be converted. </remarks>
function AsType<T>: T; overload;
/// <summary>Finds a JSON value and returns reference to it. </summary>
/// <remarks> Raises an exception when a JSON value could not be found. </remarks>
property P[const APath: string]: TJSONValue read GetValueP;{ default;}
property A[const AIndex: Integer]: TJSONValue read GetValueA;
end;
TJSONString = class(TJSONValue)
protected
FValue: string;
FIsNull: Boolean;
/// <summary> see com.borland.dbx.transport.JSONAncestor#isNull() </summary>
function IsNull: Boolean; override;
function AsTValue(ATypeInfo: PTypeInfo; var AValue: TValue): Boolean; override;
public
/// <summary> Constructor for null string. No further changes are supported. </summary>
/// <remarks> No further changes are supported. </remarks>
constructor Create; overload;
/// <summary> Constructor for a given string </summary>
/// <param name="value">String initial value, cannot be null</param>
constructor Create(const Value: string); overload;
/// <summary> Adds a character to current content </summary>
/// <param name="ch">char to be appended</param>
procedure AddChar(const Ch: Char);
function Equals(const Value: string): Boolean; reintroduce; inline;
/// <summary> see com.borland.dbx.transport.JSONAncestor#estimatedByteSize() </summary>
function EstimatedByteSize: Integer; override;
/// <summary> see com.borland.dbx.transport.JSONAncestor#toBytes(byte[], int) </summary>
function ToBytes(const Data: TArray<Byte>; Offset: Integer): Integer; override;
/// <summary> Returns the quoted string content. </summary>
procedure ToChars(Builder: TStringBuilder); override;
/// <summary> Returns the string content </summary>
function Value: string; override;
function Clone: TJSONAncestor; override;
end;
TJSONNumber = class sealed(TJSONString)
protected
/// <summary> Utility constructor with numerical argument represented as string </summary>
/// <param name="value">- string equivalent of a number</param>
constructor Create(const Value: string); overload;
/// <summary> Returns the double representation of the number </summary>
/// <returns>double</returns>
function GetAsDouble: Double;
/// <summary> Returns the integer part of the number </summary>
/// <returns>int</returns>
function GetAsInt: Integer;
/// <summary> Returns the int64 part of the number </summary>
/// <returns>int64</returns>
function GetAsInt64: Int64;
public
/// <summary> Constructor for a double number </summary>
/// <param name="value">double to be represented as JSONNumber</param>
constructor Create(const Value: Double); overload;
/// <summary> Constructor for integer </summary>
/// <param name="value">integer to be represented as JSONNumber</param>
constructor Create(const Value: Integer); overload;
/// <summary> Constructor for integer </summary>
/// <param name="value">integer to be represented as JSONNumber</param>
constructor Create(const Value: Int64); overload;
/// <seealso cref="TJSONString.estimatedByteSize()"/>
function EstimatedByteSize: Integer; override;
/// <summary> see com.borland.dbx.transport.JSONString#toBytes(byte[], int) </summary>
function ToBytes(const Data: TArray<Byte>; Offset: Integer): Integer; override;
/// <summary> Returns the non-localized string representation </summary>
procedure ToChars(Builder: TStringBuilder); override;
/// <summary> Returns the localized representation </summary>
function Value: string; override;
function Clone: TJSONAncestor; override;
/// <summary> Returns the double representation of the number </summary>
/// <returns>double</returns>
property AsDouble: Double read GetAsDouble;
/// <summary> Returns the integer part of the number </summary>
/// <returns>int</returns>
property AsInt: Integer read GetAsInt;
/// <summary> Returns the number as an int64 </summary>
/// <returns>int64</returns>
property AsInt64: Int64 read GetAsInt64;
end;
/// <summary> Implements JSON string : value </summary>
TJSONPair = class sealed(TJSONAncestor)
private
FJsonString: TJSONString;
FJsonValue: TJSONValue;
protected
/// <summary> see com.borland.dbx.transport.JSONAncestor#addDescendent(com.borland.dbx.transport.JSONAncestor) </summary>
procedure AddDescendant(const Descendant: TJSONAncestor); override;
/// <summary> Sets the pair's string value </summary>
/// <param name="descendant">string object cannot be null</param>
procedure SetJsonString(const Descendant: TJSONString);
/// <summary> Sets the pair's value member </summary>
/// <param name="val">string object cannot be null</param>
procedure SetJsonValue(const Val: TJSONValue);
function HasName(const Name: string): Boolean; inline;
public
/// <summary> Utility constructor providing pair members </summary>
/// <param name="str">- JSONString member, not null</param>
/// <param name="value">- JSONValue member, never null</param>
constructor Create(const Str: TJSONString; const Value: TJSONValue); overload;
/// <summary> Convenience constructor. Parameters will be converted into JSON equivalents</summary>
/// <remarks> Parameters will be converted into JSON equivalents </remarks>
/// <param name="str">- string member</param>
/// <param name="value">- JSON value</param>
constructor Create(const Str: string; const Value: TJSONValue); overload;
/// <summary> Convenience constructor. Parameters are converted into JSON strings pair </summary>
/// <remarks> Parameters are converted into JSON strings pair </remarks>
/// <param name="str">- string member</param>
/// <param name="value">- converted into a JSON string value</param>
constructor Create(const Str: string; const Value: string); overload;
/// <summary> Frees string and value</summary>
destructor Destroy; override;
/// <summary> see com.borland.dbx.transport.JSONAncestor#estimatedByteSize() </summary>
function EstimatedByteSize: Integer; override;
/// <summary> see com.borland.dbx.transport.JSONAncestor#toBytes(byte[], int) </summary>
function ToBytes(const Data: TArray<Byte>; Offset: Integer): Integer; override;
procedure ToChars(Builder: TStringBuilder); override;
function Clone: TJSONAncestor; override;
/// <summary> Returns the pair's string. </summary>
/// <returns>JSONString - pair's string</returns>
property JsonString: TJSONString read FJsonString write SetJsonString;
/// <summary> Returns the pair value. </summary>
/// <returns>JSONAncestor - pair's value</returns>
property JsonValue: TJSONValue read FJsonValue write SetJsonValue;
end;
/// <summary> JSON object represents {} or { members } </summary>
TJSONObject = class sealed(TJSONValue)
public type
/// <summary> JSON Parser Option </summary>
TJSONParseOption = (IsUTF8, UseBool, RaiseExc);
/// <summary>
/// JSON Parser Options
/// IsUTF8 - data should be treated as UTF8
/// UseBool - Parser should create a TJSONBool object for each instance of "true" or "false" seen in the JSON data
/// </summary>
TJSONParseOptions = set of TJSONParseOption;
/// <summary> Enumerator for JSON pairs </summary>
TEnumerator = class
private
FIndex: Integer;
FObject: TJSONObject;
public
constructor Create(const AObject: TJSONObject);
function GetCurrent: TJSONPair; inline;
function MoveNext: Boolean; inline;
property Current: TJSONPair read GetCurrent;
end;
private
FMembers: TList<TJSONPair>;
function Parse(const Br: TJSONByteReader; UseBool: Boolean): Integer; overload;
class function MakeParseOptions(IsUTF8, UseBool, RaiseExc: Boolean): TJSONObject.TJSONParseOptions; inline;
/// <summary> Consumes a JSON object </summary>
/// <param name="Br"> raw byte data</param>
/// <param name="Parent"> parent JSON entity</param>
/// <param name="UseBool"> create a TJSONBool for "true" or "false" seen
/// in the JSON data</param>
/// <returns>next offset</returns>
class function ParseObject(const Br: TJSONByteReader; const Parent: TJSONAncestor; UseBool: Boolean): Integer; static;
/// <summary> Consumes JSON pair string:value </summary>
/// <param name="Br">raw byte data</param>
/// <param name="Parent">parent JSON entity</param>
/// <param name="UseBool"> create a TJSONBool for "true" or "false" seen
/// in the JSON data</param>
/// <returns>next offset</returns>
class function ParsePair(const Br: TJSONByteReader; const Parent: TJSONObject; UseBool: Boolean): Integer; static;
/// <summary> Consumes JSON array [...] </summary>
/// <param name="Br"> raw byte data</param>
/// <param name="Parent"> parent JSON entity</param>
/// <param name="UseBool"> create a TJSONBool for "true" or "false" seen
/// in the JSON data</param>
/// <returns>next offset</returns>
class function ParseArray(const Br: TJSONByteReader; const Parent: TJSONAncestor; UseBool: Boolean): Integer; static;
/// <summary> Consumes JSON values: string, number, object, array, true, false, null </summary>
/// <param name="Br">raw byte data</param>
/// <param name="Parent">parent JSON entity</param>
/// <param name="UseBool"> create a TJSONBool for "true" or "false" seen
/// in the JSON data</param>
/// <returns>next offset</returns>
class function ParseValue(const Br: TJSONByteReader; const Parent: TJSONAncestor; UseBool: Boolean): Integer; static;
/// <summary> Consumes numbers: int | int frac | int exp | int frac exp </summary>
/// <param name="Br">raw byte data</param>
/// <param name="Parent">parent JSON entity</param>
/// <returns>next offset</returns>
class function ParseNumber(const Br: TJSONByteReader; const Parent: TJSONAncestor): Integer; static;
/// <summary> Consumes a JSON string "..." </summary>
/// <param name="Br">raw byte data</param>
/// <param name="Parent">parent JSON entity</param>
/// <returns>next offset</returns>
class function ParseString(const Br: TJSONByteReader; const Parent: TJSONAncestor): Integer; static;
protected
/// <summary> Adds a new member </summary>
/// <param name="Descendant">- JSON pair</param>
procedure AddDescendant(const Descendant: TJSONAncestor); override;
/// <summary> Returns the number of members in its content. May be zero </summary>
/// <remarks> May be zero </remarks>
/// <returns>number of members in its content</returns>
function GetCount: Integer; inline;
/// <summary> Returns the i-th pair</summary>
/// <param name="Index">- pair index</param>
/// <returns>the i-th pair</returns>
function GetPair(const Index: Integer): TJSONPair; inline;
/// <summary> Returns a JSON pair based on the pair string part.
/// The search is case sensitive and it returns the fist pair with string part matching the argument </summary>
/// <param name="pairName">- string: the pair string part</param>
/// <returns>- JSONPair : first pair encountered, null otherwise</returns>
function GetPairByName(const PairName: string): TJSONPair;
procedure Format(Builder: TStringBuilder; const ParentIdent, Ident: string); overload; override;
public
class function ParseJSONValue(const Data: PByte; const Offset: Integer; const ALength: Integer; Options: TJSONParseOptions): TJSONValue; overload; static;
/// <summary> Parses a byte array and returns the JSON value from it. </summary>
/// <remarks> Assumes buffer has only JSON pertinent data. </remarks>
/// <param name="Data">- byte array, not null</param>
/// <param name="Offset">- offset from which the parsing starts</param>
/// <param name="IsUTF8">- true if the Data should be treated as UTF-8. Optional, defaults to true</param>
/// <returns>JSONValue or nil if the parse fails</returns>
class function ParseJSONValue(const Data: TArray<Byte>; const Offset: Integer; IsUTF8: Boolean = True): TJSONValue; overload; inline; static;
/// <summary> Parses a byte array and returns the JSON value from it. </summary>
/// <remarks> Assumes buffer has only JSON pertinent data. </remarks>
/// <param name="Data">- byte array, not null</param>
/// <param name="Offset">- offset from which the parsing starts</param>
/// <param name="Options">- See TJSONParseOptions for correct values</param>
/// <returns>JSONValue or nil if the parse fails and RaiseExc option is not specified</returns>
class function ParseJSONValue(const Data: TArray<Byte>; const Offset: Integer; Options: TJSONParseOptions): TJSONValue; overload; inline; static;
/// <summary> Parses a byte array and returns the JSON value from it. </summary>
/// <param name="Data">- byte array, not null</param>
/// <param name="Offset">- offset from which the parsing starts</param>
/// <param name="ALength">- buffer capacity</param>
/// <param name="IsUTF8">- true if the Data should be treated as UTF-8. Optional, defaults to true</param>
/// <returns>JSONValue or nil if the parse fails</returns>
class function ParseJSONValue(const Data: TArray<Byte>; const Offset: Integer; const ALength: Integer; IsUTF8: Boolean = True): TJSONValue; overload; inline; static;
/// <summary> Parses a byte array and returns the JSON value from it. </summary>
/// <param name="Data">- byte array, not null</param>
/// <param name="Offset">- offset from which the parsing starts</param>
/// <param name="ALength">- buffer capacity</param>
/// <param name="Options">- See TJSONParseOptions for correct values</param>
/// <returns>JSONValue or nil if the parse fails and RaiseExc option is not specified</returns>
class function ParseJSONValue(const Data: TArray<Byte>; const Offset: Integer; const ALength: Integer; Options: TJSONParseOptions): TJSONValue; overload; inline; static;
/// <summary> Parses a string and returns the JSON value from it. </summary>
/// <param name="Data">- String to parse</param>
/// <param name="UseBool">- Create a TJSONBool for "true" or "false" seen in the JSON data</param>
/// <returns>JSONValue or nil if the parse fails and RaiseExc is False</returns>
class function ParseJSONValue(const Data: string; UseBool: Boolean = False; RaiseExc: Boolean = False): TJSONValue; overload; static;
{$IFNDEF NEXTGEN}
class function ParseJSONValue(const Data: UTF8String; UseBool: Boolean = False; RaiseExc: Boolean = False): TJSONValue; overload; static;
{$ENDIF !NEXTGEN}
class function ParseJSONFragment(const Data: PByte; var Offset: Integer; const ALength: Integer; Options: TJSONParseOptions): TJSONValue; overload; static;
class function ParseJSONFragment(const Data: TArray<Byte>; var Offset: Integer; Options: TJSONParseOptions): TJSONValue; overload; static;
class function ParseJSONFragment(const Data: string; var Offset: Integer; Options: TJSONParseOptions): TJSONValue; overload; static;
/// <summary> Default constructor, initializes the members container </summary>
constructor Create; overload;
/// <summary> Convenience constructor - builds an object around a given pair </summary>
/// <param name="Pair">first pair in the object definition, must not be null</param>
constructor Create(const Pair: TJSONPair); overload;
/// <summary> Returns an enumerator for pairs </summary>
/// <remarks> Allows JSONPairs to be accessed using a for-in loop. </remarks>
/// <returns>The enumerator</returns>
function GetEnumerator: TEnumerator; inline;
/// <summary> Returns a JSON pair value based on the pair string part. The search is case sensitive and it returns
/// the fist pair with string part matching the argument </summary>
/// <param name="Name">- string: the pair string part</param>
/// <returns>- JSONValue : value of the first pair encountered, null otherwise</returns>
function GetValue(const Name: string): TJSONValue; overload;
/// <summary> Releases the stored members </summary>
destructor Destroy; override;
/// <summary> Adds a new pair </summary>
/// <param name="Pair">- a new pair, cannot be null</param>
function AddPair(const Pair: TJSONPair): TJSONObject; overload;
/// <summary> Convenience method for adding a pair (name, value). </summary>
/// <param name="Str">- pair name</param>
/// <param name="Val">- pair value</param>
function AddPair(const Str: TJSONString; const Val: TJSONValue): TJSONObject; overload;
/// <summary> Convenience method for adding a pair to current object. </summary>
/// <param name="Str">- string: pair name</param>
/// <param name="Val">- JSONValue: pair value</param>
function AddPair(const Str: string; const Val: TJSONValue): TJSONObject; overload;
/// <summary> Convenience method for adding a pair to current object. </summary>
/// <param name="Str">- string: pair name</param>
/// <param name="Val">- string: pair value</param>
function AddPair(const Str: string; const Val: string): TJSONObject; overload;
function RemovePair(const PairName: string): TJSONPair;
/// <summary> Returns the number of bytes needed to serialize this object </summary>
function EstimatedByteSize: Integer; override;
/// <summary> see JSONAncestor#toBytes(byte[], int) </summary>
function ToBytes(const Data: TArray<Byte>; Offset: Integer): Integer; override;
procedure ToChars(Builder: TStringBuilder); override;
function Clone: TJSONAncestor; override;
/// <summary> Consumes a JSON object byte representation. </summary>
/// <remarks> It is recommended to use static function parseJSONValue, unless you are familiar
/// with parsing technology. It assumes the buffer has only JSON bytes. </remarks>
/// <param name="Data">byte[] with JSON stream</param>
/// <param name="Pos">position within the byte array to start from, negative number if
/// parser fails. If negative, the absolute value is the offset where the failure happens. </param>
/// <param name="UseBool"> create a TJSONBool for "true" or "false" seen
/// in the JSON data</param>
/// <returns>negative number on parse error, byte buffer length on success.</returns>
function Parse(const Data: TArray<Byte>; const Pos: Integer; UseBool: Boolean = False): Integer; overload;
/// <summary> Consumes a JSON object byte representation. </summary>
/// <remarks> It is recommended to use static function parseJSONValue, unless you are familiar
/// with parsing technology. </remarks>
/// <param name="Data">byte[] with JSON stream</param>
/// <param name="Pos">position within the byte array to start from</param>
/// <param name="Count">number of bytes</param>
/// <param name="UseBool"> create a TJSONBool for "true" or "false" seen
/// in the JSON data</param>
/// <returns>negative number on parse error</returns>
function Parse(const Data: TArray<Byte>; const Pos: Integer; const Count: Integer; UseBool: Boolean = False): Integer; overload;
procedure SetPairs(const AList: TList<TJSONPair>);
property Count: Integer read GetCount;
property Pairs[const Index: Integer]: TJSONPair read GetPair;
property Values[const Name: string]: TJSONValue read GetValue;
{ Deprecated functions }
function Size: Integer; inline; deprecated 'Use Count Property';
function Get(const Index: Integer): TJSONPair; overload; inline; deprecated 'Use Pairs property';
function Get(const Name: string): TJSONPair; overload; inline; // deprecated
{$IFNDEF NEXTGEN}
class function ParseJSONValueUTF8(const Data: TArray<Byte>; const Offset: Integer;
const ACount: Integer): TJSONValue; overload; static; deprecated 'Use ParseJSONValue';
class function ParseJSONValueUTF8(const Data: TArray<Byte>;
const Offset: Integer): TJSONValue; overload; static; deprecated 'Use ParseJSONValue';
{$ENDIF !NEXTGEN}
end;
TJSONPairEnumerator = class(TJSONObject.TEnumerator)
end deprecated 'Use TJSONObject.TEnumerator';
/// <summary> Implements JSON null value </summary>
TJSONNull = class sealed(TJSONValue)
strict protected const
NULLString: string = 'null';
protected
function AsTValue(ATypeInfo: PTypeInfo; var AValue: TValue): Boolean; override;
/// <summary> see com.borland.dbx.transport.JSONAncestor#isNull() </summary>
function IsNull: Boolean; override;
public
/// <summary> see com.borland.dbx.transport.JSONAncestor#estimatedByteSize() </summary>
function EstimatedByteSize: Integer; override;
/// <summary> see com.borland.dbx.transport.JSONAncestor#toBytes(byte[], int) </summary>
function ToBytes(const Data: TArray<Byte>; Offset: Integer): Integer; override;
procedure ToChars(Builder: TStringBuilder); override;
function Value: string; override;
function Clone: TJSONAncestor; override;
end;
/// <summary> Implements JSON Boolean type from which TJSONTrue and TJSONFalse derive </summary>
TJSONBool = class(TJSONValue)
private
FValue: Boolean;
strict protected const
FalseString: string = 'false';
TrueString: string = 'true';
FalseBytes: array[0..4] of Byte = (Ord('f'), Ord('a'), Ord('l'), Ord('s'), Ord('e'));
TrueBytes: array[0..3] of Byte = (Ord('t'), Ord('r'), Ord('u'), Ord('e'));
protected
function AsTValue(ATypeInfo: PTypeInfo; var AValue: TValue): Boolean; override;
public
constructor Create(AValue: Boolean);
/// <summary> see com.borland.dbx.transport.JSONAncestor#estimatedByteSize() </summary>
function EstimatedByteSize: Integer; override;
/// <summary> see com.borland.dbx.transport.JSONAncestor#toBytes(byte[], int) </summary>
function ToBytes(const Data: TArray<Byte>; Offset: Integer): Integer; override;
procedure ToChars(Builder: TStringBuilder); override;
function Value: string; override;
function Clone: TJSONAncestor; override;
property AsBoolean: Boolean read FValue;
end;
/// <summary> Implements JSON true value </summary>
TJSONTrue = class sealed(TJSONBool)
public
constructor Create;
function Clone: TJSONAncestor; override;
end;
/// <summary> Implements JSON false value </summary>
TJSONFalse = class sealed(TJSONBool)
public
constructor Create;
function Clone: TJSONAncestor; override;
end;
/// <summary> Implements JSON array [] | [ elements ] </summary>
TJSONArray = class sealed(TJSONValue)
public type
/// <summary> Support enumeration of values in a JSONArray. </summary>
TEnumerator = class
private
FIndex: Integer;
FArray: TJSONArray;
public
constructor Create(const AArray: TJSONArray);
function GetCurrent: TJSONValue; inline;
function MoveNext: Boolean; inline;
property Current: TJSONValue read GetCurrent;
end;
private
FElements: TList<TJSONValue>;
function GetValueA(const Index: Integer): TJSONValue; override;
protected
function AsTValue(ATypeInfo: PTypeInfo; var AValue: TValue): Boolean; override;
/// <summary> see com.borland.dbx.transport.JSONAncestor#addDescendent(com.borland.dbx.transport.JSONAncestor) </summary>
procedure AddDescendant(const Descendant: TJSONAncestor); override;
/// <summary> Removes the first element from the element list. </summary>
/// <remarks> No checks are made, it is the caller responsibility to check if there is at least one element. </remarks>
/// <returns>JSONValue</returns>
function Pop: TJSONValue; inline;
/// <summary> Returns the array component, null if index is out of range </summary>
/// <param name="Index">- element index</param>
/// <returns>JSONValue element, null if index is out of range</returns>
function GetValue(const Index: Integer): TJSONValue; overload; inline;
/// <summary> Returns the array size </summary>
/// <returns>int - array size</returns>
function GetCount: Integer; inline;
procedure Format(Builder: TStringBuilder; const ParentIdent, Ident: string); overload; override;
public
/// <summary> Default constructor, initializes the container </summary>
constructor Create; overload;
/// <summary> Convenience constructor, wraps an array around a JSON value </summary>
/// <param name="FirstElem">JSON value</param>
constructor Create(const FirstElem: TJSONValue); overload;
/// <summary> Convenience constructor, wraps an array around a JSON value </summary>
/// <param name="FirstElem">JSON value</param>
/// <param name="SecondElem">JSON value</param>
constructor Create(const FirstElem: TJSONValue; const SecondElem: TJSONValue); overload;
constructor Create(const FirstElem: string; const SecondElem: string); overload;
/// <summary> frees the container elements </summary>
destructor Destroy; override;
/// <summary> Returns the array size </summary>
/// <returns>int - array size</returns>
property Count: Integer read GetCount;
/// <summary> Returns the array component, null if index is out of range </summary>
/// <param name="Index">- element index</param>
/// <returns>JSONValue element, null if index is out of range</returns>
property Items[const Index: Integer]: TJSONValue read GetValue;
/// <summary>Removes the pair at the given index, returning the removed pair (or nil)</summary>
function Remove(Index: Integer): TJSONValue;
/// <summary> Adds a non-null value to the current element list </summary>
/// <param name="Element">string object cannot be null</param>
procedure AddElement(const Element: TJSONValue); inline;
function Add(const Element: string): TJSONArray; overload;
function Add(const Element: Integer): TJSONArray; overload;
function Add(const Element: Double): TJSONArray; overload;
function Add(const Element: Boolean): TJSONArray; overload;
function Add(const Element: TJSONObject): TJSONArray; overload;
function Add(const Element: TJSONArray): TJSONArray; overload;
/// <summary> see com.borland.dbx.transport.JSONAncestor#estimatedByteSize() </summary>
function EstimatedByteSize: Integer; override;
procedure SetElements(const AList: TList<TJSONValue>);
// / <seealso cref="TJSONAncestor.ToBytes(TArray<Byte>,Integer)"/>
function ToBytes(const Data: TArray<Byte>; Offset: Integer): Integer; override;
procedure ToChars(Builder: TStringBuilder); override;
function Clone: TJSONAncestor; override;
function GetEnumerator: TEnumerator; inline;
{ Deprecated functions }
function Size: Integer; inline; deprecated 'Use Count Property';
function Get(const Index: Integer): TJSONValue; inline; deprecated 'Use Items property';
end;
function GetJSONFormat: TFormatSettings;
function FloatToJson(const Value: Double): string;
function JsonToFloat(const DotValue: string): Double;
function TryJsonToFloat(const DotValue: string; var Value: Double): Boolean;
function HexToDecimal(const AHex: Byte): Byte; inline;
function DecimalToHex(const ADecimal: Byte): Byte; inline;
const
MaximumNestingLevel: Integer = 512;
DecimalToHexMap: string = '0123456789ABCDEF';
HexToDecimalMap: array[Byte] of Byte = (
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {00-0F}
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {10 0F}
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {20-2F}
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, {30-3F}
0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, {40-4F}
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {50-5F}
0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, {60-6F}
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {70-7F}
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {80-8F}
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {90-9F}
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {A0-AF}
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {B0-BF}
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {C0-CF}
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {D0-DF}
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {E0-EF}
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); {F0-FF}
implementation
uses
System.Classes, System.DateUtils, System.SysConst, System.JSONConsts;
var
JSONFormatSettings: TFormatSettings;
function GetJSONFormat: TFormatSettings;
begin
Result := JSONFormatSettings;
end;
function IncrAfter(var Arg: Integer): Integer; inline;
begin
Result := Arg;
Inc(Arg);
end;
function DecrAfter(var Arg: Integer): Integer; inline;
begin
Result := Arg;
Dec(Arg);
end;
function FloatToJson(const Value: Double): string;
begin
Result := FloatToStr(Value, JSONFormatSettings);
end;
function JsonToFloat(const DotValue: string): Double;
begin
Result := StrToFloat(DotValue, JSONFormatSettings);
end;
function TryJsonToFloat(const DotValue: string; var Value: Double): Boolean;
begin
Result := TryStrToFloat(DotValue, Value, JSONFormatSettings);
end;
{$R-}
function StrToTValue(const AStr: string; const ATypeInfo: PTypeInfo; var AValue: TValue): Boolean;
function CheckRange(const AMin, AMax: Int64; const AValue: Int64; const AStr: string): Int64;
begin
Result := AValue;
if (AValue < AMin) or (AValue > AMax) then
raise EConvertError.CreateResFmt(@SInvalidInteger, [AStr]);
end;
function IsBoolean: Boolean;
var
LTypeName: string;
begin
LTypeName := ATypeInfo.NameFld.ToString;
Result := SameText(LTypeName, 'boolean') or SameText(LTypeName, 'bool');
end;
var
LPtr: Pointer;
LValI32: Int32;
LValI64: Int64;
LValBool: Boolean;
LValSngl: Single;
LValDbl: Double;
LValExt: Extended;
LValComp: Comp;
LValCurr: Currency;
LValChr: Char;
LCode: Integer;
begin
Result := True;
LPtr := nil;
case ATypeInfo.Kind of
tkInteger:
begin
case GetTypeData(ATypeInfo)^.OrdType of
otSByte: LValI32 := CheckRange(Low(Int8), High(Int8), StrToInt(AStr), AStr);
otSWord: LValI32 := CheckRange(Low(Int16), High(Int16), StrToInt(AStr), AStr);
otSLong: LValI32 := StrToInt(AStr);
otUByte: LValI32 := CheckRange(Low(UInt8), High(UInt8), StrToInt(AStr), AStr);
otUWord: LValI32 := CheckRange(Low(UInt16), High(UInt16), StrToInt(AStr), AStr);
otULong: LValI32 := CheckRange(Low(UInt32), High(UInt32), StrToInt64(AStr), AStr);
end;
LPtr := @LValI32;
end;
tkInt64:
begin
if ATypeInfo^.TypeData^.MinInt64Value > ATypeInfo^.TypeData^.MaxInt64Value then
LValI64 := StrToUInt64(AStr)
else
LValI64 := StrToInt64(AStr);
LPtr := @LValI64;
end;
tkEnumeration:
if IsBoolean() then
begin
LValBool := StrToBool(AStr);
LPtr := @LValBool;
end
else
begin
LValI32 := GetEnumValue(ATypeInfo, AStr);
Result := LValI32 >= 0;
if not Result then
begin
Val(AStr, LValI32, LCode);
Result := LCode = 0;
end;
if Result then
LPtr := @LValI32;
end;
tkFloat:
case GetTypeData(ATypeInfo)^.FloatType of
ftSingle:
begin
LValSngl := StrToFloat(AStr, JSONFormatSettings);
LPtr := @LValSngl;
end;
ftDouble:
begin
if ATypeInfo = System.TypeInfo(TDate) then
LValDbl := ISO8601ToDate(AStr)
else if ATypeInfo = System.TypeInfo(TTime) then
LValDbl := ISO8601ToDate(AStr)
else if ATypeInfo = System.TypeInfo(TDateTime) then
LValDbl := ISO8601ToDate(AStr)
else
LValDbl := StrToFloat(AStr, JSONFormatSettings);
LPtr := @LValDbl;
end;
ftExtended:
begin
LValExt := StrToFloat(AStr, JSONFormatSettings);
LPtr := @LValExt;
end;
ftComp:
begin
LValComp := StrToFloat(AStr, JSONFormatSettings);
LPtr := @LValComp;
end;
ftCurr:
begin
LValCurr := StrToCurr(AStr, JSONFormatSettings);
LPtr := @LValCurr;
end;
end;
{$IFNDEF NEXTGEN}
tkChar,
{$ENDIF !NEXTGEN}
tkWChar:
begin
if AStr.Length = 1 then
begin
LValChr := AStr[Low(string)];
LPtr := @LValChr;
end
else
Result := False;
end;
tkString, tkLString, tkUString, tkWString:
LPtr := @AStr;
else
Result := False;
end;
if Result and (LPtr <> nil) then
TValue.Make(LPtr, ATypeInfo, AValue);
end;
{$R+}
function HexToDecimal(const AHex: Byte): Byte;
begin
Result := HexToDecimalMap[AHex];
end;
function DecimalToHex(const ADecimal: Byte): Byte;
begin
Result := Byte(DecimalToHexMap.Chars[ADecimal]);
end;
{ EJSONParseException }
constructor EJSONParseException.Create(AOffset: Integer; ABr: TJSONByteReader;
AValue: TJSONValue; AIdent: PResStringRec; const AArgs: array of const);
var
LPair: TJSONPair;
begin
FPath := '';
while AValue <> nil do
if (AValue.ClassType = TJSONArray) and (TJSONArray(AValue).Count > 0) then
begin
FPath := FPath + '[' + IntToStr(TJSONArray(AValue).Count - 1) + ']';
AValue := TJSONArray(AValue).Items[TJSONArray(AValue).Count - 1];
end
else if (AValue.ClassType = TJSONObject) and (TJSONObject(AValue).Count > 0) then
begin
LPair := TJSONObject(AValue).Pairs[TJSONObject(AValue).Count - 1];
if FPath <> '' then
FPath := FPath + '.';
if LPair.JsonString = nil then
FPath := FPath + '<null>'
else
FPath := FPath + LPair.JsonString.Value;
AValue := LPair.JsonValue;
end
else
AValue := nil;
if AOffset < 0 then
FOffset := - AOffset
else
FOffset := AOffset;
ABr.OffsetToPos(FOffset, FLine, FPosition);
Create(Format(LoadResString(AIdent), AArgs) +
Format(SJSONLocation, [FPath, FLine, FPosition, FOffset]));
end;
constructor EJSONParseException.Create(AOffset: Integer; ABr: TJSONByteReader;
AValue: TJSONValue);
begin
Create(AOffset, ABr, AValue, @SJSONSyntaxError, []);
end;
{ TJSONPathParser }
constructor TJSONPathParser.Create(const APathPtr: PChar; ALen: Integer);
begin
FPathPtr := APathPtr;
FPtr := FPathPtr;
FEndPtr := FPathPtr + ALen;
end;
constructor TJSONPathParser.Create(const APath: string);
begin
FPathPtr := PChar(APath);
FPtr := FPathPtr;
FEndPtr := FPathPtr + Length(APath);
end;
function TJSONPathParser.EnsureLength(ALength: Integer): Boolean;
begin
Result := (FPtr + ALength) < FEndPtr;
end;
function TJSONPathParser.GetIsEof: Boolean;
begin
Result := FPtr >= FEndPtr;
end;
procedure TJSONPathParser.FrontTrim(var APtr: PChar);
begin
while (APtr < FEndPtr) and (APtr^ <= ' ') do
Inc(APtr);
end;
procedure TJSONPathParser.BackTrim(var APtr: PChar);
begin
while (APtr > FPtr) and (APtr^ <= ' ') do
Dec(APtr);
end;
function TJSONPathParser.NextToken: TToken;
var
IsFirstToken: Boolean;
begin
IsFirstToken := FPtr = FPathPtr;
FrontTrim(FPtr);
if IsEof then
FToken := TToken.Eof
else
begin
case FPtr^ of
'.':
// Root element cannot start with a dot
if IsFirstToken then
RaiseError(@SJSONPathUnexpectedRootChar)
else
ParseName;
'[':
ParseIndexer;
else
// In dot notation all names are prefixed by '.', except the root element
if IsFirstToken then
ParseName
else
RaiseErrorFmt(@SJSONPathUnexpectedIndexedChar, [FPtr^]);
end;
Inc(FPtr);
end;
Result := FToken;
end;
procedure TJSONPathParser.ParseArrayIndex;
var
LPtr, LPtr2: PChar;
E: Integer;
begin
LPtr := StrScan(FPtr, ']');
if LPtr = nil then
RaiseError(@SJSONPathEndedOpenBracket);
LPtr2 := LPtr - 1;
BackTrim(LPtr2);
SetString(FTokenName, FPtr, LPtr2 - FPtr + 1);
FPtr := LPtr - 1;
Val(FTokenName, FTokenArrayIndex, E);
if E = 0 then
FToken := TToken.ArrayIndex
else
RaiseErrorFmt(@SJSONPathInvalidArrayIndex, [FTokenName]);
end;
procedure TJSONPathParser.ParseQuotedName(AQuote: Char);
var
LString: string;
begin
LString := '';
Inc(FPtr);
while not IsEof do
begin
if (FPtr^ = '\') and EnsureLength(1) and ((FPtr + 1)^ = AQuote) then // \"
begin
Inc(FPtr);
LString := LString + AQuote;
end
else if FPtr^ = AQuote then
begin
FToken := TToken.Name;
FTokenName := LString;
Exit;
end
else
LString := LString + FPtr^;
Inc(FPtr);
end;
RaiseError(@SJSONPathEndedOpenString);
end;
procedure TJSONPathParser.RaiseError(AMsg: PResStringRec);
begin
RaiseErrorFmt(AMsg, []);
end;
procedure TJSONPathParser.RaiseErrorFmt(AMsg: PResStringRec; const AParams: array of const);
begin
FToken := TToken.Error;
raise EJSONPathException.CreateResFmt(AMsg, AParams);
end;
procedure TJSONPathParser.ParseIndexer;
begin
Inc(FPtr); // [
FrontTrim(FPtr);
if IsEof then
RaiseError(@SJSONPathEndedOpenBracket);
case FPtr^ of
'"',
'''':
ParseQuotedName(FPtr^);
else
ParseArrayIndex;
end;
Inc(FPtr);
FrontTrim(FPtr);
if FPtr^ <> ']' then
RaiseErrorFmt(@SJSONPathUnexpectedIndexedChar, [FPtr^]);
end;
procedure TJSONPathParser.ParseName;
var
LPtr, LPtr2: PChar;
begin
if FPtr^ = '.' then
begin
Inc(FPtr);
if IsEof then
begin
FToken := TToken.Error;
Exit;
end;
end;
FrontTrim(FPtr);
LPtr := FPtr;
while (LPtr < FEndPtr) and not (Ord(LPtr^) in [Ord('.'), Ord('[')]) do
Inc(LPtr);
LPtr2 := LPtr - 1;
BackTrim(LPtr2);
SetString(FTokenName, FPtr, LPtr2 - FPtr + 1);
FPtr := LPtr - 1;
if FTokenName = '' then
RaiseError(@SJSONPathDotsEmptyName)
else
FToken := TToken.Name;
end;
{ TJSONAncestor }
constructor TJSONAncestor.Create;
begin
inherited Create;
FOwned := True;
end;
function TJSONAncestor.IsNull: Boolean;
begin
Result := False;
end;
function TJSONAncestor.Value: string;
begin
Result := '';
end;
procedure TJSONAncestor.AddDescendant(const Descendent: TJSONAncestor);
begin
raise EJSONException.CreateResFmt(@SCannotAddJSONValue,
[Descendent.ClassName, ClassName]);
end;
function TJSONAncestor.ToJSON: string;
var
LBytes: TBytes;
begin
SetLength(LBytes, EstimatedByteSize);
SetLength(LBytes, ToBytes(LBytes, 0));
Result := TEncoding.UTF8.GetString(LBytes);
end;
function TJSONAncestor.ToString: string;
var
Buf: TStringBuilder;
begin
Buf := TStringBuilder.Create(256);
try
ToChars(Buf);
Result := Buf.ToString(True);
finally
Buf.Free;
end;
end;
function TJSONAncestor.Format(Indentation: Integer): string;
var
Buf: TStringBuilder;
begin
Buf := TStringBuilder.Create(256);
try
Format(Buf, '', StringOfChar(' ', Indentation));
Result := Buf.ToString(True);
finally
Buf.Free;
end;
end;
procedure TJSONAncestor.Format(Builder: TStringBuilder; const ParentIdent, Ident: string);
begin
ToChars(Builder);
end;
{ TJSONByteReader }
procedure TJSONByteReader.Init(const Data: PByte; const Offset: Integer; const Range: Integer);
const
CInitialLen = $10;
begin
if (Data = nil) or (Offset < 0) or (Offset >= Range) then
begin
// next IsEof call will return True
FDataStart := Pointer(1);
FData := Pointer(1);
FDataEnd := nil;
end
else
begin
FDataStart := Data;
FData := Data + Offset;
FDataEnd := Data + Range - 1;
end;
FStringCache := TDictionary<Cardinal, String>.Create();
SetLength(FCharData, CInitialLen);
FCharLen := CInitialLen;
FCharPos := 0;
FCache := (Range - Offset) > 1000000;
end;
constructor TJSONByteReader.Create(const Data: PByte; const Offset: Integer; const Range: Integer);
begin
inherited Create;
Init(Data, Offset, Range);
ConsumeBOM;
end;
constructor TJSONByteReader.Create(const Data: PByte; const Offset: Integer; const Range: Integer; const IsUTF8: Boolean);
begin
inherited Create;
Init(Data, Offset, Range);
FIsUTF8 := IsUTF8;
if IsUTF8 then
ConsumeBOM;
end;
destructor TJSONByteReader.Destroy;
begin
FStringCache.Free;
inherited Destroy;
end;
function TJSONByteReader.GetOffset: Integer;
begin
Result := FData - FDataStart;
end;
procedure TJSONByteReader.ConsumeBOM;
begin
if FData + 2 <= FDataEnd then
begin
if (FData^ = Byte(239)) and ((FData + 1)^ = Byte(187)) and ((FData + 2)^ = Byte(191)) then
begin
FIsUTF8 := True;
Inc(FData, 3);
end;
end;
end;
procedure TJSONByteReader.MoveOffset;
begin
if FUtf8offset < FUtf8length then
Inc(FUtf8offset)
else
Inc(FData);
end;
function TJSONByteReader.ConsumeByte: Byte;
begin
Result := PeekByte;
MoveOffset;
end;
procedure TJSONByteReader.SkipByte;
begin
MoveOffset;
end;
procedure TJSONByteReader.ProcessMBCS;
var
Bmp: Int64;
W1: Integer;
W2: Integer;
begin
FUtf8offset := 0;
if (FData^ and Byte(224)) = Byte(192) then
begin
if FData + 1 > FDataEnd then
raise EJSONParseException.Create(Offset, Self, nil, @SUTF8Start, []);
if ((FData + 1)^ and Byte(192)) <> Byte(128) then
raise EJSONParseException.Create(Offset + 1, Self, nil, @SUTF8UnexpectedByte, [2]);
SetLength(FUtf8data, 6);
FUtf8length := 6;
FUtf8data[0] := Ord('\');
FUtf8data[1] := Ord('u');
FUtf8data[2] := DecimalToHex(0);
FUtf8data[3] := DecimalToHex((FData^ and Byte(28)) shr 2);
FUtf8data[4] := DecimalToHex((Byte(FData^ and Byte(3)) shl 2) or Byte(Byte((FData + 1)^ and Byte(48)) shr 4));
FUtf8data[5] := DecimalToHex((FData + 1)^ and Byte(15));
Inc(FData, 2);
end
else if (FData^ and Byte(240)) = Byte(224) then
begin
if FData + 2 > FDataEnd then
raise EJSONParseException.Create(Offset, Self, nil, @SUTF8Start, []);
if ((FData + 1)^ and Byte(192)) <> Byte(128) then
raise EJSONParseException.Create(Offset + 1, Self, nil, @SUTF8UnexpectedByte, [3]);
if ((FData + 2)^ and Byte(192)) <> Byte(128) then
raise EJSONParseException.Create(Offset + 2, Self, nil, @SUTF8UnexpectedByte, [3]);
SetLength(FUtf8data,6);
FUtf8length := 6;
FUtf8data[0] := Ord('\');
FUtf8data[1] := Ord('u');
FUtf8data[2] := DecimalToHex(FData^ and Byte(15));
FUtf8data[3] := DecimalToHex((Byte((FData + 1)^ and Byte(60))) shr 2);
FUtf8data[4] := DecimalToHex((Byte((FData + 1)^ and Byte(3)) shl 2) or Byte(Byte((FData + 2)^ and Byte(48)) shr 4));
FUtf8data[5] := DecimalToHex((FData + 2)^ and Byte(15));
Inc(FData, 3);
end
else if (FData^ and Byte(248)) = Byte(240) then
begin
if FData + 3 > FDataEnd then
raise EJSONParseException.Create(Offset, Self, nil, @SUTF8Start, []);
if ((FData + 1)^ and Byte(192)) <> Byte(128) then
raise EJSONParseException.Create(Offset + 1, Self, nil, @SUTF8UnexpectedByte, [4]);
if ((FData + 2)^ and Byte(192)) <> Byte(128) then
raise EJSONParseException.Create(Offset + 2, Self, nil, @SUTF8UnexpectedByte, [4]);
if ((FData + 3)^ and Byte(192)) <> Byte(128) then
raise EJSONParseException.Create(Offset + 3, Self, nil, @SUTF8UnexpectedByte, [4]);
Bmp := FData^ and Byte(7);
Bmp := (Bmp shl 6) or ((FData + 1)^ and Byte(63));
Bmp := (Bmp shl 6) or ((FData + 2)^ and Byte(63));
Bmp := (Bmp shl 6) or ((FData + 3)^ and Byte(63));
Bmp := Bmp - 65536;
W1 := 55296;
W1 := W1 or ((Integer((Bmp shr 10))) and 2047);
W2 := 56320;
W2 := W2 or Integer((Bmp and 2047));
SetLength(FUtf8data,12);
FUtf8length := 12;
FUtf8data[0] := Ord('\');
FUtf8data[1] := Ord('u');
FUtf8data[2] := DecimalToHex((W1 and 61440) shr 12);
FUtf8data[3] := DecimalToHex((W1 and 3840) shr 8);
FUtf8data[4] := DecimalToHex((W1 and 240) shr 4);
FUtf8data[5] := DecimalToHex(W1 and 15);
FUtf8data[6] := Ord('\');
FUtf8data[7] := Ord('u');
FUtf8data[8] := DecimalToHex((W2 and 61440) shr 12);
FUtf8data[9] := DecimalToHex((W2 and 3840) shr 8);
FUtf8data[10] := DecimalToHex((W2 and 240) shr 4);
FUtf8data[11] := DecimalToHex(W2 and 15);
Inc(FData, 4);
end
else
raise EJSONParseException.Create(Offset, Self, nil, @SUTF8InvalidHeaderByte, []);
end;
function TJSONByteReader.PeekRawByte: Byte;
begin
if not FIsUTF8 then
Exit(FData^);
if FUtf8offset < FUtf8length then
Exit(FUtf8data[FUtf8offset]);
Result := FData^;
end;
function TJSONByteReader.PeekByte: Byte;
begin
Result := PeekRawByte;
if (Result and Byte(128)) <> 0 then
begin
ProcessMBCS;
Result := FUtf8data[FUtf8offset];
end;
end;
function TJSONByteReader.IsEof: Boolean;
begin
Result := (FData > FDataEnd) and (FUtf8offset >= FUtf8length);
end;
procedure TJSONByteReader.SkipWhitespaces;
begin
while not IsEof and (PeekRawByte in [32, 9, 10, 13]) do
SkipByte;
end;
function TJSONByteReader.HasMore(const Size: Integer): Boolean;
begin
if FData + Size <= FDataEnd then
Result := True
else if FUtf8offset + Size <= FUtf8length then
Result := True
else
Result := False;
end;
procedure TJSONByteReader.AddChar(Ch: Char);
begin
if FCharPos = FCharLen then
begin
FCharLen := FCharLen * 2;
SetLength(FCharData, FCharLen);
end;
FCharData[FCharPos] := Ch;
Inc(FCharPos);
end;
procedure TJSONByteReader.ResetString;
begin
FCharPos := 0;
end;
procedure TJSONByteReader.FlushString(var ADest: string; ACache: Boolean);
function HashString(const s: string): Cardinal; inline;
var
P, PEnd: PChar;
begin
Result := Length(s);
P := Pointer(s);
PEnd := P + Result;
while P < PEnd do
begin
Result := (Result xor Ord(P^)) * 16777619;
Inc(P);
end;
end;
procedure CheckCache;
var
LCached: string;
LHash: Cardinal;
begin
LHash := HashString(ADest);
// NOTE: We have strings that produce the same hashes here,
// only the first benefits from cache (which is really an intern pool).
if FStringCache.ContainsKey(LHash) then
begin
LCached := FStringCache[LHash];
if LCached = ADest then
ADest := LCached;
end
else
FStringCache.Add(LHash, ADest);
end;
begin
SetString(ADest, PChar(FCharData), FCharPos);
ResetString;
if ACache and FCache then
CheckCache;
end;
procedure TJSONByteReader.OffsetToPos(AOffset: Integer; var ALine,
APos: Integer);
var
P: PByte;
I: Integer;
begin
P := FDataStart;
ALine := 1;
APos := 1;
while (P <= FDataEnd) and (AOffset > 0) do
begin
if (P^ and Byte(128)) = 0 then
begin
I := 1;
if (P^ = 13) or (P^ = 10) then
begin
Inc(ALine);
APos := 0;
if (((P + 1)^ = 13) or ((P + 1)^ = 10)) and ((P + 1)^ <> P^) then
Inc(I);
end;
end
else if (P^ and Byte(224)) = Byte(192) then
I := 2
else if (P^ and Byte(240)) = Byte(224) then
I := 3
else if (P^ and Byte(248)) = Byte(240) then
I := 4
else
I := 1;
Inc(P, I);
Dec(AOffset, I);
Inc(APos);
end;
end;
procedure TJSONByteReader.EnterLevel;
begin
if FLevel >= MaximumNestingLevel then
raise EJSONParseException.Create(Offset, Self, nil, @STooMuchNesting, [MaximumNestingLevel]);
Inc(FLevel);
end;
procedure TJSONByteReader.ExitLevel;
begin
Dec(FLevel);
end;
{ TJSONValue }
function TJSONValue.GetValue<T>(const APath: string; ADefaultValue: T): T;
var
LJSONValue: TJSONValue;
LTypeInfo: PTypeInfo;
begin
LJSONValue := FindValue(APath);
// Treat JSONNull as nil
if LJSONValue is TJSONNull then
begin
LTypeInfo := System.TypeInfo(T);
if LTypeInfo.TypeData.ClassType <> nil then
LJSONValue := nil;
end;
if LJSONValue <> nil then
Result := LJSONValue.AsType<T>
else
Result := ADefaultValue
end;
function TJSONValue.GetValueP(const APath: string): TJSONValue;
begin
Result := FindValue(APath);
if Result = nil then
raise EJSONException.CreateResFmt(@SValueNotFound, [APath]);
end;
function TJSONValue.GetValue<T>(const APath: string): T;
begin
Result := P[APath].AsType<T>;
end;
function TJSONValue.GetValueA(const AIndex: Integer): TJSONValue;
begin
Result := P['[' + AIndex.ToString + ']'];
end;
function TJSONValue.AsTValue(ATypeInfo: PTypeInfo; var AValue: TValue): Boolean;
begin
Result := True;
case ATypeInfo^.Kind of
tkClass:
TValue.Make(@Self, ATypeInfo, AValue);
else
Result := False;
end;
end;
function TJSONValue.AsType<T>: T;
var
LTypeInfo: PTypeInfo;
LValue: TValue;
begin
LTypeInfo := System.TypeInfo(T);
if not AsTValue(LTypeInfo, LValue) then
raise EJSONException.CreateResFmt(@SCannotConvertJSONValueToType,
[ClassName, LTypeInfo.Name]);
Result := LValue.AsType<T>;
end;
function TJSONValue.TryGetValue<T>(out AValue: T): Boolean;
begin
Result := TryGetValue<T>('', AValue);
end;
function TJSONValue.TryGetValue<T>(const APath: string; out AValue: T): Boolean;
var
LJSONValue: TJSONValue;
begin
LJSONValue := FindValue(APath);
Result := LJSONValue <> nil;
if Result then
try
AValue := LJSONValue.AsType<T>;
except
Result := False;
end;
end;
{ TJSONTrue }
constructor TJSONTrue.Create;
begin
inherited Create(True);
end;
function TJSONTrue.Clone: TJSONAncestor;
begin
Result := TJSONTrue.Create;
end;
{ TJSONString }
constructor TJSONString.Create;
begin
inherited Create;
FIsNull := True;
end;
constructor TJSONString.Create(const Value: string);
begin
inherited Create;
FValue := Value;
FIsNull := False;
end;
procedure TJSONString.AddChar(const Ch: Char);
begin
FValue := FValue + Ch;
FIsNull := False;
end;
function TJSONString.IsNull: Boolean;
begin
Result := FIsNull;
end;
function TJSONString.AsTValue(ATypeInfo: PTypeInfo; var AValue: TValue): Boolean;
begin
case ATypeInfo^.Kind of
tkInteger, tkInt64, tkFloat,
tkString, tkLString, tkWString, tkUString,
{$IFNDEF NEXTGEN}
tkChar,
{$ENDIF !NEXTGEN}
tkWChar,
tkEnumeration:
Result := StrToTValue(FValue, ATypeInfo, AValue)
else
Result := inherited;
end;
end;
function TJSONString.EstimatedByteSize: Integer;
begin
if FIsNull then
Result := 4
else
Result := 2 + 6 * System.Length(FValue);
end;
function TJSONString.ToBytes(const Data: TArray<Byte>; Offset: Integer): Integer;
var
CurrentChar: Char;
UnicodeValue: Integer;
begin
if FIsNull then
begin
Data[IncrAfter(Offset)] := Ord('n');
Data[IncrAfter(Offset)] := Ord('u');
Data[IncrAfter(Offset)] := Ord('l');
Data[IncrAfter(Offset)] := Ord('l');
end
else
begin
Data[IncrAfter(Offset)] := Ord('"');
for CurrentChar in FValue do
begin
case CurrentChar of
'"':
begin
Data[IncrAfter(Offset)] := Ord('\');
Data[IncrAfter(Offset)] := Ord('"');
end;
'\':
begin
Data[IncrAfter(Offset)] := Ord('\');
Data[IncrAfter(Offset)] := Ord('\');
end;
'/':
begin
Data[IncrAfter(Offset)] := Ord('\');
Data[IncrAfter(Offset)] := Ord('/');
end;
#$8:
begin
Data[IncrAfter(Offset)] := Ord('\');
Data[IncrAfter(Offset)] := Ord('b');
end;
#$c:
begin
Data[IncrAfter(Offset)] := Ord('\');
Data[IncrAfter(Offset)] := Ord('f');
end;
#$a:
begin
Data[IncrAfter(Offset)] := Ord('\');
Data[IncrAfter(Offset)] := Ord('n');
end;
#$d:
begin
Data[IncrAfter(Offset)] := Ord('\');
Data[IncrAfter(Offset)] := Ord('r');
end;
#$9:
begin
Data[IncrAfter(Offset)] := Ord('\');
Data[IncrAfter(Offset)] := Ord('t');
end;
else
if (CurrentChar >= Char(32)) and (CurrentChar <= Char(127)) then
Data[IncrAfter(Offset)] := Ord(CurrentChar)
else
begin
Data[IncrAfter(Offset)] := Ord('\');
Data[IncrAfter(Offset)] := Ord('u');
UnicodeValue := Ord(CurrentChar);
Data[IncrAfter(Offset)] := DecimalToHex((UnicodeValue and 61440) shr 12);
Data[IncrAfter(Offset)] := DecimalToHex((UnicodeValue and 3840) shr 8);
Data[IncrAfter(Offset)] := DecimalToHex((UnicodeValue and 240) shr 4);
Data[IncrAfter(Offset)] := DecimalToHex((UnicodeValue and 15));
end;
end;
end;
Data[IncrAfter(Offset)] := Ord('"');
end;
Result := Offset;
end;
procedure TJSONString.ToChars(Builder: TStringBuilder);
procedure AppendWithSpecialChars;
var
P, PEnd: PChar;
begin
P := Pointer(FValue);
PEnd := P + Length(FValue);
while P < PEnd do
begin
case P^ of
'"': Builder.Append('\"');
'\': Builder.Append('\\');
'/': Builder.Append('\/');
#$8: Builder.Append('\b');
#$c: Builder.Append('\f');
#$a: Builder.Append('\n');
#$d: Builder.Append('\r');
#$9: Builder.Append('\t');
else Builder.Append(P^);
end;
Inc(P);
end;
end;
{$WARNINGS OFF}
function ContainsSpecialChars: Boolean;
var
P, PEnd: PChar;
begin
P := Pointer(FValue);
PEnd := P + Length(FValue);
while P < PEnd do
begin
if P^ in ['"', '\', '/', #$8, #$c, #$a, #$d, #$9] then
Exit(True);
Inc(P);
end;
Result := False;
end;
{$WARNINGS ON}
begin
if not FIsNull then
begin
Builder.Append('"');
if ContainsSpecialChars then
AppendWithSpecialChars
else
Builder.Append(FValue);
Builder.Append('"');
end;
end;
function TJSONString.Value: string;
begin
Result := FValue;
end;
function TJSONString.Clone: TJSONAncestor;
begin
if FIsNull then
Result := TJSONString.Create
else
Result := TJSONString.Create(Value);
end;
function TJSONString.Equals(const Value: string): Boolean;
begin
Result := FValue = Value;
end;
{ TJSONNumber }
constructor TJSONNumber.Create(const Value: Double);
begin
inherited Create(FloatToJson(Value));
end;
constructor TJSONNumber.Create(const Value: string);
begin
inherited Create(Value);
end;
constructor TJSONNumber.Create(const Value: Int64);
begin
inherited Create(IntToStr(Value));
end;
constructor TJSONNumber.Create(const Value: Integer);
begin
inherited Create(IntToStr(Value));
end;
function TJSONNumber.EstimatedByteSize: Integer;
begin
Result := System.Length(FValue);
end;
function TJSONNumber.ToBytes(const Data: TArray<Byte>; Offset: Integer): Integer;
var
CurrentChar: Char;
begin
for CurrentChar in FValue do
Data[IncrAfter(Offset)] := Ord(CurrentChar);
Result := Offset;
end;
procedure TJSONNumber.ToChars(Builder: TStringBuilder);
begin
Builder.Append(FValue);
end;
function TJSONNumber.Value: string;
begin
if FIsNull then
Result := ''
else if (System.Length(FValue) > 11) and not FValue.Contains(JSONFormatSettings.DecimalSeparator) then
Result := IntToStr(GetAsInt64)
else
Result := FloatToStr(JsonToFloat(FValue));
end;
function TJSONNumber.Clone: TJSONAncestor;
begin
if FIsNull then
Result := TJSONNumber.Create
else
Result := TJSONNumber.Create(FValue);
end;
function TJSONNumber.GetAsDouble: Double;
begin
Result := JsonToFloat(FValue);
end;
function TJSONNumber.GetAsInt: Integer;
begin
Result := StrToInt(FValue);
end;
function TJSONNumber.GetAsInt64: Int64;
begin
Result := StrToInt64(FValue);
end;
{ TJSONPair }
constructor TJSONPair.Create(const Str: TJSONString; const Value: TJSONValue);
begin
inherited Create;
FJsonString := Str;
FJsonValue := Value;
end;
constructor TJSONPair.Create(const Str: string; const Value: TJSONValue);
begin
Create(TJSONString.Create(Str), Value);
end;
constructor TJSONPair.Create(const Str: string; const Value: string);
begin
Create(TJSONString.Create(Str), TJSONString.Create(Value));
end;
destructor TJSONPair.Destroy;
begin
if (FJsonString <> nil) and FJsonString.Owned then
FreeAndNil(FJsonString);
if (FJsonValue <> nil) and FJsonValue.Owned then
FreeAndNil(FJsonValue);
inherited Destroy;
end;
procedure TJSONPair.AddDescendant(const Descendant: TJSONAncestor);
begin
if FJsonString = nil then
FJsonString := TJSONString(Descendant)
else if FJsonValue = nil then
FJsonValue := TJSONValue(Descendant)
else
inherited AddDescendant(Descendant);
end;
procedure TJSONPair.SetJsonString(const Descendant: TJSONString);
begin
if Descendant <> nil then
begin
if (FJsonString <> nil) and FJsonString.Owned then
FreeAndNil(FJsonString);
FJsonString := Descendant;
end;
end;
procedure TJSONPair.SetJsonValue(const Val: TJSONValue);
begin
if Val <> nil then
begin
if (FJsonValue <> nil) and FJsonValue.Owned then
FreeAndNil(FJsonValue);
FJsonValue := Val;
end;
end;
function TJSONPair.EstimatedByteSize: Integer;
begin
Result := 1 + FJsonString.EstimatedByteSize + FJsonValue.EstimatedByteSize;
end;
function TJSONPair.ToBytes(const Data: TArray<Byte>; Offset: Integer): Integer;
begin
Offset := FJsonString.ToBytes(Data, Offset);
Data[IncrAfter(Offset)] := Ord(':');
Result := FJsonValue.ToBytes(Data, Offset);
end;
procedure TJSONPair.ToChars(Builder: TStringBuilder);
begin
if (FJsonString <> nil) and (FJsonValue <> nil) then
begin
FJsonString.ToChars(Builder);
Builder.Append(':');
FJsonValue.ToChars(Builder);
end;
end;
function TJSONPair.Clone: TJSONAncestor;
begin
Result := TJSONPair.Create(TJSONString(FJsonString.Clone), TJSONValue(FJsonValue.Clone));
end;
function TJSONPair.HasName(const Name: string): Boolean;
begin
Result := FJsonString.Equals(Name);
end;
{ TJSONObject }
class function TJSONObject.ParseJSONValue(const Data: PByte; const Offset: Integer;
const ALength: Integer; Options: TJSONParseOptions): TJSONValue;
var
Parent: TJSONArray;
Br: TJSONByteReader;
FinOff: Integer;
LExc: Boolean;
begin
Parent := TJSONArray.Create;
Result := nil;
LExc := False;
Br := TJSONByteReader.Create(Data, Offset, ALength, TJSONParseOption.IsUTF8 in Options);
try
try
Br.SkipWhitespaces;
FinOff := ParseValue(Br, Parent, TJSONParseOption.UseBool in Options);
except
on E: EJSONParseException do
if TJSONParseOption.RaiseExc in Options then
raise
else
begin
LExc := True;
FinOff := E.Offset;
end;
end;
if not LExc and (FinOff = ALength) and (Parent.Count = 1) then
Result := Parent.Pop
else if TJSONParseOption.RaiseExc in Options then
if Parent.Count >= 1 then
raise EJSONParseException.Create(FinOff, Br, Parent.Items[0])
else
raise EJSONParseException.Create(FinOff, Br, nil);
finally
Parent.Free;
Br.Free;
end;
end;
class function TJSONObject.ParseJSONValue(const Data: TArray<Byte>; const Offset: Integer;
const ALength: Integer; Options: TJSONParseOptions): TJSONValue;
begin
Result := ParseJSONValue(PByte(Data), Offset, ALength, Options);
end;
class function TJSONObject.MakeParseOptions(IsUTF8, UseBool, RaiseExc: Boolean): TJSONObject.TJSONParseOptions;
begin
Result := [];
if IsUTF8 then Include(Result, TJSONObject.TJSONParseOption.IsUTF8);
if UseBool then Include(Result, TJSONObject.TJSONParseOption.UseBool);
if RaiseExc then Include(Result, TJSONObject.TJSONParseOption.RaiseExc);
end;
class function TJSONObject.ParseJSONValue(const Data: TArray<Byte>; const Offset: Integer;
Options: TJSONParseOptions): TJSONValue;
begin
Result := ParseJSONValue(PByte(Data), Offset, Length(Data), Options);
end;
class function TJSONObject.ParseJSONValue(const Data: TArray<Byte>; const Offset: Integer;
IsUTF8: Boolean): TJSONValue;
begin
Result := ParseJSONValue(PByte(Data), Offset, Length(Data), MakeParseOptions(IsUTF8, False, False));
end;
class function TJSONObject.ParseJSONValue(const Data: TArray<Byte>; const Offset: Integer;
const ALength: Integer; IsUTF8: Boolean): TJSONValue;
begin
Result := ParseJSONValue(PByte(Data), Offset, ALength, MakeParseOptions(IsUTF8, False, False));
end;
class function TJSONObject.ParseJSONValue(const Data: string; UseBool, RaiseExc: Boolean): TJSONValue;
begin
Result := ParseJSONValue(TEncoding.UTF8.GetBytes(Data), 0, MakeParseOptions(True, UseBool, RaiseExc));
end;
{$IFNDEF NEXTGEN}
class function TJSONObject.ParseJSONValue(const Data: UTF8String; UseBool, RaiseExc: Boolean): TJSONValue;
begin
Result := ParseJSONValue(PByte(Data), 0, Length(Data), MakeParseOptions(True, UseBool, RaiseExc));
end;
class function TJSONObject.ParseJSONValueUTF8(const Data: TArray<Byte>; const Offset: Integer;
const ACount: Integer): TJSONValue;
begin
Result := ParseJSONValue(Data, Offset, ACount, MakeParseOptions(True, False, False));
end;
class function TJSONObject.ParseJSONValueUTF8(const Data: TArray<Byte>; const Offset: Integer): TJSONValue;
begin
Result := ParseJSONValue(PByte(Data), Offset, Length(Data), MakeParseOptions(True, False, False));
end;
{$ENDIF !NEXTGEN}
class function TJSONObject.ParseJSONFragment(const Data: PByte; var Offset: Integer;
const ALength: Integer; Options: TJSONParseOptions): TJSONValue;
var
Parent: TJSONArray;
Br: TJSONByteReader;
FinOff: Integer;
LExc: Boolean;
begin
Parent := TJSONArray.Create;
Result := nil;
LExc := False;
Br := TJSONByteReader.Create(Data, Offset, ALength, TJSONParseOption.IsUTF8 in Options);
try
try
Br.SkipWhitespaces;
FinOff := ParseValue(Br, Parent, TJSONParseOption.UseBool in Options);
except
on E: EJSONParseException do
if TJSONParseOption.RaiseExc in Options then
raise
else
begin
LExc := True;
FinOff := E.Offset;
end;
end;
if not LExc and (FinOff > Offset) and (Parent.Count = 1) then
begin
Offset := FinOff;
Result := Parent.Pop;
end
else if TJSONParseOption.RaiseExc in Options then
if Parent.Count >= 1 then
raise EJSONParseException.Create(FinOff, Br, Parent.Items[0])
else
raise EJSONParseException.Create(FinOff, Br, nil);
finally
Parent.Free;
Br.Free;
end;
end;
class function TJSONObject.ParseJSONFragment(const Data: TArray<Byte>; var Offset: Integer;
Options: TJSONParseOptions): TJSONValue;
begin
Result := ParseJSONFragment(PByte(Data), Offset, Length(Data), Options);
end;
class function TJSONObject.ParseJSONFragment(const Data: string; var Offset: Integer;
Options: TJSONParseOptions): TJSONValue;
begin
Result := ParseJSONFragment(TEncoding.UTF8.GetBytes(Data), Offset, Options +
[TJSONParseOption.IsUTF8]);
end;
constructor TJSONObject.Create;
begin
inherited Create;
FMembers := TList<TJSONPair>.Create;
end;
constructor TJSONObject.Create(const Pair: TJSONPair);
begin
Create;
if Pair <> nil then
FMembers.Add(Pair);
end;
procedure TJSONObject.SetPairs(const AList: TList<TJSONPair>);
begin
FMembers.Free;
FMembers := AList;
end;
function TJSONObject.GetCount: Integer;
begin
Result := FMembers.Count;
end;
function TJSONObject.GetPair(const Index: Integer): TJSONPair;
begin
Result := FMembers[Index];
end;
function TJSONObject.GetPairByName(const PairName: string): TJSONPair;
var
Candidate: TJSONPair;
I: Integer;
begin
for i := 0 to Count - 1 do
begin
Candidate := FMembers.List[I];
if Candidate.HasName(PairName) then
Exit(Candidate);
end;
Result := nil;
end;
function TJSONObject.Size: Integer;
begin
Result := GetCount;
end;
function TJSONObject.Get(const Index: Integer): TJSONPair;
begin
Result := Pairs[Index];
end;
function TJSONObject.Get(const Name: string): TJSONPair;
begin
Result := GetPairByName(Name);
end;
function TJSONObject.GetValue(const Name: string): TJSONValue;
var
Candidate: TJSONPair;
I: Integer;
begin
for i := 0 to Count - 1 do
begin
Candidate := FMembers.List[I];
if Candidate.HasName(Name) then
Exit(Candidate.JsonValue);
end;
Result := nil;
end;
destructor TJSONObject.Destroy;
var
Member: TJSONAncestor;
I: Integer;
begin
for i := 0 to FMembers.Count - 1 do
begin
Member := FMembers.List[I];
if Member.Owned then
Member.Free;
end;
FreeAndNil(FMembers);
inherited Destroy;
end;
function TJSONObject.AddPair(const Pair: TJSONPair): TJSONObject;
begin
if Pair <> nil then
AddDescendant(Pair);
Result := Self;
end;
function TJSONObject.AddPair(const Str: TJSONString; const Val: TJSONValue): TJSONObject;
begin
if (Str <> nil) and (Val <> nil) then
AddPair(TJSONPair.Create(Str, Val));
Result := Self;
end;
function TJSONObject.AddPair(const Str: string; const Val: TJSONValue): TJSONObject;
begin
if not Str.IsEmpty and (Val <> nil) then
AddPair(TJSONPair.Create(Str, Val));
Result := Self;
end;
function TJSONObject.AddPair(const Str: string; const Val: string): TJSONObject;
begin
if not Str.IsEmpty then
AddPair(TJSONPair.Create(Str, Val));
Result := Self;
end;
procedure TJSONObject.AddDescendant(const Descendant: TJSONAncestor);
begin
FMembers.Add(TJSONPair(Descendant));
end;
function TJSONObject.EstimatedByteSize: Integer;
var
I: Integer;
begin
Result := 1;
for i := 0 to FMembers.Count - 1 do
Inc(Result, FMembers.List[I].EstimatedByteSize + 1);
if Result = 1 then
Result := 2;
end;
function TJSONObject.ToBytes(const Data: TArray<Byte>; Offset: Integer): Integer;
var
Size: Integer;
I: Integer;
begin
Size := FMembers.Count;
Data[IncrAfter(Offset)] := Ord('{');
if Size > 0 then
Offset := FMembers.List[0].ToBytes(Data, Offset);
for i := 1 to Size - 1 do
begin
Data[IncrAfter(Offset)] := Ord(',');
Offset := FMembers.List[I].ToBytes(Data, Offset);
end;
Data[IncrAfter(Offset)] := Ord('}');
Result := Offset;
end;
procedure TJSONObject.ToChars(Builder: TStringBuilder);
var
Size: Integer;
I: Integer;
begin
Size := FMembers.Count;
Builder.Append('{');
if Size > 0 then
FMembers.List[0].ToChars(Builder);
for I := 1 to Size - 1 do
begin
Builder.Append(',');
FMembers.List[I].ToChars(Builder);
end;
Builder.Append('}');
end;
procedure TJSONObject.Format(Builder: TStringBuilder; const ParentIdent, Ident: string);
var
LIdent: string;
i: Integer;
begin
Builder.Append('{').Append(sLineBreak);
LIdent := ParentIdent + Ident;
for i := 0 to Count - 1 do
begin
Builder.Append(LIdent);
Pairs[i].JsonString.Format(Builder, '', Ident);
Builder.Append(': ');
Pairs[i].JsonValue.Format(Builder, LIdent, Ident);
if i < Count - 1 then
Builder.Append(',');
Builder.Append(sLineBreak);
end;
Builder.Append(ParentIdent).Append('}');
end;
function TJSONObject.Clone: TJSONAncestor;
var
Data: TJSONObject;
I: Integer;
begin
Data := TJSONObject.Create;
for I := 0 to FMembers.Count - 1 do
Data.AddPair(TJSONPair(Pairs[I].Clone));
Result := Data;
end;
function TJSONObject.Parse(const Data: TArray<Byte>; const Pos: Integer; UseBool: Boolean = False): Integer;
begin
Result := Parse(Data, Pos, Length(Data), UseBool);
end;
function TJSONObject.Parse(const Data: TArray<Byte>; const Pos: Integer; const Count: Integer; UseBool: Boolean = False): Integer;
var
Br: TJSONByteReader;
begin
if (Data = nil) or (Pos < 0) or (Pos >= Count) then
Exit(-1);
Br := TJSONByteReader.Create(PByte(Data), Pos, Count, True);
try
Result := Parse(Br, UseBool);
finally
Br.Free;
end;
end;
function TJSONObject.Parse(const Br: TJSONByteReader; UseBool: Boolean): Integer;
var
SepPos: Integer;
PairExpected: Boolean;
begin
Br.SkipWhitespaces;
if Br.IsEof then
Exit(-Br.Offset);
if Br.PeekByte <> Ord('{') then
Exit(-Br.Offset);
Br.SkipByte;
Br.SkipWhitespaces;
if Br.IsEof then
Exit(-Br.Offset);
PairExpected := False;
while PairExpected or (Br.PeekByte <> Ord('}')) do
begin
SepPos := ParsePair(Br, Self, UseBool);
if SepPos <= 0 then
Exit(SepPos);
Br.SkipWhitespaces;
if Br.IsEof then
Exit(-Br.Offset);
PairExpected := False;
if Br.PeekByte = Ord(',') then
begin
Br.SkipByte;
Br.SkipWhitespaces;
PairExpected := True;
if Br.PeekByte = Ord('}') then
Exit(-Br.Offset);
end
else if Br.PeekByte <> Ord('}') then
Exit(-Br.Offset);
end;
Br.SkipByte;
Br.SkipWhitespaces;
Result := Br.Offset;
end;
class function TJSONObject.ParseObject(const Br: TJSONByteReader; const Parent: TJSONAncestor; UseBool: Boolean): Integer;
var
JsonObj: TJSONObject;
begin
Br.EnterLevel;
JsonObj := TJSONObject.Create;
Parent.AddDescendant(JsonObj);
Result := JsonObj.Parse(Br, UseBool);
Br.ExitLevel;
end;
class function TJSONObject.ParsePair(const Br: TJSONByteReader; const Parent: TJSONObject; UseBool: Boolean): Integer;
var
Pair: TJSONPair;
CommaPos: Integer;
begin
Pair := TJSONPair.Create;
Parent.AddDescendant(Pair);
CommaPos := ParseString(Br, Pair);
if CommaPos > 0 then
begin
Br.SkipWhitespaces;
if Br.IsEof then
Exit(-Br.Offset);
if Br.PeekByte <> Ord(':') then
Exit(-Br.Offset);
Br.SkipByte;
Br.SkipWhitespaces;
CommaPos := ParseValue(Br, Pair, UseBool);
end;
Result := CommaPos;
end;
class function TJSONObject.ParseArray(const Br: TJSONByteReader; const Parent: TJSONAncestor; UseBool: Boolean): Integer;
var
ValueExpected: Boolean;
JsonArray: TJSONArray;
Pos: Integer;
begin
Br.SkipWhitespaces;
if Br.IsEof then
Exit(-Br.Offset);
if Br.PeekByte <> Ord('[') then
Exit(-Br.Offset);
Br.SkipByte;
Br.EnterLevel;
JsonArray := TJSONArray.Create;
Parent.AddDescendant(JsonArray);
ValueExpected := False;
Br.SkipWhitespaces;
while ValueExpected or (Br.PeekByte <> Ord(']')) do
begin
Br.SkipWhitespaces;
Pos := ParseValue(Br, JsonArray, UseBool);
if Pos <= 0 then
Exit(Pos);
Br.SkipWhitespaces;
if Br.IsEof then
Exit(-Br.Offset);
ValueExpected := False;
if Br.PeekByte = Ord(',') then
begin
Br.SkipByte;
ValueExpected := True;
end
else if Br.PeekByte <> Ord(']') then
Exit(-Br.Offset);
end;
Br.SkipByte;
Br.SkipWhitespaces;
Br.ExitLevel;
Result := Br.Offset;
end;
class function TJSONObject.ParseValue(const Br: TJSONByteReader; const Parent: TJSONAncestor; UseBool: Boolean): Integer;
var
Pos: Integer;
begin
Pos := Br.Offset;
if Br.IsEof then
Exit(-Pos);
case Br.PeekByte of
Ord('"'):
Exit(ParseString(Br, Parent));
Ord('-'),
Ord('0'),
Ord('1'),
Ord('2'),
Ord('3'),
Ord('4'),
Ord('5'),
Ord('6'),
Ord('7'),
Ord('8'),
Ord('9'):
Exit(ParseNumber(Br, Parent));
Ord('{'):
Exit(ParseObject(Br, Parent, UseBool));
Ord('['):
Exit(ParseArray(Br, Parent, UseBool));
Ord('t'):
begin
if not Br.HasMore(3) then
Exit(-Pos);
Br.SkipByte;
if (Br.ConsumeByte <> Ord('r')) or (Br.ConsumeByte <> Ord('u')) or (Br.ConsumeByte <> Ord('e')) then
Exit(-Pos);
if UseBool then
Parent.AddDescendant(TJSONBool.Create(True))
else
Parent.AddDescendant(TJSONTrue.Create);
Exit(Br.Offset);
end;
Ord('f'):
begin
if not Br.HasMore(4) then
Exit(-Pos);
Br.SkipByte;
if (Br.ConsumeByte <> Ord('a')) or (Br.ConsumeByte <> Ord('l')) or (Br.ConsumeByte <> Ord('s')) or (Br.ConsumeByte <> Ord('e')) then
Exit(-Pos);
if UseBool then
Parent.AddDescendant(TJSONBool.Create(False))
else
Parent.AddDescendant(TJSONFalse.Create);
Exit(Br.Offset);
end;
Ord('n'):
begin
if not Br.HasMore(3) then
Exit(-Pos);
Br.SkipByte;
if (Br.ConsumeByte <> Ord('u')) or (Br.ConsumeByte <> Ord('l')) or (Br.ConsumeByte <> Ord('l')) then
Exit(-Pos);
Parent.AddDescendant(TJSONNull.Create);
Exit(Br.Offset);
end;
end;
Result := -Pos;
end;
function TJSONObject.RemovePair(const PairName: string): TJSONPair;
var
Candidate: TJSONPair;
I: Integer;
begin
for I := 0 to Count - 1 do
begin
Candidate := TJSONPair(FMembers.List[I]);
if (Candidate.JsonString.Value = PairName) then
begin
FMembers.Remove(Candidate);
Exit(Candidate);
end;
end;
Result := nil;
end;
class function TJSONObject.ParseNumber(const Br: TJSONByteReader; const Parent: TJSONAncestor): Integer;
var
Nb: TJSONNumber;
Consume: Boolean;
Exponent: Boolean;
OneAdded: Boolean;
function FlushString(Br: TJSONByteReader; Nb: TJSONNumber): Integer; inline;
begin
Br.FlushString(Nb.FValue, False);
Result := Br.Offset;
end;
begin
Nb := TJSONNumber.Create('');
Parent.AddDescendant(Nb);
Br.ResetString;
if Br.PeekByte = Ord('-') then
begin
Br.AddChar('-');
Br.SkipByte;
if Br.IsEof or not (Br.PeekByte in [Ord('0') .. Ord('9'), Ord('e'), Ord('E')]) then
Exit(-Br.Offset);
end;
if Br.PeekByte = Ord('0') then
begin
Br.AddChar('0');
Br.SkipByte;
if Br.IsEof then
Exit(FlushString(Br, Nb));
if Br.PeekByte in [Ord('0') .. Ord('9')] then
Exit(-Br.Offset);
end;
Consume := True;
while Consume do
if Br.PeekByte in [Ord('0') .. Ord('9')] then
begin
Br.AddChar(Char(Br.ConsumeByte));
if Br.IsEof then
Exit(FlushString(Br, Nb));
end
else
Consume := False;
Exponent := False;
if Br.PeekByte = Ord(JSONFormatSettings.DecimalSeparator) then
begin
Br.AddChar(JSONFormatSettings.DecimalSeparator);
Br.SkipByte;
if Br.IsEof then
Exit(-Br.Offset);
end
else if (Br.PeekByte = Ord('e')) or (Br.PeekByte = Ord('E')) then
begin
Br.AddChar(Char(Br.ConsumeByte));
Exponent := True;
if Br.IsEof then
Exit(-Br.Offset);
if (Br.PeekByte = Ord('-')) or (Br.PeekByte = Ord('+')) then
begin
Br.AddChar(Char(Br.ConsumeByte));
if Br.IsEof then
Exit(-Br.Offset);
end;
end
else
Exit(FlushString(Br, Nb));
OneAdded := False;
Consume := True;
while Consume do
if Br.PeekByte in [Ord('0') .. Ord('9')] then
begin
Br.AddChar(Char(Br.ConsumeByte));
OneAdded := True;
if Br.IsEof then
Exit(FlushString(Br, Nb));
end
else
Consume := False;
if not OneAdded then
Exit(-Br.Offset);
if not Exponent and ((Br.PeekByte = Ord('e')) or (Br.PeekByte = Ord('E'))) then
begin
Br.AddChar(Char(Br.ConsumeByte));
if Br.IsEof then
Exit(-Br.Offset);
if (Br.PeekByte = Ord('-')) or (Br.PeekByte = Ord('+')) then
begin
Br.AddChar(Char(Br.ConsumeByte));
if Br.IsEof then
Exit(-Br.Offset);
end;
OneAdded := False;
Consume := True;
while Consume do
if Br.PeekByte in [Ord('0') .. Ord('9')] then
begin
Br.AddChar(Char(Br.ConsumeByte));
OneAdded := True;
if Br.IsEof then
Exit(FlushString(Br, Nb));
end
else
Consume := False;
if not OneAdded then
Exit(-Br.Offset);
end;
Result := FlushString(Br, Nb);
end;
class function TJSONObject.ParseString(const Br: TJSONByteReader; const Parent: TJSONAncestor): Integer;
var
UnicodeCh: Integer;
Ch: Char;
Str: TJSONString;
B: Byte;
i: Integer;
begin
if Br.PeekByte <> Ord('"') then
Exit(-Br.Offset);
Br.SkipByte;
if Br.IsEof then
Exit(-Br.Offset);
Str := TJSONString.Create('');
Parent.AddDescendant(Str);
Br.ResetString;
while True do
begin
B := Br.PeekByte;
case B of
Ord('"'):
Break;
Ord('\'):
begin
Br.SkipByte;
if Br.IsEof then
Exit(-Br.Offset);
case Br.PeekRawByte of
Ord('"'):
Ch := '"';
Ord('\'):
Ch := '\';
Ord('/'):
Ch := '/';
Ord('b'):
Ch := #$8;
Ord('f'):
Ch := #$c;
Ord('n'):
Ch := #$a;
Ord('r'):
Ch := #$d;
Ord('t'):
Ch := #$9;
Ord('u'):
begin
Br.SkipByte;
if not Br.HasMore(4) then
Exit(-Br.Offset);
i := 12;
UnicodeCh := 0;
while True do
begin
B := Br.PeekRawByte;
if not (B in [Ord('0') .. Ord('9'), Ord('a') .. Ord('f'), Ord('A') .. Ord('F')]) then
Exit(-Br.Offset);
UnicodeCh := UnicodeCh or HexToDecimal(B) shl i;
Dec(i, 4);
if i < 0 then
Break;
Br.SkipByte;
end;
Ch := Char(UnicodeCh);
end;
else
Exit(-Br.Offset);
end;
end;
else
Ch := Char(B);
end;
Br.AddChar(Ch);
Br.SkipByte;
if Br.IsEof then
Exit(-Br.Offset);
end;
Br.SkipByte;
Br.FlushString(Str.FValue, Br.FCache and (Parent.ClassType = TJSONPair) and (TJSONPair(Parent).JsonValue = nil));
Result := Br.Offset;
end;
{ TEnumerator }
constructor TJSONObject.TEnumerator.Create(const AObject: TJSONObject);
begin
inherited Create;
FIndex := -1;
FObject := AObject;
end;
function TJSONObject.TEnumerator.GetCurrent: TJSONPair;
begin
Result := FObject.FMembers.List[FIndex];
end;
function TJSONObject.TEnumerator.MoveNext: Boolean;
begin
Inc(FIndex);
Result := FIndex < FObject.Count;
end;
function TJSONObject.GetEnumerator: TEnumerator;
begin
Result := TEnumerator.Create(Self);
end;
{ TJSONNull }
function TJSONNull.AsTValue(ATypeInfo: PTypeInfo; var AValue: TValue): Boolean;
begin
Result := True;
case ATypeInfo^.Kind of
tkString, tkLString, tkUString, TkWString:
AValue := '';
else
Result := inherited;
end;
end;
function TJSONNull.IsNull: Boolean;
begin
Result := True;
end;
function TJSONNull.EstimatedByteSize: Integer;
begin
Result := 4;
end;
function TJSONNull.ToBytes(const Data: TArray<Byte>; Offset: Integer): Integer;
begin
Data[IncrAfter(Offset)] := Ord('n');
Data[IncrAfter(Offset)] := Ord('u');
Data[IncrAfter(Offset)] := Ord('l');
Data[IncrAfter(Offset)] := Ord('l');
Result := Offset;
end;
procedure TJSONNull.ToChars(Builder: TStringBuilder);
begin
Builder.Append(NULLString);
end;
function TJSONNull.Value: string;
begin
Result := NULLString;
end;
function TJSONNull.Clone: TJSONAncestor;
begin
Result := TJSONNull.Create;
end;
{ TJSONFalse }
constructor TJSONFalse.Create;
begin
inherited Create(False);
end;
function TJSONFalse.Clone: TJSONAncestor;
begin
Result := TJSONFalse.Create;
end;
{ TJSONArray }
constructor TJSONArray.Create;
begin
inherited Create;
FElements := TList<TJSONValue>.Create;
end;
procedure TJSONArray.AddElement(const Element: TJSONValue);
begin
AddDescendant(Element);
end;
constructor TJSONArray.Create(const FirstElem: TJSONValue);
begin
Create;
AddElement(FirstElem);
end;
constructor TJSONArray.Create(const FirstElem: TJSONValue; const SecondElem: TJSONValue);
begin
Create;
AddElement(FirstElem);
AddElement(SecondElem);
end;
constructor TJSONArray.Create(const FirstElem: string; const SecondElem: string);
begin
Create;
AddElement(TJSONString.Create(FirstElem));
AddElement(TJSONString.Create(SecondElem));
end;
destructor TJSONArray.Destroy;
var
Element: TJSONAncestor;
I: Integer;
begin
for I := 0 to FElements.Count - 1 do
begin
Element := FElements[I];
if Element.Owned then
Element.Free;
end;
FreeAndNil(FElements);
inherited Destroy;
end;
procedure TJSONArray.SetElements(const AList: TList<TJSONValue>);
begin
FElements.Free;
FElements := AList;
end;
function TJSONArray.GetCount: Integer;
begin
Result := FElements.Count;
end;
function TJSONArray.GetValue(const Index: Integer): TJSONValue;
begin
Result := FElements[Index];
end;
function TJSONArray.GetValueA(const Index: Integer): TJSONValue;
begin
Result := GetValue(Index);
end;
function TJSONArray.Size: Integer;
begin
Result := GetCount;
end;
function TJSONArray.Get(const Index: Integer): TJSONValue;
begin
Result := Items[Index];
end;
procedure TJSONArray.AddDescendant(const Descendant: TJSONAncestor);
begin
FElements.Add(TJSONValue(Descendant));
end;
function TJSONArray.Pop: TJSONValue;
begin
Result := Remove(0);
end;
function TJSONArray.Remove(Index: Integer): TJSONValue;
begin
Result := FElements.ExtractAt(Index);
end;
function TJSONArray.Add(const Element: string): TJSONArray;
begin
AddElement(TJSONString.Create(Element));
Result := Self;
end;
function TJSONArray.Add(const Element: Integer): TJSONArray;
begin
AddElement(TJSONNumber.Create(Element));
Result := Self;
end;
function TJSONArray.Add(const Element: Double): TJSONArray;
begin
AddElement(TJSONNumber.Create(Element));
Result := Self;
end;
function TJSONArray.Add(const Element: Boolean): TJSONArray;
begin
if Element then
AddElement(TJSONTrue.Create)
else
AddElement(TJSONFalse.Create);
Result := Self;
end;
function TJSONArray.Add(const Element: TJSONObject): TJSONArray;
begin
if Element <> nil then
AddElement(Element)
else
AddElement(TJSONNull.Create);
Result := Self;
end;
function TJSONArray.Add(const Element: TJSONArray): TJSONArray;
begin
AddElement(Element);
Result := Self;
end;
function TJSONArray.EstimatedByteSize: Integer;
var
I: Integer;
begin
Result := 1;
for I := 0 to FElements.Count - 1 do
Inc(Result, FElements[I].EstimatedByteSize + 1);
if Result = 1 then
Result := 2;
end;
function TJSONArray.ToBytes(const Data: TArray<Byte>; Offset: Integer): Integer;
var
Size: Integer;
I: Integer;
begin
Size := FElements.Count;
Data[IncrAfter(Offset)] := Ord('[');
if Size > 0 then
Offset := FElements[0].ToBytes(Data, Offset);
for I := 1 to Size - 1 do
begin
Data[IncrAfter(Offset)] := Ord(',');
Offset := FElements[I].ToBytes(Data, Offset);
end;
Data[IncrAfter(Offset)] := Ord(']');
Result := Offset;
end;
procedure TJSONArray.ToChars(Builder: TStringBuilder);
var
Size: Integer;
I: Integer;
begin
Size := FElements.Count;
Builder.Append('[');
if Size > 0 then
FElements[0].ToChars(Builder);
for I := 1 to Size - 1 do
begin
Builder.Append(',');
FElements[i].ToChars(Builder);
end;
Builder.Append(']');
end;
procedure TJSONArray.Format(Builder: TStringBuilder; const ParentIdent, Ident: string);
var
LIdent: string;
i: Integer;
begin
Builder.Append('[').Append(sLineBreak);
LIdent := ParentIdent + Ident;
for i := 0 to Count - 1 do
begin
Builder.Append(LIdent);
Items[i].Format(Builder, LIdent, Ident);
if i < Count - 1 then
Builder.Append(',');
Builder.Append(sLineBreak);
end;
Builder.Append(ParentIdent).Append(']');
end;
function TJSONArray.Clone: TJSONAncestor;
var
Data: TJSONArray;
I: Integer;
begin
Data := TJSONArray.Create;
for I := 0 to Count - 1 do
Data.AddDescendant(Items[I].Clone);
Result := Data;
end;
function TJSONArray.AsTValue(ATypeInfo: PTypeInfo; var AValue: TValue): Boolean;
var
LSet, I: Integer;
LpEnumInfo: PPTypeInfo;
LPtr, LArr: Pointer;
LDims: array[0..0] of NativeInt;
LVal: TValue;
LpItem: PByte;
LItemInfo: PTypeInfo;
LItemSize: Integer;
begin
Result := True;
LPtr := nil;
LArr := nil;
try
case ATypeInfo^.Kind of
tkSet:
begin
LSet := 0;
LpEnumInfo := GetTypeData(ATypeInfo)^.CompType;
if LpEnumInfo = nil then
LItemInfo := System.TypeInfo(Integer)
else
LItemInfo := LpEnumInfo^;
for I := 0 to Count - 1 do
begin
if not Items[I].AsTValue(LItemInfo, LVal) then
Exit(False);
Include(TIntegerSet(LSet), LVal.AsOrdinal);
end;
LPtr := @LSet;
end;
tkDynArray:
begin
LDims[0] := Count;
DynArraySetLength(LArr, ATypeInfo, 1, @LDims[0]);
LItemInfo := ATypeInfo^.TypeData^.elType2^;
LItemSize := ATypeInfo^.TypeData^.elSize;
LpItem := LArr;
for I := 0 to Count - 1 do
begin
if not Items[I].AsTValue(LItemInfo, LVal) then
Exit(False);
LVal.ExtractRawData(LpItem);
LpItem := LpItem + LItemSize;
end;
LPtr := @LArr;
end;
tkArray:
begin
if ATypeInfo^.TypeData^.ArrayData.ElCount <> Count then
Exit(False);
GetMem(LArr, ATypeInfo^.TypeData^.ArrayData.Size);
if IsManaged(ATypeInfo) then
InitializeArray(LArr, ATypeInfo, Count);
LItemInfo := ATypeInfo^.TypeData^.ArrayData.ElType^;
LItemSize := ATypeInfo^.TypeData^.ArrayData.Size div ATypeInfo^.TypeData^.ArrayData.ElCount;
LpItem := LArr;
for I := 0 to Count - 1 do
begin
if not Items[I].AsTValue(LItemInfo, LVal) then
Exit(False);
LVal.ExtractRawData(LpItem);
LpItem := LpItem + LItemSize;
end;
LPtr := LArr;
end;
else
Result := inherited;
end;
if Result and (LPtr <> nil) then
TValue.MakeWithoutCopy(LPtr, ATypeInfo, AValue, False);
finally
if LArr <> nil then
case ATypeInfo^.Kind of
tkDynArray:
if LPtr = nil then
DynArrayClear(LArr, ATypeInfo);
tkArray:
begin
if (LPtr = nil) and IsManaged(ATypeInfo) then
FinalizeArray(LArr, ATypeInfo, Count);
FreeMem(LArr);
end;
end;
end;
end;
{ TEnumerator }
constructor TJSONArray.TEnumerator.Create(const AArray: TJSONArray);
begin
inherited Create;
FIndex := -1;
FArray := AArray;
end;
function TJSONArray.TEnumerator.GetCurrent: TJSONValue;
begin
Result := FArray.FElements.List[FIndex];
end;
function TJSONArray.TEnumerator.MoveNext: Boolean;
begin
Inc(FIndex);
Result := FIndex < FArray.Count;
end;
function TJSONArray.GetEnumerator: TEnumerator;
begin
Result := TEnumerator.Create(Self);
end;
{ TJSONBool }
function TJSONBool.AsTValue(ATypeInfo: PTypeInfo; var AValue: TValue): Boolean;
begin
Result := True;
case ATypeInfo^.Kind of
tkEnumeration:
Result := StrToTValue(Value, ATypeInfo, AValue);
tkInteger, tkInt64, tkFloat:
if FValue then
AValue := 1
else
AValue := 0;
tkString, tkLString, tkWString, tkUString:
AValue := Value;
else
Result := inherited;
end;
end;
function TJSONBool.Clone: TJSONAncestor;
begin
Result := TJSONBool.Create(FValue);
end;
constructor TJSONBool.Create(AValue: Boolean);
begin
inherited Create;
FValue := AValue;
end;
function TJSONBool.EstimatedByteSize: Integer;
begin
if FValue then
Result := Length(TrueBytes)
else
Result := Length(FalseBytes);
end;
function TJSONBool.ToBytes(const Data: TArray<Byte>; Offset: Integer): Integer;
begin
if FValue then
begin
Move(TrueBytes[0], Data[Offset], Length(TrueBytes));
Result := Offset + Length(TrueBytes);
end
else
begin
Move(FalseBytes[0], Data[Offset], Length(FalseBytes));
Result := Offset + Length(FalseBytes);
end;
end;
procedure TJSONBool.ToChars(Builder: TStringBuilder);
begin
Builder.Append(Value);
end;
function TJSONBool.Value: string;
begin
if FValue then
Result := TrueString
else
Result := FalseString;
end;
// Moved here after all referenced inline methods
function TJSONValue.FindValue(const APath: string): TJSONValue;
var
LParser: TJSONPathParser;
LCurrentValue: TJSONValue;
begin
if (Self = nil) or (APath = '') then
Exit(Self);
Result := nil;
LParser := TJSONPathParser.Create(APath);
LCurrentValue := Self;
while not LParser.IsEof do
begin
case LParser.NextToken of
TJSONPathParser.TToken.Name:
if LCurrentValue.ClassType = TJSONObject then
begin
LCurrentValue := TJSONObject(LCurrentValue).Values[LParser.TokenName];
if LCurrentValue = nil then
Exit;
end
else
Exit;
TJSONPathParser.TToken.ArrayIndex:
if LCurrentValue.ClassType = TJSONArray then
if LParser.TokenArrayIndex < TJSONArray(LCurrentValue).Count then
LCurrentValue := TJSONArray(LCurrentValue).Items[LParser.TokenArrayIndex]
else
Exit
else
Exit;
TJSONPathParser.TToken.Error,
TJSONPathParser.TToken.Undefined:
Exit;
TJSONPathParser.TToken.Eof:
;
end;
end;
Result := LCurrentValue;
end;
initialization
JSONFormatSettings := TFormatSettings.Invariant;
end.
|
{**********************************************}
{ TeeChart Database Cross-Tab Source }
{ Copyright (c) 1996-2004 by David Berneda }
{**********************************************}
unit TeeDBCrossTab;
{$I TeeDefs.inc}
interface
{ The procedure below creates an array of Chart Series
and fills them using the DataSet parameter.
The Series are created using the "AGroupField" parameter.
The "ASeries" parameter will be used to duplicate it many times,
one for each "group", thus using it as a template.
Example of use:
---------------
Imagine you have a table with "Product sales".
In this table you have the following fields:
Product ( Cars, Bikes, Trucks... )
Country ( USA, UK, Germany, Australia... )
Amount ( $1234... )
Now we want to create a crosstab Chart consisting of one Bar
Series for each "Product", each one showing the sum of
"Amount" for each "Country".
So,
our "GroupField" is "Product",
our "LabelField" is "Country" and
our "ValueField" is "Amount".
Choose between 1 or 2:
1) Calling a direct global procedure:
FillDataSet( Table1, BarSeries1, "Product", "Country", "Amount", gfSum );
After calling this procedure, the Chart will show several Series,
one for each "Product".
Each series will show the "Sum of Amount" by "Country".
You can access and modify these Series as usually, like for example
changing the Series Color, Title, etc.
2) Use a TDBCrossTabSource component, set properties and Active:=True;
}
uses
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls,
{$ENDIF}
DB, Chart, DBChart, TeEngine, TeeProcs, TeeSourceEdit, TeeDBEdit, TeCanvas;
type
TGroupFormula = (gfCount, gfSum); { count records or sum record values }
TDBCrossTabSource=class(TTeeSeriesDBSource)
private
FCase : Boolean;
FDataSet: TDataSet;
FFormula: TGroupFormula;
FGroup : String;
FLabel : String;
FValue : String;
ISource : TDBChartDataSource;
procedure DataSourceCheckDataSet(ADataSet: TDataSet);
procedure DataSourceCloseDataSet(ADataSet: TDataSet);
Procedure LoadDataSet;
procedure RemoveSeries;
procedure SetDataSet(const Value: TDataSet);
procedure SetFormula(const Value: TGroupFormula);
procedure SetGroup(const Value: String);
procedure SetLabel(const Value: String);
procedure SetValue(const Value: String);
procedure SetCase(const Value: Boolean);
protected
KeepDataOnClose : Boolean;
procedure SetActive(const Value:Boolean); override;
public
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
class Function Available(AChart: TCustomAxisPanel):Boolean; override;
class Function Description:String; override;
class Function Editor:TComponentClass; override;
class Function HasSeries(ASeries:TChartSeries):Boolean; override;
Procedure Load; override;
published
property Active;
property CaseSensitive:Boolean read FCase write SetCase default True;
property DataSet: TDataSet read FDataSet write SetDataSet;
property Formula : TGroupFormula read FFormula write SetFormula default gfSum;
property GroupField : String read FGroup write SetGroup;
property LabelField : String read FLabel write SetLabel;
property Series;
property ValueField : String read FValue write SetValue;
end;
TDBChartCrossTabEditor = class(TBaseDBChartEditor)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
CBAgg: TComboFlat;
CBValue: TComboFlat;
CBGroup: TComboFlat;
Label4: TLabel;
CBLabels: TComboFlat;
CBActive: TCheckBox;
CBCase: TCheckBox;
procedure CBSourcesChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure BApplyClick(Sender: TObject);
procedure CBAggChange(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure CBActiveClick(Sender: TObject);
procedure CBCaseClick(Sender: TObject);
private
{ Private declarations }
DataSource : TDBCrossTabSource;
Procedure EnableCombos;
public
{ Public declarations }
end;
Procedure FillDataSet( ADataSet:TDataSet;
ASeries:TChartSeries;
Const AGroupField,ALabelField,AValueField:String;
GroupFormula:TGroupFormula);
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
{$IFDEF CLR}
uses Variants;
{$ENDIF}
Const TeeMsg_CrossTab ='CrossTab';
type TSeriesAccess=class(TChartSeries);
{ Create a cross-tab of Series using DataSet records. }
Procedure FillDataSet( ADataSet:TDataSet;
ASeries:TChartSeries;
Const AGroupField,ALabelField,AValueField:String;
GroupFormula:TGroupFormula);
begin
with TDBCrossTabSource.Create(nil) do
try
Series:=ASeries;
DataSet:=ADataSet;
GroupField:=AGroupField;
LabelField:=ALabelField;
ValueField:=AValueField;
Formula:=GroupFormula;
KeepDataOnClose:=True;
Open;
finally
Free;
end;
end;
type TChartAccess=class(TCustomAxisPanel);
Procedure TDBCrossTabSource.LoadDataSet;
Function LocateSeries(Const ATitle:String):TChartSeries;
var t : Integer;
tmp : String;
begin
With Series.ParentChart do
if FCase then
begin
for t:=0 to SeriesCount-1 do
if Series[t].Title=ATitle then
begin
result:=Series[t];
exit;
end;
end
else
begin
tmp:=UpperCase(ATitle);
for t:=0 to SeriesCount-1 do
if UpperCase(Series[t].Title)=tmp then
begin
result:=Series[t];
exit;
end;
end;
result:=nil;
end;
var tmpGroup : String;
tmpSeries : TChartSeries;
tmpLabel : String;
tmpValue : Double;
t,tt : Integer;
tmpPoint : Integer;
tmpBookMark : TBookMark;
tmpGroupField,
tmpValueField,
tmpLabelField : TField;
begin
RemoveSeries;
With DataSet do
begin
tmpBookMark:=GetBookMark;
DisableControls;
try
if LabelField='' then tmpLabelField:=nil
else tmpLabelField:=FieldByName(LabelField);
if GroupField='' then
begin
tmpSeries:=Series;
Series.Title:=ValueField;
tmpGroupField:=nil;
end
else
begin
tmpSeries:=nil;
tmpGroupField:=FieldByName(GroupField);
end;
tmpValueField:=FieldByName(ValueField);
tmpValue:=1;
First;
While not eof do
begin
if GroupField<>'' then
begin
tmpGroup:=tmpGroupField.AsString;
tmpSeries:=LocateSeries(tmpGroup);
if tmpSeries=nil then
begin
if Series.Title='' then
tmpSeries:=Series
else
begin
with Series do
begin
tmpSeries:=CreateNewSeries(Owner,ParentChart,
TChartSeriesClass(ClassType));
tmpSeries.Clear;
TSeriesAccess(tmpSeries).ManualData:=True;
tmpSeries.AssignFormat(Series);
tmpSeries.ShowInLegend:=ShowInLegend;
tmpSeries.Active:=Active;
tmpSeries.Brush:=Brush;
tmpSeries.Pen:=Pen;
TSeriesAccess(tmpSeries).InternalUse:=True;
end;
tmpSeries.SeriesColor:=Series.ParentChart.GetFreeSeriesColor;
tmpSeries.Tag:={$IFDEF CLR}Variant{$ELSE}Integer{$ENDIF}(Series);
for t:=0 to Series.Count-1 do
tmpSeries.Add(0,Series.Labels[t]);
end;
tmpSeries.Title:=tmpGroup;
end;
end;
if Formula<>gfCount then tmpValue:=tmpValueField.AsFloat;
if not Assigned(tmpLabelField) then
begin
tmpLabel:='';
if tmpSeries.Count>0 then tmpPoint:=0
else tmpPoint:=-1;
end
else
begin
tmpLabel:=tmpLabelField.AsString;
tmpPoint:=tmpSeries.Labels.IndexOfLabel(tmpLabel,FCase);
end;
if tmpPoint=-1 then
begin
tmpSeries.Add(tmpValue,tmpLabel,clTeeColor);
with Series.ParentChart do
for t:=0 to SeriesCount-1 do
if tmpSeries<>Series[t] then
if tmpSeries.Count>Series[t].Count then
for tt:=1 to (tmpSeries.Count-Series[t].Count) do
Series[t].Add(0,tmpLabel);
end
else
begin
With tmpSeries.MandatoryValueList do
case Formula of
gfCount,
gfSum: Value[tmpPoint]:=Value[tmpPoint]+tmpValue;
end;
end;
Next;
end;
finally
GotoBookMark(tmpBookMark);
FreeBookmark(tmpBookMark);
EnableControls;
TChartAccess(Series.ParentChart).BroadcastSeriesEvent(Series,seAdd);
end;
end;
end;
Procedure TDBChartCrossTabEditor.EnableCombos;
begin
EnableControls(DataSet<>nil,[CBAgg,CBValue,CBGroup,CBLabels]);
end;
procedure TDBChartCrossTabEditor.CBSourcesChange(Sender: TObject);
begin
inherited;
EnableCombos;
FillFields([CBValue,CBGroup,CBLabels]);
BApply.Enabled:=True;
end;
procedure TDBChartCrossTabEditor.FormShow(Sender: TObject);
begin
SkipValidation:=True;
inherited;
if not Assigned(TheSeries) then exit;
if TheSeries.DataSource is TDBCrossTabSource then
DataSource:=TDBCrossTabSource(TheSeries.DataSource)
else
begin
DataSource:=TDBCrossTabSource.Create(TheSeries.Owner);
DataSource.Name:=TeeGetUniqueName(DataSource.Owner,'DBCrossTabSource');
end;
With CBSources do
ItemIndex:=Items.IndexOfObject(DataSource.DataSet);
EnableCombos;
FillFields([CBValue,CBGroup,CBLabels]);
if DataSource.Formula=gfSum then CBAgg.ItemIndex:=0
else CBAgg.ItemIndex:=1;
With CBValue do ItemIndex:=Items.IndexOf(DataSource.ValueField);
With CBGroup do ItemIndex:=Items.IndexOf(DataSource.GroupField);
With CBLabels do ItemIndex:=Items.IndexOf(DataSource.LabelField);
CBActive.Checked:=DataSource.Active;
CBCase.Checked:=DataSource.CaseSensitive;
BApply.Enabled:=Assigned(TheSeries) and (DataSource<>TheSeries.DataSource);
end;
{ TDBCrossTabSource }
constructor TDBCrossTabSource.Create(AOwner: TComponent);
begin
inherited;
FFormula:=gfSum;
FCase:=True;
end;
class function TDBCrossTabSource.Description: String;
begin
result:=TeeMsg_CrossTab;
end;
class function TDBCrossTabSource.Editor: TComponentClass;
begin
result:=TDBChartCrossTabEditor;
end;
class function TDBCrossTabSource.HasSeries(
ASeries: TChartSeries): Boolean;
begin
result:=(ASeries.DataSource is TDBCrossTabSource);
end;
procedure TDBChartCrossTabEditor.BApplyClick(Sender: TObject);
Function GetFieldCombo(Combo:TComboBox):String;
begin
With Combo do
if ItemIndex=-1 then result:=Text
else result:=Items[ItemIndex];
end;
begin
inherited;
CheckReplaceSource(DataSource);
TheSeries.Tag:=0;
with DataSource do
begin
Case CBAgg.ItemIndex of
0: Formula:=gfSum;
else
Formula:=gfCount;
end;
ValueField:=GetFieldCombo(CBValue);
GroupField:=GetFieldCombo(CBGroup);
LabelField:=GetFieldCombo(CBLabels);
DataSet:=Self.DataSet;
CaseSensitive:=CBCase.Checked;
Active:=CBActive.Checked;
end;
BApply.Enabled:=False;
end;
procedure TDBCrossTabSource.Load;
begin
if Assigned(Series) and Assigned(DataSet) and
(ValueField<>'') and DataSet.Active then
LoadDataSet;
end;
procedure TDBChartCrossTabEditor.CBAggChange(Sender: TObject);
begin
inherited;
BApply.Enabled:=True;
end;
procedure TDBChartCrossTabEditor.FormDestroy(Sender: TObject);
begin
if Assigned(DataSource) and
(not Assigned(DataSource.Series)) then
DataSource.Free;
inherited;
end;
type TDBChartDataSourceAccess=class(TDBChartDataSource);
procedure TDBCrossTabSource.SetDataSet(const Value: TDataSet);
begin
if FDataSet<>Value then
begin
Close;
FDataSet:=Value;
ISource.Free;
ISource:=TDBChartDataSource.Create(nil); { 5.02 }
// No "with" here due to CLR restriction...
TDBChartDataSourceAccess(ISource).SetDataSet(FDataSet);
TDBChartDataSourceAccess(ISource).OnCheckDataSet:=DataSourceCheckDataSet;
TDBChartDataSourceAccess(ISource).OnCloseDataSet:=DataSourceCloseDataSet;
end;
end;
procedure TDBCrossTabSource.RemoveSeries;
var t : Integer;
begin
t:=0;
if Assigned(Series.ParentChart) then
with Series.ParentChart do
while t<SeriesCount do
if (Series[t]<>Self.Series) and (TChartSeries(Series[t].Tag)=Self.Series) then
Series[t].Free
else
Inc(t);
if not (csDestroying in Series.ComponentState) then
begin
Series.Clear;
Series.Title:='';
end;
end;
procedure TDBCrossTabSource.DataSourceCloseDataSet(ADataSet: TDataSet);
begin
if (not KeepDataOnClose) and Assigned(Series) then
RemoveSeries;
end;
procedure TDBCrossTabSource.SetActive(const Value:Boolean);
begin
inherited;
if not Active then DataSourceCloseDataSet(DataSet);
end;
procedure TDBCrossTabSource.DataSourceCheckDataSet(ADataSet: TDataSet);
begin
Refresh;
end;
class function TDBCrossTabSource.Available(AChart: TCustomAxisPanel):Boolean;
begin
result:=AChart is TCustomChart;
end;
procedure TDBCrossTabSource.SetFormula(const Value: TGroupFormula);
begin
if FFormula<>Value then
begin
Close;
FFormula:=Value;
end;
end;
procedure TDBCrossTabSource.SetGroup(const Value: String);
begin
if FGroup<>Value then
begin
Close;
FGroup:=Value;
end;
end;
procedure TDBCrossTabSource.SetLabel(const Value: String);
begin
if FLabel<>Value then
begin
Close;
FLabel:=Value;
end;
end;
procedure TDBCrossTabSource.SetValue(const Value: String);
begin
if FValue<>Value then
begin
Close;
FValue:=Value;
end;
end;
destructor TDBCrossTabSource.Destroy;
begin
ISource.Free;
inherited;
end;
procedure TDBChartCrossTabEditor.CBActiveClick(Sender: TObject);
begin
BApply.Enabled:=True;
end;
procedure TDBCrossTabSource.SetCase(const Value: Boolean);
begin
if FCase<>Value then
begin
Close;
FCase:=Value;
end;
end;
procedure TDBChartCrossTabEditor.CBCaseClick(Sender: TObject);
begin
BApply.Enabled:=True;
end;
initialization
RegisterClass(TDBCrossTabSource);
TeeSources.Add({$IFDEF CLR}TObject{$ENDIF}(TDBCrossTabSource));
finalization
TeeSources.Remove({$IFDEF CLR}TObject{$ENDIF}(TDBCrossTabSource));
end.
|
unit HKLogFile;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, syncobjs, LResources, Forms, Controls, Graphics, Dialogs,
HKCompPacksTypes;
type
{ THKLogFile }
THKLogFile = class(TComponent)
private
FAbsPath: String;
FDirPath: String;
FLogExtension: String;
FLogFormat: String;
//FCSession:TCriticalSection;
FLogLevel: Integer;
procedure SetDirPath(AValue: String);
procedure SetLogExtension(AValue: String);
procedure SetLogFormat(AValue: String);
procedure SetLogLevel(AValue: Integer);
protected
public
constructor Create(AOwner: TComponent); override;
procedure WriteLog(aMessage:String; aDebugType:TDebugType);
Procedure InitCs;
destructor Destroy; override;
published
property DirPath:String read FDirPath write SetDirPath;
//property AbsPath:String read FAbsPath;
property LogExtension:String read FLogExtension write SetLogExtension;
property LogFormat:String read FLogFormat write SetLogFormat;
property LogLevel:Integer read FLogLevel write SetLogLevel;
end;
procedure Register;
implementation
procedure Register;
begin
{$I hklogfile_icon.lrs}
RegisterComponents('HKCompPacks',[THKLogFile]);
end;
{ THKLogFile }
procedure THKLogFile.SetDirPath(AValue: String);
var
path: String;
begin
if FDirPath=AValue then Exit;
FDirPath:=AValue;
FAbsPath:=ExtractFileDir(ParamStr(1))+PathDelim+AValue+PathDelim;
if Not DirectoryExists(FAbsPath) then MkDir(FAbsPath);
end;
procedure THKLogFile.SetLogExtension(AValue: String);
begin
if FLogExtension=AValue then Exit;
FLogExtension:=AValue;
end;
procedure THKLogFile.SetLogFormat(AValue: String);
begin
if FLogFormat=AValue then Exit;
FLogFormat:=AValue;
end;
procedure THKLogFile.SetLogLevel(AValue: Integer);
begin
if FLogLevel=AValue then Exit;
FLogLevel:=AValue;
end;
constructor THKLogFile.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
LogLevel:=1;
LogFormat:='YYYYMMDD';
DirPath:='log';
LogExtension:='log';
FAbsPath:=ExtractFileDir(ParamStr(0))+PathDelim+DirPath+PathDelim;
end;
procedure THKLogFile.WriteLog(aMessage: String; aDebugType: TDebugType);
var Log:Text;
logFile, message:String;
begin
if Not DirectoryExists(FAbsPath) then MkDir(FAbsPath);
if ((aDebugType=DTInfo2)and(LogLevel<2))or((aDebugType=DTInfo3)and(LogLevel<3)) then
begin
Exit;
end;
//FCSession.Enter;
try
logFile:=FAbsPath+'Log_'+FormatDateTime(LogFormat, Now)+ExtensionSeparator+LogExtension;
message:=GetLogMessage(aMessage, aDebugType);
AssignFile(Log, logFile);
if FileExists(logFile)then Append(Log)
else Rewrite(Log);
WriteLn(Log, message);
Flush(Log);
finally
CloseFile(Log);
//FCSession.Leave;
end;
end;
procedure THKLogFile.InitCs;
begin
//FCSession:=TCriticalSection.Create;
end;
destructor THKLogFile.Destroy;
begin
//if FCSession<>nil then FCSession.Free;
inherited Destroy;
end;
end.
|
unit ncFrmWebPopup;
{
ResourceString: Dario 12/03/13
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OleCtrls, Automation, ncClassesBase, mshtml,
ExtCtrls, ncBaseWebApi, SHDocVw, uMyBrowser;
type
TFrmWebPopup = class(TForm)
TimerErro: TTimer;
WB: TMyBrowser;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure WBCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure TimerErroTimer(Sender: TObject);
procedure WBGetWebApi(Sender: TMyBrowser; var aWebApi: TMyWebApi);
procedure WBDocumentComplete(ASender: TObject; const pDisp: IDispatch;
const [Ref] URL: OleVariant);
procedure WBNavigateComplete2(ASender: TObject; const pDisp: IDispatch;
const [Ref] URL: OleVariant);
procedure WBNavigateError(ASender: TObject; const pDisp: IDispatch;
const [Ref] URL, Frame, StatusCode: OleVariant; var Cancel: WordBool);
private
FNavOk : Boolean;
{ Private declarations }
function NavURL: String;
protected
function CreateApi: TncBaseWebApi; virtual; abstract;
procedure wmNavigate(var Msg: TMessage);
message wm_user;
procedure wmFechar(var Msg: TMessage);
message wm_user+1;
public
Fechar : Boolean;
URL : String;
function AddParams(S: String): String;
{ Public declarations }
end;
TFrmWebPopupClass = class of TFrmWebPopup;
var
FrmWebPopup: TFrmWebPopup;
FrmWebPopupClass: TFrmWebPopupClass = nil;
implementation
uses ncVersionInfo, ncDebug, ncGuidUtils, nexUrls;
{$R *.dfm}
function TFrmWebPopup.AddParams(S: String): String;
begin
Result := AddParamUrl(S, 'conta='+ // do not localize
gConfig.Conta+'&cok='+BoolStr[gConfig.FreePremium or (gConfig.QtdLic>0)]+ // do not localize
'&ver='+SelfShortVer+ // do not localize
'&sw='+prefixo_versao+
'&random='+TGuidEx.ToString(TGuidEx.NewGuid));
DebugMsg('TFrmWebPopup.AddParams - Result: '+Result);
end;
procedure TFrmWebPopup.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmWebPopup.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := Fechar;
end;
procedure TFrmWebPopup.FormCreate(Sender: TObject);
begin
Width := 1;
Height := 1;
Fechar := False;
URL := '';
end;
procedure TFrmWebPopup.FormShow(Sender: TObject);
begin
PostMessage(Handle, wm_user, 0, 0);
// WB.navigate('file:///C:/Users/Joao/Desktop/premium_popup.html');
end;
procedure TFrmWebPopup.TimerErroTimer(Sender: TObject);
begin
TimerErro.Enabled := False;
WB.navigate(navURL);
end;
function TFrmWebPopup.navURL: String;
begin
if Trim(URL) = '' then
Result := AddParams(gUrls.Url('nexmsg')) else
Result := URL;
DebugMsg('TFrmWebPopup.navURL: '+Result);
end;
procedure TFrmWebPopup.WBCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
Fechar := True;
CanClose := True;
Close;
end;
procedure TFrmWebPopup.WBDocumentComplete(ASender: TObject;
const pDisp: IDispatch; const [Ref] URL: OleVariant);
var
S: String;
I, P: Integer;
SL : TStrings;
Sair : Boolean;
begin
if not WB.MasterDoc(pDisp) then Exit;
Sair := True;
try
S := WB.BodyHtml(pDisp);
P := Pos('!nexinfo!="', S); // do not localize
if P=0 then Exit;
Delete(S, 1, P+10);
S := Copy(S, 1, Pos('"', S)-1);
if S='' then Exit;
SL := TStringList.Create;
try
P := Pos(';', S);
while P > 0 do begin
SL.Add(Copy(S, 1, P-1));
Delete(S, 1, P);
P := Pos(';', S);
end;
if Trim(S)>'' then SL.Add(Trim(S));
if not SameText(SL.Values['Ok'], 'Ok') then Exit; // do not localize
Width := StrToIntDef(Sl.Values['W'], 0);
Height := StrToIntDef(Sl.Values['H'], 0);
if (Width=0) or (Height=0) then Exit;
case StrToIntDef(SL.Values['BS'], 2) of // do not localize
0 : BorderStyle := bsNone;
1 : BorderStyle := bsSingle;
2 : BorderStyle := bsDialog;
3 : BorderStyle := bsToolWindow;
4 : BorderStyle := bsSizeToolWin;
else
BorderStyle := bsDialog;
end;
Caption := (WB.Document as IHTMLDocument2).title;
{ if not SameText(SL.Values['SC'], 'S') then
WB.UserInterfaceOptions := WB.UserInterfaceOptions + [DontUseScrollbars];}
WB.Repaint;
Fechar := SameText(SL.Values['CC'], 'S'); // do not localize
Top := (Screen.Height - Height) div 2;
Left := (Screen.Width - Width) div 2;
Sair := False;
finally
SL.Free;
end;
finally
if Sair then
PostMessage(Self.Handle, wm_user+1, 0, 0);
end;
end;
procedure TFrmWebPopup.WBGetWebApi(Sender: TMyBrowser; var aWebApi: TMyWebApi);
begin
aWebApi := CreateApi;
end;
procedure TFrmWebPopup.WBNavigateComplete2(ASender: TObject;
const pDisp: IDispatch; const [Ref] URL: OleVariant);
begin
FNavOk := True;
end;
procedure TFrmWebPopup.WBNavigateError(ASender: TObject; const pDisp: IDispatch;
const [Ref] URL, Frame, StatusCode: OleVariant; var Cancel: WordBool);
begin
Cancel := True;
TimerErro.Enabled := True;
end;
procedure TFrmWebPopup.wmFechar(var Msg: TMessage);
begin
Fechar := True;
Close;
end;
procedure TFrmWebPopup.wmNavigate(var Msg: TMessage);
begin
DebugMsg('TFrmWebPopup.wmNavigate 1');
try
FNavOk := False;
WB.Navigate(navUrl);
DebugMsg('TFrmWebPopup.wmNavigate 2');
except
on E: Exception do
DebugMsg('TFrmWebPopup.wmNAvigate - Exception: ' + E.Message);
end;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit RSConsole.TypesViews;
interface
uses System.Classes, System.SysUtils, System.JSON,
FMX.TabControl, FMX.Grid, System.Generics.Collections,
RSConsole.FrameAdd, FMX.ListBox,
RSConsole.Data, RSConsole.Types,
RSConsole.DlgModifyU, RSConsole.Consts,
Data.Bind.Grid, FireDAC.Comp.Client, REST.Response.Adapter,
Data.Bind.DBScope, Data.Bind.Components, RSConsole.FrameJSONGridU;
type
TEMSTabItem = class(TTabItem)
public type
TGetJSONEvent = procedure(Sender: TObject; const AJSON: TJSONArray)
of object;
TGetJSONArrayEvent = procedure(Sender: TObject; const AJSON: TJSONArray)
of object;
private
FFrameJSONGrid: TFrameJSONGrid;
FColumnNames: TList<string>;
FColumnsReadOnly: TList<integer>;
FEMSConsoleData: TEMSConsoleData;
FLoadedData: Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure UpdateView(AIndetifier: string; ACellList: TList<TCell>);
virtual; abstract;
procedure ShowFrame(ADialog: TFormAddDlg); virtual; abstract;
procedure SetObjectInfoToAddDlg(ADialog: TFormAddDlg); virtual; abstract;
function GetObjectIdentifier(const Row: integer): string; virtual; abstract;
function Delete(const AID: string): Boolean; virtual; abstract;
procedure Load(const AID: string);
function GetDefaultStyleLookupName: string; override;
property EMSConsoleData: TEMSConsoleData read FEMSConsoleData
write FEMSConsoleData;
property ColumnsReadOnly: TList<integer> read FColumnsReadOnly
write FColumnsReadOnly;
property FrameJSONGrid: TFrameJSONGrid read FFrameJSONGrid
write FFrameJSONGrid;
procedure OnTabItemClick(Sender: TObject);
function GetCombo: TComboBox;
function GetHeaderIndex(AHeaderName: string): integer;
end;
TUsersTabItem = class(TEMSTabItem)
public
constructor Create(AOwner: TComponent); override;
procedure UpdateView(AIndetifier: string; ACellList: TList<TCell>);
override;
procedure ShowFrame(ADialog: TFormAddDlg); override;
procedure SetObjectInfoToAddDlg(ADialog: TFormAddDlg); override;
function GetObjectIdentifier(const Row: integer): string; override;
function Delete(const AID: string): Boolean; override;
procedure OnGetUsersData(Sender: TObject; const AJSON: TJSONArray);
procedure OnGetUsersFields(Sender: TObject; const AJSON: TJSONArray);
end;
TGroupsTabItem = class(TEMSTabItem)
public
constructor Create(AOwner: TComponent); override;
procedure UpdateView(AIndetifier: string; ACellList: TList<TCell>);
override;
procedure ShowFrame(ADialog: TFormAddDlg); override;
procedure SetObjectInfoToAddDlg(ADialog: TFormAddDlg); override;
function GetObjectIdentifier(const Row: integer): string; override;
function Delete(const AID: string): Boolean; override;
procedure OnGetGroupsSData(Sender: TObject; const AJSON: TJSONArray);
procedure OnGetGroupsFields(Sender: TObject; const AJSON: TJSONArray);
end;
TInstallationTabItem = class(TEMSTabItem)
public
constructor Create(AOwner: TComponent); override;
procedure UpdateView(AIndetifier: string; ACellList: TList<TCell>);
override;
procedure ShowFrame(ADialog: TFormAddDlg); override;
procedure SetObjectInfoToAddDlg(ADialog: TFormAddDlg); override;
function GetObjectIdentifier(const Row: integer): string; override;
function Delete(const AID: string): Boolean; override;
procedure OnGetInstallationsData(Sender: TObject; const AJSON: TJSONArray);
procedure OnGetInstallationsFields(Sender: TObject;
const AJSON: TJSONArray);
end;
TEdgeModuleTabItem = class(TEMSTabItem)
public
constructor Create(AOwner: TComponent); override;
procedure UpdateView(AIndetifier: string; ACellList: TList<TCell>);
override;
procedure ShowFrame(ADialog: TFormAddDlg); override;
procedure SetObjectInfoToAddDlg(ADialog: TFormAddDlg); override;
function GetObjectIdentifier(const Row: integer): string; override;
function Delete(const AID: string): Boolean; override;
procedure OnGetEdgeModulesData(Sender: TObject; const AJSON: TJSONArray);
procedure OnGetEdgeModulesFields(Sender: TObject; const AJSON: TJSONArray);
end;
TResourceTabItem = class(TEMSTabItem)
public
constructor Create(AOwner: TComponent); override;
procedure UpdateView(AIndetifier: string; ACellList: TList<TCell>);
override;
procedure ShowFrame(ADialog: TFormAddDlg); override;
procedure SetObjectInfoToAddDlg(ADialog: TFormAddDlg); override;
function GetObjectIdentifier(const Row: integer): string; override;
function Delete(const AID: string): Boolean; override;
procedure OnGetResourcesData(Sender: TObject; const AJSON: TJSONArray);
procedure OnGetResourcesFields(Sender: TObject; const AJSON: TJSONArray);
function GetSelectedModule: string;
procedure LoadComboModules;
end;
implementation
uses RSConsole.FrameViews, System.UITypes, FMX.Types,
RSConsole.ModuleBackend, REST.Backend.EMSApi, REST.Backend.EMSProvider,
FireDAC.Stan.Option, Data.DB, RSConsole.Form, FMX.Dialogs;
{ TEMSTabItem }
function TEMSTabItem.GetCombo: TComboBox;
begin
Result := FFrameJSONGrid.ComboBoxExtras;
end;
function TEMSTabItem.GetDefaultStyleLookupName: string;
begin
Result := 'TabItemstyle';
end;
function TEMSTabItem.GetHeaderIndex(AHeaderName: string): integer;
var
I: integer;
begin
Result := -1;
for I := 0 to FFrameJSONGrid.StringGrid.ColumnCount - 1 do
if AHeaderName = FFrameJSONGrid.StringGrid.Columns[I].Header then
Result := I;
end;
function TResourceTabItem.GetSelectedModule: string;
begin;
FFrameJSONGrid.ToolBar2.Visible := True;
FFrameJSONGrid.LabelExtras.Text := strEdgeModules;
if (GetCombo.Selected <> nil) and (GetCombo.Selected.Text <> strAllEdgeModule)
then
Result := GetCombo.ListItems[GetCombo.ItemIndex].ItemData.Detail
else
Result := '';
end;
procedure TEMSTabItem.Load(const AID: string);
begin
TMainForm(root).ViewsFrame.EnableTabs;
FrameJSONGrid.Refresh;
end;
procedure TEMSTabItem.OnTabItemClick(Sender: TObject);
begin
if not FLoadedData then
begin
FFrameJSONGrid.Refresh;
FLoadedData := True;
end;
end;
destructor TEMSTabItem.Destroy;
begin
FFrameJSONGrid.Free;
FColumnNames.Free;
FColumnsReadOnly.Free;
inherited;
end;
constructor TEMSTabItem.Create(AOwner: TComponent);
begin
inherited;
FFrameJSONGrid := TFrameJSONGrid.Create(Self);
FFrameJSONGrid.Parent := Self;
FFrameJSONGrid.Align := TAlignLayout.Client;
FFrameJSONGrid.StringGrid.Options := FFrameJSONGrid.StringGrid.Options +
[TGridOption.RowSelect, TGridOption.AlwaysShowSelection] -
[TGridOption.Editing];
FColumnNames := TList<string>.Create;
FColumnsReadOnly := TList<integer>.Create;
OnClick := OnTabItemClick;
end;
{ TUsersTabItem }
procedure TUsersTabItem.OnGetUsersData(Sender: TObject;
const AJSON: TJSONArray);
begin
FEMSConsoleData.GetUsers(Sender, AJSON);
end;
procedure TUsersTabItem.OnGetUsersFields(Sender: TObject;
const AJSON: TJSONArray);
begin
FEMSConsoleData.GetUsersFields(Sender, AJSON);
end;
procedure TUsersTabItem.SetObjectInfoToAddDlg(ADialog: TFormAddDlg);
var
I, LColIndex: integer;
LDetailsKeys: TArray<string>;
LHeaderList: TList<string>;
LUserInfo: TUserInfo;
begin
LUserInfo.UserName := FFrameJSONGrid.StringGrid.Cells
[GetHeaderIndex(TUserInfo.cUserName), FFrameJSONGrid.StringGrid.Selected];
LUserInfo.UserId := FFrameJSONGrid.StringGrid.Cells
[GetHeaderIndex(TUserInfo.cID), FFrameJSONGrid.StringGrid.Selected];
LDetailsKeys := EMSConsoleData.GetUsersFieldsArray;
SetLength(LUserInfo.Details, Length(LDetailsKeys));
LHeaderList := TList<string>.Create;
try
for I := 0 to FFrameJSONGrid.StringGrid.ColumnCount - 1 do
LHeaderList.Add(FFrameJSONGrid.StringGrid.Columns[I].Header);
for I := Low(LDetailsKeys) to High(LDetailsKeys) do
begin
LUserInfo.Details[I].Key := LDetailsKeys[I];
LColIndex := LHeaderList.IndexOf(LDetailsKeys[I]);
LUserInfo.Details[I].Value := FFrameJSONGrid.StringGrid.Cells
[LColIndex, FFrameJSONGrid.StringGrid.Selected];
end;
ADialog.UserInfo := LUserInfo;
finally
LHeaderList.Free;
end;
end;
procedure TUsersTabItem.ShowFrame(ADialog: TFormAddDlg);
begin
ADialog.AddFrame.ShowUserAddTab;
end;
procedure TUsersTabItem.UpdateView(AIndetifier: string;
ACellList: TList<TCell>);
var
LJSON: TJSONObject;
I, Col, Row: integer;
begin
LJSON := TJSONObject.Create;
try
for I := 0 to ACellList.Count - 1 do
begin
Col := ACellList.Items[I].Col;
Row := ACellList.Items[I].Row;
LJSON.AddPair(FFrameJSONGrid.StringGrid.Columns[Col].Header,
FFrameJSONGrid.StringGrid.Cells[Col, Row]);
end;
FEMSConsoleData.UpdateUser(AIndetifier, LJSON);
finally
LJSON.Free;
end;
end;
constructor TUsersTabItem.Create(AOwner: TComponent);
begin
inherited;
FrameJSONGrid.OnGetData := OnGetUsersData;
FrameJSONGrid.OnGetFields := OnGetUsersFields;
TabOrder := 0;
end;
function TUsersTabItem.Delete(const AID: string): Boolean;
begin
Result := FEMSConsoleData.DeleteUser(AID);
end;
function TUsersTabItem.GetObjectIdentifier(const Row: integer): string;
var
ColIndex: integer;
begin
ColIndex := GetHeaderIndex(TUserInfo.cID);
if ColIndex >= 0 then
Result := FFrameJSONGrid.StringGrid.Cells[ColIndex, Row];
end;
{ TGroupsTabItem }
procedure TGroupsTabItem.OnGetGroupsFields(Sender: TObject;
const AJSON: TJSONArray);
begin
FEMSConsoleData.GetGroupsFields(Sender, AJSON);
end;
procedure TGroupsTabItem.OnGetGroupsSData(Sender: TObject;
const AJSON: TJSONArray);
begin
FEMSConsoleData.GetGroups(Sender, AJSON);
end;
procedure TGroupsTabItem.SetObjectInfoToAddDlg(ADialog: TFormAddDlg);
var
I, LColIndex: integer;
LDetailsKeys: TArray<string>;
LUsersString: string;
LHeaderList: TList<string>;
LOutPutList: TStringList;
LGroupInfo: TGroupInfo;
LJSONArray: TJSONArray;
begin
LGroupInfo.GroupName := FFrameJSONGrid.StringGrid.Cells
[GetHeaderIndex(TGroupInfo.cGroupName), FFrameJSONGrid.StringGrid.Selected];
LJSONArray := TJSONArray.Create;
try
FEMSConsoleData.GetGroup(Self, LGroupInfo.GroupName, LJSONArray);
if TJSONObject(LJSONArray.Items[0]).GetValue(TGroupInfo.cUsers) <> nil then
LUsersString := TJSONObject(LJSONArray.Items[0])
.GetValue(TGroupInfo.cUsers).ToString;
finally
LJSONArray.Free
end;
LUsersString := LUsersString.Substring(1, LUsersString.Length - 2);
LOutPutList := TStringList.Create;
LGroupInfo.Users := TStringList.Create;
try
LOutPutList.Delimiter := ',';
LOutPutList.DelimitedText := LUsersString;
for I := 0 to LOutPutList.Count - 1 do
LGroupInfo.Users.Add(LOutPutList[I]);
finally
LOutPutList.Free;
end;
LDetailsKeys := EMSConsoleData.GetGroupsFieldsArray;
SetLength(LGroupInfo.Details, Length(LDetailsKeys));
LHeaderList := TList<string>.Create;
try
for I := 0 to FFrameJSONGrid.StringGrid.ColumnCount - 1 do
LHeaderList.Add(FFrameJSONGrid.StringGrid.Columns[I].Header);
for I := Low(LDetailsKeys) to High(LDetailsKeys) do
begin
LGroupInfo.Details[I].Key := LDetailsKeys[I];
LColIndex := LHeaderList.IndexOf(LDetailsKeys[I]);
LGroupInfo.Details[I].Value := FFrameJSONGrid.StringGrid.Cells
[LColIndex, FFrameJSONGrid.StringGrid.Selected];
end;
ADialog.GroupInfo := LGroupInfo;
finally
LHeaderList.Free;
end;
end;
procedure TGroupsTabItem.ShowFrame(ADialog: TFormAddDlg);
begin
ADialog.AddFrame.ShowGroupAddTab;
end;
procedure TGroupsTabItem.UpdateView(AIndetifier: string;
ACellList: TList<TCell>);
var
LJSON: TJSONObject;
I, Col, Row: integer;
begin
LJSON := TJSONObject.Create;
try
for I := 0 to ACellList.Count - 1 do
begin
Col := ACellList.Items[I].Col;
Row := ACellList.Items[I].Row;
LJSON.AddPair(FFrameJSONGrid.StringGrid.Columns[Col].Header,
FFrameJSONGrid.StringGrid.Cells[Col, Row]);
end;
FEMSConsoleData.UpdateGroup(AIndetifier, LJSON);
finally
LJSON.Free;
end;
end;
constructor TGroupsTabItem.Create(AOwner: TComponent);
begin
inherited;
FrameJSONGrid.OnGetData := OnGetGroupsSData;
FrameJSONGrid.OnGetFields := OnGetGroupsFields;
end;
function TGroupsTabItem.Delete(const AID: string): Boolean;
begin
Result := FEMSConsoleData.DeleteGroup(AID);
end;
function TGroupsTabItem.GetObjectIdentifier(const Row: integer): string;
var
ColIndex: integer;
begin
ColIndex := GetHeaderIndex(TGroupInfo.cGroupName);
if ColIndex >= 0 then
Result := FFrameJSONGrid.StringGrid.Cells[ColIndex, Row];
end;
{ TInstallationTabItem }
procedure TInstallationTabItem.OnGetInstallationsData(Sender: TObject;
const AJSON: TJSONArray);
begin
FEMSConsoleData.GetInstallations(Sender, AJSON);
end;
procedure TInstallationTabItem.OnGetInstallationsFields(Sender: TObject;
const AJSON: TJSONArray);
begin
FEMSConsoleData.GetInstallationsFields(Sender, AJSON);
end;
procedure TInstallationTabItem.SetObjectInfoToAddDlg(ADialog: TFormAddDlg);
var
I, LColIndex: integer;
LDetailsKeys: TArray<string>;
LHeaderList: TList<string>;
LChannelsString: string;
LOutPutList: TStringList;
LInstallationInfo: TInstallationInfo;
begin
LInstallationInfo.InstallationID := FFrameJSONGrid.StringGrid.Cells
[GetHeaderIndex(TInstallationInfo.cID), FFrameJSONGrid.StringGrid.Selected];
LInstallationInfo.DeviceToken := FFrameJSONGrid.StringGrid.Cells
[GetHeaderIndex(TInstallationInfo.cDeviceToken),
FFrameJSONGrid.StringGrid.Selected];
LInstallationInfo.DeviceType := FFrameJSONGrid.StringGrid.Cells
[GetHeaderIndex(TInstallationInfo.cDeviceType),
FFrameJSONGrid.StringGrid.Selected];
LChannelsString := FFrameJSONGrid.StringGrid.Cells
[GetHeaderIndex(TInstallationInfo.cChannels),
FFrameJSONGrid.StringGrid.Selected];
LChannelsString := LChannelsString.Substring(1, LChannelsString.Length - 2);
LOutPutList := TStringList.Create;
try
LOutPutList.Delimiter := ',';
LOutPutList.DelimitedText := LChannelsString;
SetLength(LInstallationInfo.Channels, LOutPutList.Count);
for I := 0 to LOutPutList.Count - 1 do
LInstallationInfo.Channels[I] := LOutPutList[I];
finally
LOutPutList.Free;
end;
LDetailsKeys := EMSConsoleData.GetInstallationsFieldsArray;
SetLength(LInstallationInfo.Details, Length(LDetailsKeys));
LHeaderList := TList<string>.Create;
try
for I := 0 to FFrameJSONGrid.StringGrid.ColumnCount - 1 do
LHeaderList.Add(FFrameJSONGrid.StringGrid.Columns[I].Header);
for I := Low(LDetailsKeys) to High(LDetailsKeys) do
begin
LInstallationInfo.Details[I].Key := LDetailsKeys[I];
LColIndex := LHeaderList.IndexOf(LDetailsKeys[I]);
LInstallationInfo.Details[I].Value := FFrameJSONGrid.StringGrid.Cells
[LColIndex, FFrameJSONGrid.StringGrid.Selected];
end;
ADialog.InstallationInfo := LInstallationInfo;
finally
LHeaderList.Free;
end;
end;
procedure TInstallationTabItem.ShowFrame(ADialog: TFormAddDlg);
begin
ADialog.AddFrame.ShowInstallationAddTab;
end;
procedure TInstallationTabItem.UpdateView(AIndetifier: string;
ACellList: TList<TCell>);
var
LJSON: TJSONObject;
I, Col, Row: integer;
begin
LJSON := TJSONObject.Create;
try
for I := 0 to ACellList.Count - 1 do
begin
Col := ACellList.Items[I].Col;
Row := ACellList.Items[I].Row;
LJSON.AddPair(FFrameJSONGrid.StringGrid.Columns[Col].Header,
FFrameJSONGrid.StringGrid.Cells[Col, Row]);
end;
FEMSConsoleData.UpdateInstallation(AIndetifier, LJSON);
finally
LJSON.Free;
end;
end;
constructor TInstallationTabItem.Create(AOwner: TComponent);
begin
inherited;
FrameJSONGrid.OnGetData := OnGetInstallationsData;
FrameJSONGrid.OnGetFields := OnGetInstallationsFields;
end;
function TInstallationTabItem.Delete(const AID: string): Boolean;
begin
Result := FEMSConsoleData.DeleteInstallation(AID);
end;
function TInstallationTabItem.GetObjectIdentifier(const Row: integer): string;
var
ColIndex: integer;
begin
ColIndex := GetHeaderIndex(TInstallationInfo.cID);
if ColIndex >= 0 then
Result := FFrameJSONGrid.StringGrid.Cells[ColIndex, Row];
end;
{ TEdgeModuleTabItem }
constructor TEdgeModuleTabItem.Create(AOwner: TComponent);
begin
inherited;
FrameJSONGrid.OnGetData := OnGetEdgeModulesData;
FrameJSONGrid.OnGetFields := OnGetEdgeModulesFields;
TabOrder := 0;
end;
function TEdgeModuleTabItem.Delete(const AID: string): Boolean;
begin
Result := FEMSConsoleData.DeleteEdgeModule(AID);
end;
function TEdgeModuleTabItem.GetObjectIdentifier(const Row: integer): string;
var
ColIndex: integer;
begin
ColIndex := GetHeaderIndex(TEdgeModuleInfo.cID);
if ColIndex >= 0 then
Result := FFrameJSONGrid.StringGrid.Cells[ColIndex, Row];
end;
procedure TEdgeModuleTabItem.OnGetEdgeModulesData(Sender: TObject;
const AJSON: TJSONArray);
begin
FEMSConsoleData.GetEdgeModules(Sender, AJSON);
end;
procedure TEdgeModuleTabItem.OnGetEdgeModulesFields(Sender: TObject;
const AJSON: TJSONArray);
begin
FEMSConsoleData.GetEdgeModulesFields(Sender, AJSON);
end;
procedure TEdgeModuleTabItem.SetObjectInfoToAddDlg(ADialog: TFormAddDlg);
var
I, LColIndex: integer;
LDetailsKeys: TArray<string>;
LHeaderList: TList<string>;
LEdgeModuleInfo: TEdgeModuleInfo;
begin
LEdgeModuleInfo.ModuleName := FFrameJSONGrid.StringGrid.Cells
[GetHeaderIndex(TEdgeModuleInfo.cModuleName),
FFrameJSONGrid.StringGrid.Selected];
LEdgeModuleInfo.ModuleID := FFrameJSONGrid.StringGrid.Cells
[GetHeaderIndex(TEdgeModuleInfo.cID), FFrameJSONGrid.StringGrid.Selected];
LEdgeModuleInfo.Protocol := FFrameJSONGrid.StringGrid.Cells
[GetHeaderIndex(TEdgeModuleInfo.cModuleProtocol),
FFrameJSONGrid.StringGrid.Selected];
LEdgeModuleInfo.ProtocolProps := FFrameJSONGrid.StringGrid.Cells
[GetHeaderIndex(TEdgeModuleInfo.cModuleProtocolProps),
FFrameJSONGrid.StringGrid.Selected];
LDetailsKeys := EMSConsoleData.GetEdgeModulesFieldsArray;
SetLength(LEdgeModuleInfo.Details, Length(LDetailsKeys));
LHeaderList := TList<string>.Create;
try
for I := 0 to FFrameJSONGrid.StringGrid.ColumnCount - 1 do
LHeaderList.Add(FFrameJSONGrid.StringGrid.Columns[I].Header);
for I := Low(LDetailsKeys) to High(LDetailsKeys) do
begin
LEdgeModuleInfo.Details[I].Key := LDetailsKeys[I];
LColIndex := LHeaderList.IndexOf(LDetailsKeys[I]);
LEdgeModuleInfo.Details[I].Value := FFrameJSONGrid.StringGrid.Cells
[LColIndex, FFrameJSONGrid.StringGrid.Selected]
end;
ADialog.EdgeModuleInfo := LEdgeModuleInfo;
finally
LHeaderList.Free;
end;
end;
procedure TEdgeModuleTabItem.ShowFrame(ADialog: TFormAddDlg);
begin
ADialog.AddFrame.ShowEdgeModuleAddTab;
end;
procedure TEdgeModuleTabItem.UpdateView(AIndetifier: string;
ACellList: TList<TCell>);
var
LJSON: TJSONObject;
I, Col, Row: integer;
begin
LJSON := TJSONObject.Create;
try
Row := -1;
for I := 0 to ACellList.Count - 1 do
begin
Col := ACellList.Items[I].Col;
Row := ACellList.Items[I].Row;
LJSON.AddPair(FFrameJSONGrid.StringGrid.Columns[Col].Header,
FFrameJSONGrid.StringGrid.Cells[Col, Row]);
end;
FEMSConsoleData.UpdateEdgeModule(AIndetifier, '',
FFrameJSONGrid.StringGrid.Cells
[GetHeaderIndex(TEdgeModuleInfo.cModuleProtocol), Row],
FrameJSONGrid.StringGrid.Cells
[GetHeaderIndex(TEdgeModuleInfo.cModuleProtocolProps), Row], LJSON);
finally
LJSON.Free;
end;
end;
{ TResourceTabItem }
constructor TResourceTabItem.Create(AOwner: TComponent);
begin
inherited;
FrameJSONGrid.OnGetData := OnGetResourcesData;
FrameJSONGrid.OnGetFields := OnGetResourcesFields;
// FrameJSONGrid.ComboBoxExtras.Items.Clear;
TabOrder := 0;
end;
function TResourceTabItem.Delete(const AID: string): Boolean;
begin
Result := FEMSConsoleData.DeleteResource(FFrameJSONGrid.StringGrid.Cells
[GetHeaderIndex(TResourcesInfo.cModuleID),
FFrameJSONGrid.StringGrid.Selected], AID);
end;
function TResourceTabItem.GetObjectIdentifier(const Row: integer): string;
var
ColIndex: integer;
begin
ColIndex := GetHeaderIndex(TResourcesInfo.cResourceName);
if ColIndex >= 0 then
Result := FFrameJSONGrid.StringGrid.Cells[ColIndex, Row];
end;
procedure TResourceTabItem.LoadComboModules;
var
LJSON: TJSONArray;
LJSONValue: TJSONValue;
I, Index: integer;
begin
LJSON := TJSONArray.Create;
try
FEMSConsoleData.GetEdgeModules(Self, LJSON);
if GetCombo.Items.Count <> LJSON.Count + 1 then
begin
GetCombo.Clear;
GetCombo.Items.Add(strAllEdgeModule);
for I := 0 to LJSON.Count - 1 do
begin
LJSONValue := LJSON.Items[I];
Index := GetCombo.Items.Add
(LJSONValue.GetValue<string>(TResourcesInfo.cModuleName));
GetCombo.ListItems[Index].ItemData.Detail :=
LJSONValue.GetValue<string>(TResourcesInfo.cID);
end;
GetCombo.ItemIndex := 0;
end;
finally
LJSON.Free
end;
end;
procedure TResourceTabItem.OnGetResourcesData(Sender: TObject;
const AJSON: TJSONArray);
var
LSelectedModule: string;
begin
LSelectedModule := GetSelectedModule;
if LSelectedModule = '' then
LoadComboModules;
FEMSConsoleData.GetResource(Sender, LSelectedModule, AJSON);
end;
procedure TResourceTabItem.OnGetResourcesFields(Sender: TObject;
const AJSON: TJSONArray);
begin
FEMSConsoleData.GetResourcesFields(Sender, AJSON);
end;
procedure TResourceTabItem.SetObjectInfoToAddDlg(ADialog: TFormAddDlg);
var
I, LColIndex: integer;
LDetailsKeys: TArray<string>;
LHeaderList: TList<string>;
LResourceInfo: TResourcesInfo;
begin
LResourceInfo.ResourceName := FFrameJSONGrid.StringGrid.Cells
[GetHeaderIndex(TResourcesInfo.cResourceName),
FFrameJSONGrid.StringGrid.Selected];
LResourceInfo.ModuleName := FFrameJSONGrid.StringGrid.Cells
[GetHeaderIndex(TResourcesInfo.cModuleName),
FFrameJSONGrid.StringGrid.Selected];
LResourceInfo.ModuleID := FFrameJSONGrid.StringGrid.Cells
[GetHeaderIndex(TResourcesInfo.cModuleID),
FFrameJSONGrid.StringGrid.Selected];
LDetailsKeys := EMSConsoleData.GetResourcesFieldsArray;
SetLength(LResourceInfo.Details, Length(LDetailsKeys));
LHeaderList := TList<string>.Create;
try
for I := 0 to FFrameJSONGrid.StringGrid.ColumnCount - 1 do
LHeaderList.Add(FFrameJSONGrid.StringGrid.Columns[I].Header);
for I := Low(LDetailsKeys) to High(LDetailsKeys) do
begin
LResourceInfo.Details[I].Key := LDetailsKeys[I];
LColIndex := LHeaderList.IndexOf(LDetailsKeys[I]);
LResourceInfo.Details[I].Value := FFrameJSONGrid.StringGrid.Cells
[LColIndex, FFrameJSONGrid.StringGrid.Selected];
end;
ADialog.ResourceInfo := LResourceInfo;
finally
LHeaderList.Free;
end;
end;
procedure TResourceTabItem.ShowFrame(ADialog: TFormAddDlg);
begin
ADialog.AddFrame.ShowResourceAddTab;
end;
procedure TResourceTabItem.UpdateView(AIndetifier: string;
ACellList: TList<TCell>);
var
LJSON: TJSONObject;
I, Col, Row, ColIndex: integer;
begin
LJSON := TJSONObject.Create;
try
Row := -1;
for I := 0 to ACellList.Count - 1 do
begin
Col := ACellList.Items[I].Col;
Row := ACellList.Items[I].Row;
LJSON.AddPair(FFrameJSONGrid.StringGrid.Columns[Col].Header,
FFrameJSONGrid.StringGrid.Cells[Col, Row]);
end;
ColIndex := GetHeaderIndex(TResourcesInfo.cModuleID);
FEMSConsoleData.UpdateResource(FFrameJSONGrid.StringGrid.Cells[ColIndex,
Row], AIndetifier, LJSON);
finally
LJSON.Free;
end;
end;
end.
|
unit uRescanThread;
interface
uses
Classes, Windows, SysUtils, SyncObjs, Dialogs, uGetHandlesThread, Messages;
type
TRescanThread = class(TThread)
private
{ Private declarations }
mEvent: TEvent;
FDeleteJob: Boolean;
FhWindow: THandle;
FhEdit: THandle;
protected
procedure Execute; override;
public
property DeleteJob: Boolean read FDeleteJob;
constructor Create(const hWindow, hEdit: THandle);
destructor Destroy; override;
procedure Terminate;
end;
implementation
uses Mainform;
constructor TRescanThread.Create(const hWindow, hEdit: THandle);
begin
inherited Create(False);
FDeleteJob := False;
FhWindow := hWindow;
FhEdit := hEdit;
mEvent := TEvent.Create(nil, True, False, '');
end; { TRescanThread.Create }
function GetProcessImageFileName(hProcess: THandle; lpImageFileName: LPCWSTR; nSize: DWORD): DWORD; stdcall; external 'PSAPI.dll' name 'GetProcessImageFileNameW';
procedure TRescanThread.Execute;
var
i: Integer;
hProcess: THandle;
lpszProcess: PChar;
ProcessExist: Boolean;
begin
try
repeat
for i := 0 to High(OpenHandlesInfo) do
begin
if Terminated then
Exit;
ProcessExist := False;
try
hProcess := OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, OpenHandlesInfo[i].ProcessID);
except
hProcess := 0;
end;
if hProcess <> 0 then
begin
lpszProcess := AllocMem(MAX_PATH);
try
if GetProcessImageFileName(hProcess, lpszProcess, 2 * MAX_PATH) > 0 then
ProcessExist := OpenHandlesInfo[i].ProcessFullPath = ConvertPhysicalNameToVirtualPathName(string(lpszProcess));
finally
FreeMem(lpszProcess);
CloseHandle(hProcess);
end;
end;
OpenHandlesInfo[i].Delete := not ProcessExist;
FDeleteJob := FDeleteJob or OpenHandlesInfo[i].Delete;
end;
if FDeleteJob then
PostMessage(frmMain.Handle, WM_USER + 1000, FhWindow, FhEdit);
mEvent.WaitFor(500);
until Terminated;
finally
FRescanJobDone := True;
end;
end; { TRescanThread.Execute }
destructor TRescanThread.Destroy;
begin
mEvent.Free;
mEvent := nil;
end;
procedure TRescanThread.Terminate;
begin
TThread(Self).Terminate;
mEvent.SetEvent;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC GUIx layer base classes }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.UI;
interface
uses
System.Classes, System.IniFiles,
FireDAC.Stan.Factory, FireDAC.Stan.Intf, FireDAC.Stan.Util, FireDAC.Stan.Consts,
FireDAC.UI.Intf;
type
TFDGUIxObject = class(TFDObject)
protected
class function IsFactoryEnabled(const AMyProvider, AReqProvider: String): Boolean; override;
end;
PFDLoginItem = ^TFDLoginItem;
TFDLoginItem = record
FParam: String;
FType: String;
FCaption: String;
FOrder: Integer;
FValue: String;
end;
TFDGUIxLoginDialogImplBase = class(TFDGUIxObject, IFDGUIxLoginDialog)
private
FOnHide: TNotifyEvent;
FOnShow: TNotifyEvent;
FLoginRetries: Integer;
FOnChangePassword: TFDGUIxLoginDialogEvent;
FOnLogin: TFDGUIxLoginDialogEvent;
FChangeExpiredPassword: Boolean;
function CreateHistoryIniFile: TCustomIniFile;
function InitParamList: Boolean;
procedure LoadHistory;
procedure SaveHistory;
protected
// run-time
FParams: array of TFDLoginItem;
FHistory: TStrings;
FHistoryIndex: Integer;
// setup
FCaption: String;
FConnectionDef: IFDStanConnectionDef;
FHistoryEnabled: Boolean;
FHistoryKey: String;
FHistoryStorage: TFDGUIxLoginHistoryStorage;
FHistoryWithPassword: Boolean;
FVisibleItems: TStrings;
// IFDGUIxLoginDialog
function GetCaption: String;
function GetChangeExpiredPassword: Boolean;
function GetHistoryEnabled: Boolean;
function GetHistoryKey: String;
function GetHistoryStorage: TFDGUIxLoginHistoryStorage;
function GetHistoryWithPassword: Boolean;
function GetLoginRetries: Integer;
function GetVisibleItems: TStrings;
function GetConnectionDef: IFDStanConnectionDef;
function GetOnHide: TNotifyEvent;
function GetOnShow: TNotifyEvent;
function GetOnChangePassword: TFDGUIxLoginDialogEvent;
function GetOnLogin: TFDGUIxLoginDialogEvent;
procedure SetCaption(const AValue: String);
procedure SetChangeExpiredPassword(const AValue: Boolean);
procedure SetHistoryEnabled(const AValue: Boolean);
procedure SetHistoryKey(const AValue: String);
procedure SetHistoryStorage(const AValue: TFDGUIxLoginHistoryStorage);
procedure SetHistoryWithPassword(const AValue: Boolean);
procedure SetLoginRetries(const AValue: Integer);
procedure SetVisibleItems(const AValue: TStrings);
procedure SetConnectionDef(const AValue: IFDStanConnectionDef);
procedure SetOnHide(const AValue: TNotifyEvent);
procedure SetOnShow(const AValue: TNotifyEvent);
procedure SetOnChangePassword(const AValue: TFDGUIxLoginDialogEvent);
procedure SetOnLogin(const AValue: TFDGUIxLoginDialogEvent);
function Execute(ALoginAction: TFDGUIxLoginAction): Boolean;
procedure GetAllLoginParams;
// Forms & FMX
function ExecuteLogin: Boolean; virtual; abstract;
function ExecuteChngPwd: Boolean; virtual; abstract;
// runtime
procedure RemoveHistory(const AName: String);
procedure ReadHistory(const AName: String; AList: TStrings);
public
procedure Initialize; override;
destructor Destroy; override;
end;
TFDGUIxScriptImplBase = class(TFDGUIxObject, IFDGUIxScriptDialog)
protected
FOnShow: TNotifyEvent;
FOnHide: TNotifyEvent;
FOnProgress: TFDGUIxScriptProgressEvent;
FOnOutput: TFDGUIxScriptOutputEvent;
FOnInput: TFDGUIxScriptInputEvent;
FOnPause: TFDGUIxScriptPauseEvent;
FCaption: String;
FOptions: TFDGUIxScriptOptions;
// IFDGUIxScriptDialog
function GetOnShow: TNotifyEvent;
procedure SetOnShow(const AValue: TNotifyEvent);
function GetOnHide: TNotifyEvent;
procedure SetOnHide(const AValue: TNotifyEvent);
function GetOnProgress: TFDGUIxScriptProgressEvent;
procedure SetOnProgress(const AValue: TFDGUIxScriptProgressEvent);
function GetOnOutput: TFDGUIxScriptOutputEvent;
procedure SetOnOutput(const AValue: TFDGUIxScriptOutputEvent);
function GetOnInput: TFDGUIxScriptInputEvent;
procedure SetOnInput(const AValue: TFDGUIxScriptInputEvent);
function GetOnPause: TFDGUIxScriptPauseEvent;
procedure SetOnPause(const AValue: TFDGUIxScriptPauseEvent);
function GetCaption: String;
procedure SetCaption(const AValue: String);
function GetOptions: TFDGUIxScriptOptions;
procedure SetOptions(AValue: TFDGUIxScriptOptions);
procedure Show; virtual; abstract;
procedure Progress(const AInfoProvider: IFDGUIxScriptDialogInfoProvider); virtual; abstract;
procedure Output(const AStr: String; AKind: TFDScriptOutputKind); virtual; abstract;
procedure Input(const APrompt: String; var AResult: String); virtual; abstract;
procedure Pause(const APrompt: String); virtual; abstract;
procedure Hide; virtual; abstract;
end;
TFDGUIxVisualScriptImplBase = class(TFDGUIxScriptImplBase)
public
procedure Initialize; override;
end;
TFDGUIxWaitCursorImplBase = class(TFDGUIxObject, IFDGUIxWaitCursor)
protected
FWaitCursor: TFDGUIxScreenCursor;
FOnShow: TNotifyEvent;
FOnHide: TNotifyEvent;
// IFDGUIxWaitCursor
procedure StartWait; virtual; abstract;
procedure StopWait; virtual; abstract;
procedure PushWait; virtual; abstract;
procedure PopWait; virtual; abstract;
procedure ForceStopWait; virtual; abstract;
function GetWaitCursor: TFDGUIxScreenCursor;
procedure SetWaitCursor(const AValue: TFDGUIxScreenCursor);
function GetOnShow: TNotifyEvent;
procedure SetOnShow(const AValue: TNotifyEvent);
function GetOnHide: TNotifyEvent;
procedure SetOnHide(const AValue: TNotifyEvent);
end;
TFDGUIxVisualWaitCursorImplBase = class(TFDGUIxWaitCursorImplBase)
private
FTimer: IFDGUIxTimer;
FStopRequestTime: Cardinal;
FWasActive: Integer;
function IsVisible: Boolean;
procedure HideCursor;
procedure ShowCursor;
procedure TimerProc(ASender: TObject);
procedure StopTimer;
procedure StartTimer;
protected
function CheckCurCursor: Boolean; virtual; abstract;
function InternalHideCursor: Boolean; virtual; abstract;
procedure InternalShowCursor; virtual; abstract;
// IFDGUIxWaitCursor
procedure StartWait; override;
procedure StopWait; override;
procedure PushWait; override;
procedure PopWait; override;
procedure ForceStopWait; override;
public
procedure Initialize; override;
destructor Destroy; override;
end;
implementation
uses
{$IFDEF MSWINDOWS}
System.Win.Registry,
{$ENDIF}
System.SysUtils,
FireDAC.Stan.ResStrs, FireDAC.Stan.Error,
FireDAC.DatS,
FireDAC.Phys.Intf;
var
FWait: TFDGUIxWaitCursorImplBase;
{-------------------------------------------------------------------------------}
{ TFDGUIxObject }
{-------------------------------------------------------------------------------}
class function TFDGUIxObject.IsFactoryEnabled(const AMyProvider,
AReqProvider: String): Boolean;
begin
if FDIsDesignTime then
Result := CompareText(AMyProvider, C_FD_GUIxFormsProvider) = 0
else if AReqProvider = '' then
Result := CompareText(AMyProvider, FFDGUIxProvider) = 0
else
Result := CompareText(AMyProvider, AReqProvider) = 0;
end;
{-------------------------------------------------------------------------------}
{ TFDGUIxLoginDialogImplBase }
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.Initialize;
begin
inherited Initialize;
{$IFDEF MSWINDOWS}
FHistoryStorage := hsRegistry;
FHistoryKey := S_FD_CfgKeyName + '\' + S_FD_Profiles;
{$ENDIF}
{$IFDEF POSIX}
FHistoryStorage := hsFile;
FHistoryKey := S_FD_Profiles;
{$ENDIF}
FHistoryWithPassword := True;
FHistoryEnabled := False;
FHistory := TFDStringList.Create;
FHistoryIndex := -1;
FCaption := S_FD_LoginDialogDefCaption;
FVisibleItems := TFDStringList.Create;
FVisibleItems.Add(S_FD_ConnParam_Common_UserName);
FVisibleItems.Add(S_FD_ConnParam_Common_Password);
FLoginRetries := 3;
FChangeExpiredPassword := True;
end;
{-------------------------------------------------------------------------------}
destructor TFDGUIxLoginDialogImplBase.Destroy;
begin
FDFreeAndNil(FHistory);
FDFreeAndNil(FVisibleItems);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialogImplBase.GetCaption: String;
begin
Result := FCaption;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialogImplBase.GetChangeExpiredPassword: Boolean;
begin
Result := FChangeExpiredPassword;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialogImplBase.GetConnectionDef: IFDStanConnectionDef;
begin
Result := FConnectionDef;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialogImplBase.GetHistoryEnabled: Boolean;
begin
Result := FHistoryEnabled;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialogImplBase.GetHistoryKey: String;
begin
Result := FHistoryKey;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialogImplBase.GetHistoryStorage: TFDGUIxLoginHistoryStorage;
begin
Result := FHistoryStorage;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialogImplBase.GetHistoryWithPassword: Boolean;
begin
Result := FHistoryWithPassword;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialogImplBase.GetLoginRetries: Integer;
begin
Result := FLoginRetries;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialogImplBase.GetVisibleItems: TStrings;
begin
Result := FVisibleItems;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialogImplBase.GetOnHide: TNotifyEvent;
begin
Result := FOnHide;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialogImplBase.GetOnShow: TNotifyEvent;
begin
Result := FOnShow;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialogImplBase.GetOnChangePassword: TFDGUIxLoginDialogEvent;
begin
Result := FOnChangePassword;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialogImplBase.GetOnLogin: TFDGUIxLoginDialogEvent;
begin
Result := FOnLogin;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.SetOnHide(const AValue: TNotifyEvent);
begin
FOnHide := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.SetCaption(const AValue: String);
begin
FCaption := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.SetChangeExpiredPassword(const AValue: Boolean);
begin
FChangeExpiredPassword := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.SetConnectionDef(const AValue: IFDStanConnectionDef);
begin
FConnectionDef := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.SetHistoryEnabled(const AValue: Boolean);
begin
FHistoryEnabled := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.SetHistoryKey(const AValue: String);
begin
FHistoryKey := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.SetHistoryStorage(const AValue: TFDGUIxLoginHistoryStorage);
begin
FHistoryStorage := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.SetHistoryWithPassword(const AValue: Boolean);
begin
FHistoryWithPassword := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.SetLoginRetries(const AValue: Integer);
begin
FLoginRetries := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.SetVisibleItems(const AValue: TStrings);
begin
FVisibleItems.SetStrings(AValue);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.SetOnShow(const AValue: TNotifyEvent);
begin
FOnShow := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.SetOnChangePassword(const AValue: TFDGUIxLoginDialogEvent);
begin
FOnChangePassword := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.SetOnLogin(const AValue: TFDGUIxLoginDialogEvent);
begin
FOnLogin := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.GetAllLoginParams;
var
oMeta: IFDPhysManagerMetadata;
oDrv: IFDPhysDriverMetadata;
i: Integer;
oTab: TFDDatSTable;
begin
FDPhysManager.CreateMetadata(oMeta);
if FDPhysManager.State <> dmsActive then
FDPhysManager.Open;
oMeta.CreateDriverMetadata(FConnectionDef.Params.DriverID, oDrv);
oTab := oDrv.GetConnParams(FConnectionDef.Params);
try
FVisibleItems.Clear;
for i := 0 to oTab.Rows.Count - 1 do
if oTab.Rows[i].GetData('LoginIndex') <> -1 then
FVisibleItems.Add(oTab.Rows[i].GetData('Name') + '=' + oTab.Rows[i].GetData('Caption'));
finally
FDFree(oTab);
end;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialogImplBase.InitParamList: Boolean;
var
oMeta: IFDPhysManagerMetadata;
oDrv: IFDPhysDriverMetadata;
i: Integer;
oTab: TFDDatSTable;
procedure AddItem(const AName, AType, ACaption: String; AOrder: Integer;
const AValue: String);
var
i: Integer;
s, sCaption: String;
lOk: Boolean;
pParam: PFDLoginItem;
begin
sCaption := ACaption;
lOk := FVisibleItems.Count = 0;
if not lOk then begin
for i := 0 to FVisibleItems.Count - 1 do
if CompareText(FVisibleItems.KeyNames[i], AName) = 0 then begin
s := FVisibleItems.ValueFromIndex[i];
if s <> '' then
sCaption := s;
lOk := True;
Break;
end;
if not lOk then begin
s := Trim(FVisibleItems.Text);
lOk := (s = '') or (s = '*');
end;
end;
if lOk then begin
SetLength(FParams, Length(FParams) + 1);
pParam := @FParams[Length(FParams) - 1];
pParam^.FParam := AName;
pParam^.FType := AType;
pParam^.FCaption := sCaption;
pParam^.FOrder := AOrder;
pParam^.FValue := AValue;
end;
end;
begin
SetLength(FParams, 0);
if FDPhysManager.State = dmsInactive then
FDPhysManager.Open;
FDPhysManager.CreateMetadata(oMeta);
oMeta.CreateDriverMetadata(FConnectionDef.Params.DriverID, oDrv);
oTab := oDrv.GetConnParams(FConnectionDef.Params);
try
for i := 0 to oTab.Rows.Count - 1 do
if oTab.Rows[i].GetData('LoginIndex') <> -1 then
AddItem(oTab.Rows[i].GetData('Name'), oTab.Rows[i].GetData('Type'),
oTab.Rows[i].GetData('Caption'), oTab.Rows[i].GetData('LoginIndex'),
FConnectionDef.AsString[oTab.Rows[i].GetData('Name')]);
finally
FDFree(oTab);
end;
Result := Length(FParams) > 0;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.LoadHistory;
var
oIni: TCustomIniFile;
i: Integer;
begin
FHistoryIndex := -1;
FHistory.Clear;
if FHistoryEnabled then begin
oIni := CreateHistoryIniFile;
try
oIni.ReadSections(FHistory);
i := 0;
while i < FHistory.Count do
if Pos(FConnectionDef.Params.DriverID + ' - ', FHistory[i]) = 0 then
FHistory.Delete(i)
else begin
FHistory[i] := FDStrReplace(FHistory[i], '/', '\');
Inc(i);
end;
FHistoryIndex := FHistory.IndexOf(FConnectionDef.Params.DriverID + ' - ' +
AnsiUpperCase(FConnectionDef.Params.Database) + ' - ' + FConnectionDef.Params.UserName);
finally
FDFree(oIni);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.SaveHistory;
var
oIni: TCustomIniFile;
i: Integer;
sName: String;
begin
if FHistoryEnabled then begin
oIni := CreateHistoryIniFile;
try
sName := FConnectionDef.Params.DriverID + ' - ' +
FDStrReplace(AnsiUpperCase(FConnectionDef.Params.Database), '\', '/') + ' - ' +
FConnectionDef.Params.UserName;
oIni.EraseSection(sName);
for i := 0 to Length(FParams) - 1 do
if FHistoryWithPassword or
(CompareText(FParams[i].FParam, S_FD_ConnParam_Common_Password) <> 0) then
oIni.WriteString(sName, FParams[i].FParam, FConnectionDef.AsString[FParams[i].FParam]);
finally
FDFree(oIni);
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialogImplBase.CreateHistoryIniFile: TCustomIniFile;
begin
Result := nil;
if FHistoryStorage = hsRegistry then
{$IFDEF MSWINDOWS}
Result := TRegistryIniFile.Create(FHistoryKey)
{$ELSE}
FDCapabilityNotSupported(nil, [S_FD_LGUIx, S_FD_LGUIx_PForms])
{$ENDIF}
else if FHistoryStorage = hsFile then begin
Result := TMemIniFile.Create(FHistoryKey);
TMemIniFile(Result).AutoSave := True;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.RemoveHistory(const AName: String);
var
oIni: TCustomIniFile;
begin
oIni := CreateHistoryIniFile;
try
oIni.EraseSection(FDStrReplace(AName, '\', '/'));
finally
FDFree(oIni);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialogImplBase.ReadHistory(const AName: String; AList: TStrings);
var
oIni: TCustomIniFile;
begin
oIni := CreateHistoryIniFile;
try
oIni.ReadSectionValues(FDStrReplace(AName, '\', '/'), AList);
finally
FDFree(oIni);
end;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialogImplBase.Execute(ALoginAction: TFDGUIxLoginAction): Boolean;
var
iRetries: Integer;
lRetry, lLoginPrompt, lInit: Boolean;
begin
if FConnectionDef = nil then begin
Result := False;
Exit;
end;
if FDGUIxSilent() then begin
if Assigned(ALoginAction) then
ALoginAction;
Result := True;
Exit;
end;
if Assigned(FOnShow) then
FOnShow(Self);
iRetries := 0;
lRetry := False;
lLoginPrompt := True;
lInit := True;
try
repeat
try
if lLoginPrompt then begin
if Assigned(FOnLogin) then begin
Result := True;
FOnLogin(Self, Result);
end
else begin
if lInit or lRetry then begin
if not InitParamList then begin
Result := True;
Exit;
end;
LoadHistory;
lInit := False;
end;
Result := ExecuteLogin;
end;
end
else begin
lLoginPrompt := True;
Result := True;
end;
if Result and Assigned(ALoginAction) then
ALoginAction;
lRetry := False;
except on E: EFDDBEngineException do
// invalid password/user name
if (E.Kind = ekUserPwdInvalid) and (FLoginRetries >= 0) then begin
FDHandleException;
Inc(iRetries);
if iRetries >= FLoginRetries then
FDException(Self, [S_FD_LGUIx, S_FD_LGUIx_PForms], er_FD_AccToManyLogins,
[FLoginRetries]);
lRetry := True;
end
// password expired
else if (E.Kind = ekUserPwdExpired) and FChangeExpiredPassword then begin
FDHandleException;
if Assigned(FOnChangePassword) then begin
Result := True;
FOnChangePassword(Self, Result);
end
else
Result := ExecuteChngPwd;
lLoginPrompt := False;
lRetry := Result;
end
// will expired
else if E.Kind = ekUserPwdWillExpire then
FDHandleException
else
raise;
end;
until not lRetry;
if Result then begin
SaveHistory;
if Assigned(FOnHide) then
FOnHide(Self);
end;
finally
SetLength(FParams, 0);
end;
end;
{-------------------------------------------------------------------------------}
{ TFDGUIxScriptImplBase }
{-------------------------------------------------------------------------------}
function TFDGUIxScriptImplBase.GetOnHide: TNotifyEvent;
begin
Result := FOnHide;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxScriptImplBase.GetOnShow: TNotifyEvent;
begin
Result := FOnShow;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxScriptImplBase.SetOnHide(const AValue: TNotifyEvent);
begin
FOnHide := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxScriptImplBase.SetOnShow(const AValue: TNotifyEvent);
begin
FOnShow := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxScriptImplBase.GetOnOutput: TFDGUIxScriptOutputEvent;
begin
Result := FOnOutput;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxScriptImplBase.SetOnOutput(const AValue: TFDGUIxScriptOutputEvent);
begin
FOnOutput := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxScriptImplBase.GetOnInput: TFDGUIxScriptInputEvent;
begin
Result := FOnInput;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxScriptImplBase.SetOnInput(const AValue: TFDGUIxScriptInputEvent);
begin
FOnInput := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxScriptImplBase.GetOnPause: TFDGUIxScriptPauseEvent;
begin
Result := FOnPause;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxScriptImplBase.SetOnPause(const AValue: TFDGUIxScriptPauseEvent);
begin
FOnPause := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxScriptImplBase.GetOnProgress: TFDGUIxScriptProgressEvent;
begin
Result := FOnProgress;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxScriptImplBase.SetOnProgress(const AValue: TFDGUIxScriptProgressEvent);
begin
FOnProgress := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxScriptImplBase.GetCaption: String;
begin
Result := FCaption;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxScriptImplBase.SetCaption(const AValue: String);
begin
FCaption := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxScriptImplBase.GetOptions: TFDGUIxScriptOptions;
begin
Result := FOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxScriptImplBase.SetOptions(AValue: TFDGUIxScriptOptions);
begin
FOptions := AValue;
end;
{-------------------------------------------------------------------------------}
{ TFDGUIxVisualScriptImplBase }
{-------------------------------------------------------------------------------}
procedure TFDGUIxVisualScriptImplBase.Initialize;
begin
inherited Initialize;
FCaption := S_FD_ScriptDialogDefCaption;
FOptions := [ssCallstack, ssConsole, ssAutoHide];
FOnShow := nil;
FOnHide := nil;
FOnProgress := nil;
FOnOutput := nil;
FOnInput := nil;
FOnPause := nil;
end;
{-------------------------------------------------------------------------------}
{ TFDGUIxWaitCursorImplBase }
{-------------------------------------------------------------------------------}
function TFDGUIxWaitCursorImplBase.GetWaitCursor: TFDGUIxScreenCursor;
begin
Result := FWaitCursor;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxWaitCursorImplBase.SetWaitCursor(const AValue: TFDGUIxScreenCursor);
begin
FWaitCursor := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxWaitCursorImplBase.GetOnHide: TNotifyEvent;
begin
Result := FOnHide;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxWaitCursorImplBase.GetOnShow: TNotifyEvent;
begin
Result := FOnShow;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxWaitCursorImplBase.SetOnHide(const AValue: TNotifyEvent);
begin
FOnHide := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxWaitCursorImplBase.SetOnShow(const AValue: TNotifyEvent);
begin
FOnShow := AValue;
end;
{-------------------------------------------------------------------------------}
{ TFDGUIxVisualWaitCursorImplBase }
{-------------------------------------------------------------------------------}
procedure TFDGUIxVisualWaitCursorImplBase.Initialize;
begin
inherited Initialize;
FWait := Self;
FWaitCursor := gcrSQLWait;
end;
{-------------------------------------------------------------------------------}
destructor TFDGUIxVisualWaitCursorImplBase.Destroy;
begin
ForceStopWait;
FTimer := nil;
inherited Destroy;
FWait := nil;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxVisualWaitCursorImplBase.IsVisible: Boolean;
begin
Result := not FDGUIxSilent() and (FWaitCursor <> gcrNone);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxVisualWaitCursorImplBase.StopTimer;
begin
FStopRequestTime := 0;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxVisualWaitCursorImplBase.TimerProc(ASender: TObject);
begin
if (FStopRequestTime <> 0) and
FDTimeout(FStopRequestTime, C_FD_HideCursorDelay) then begin
if IsVisible then
HideCursor;
StopTimer;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxVisualWaitCursorImplBase.StartTimer;
begin
if FTimer = nil then begin
FDCreateInterface(IFDGUIxTimer, FTimer);
FTimer.Enabled := False;
FTimer.SetEvent(TimerProc, C_FD_HideCursorDelay);
end;
FTimer.Enabled := True;
FStopRequestTime := TThread.GetTickCount();
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxVisualWaitCursorImplBase.ShowCursor;
begin
if not CheckCurCursor then begin
if Assigned(FOnShow) then
FOnShow(Self);
InternalShowCursor;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxVisualWaitCursorImplBase.HideCursor;
begin
if FTimer <> nil then
FTimer.Enabled := False;
if InternalHideCursor then
if Assigned(FOnHide) then
FOnHide(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxVisualWaitCursorImplBase.StartWait;
begin
if not IsVisible then
Exit;
StopTimer;
ShowCursor;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxVisualWaitCursorImplBase.StopWait;
begin
if not IsVisible then
Exit;
StartTimer;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxVisualWaitCursorImplBase.PopWait;
begin
if not IsVisible then
Exit;
if CheckCurCursor then
if FStopRequestTime > 0 then
FWasActive := 2
else
FWasActive := 1
else
FWasActive := 0;
HideCursor;
StopTimer;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxVisualWaitCursorImplBase.PushWait;
begin
if not IsVisible then
Exit;
case FWasActive of
2: begin
ShowCursor;
StartTimer;
end;
1: ShowCursor;
0: ;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxVisualWaitCursorImplBase.ForceStopWait;
begin
StopTimer;
if FTimer <> nil then
FTimer.Enabled := False;
HideCursor;
FWasActive := 0;
end;
end.
|
unit UVenda;
interface
uses UCliente, UUsuario, UCondicaoPagamento, UProdutoVenda,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
UParcelas, Dialogs, UCalcProduto;
type Venda = class
private
protected
numNota : Integer;
serieNota : string[2];
idOrdemServico : Integer;
umCliente : Cliente;
umUsuario : Usuario;
umaCondicaoPgto : CondicaoPagamento;
umProdutoVenda : ProdutoVenda;
umCalcProduto : CalcProduto;
umaParcela : Parcelas;
ListaProdutos : TList;
ListaParcelas : TList;
ListaCalcProduto: TList;
status : string[15];
TotalAux : Real;
dataCadastro : TDateTime;
dataAlteracao : TDateTime;
dataEmissao : TDateTime;
dataVenda : TDateTime;
observacao : string[255];
tipo : Boolean; //Condição para verificar quando os dados vem de uma compra ou contas a pagar
public
indice : Integer;
Constructor CrieObjeto;
Destructor Destrua_Se;
Procedure setNumNota (vNumNota : Integer);
Procedure setSerieNota (vSerieNota : String);
Procedure setIdOrdemServico (vIdOrdemServico : Integer);
Procedure setUmCliente (vCliente : Cliente);
Procedure setUmUsuario (vUsuario : Usuario);
Procedure setUmaCondicaoPagamento (vCondicaoPagamento : CondicaoPagamento);
procedure setumProdutoVenda (vProdutoVenda : ProdutoVenda);
procedure setUmCalcProduto (vCalcProduto : CalcProduto);
Procedure setStatus (vStatus : String);
Procedure setTotalAux (vTotalAux : Real);
Procedure setDataEmissao (vDataEmissao : TDateTime);
Procedure setDataVenda (vDataVenda : TDateTime);
Procedure setDataCadastro (vDataCadastro : TDateTime);
Procedure setDataAlteracao (vDataAlteracao : TDateTime);
Procedure setObservacao (vObservacao : String);
Procedure setTipo (vTipo : Boolean);
Function getNumNota : Integer;
Function getSerieNota : String;
Function getIdOrdemServico : Integer;
Function getUmCliente : Cliente;
Function getUmUsuario : Usuario;
Function getUmaCondicaoPagamento : CondicaoPagamento;
Function getUmProdutoVenda : ProdutoVenda;
Function getUmCalcProduto : CalcProduto;
Function getStatus : String;
Function getTotalAux : Real;
Function getDataEmissao : TDateTime;
Function getDataVenda : TDateTime;
Function getDataCadastro : TDateTime;
Function getDataAlteracao : TDateTime;
Function getObservacao : String;
Function getTipo : Boolean;
//Produto
procedure CrieObejtoProduto;
procedure addProdutoVenda(vProdutoVenda : ProdutoVenda);
function getProdutoVenda(produto:Integer):ProdutoVenda;
procedure LimparListaProduto;
procedure removeItemProdutoVenda(Index : Integer);
function CountProdutos : Integer;
//Parcelas
procedure CrieObjetoParcela;
procedure addParcelas(vParcelas : Parcelas);
function getParcelas(parcela:Integer):Parcelas;
procedure LimparListaParcelas;
function CountParcelas : Integer;
//Calcular Produto
procedure CrieObjetoCalcProduto;
procedure addCalcProduto(vCalcProduto : CalcProduto);
function getCalcProduto(calc:Integer): CalcProduto;
procedure LimparListaCalcProduto;
function CountCalcProduto : Integer;
end;
implementation
{ Venda }
constructor Venda.CrieObjeto;
var dataAtual : TDateTime;
begin
dataAtual := Date;
numNota := 0;
serieNota := '';
idOrdemServico := 0;
umCliente := Cliente.CrieObjeto;
umUsuario := Usuario.CrieObjeto;
umaCondicaoPgto := CondicaoPagamento.CrieObjeto;
ListaProdutos := TList.Create;
ListaParcelas := TList.Create;
ListaCalcProduto:= TList.Create;
status := '';
TotalAux := 0;
dataCadastro := dataAtual;
dataAlteracao := dataAtual;
dataEmissao := dataAtual;
dataVenda := dataAtual;
observacao := '';
end;
destructor Venda.Destrua_Se;
begin
ListaProdutos.Destroy;
ListaParcelas.Destroy;
ListaCalcProduto.Destroy;
end;
procedure Venda.addProdutoVenda(vProdutoVenda : ProdutoVenda);
begin
ListaProdutos.Add(vProdutoVenda);
end;
function Venda.CountProdutos: Integer;
begin
Result := ListaProdutos.Count;
end;
function Venda.CountCalcProduto: Integer;
begin
Result := ListaCalcProduto.Count;
end;
function Venda.CountParcelas: Integer;
begin
Result := ListaParcelas.Count;
end;
procedure Venda.CrieObejtoProduto;
begin
umProdutoVenda := ProdutoVenda.CrieObjeto;
end;
procedure Venda.CrieObjetoCalcProduto;
begin
umCalcProduto := CalcProduto.CrieObjeto;
end;
procedure Venda.CrieObjetoParcela;
begin
umaParcela := Parcelas.CrieObjeto;
end;
function Venda.getDataAlteracao: TDateTime;
begin
Result := dataAlteracao;
end;
function Venda.getDataCadastro: TDateTime;
begin
Result := dataCadastro;
end;
function Venda.getDataEmissao: TDateTime;
begin
Result := dataEmissao;
end;
function Venda.getDataVenda: TDateTime;
begin
Result := dataVenda;
end;
function Venda.getIdOrdemServico: Integer;
begin
Result := idOrdemServico;
end;
function Venda.getNumNota: Integer;
begin
Result := numNota;
end;
function Venda.getObservacao: String;
begin
Result := observacao;
end;
//function Venda.getProdutos: ProdutoVenda;
//begin
// Result := ListaProdutos[indice-1];
//end;
//
function Venda.getParcelas(parcela: Integer): Parcelas;
begin
Result := ListaParcelas[parcela];
end;
function Venda.getProdutoVenda(produto: Integer): ProdutoVenda;
begin
Result := ListaProdutos[produto];
end;
function Venda.getCalcProduto(calc: Integer): CalcProduto;
begin
Result := ListaCalcProduto[calc];
end;
function Venda.getSerieNota: String;
begin
Result := serieNota;
end;
function Venda.getStatus: String;
begin
Result := status;
end;
function Venda.getTotalAux: Real;
begin
Result := TotalAux;
end;
function Venda.getUmaCondicaoPagamento: CondicaoPagamento;
begin
Result := umaCondicaoPgto;
end;
function Venda.getUmCalcProduto: CalcProduto;
begin
Result := umCalcProduto;
end;
function Venda.getUmCliente: Cliente;
begin
Result := umCliente;
end;
function Venda.getUmUsuario: Usuario;
begin
Result := umUsuario;
end;
function Venda.getUmProdutoVenda: ProdutoVenda;
begin
Result := umProdutoVenda;
end;
procedure Venda.LimparListaParcelas;
var i : Integer;
begin
for i := 0 to ListaParcelas.Count -1 do
Parcelas(ListaParcelas[i]).Free;
ListaParcelas.Clear;
end;
procedure Venda.LimparListaProduto;
var i : Integer;
begin
for i := 0 to ListaProdutos.Count -1 do
ProdutoVenda(ListaProdutos[i]).Free;
ListaProdutos.Clear;
end;
procedure Venda.LimparListaCalcProduto;
var i : Integer;
begin
for i := 0 to ListaCalcProduto.Count -1 do
CalcProduto(ListaCalcProduto[i]).Free;
ListaCalcProduto.Clear;
end;
procedure Venda.addParcelas(vParcelas: Parcelas);
begin
ListaParcelas.Add(vParcelas);
end;
procedure Venda.addCalcProduto(vCalcProduto: CalcProduto);
begin
ListaCalcProduto.Add(vCalcProduto);
end;
procedure Venda.removeItemProdutoVenda(Index: Integer);
begin
ListaProdutos.Delete(Index);
end;
procedure Venda.setDataAlteracao(vDataAlteracao: TDateTime);
begin
dataAlteracao := vDataAlteracao;
end;
procedure Venda.setDataCadastro(vDataCadastro: TDateTime);
begin
dataCadastro := vDataCadastro;
end;
procedure Venda.setDataEmissao(vDataEmissao: TDateTime);
begin
dataEmissao := vDataEmissao;
end;
procedure Venda.setDataVenda(vDataVenda: TDateTime);
begin
dataVenda := vDataVenda;
end;
procedure Venda.setIdOrdemServico(vIdOrdemServico: Integer);
begin
idOrdemServico := vIdOrdemServico;
end;
procedure Venda.setNumNota(vNumNota: Integer);
begin
numNota := vNumNota;
end;
procedure Venda.setObservacao(vObservacao: String);
begin
observacao := vObservacao;
end;
procedure Venda.setSerieNota(vSerieNota: String);
begin
serieNota := vSerieNota;
end;
procedure Venda.setStatus(vStatus: String);
begin
status := vStatus;
end;
procedure Venda.setTotalAux(vTotalAux: Real);
begin
TotalAux := vTotalAux;
end;
procedure Venda.setUmaCondicaoPagamento(
vCondicaoPagamento: CondicaoPagamento);
begin
umaCondicaoPgto := vCondicaoPagamento;
end;
procedure Venda.setUmCalcProduto(vCalcProduto: CalcProduto);
begin
umCalcProduto := vCalcProduto;
end;
procedure Venda.setUmCliente(vCliente: Cliente);
begin
umCliente := vCliente;
end;
procedure Venda.setUmUsuario(vUsuario: Usuario);
begin
umUsuario := vUsuario;
end;
procedure Venda.setumProdutoVenda(vProdutoVenda: ProdutoVenda);
begin
umProdutoVenda := vProdutoVenda;
end;
//Tipo da Compra
procedure Venda.setTipo (vTipo : Boolean);
begin
tipo := vTipo;
end;
function Venda.getTipo: Boolean;
begin
Result := tipo
end;
end.
|
unit bool_or_not_4;
interface
implementation
interface
implementation
function GetBool(Cond: Boolean): Boolean;
begin
Result := Cond;
end;
procedure Test1;
begin
var r := GetBool(false) or not GetBool(false);
Assert(r);
end;
procedure Test2;
begin
var r := GetBool(True) or not GetBool(false);
Assert(r);
end;
procedure Test3;
begin
var r := GetBool(False) or not GetBool(True);
Assert(not r);
end;
procedure Test4;
begin
var r := GetBool(True) or not GetBool(True);
Assert(r);
end;
initialization
Test1();
Test2();
Test3();
Test4();
finalization
end. |
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2016-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit EMSHosting.APIDocConsts;
interface
resourcestring
sResponseBadRequest = 'Bad Request';
sResponseOK = 'OK';
sResponseNoContent = 'No Content';
sResponseNotFound = 'Not Found';
sResponseUnexpextedRequestBody = 'Unexpexted Request Body';
//User Resource
sResponseUserCreated = 'User Created';
sResponseUserExist = 'User already exists';
sResponseWrongCredentials = 'The credentials of the request are not authorized for the requested operation.';
sResponseUserNotFound = 'User not found';
sResponseOpNotCompleted = 'Operation could not be completed because one or more dynamic names conflicts with a static name.';
sResponseRequestNotIdentify = 'The request does not identify a known application, resource, endpoint, or entity';
sGetUserSummaryTitle = 'Get User';
sGetUserSummaryDesc = ' |' + slineBreak + ' Used to retrieve all data from a `User`. **id** is the unique RAD Server User identifier (UID) in the RAD Server database.';
sGetUsersSummaryTitle = 'Get Users';
sGetUsersSummaryDesc = ' |' + slineBreak + ' Used to retrieve all data from `Users`.' + slineBreak +
' Optional query param of **skip, limit, order, where** determines ' + slineBreak +
' size of returned array, filtered and order by.';
sGetUserFieldsSummaryTitle = 'Get Fields';
sGetUserFieldsSummaryDesc = ' |' + slineBreak + ' Used to retrieve all the `field names` of the RAD Server Users (including the custom fields).';
sGetUserGroupsSummaryTitle = 'Get User Groups';
sGetUserGroupsSummaryDesc = ' |' + slineBreak + ' Used to retrieve the RAD Server Groups the RAD Server User belongs to. **id** is the unique RAD Server User identifier (UID) in the RAD Server database.';
sUserSignUpSummaryTitle = 'Sign Up User';
sUserSignUpSummaryDesc = ' |' + slineBreak + ' Signs up to the RAD Server with an appropriate RAD Server User.';
sPostLoginSummaryTitle = 'Log In';
sPostLoginSummaryDesc = ' |' + slineBreak + ' Logs in to the RAD Server with a specific RAD Server User.';
sPostLogoutSummaryTitle = 'Log Out';
sPostLogoutSummaryDesc = ' |' + slineBreak + ' Logs out a specific RAD Server User from the RAD Server.';
sPostUserSummaryTitle = 'Add User';
sPostUserSummaryDesc = ' |' + slineBreak + ' Used to add a new `User` object to the RAD Server database.';
sPutUserSummaryTitle = 'Update User';
sPutUserSummaryDesc = ' |' + slineBreak + ' Used to update a `User`. **id** is the unique RAD Server User identifier (UID) in the RAD Server database.';
sDeleteUserSummaryTitle = 'Delete User';
sDeleteUserSummaryDesc = ' |' + slineBreak + ' Used to delete a `User`. **id** is the unique RAD Server User identifier (UID) in the RAD Server database.';
sUserPathParamIDDesc = 'A user ID';
sLoginPathParamIDDesc = 'A user object';
sSignUpObject = 'Object to sign up a new RAD Server User in the RAD Server';
sAddObject = 'Object to add a new RAD Server User in the RAD Server';
sAddFieldName = 'Add any fieldName';
sUserReqParamSkipDesc = 'users skipped';
sUserReqParamLimitDesc = 'maximum number of results to return';
sUserReqParamOrderDesc = 'order ascending or descending (asc, desc)';
sUserReqParamWhereDesc = 'filter operators (lt, lte, gt, gte, eq, neq, like, nlike)';
//Version Resource
sGetVersionSummaryTitle = 'Get version';
sGetVersionSummaryDesc = ' |' + slineBreak + ' Used to retrieve the `Version` of the RAD Server.';
sGetVersion200Response = 'Ok. Provides the current version of the RAD Server';
//APIDoc Resource
sGetAPITitle = 'Get API EndPoints';
sGetOneAPITitle = 'Get API EndPoint';
sGetAPIDesc = ' |' + slineBreak + ' Used to retrieve all the API EndPoints.';
sGetOneAPIDesc = ' |' + slineBreak + ' Used to retrieve an EndPoint for the API EndPoints.';
sEndPointPath = 'Path Segment to an EndPoint';
sGetAPIYAMLTitle = 'Get YAML';
sGetAPIJSONTitle = 'Get JSON';
sGetAPIYAMLDesc = 'Get API in YAML format';
sGetAPIJSONDesc = 'Get API in JSON format';
//APIDoc Resource
sGetGroupSummaryTitle = 'Get Group';
sGetGroupSummaryDesc = ' |' + slineBreak + ' Used to retrieve all data from a `Group`. **item** is the unique RAD Server Group name in the RAD Server database.';
sGetGroupsSummaryTitle = 'Get Groups';
sGetGroupsSummaryDesc = ' |' + slineBreak + ' Used to retrieve all data from `Groups`.'+ slineBreak +
' Optional query param of **skip, limit, order, where** determines ' + slineBreak +
' size of returned array, filtered and order by.';
sGetGroupFieldsSummaryTitle = 'Get Fields';
sGetGroupFieldsSummaryDesc = ' |' + slineBreak + ' Used to retrieve all the `field names` of the RAD Server Group (including the custom fields).';
sPostGroupSummaryTitle = 'Add Group';
sPostGroupSummaryDesc = ' |' + slineBreak + ' Used to add a new `Group` object to the RAD Server database.';
sPutGroupSummaryTitle = 'Update Group';
sPutGroupSummaryDesc = ' |' + slineBreak + ' Used to update a `Group`. **item** is the unique RAD Server Group name in the RAD Server database.';
sDeleteGroupSummaryTitle = 'Delete Group';
sDeleteGroupSummaryDesc = ' |' + slineBreak + ' Used to delete a `Group`. **item** is the unique RAD Server Group name in the RAD Server database.';
sGroupPathParamItemDesc = 'A group name';
sResponseGroupNotFound = 'Group not found';
sResponseGroupUserNotFound = 'Group not found / User not found';
sResponseGroupExist = 'Group already exist';
//Intallations Resource
sGetInstallationSummaryTitle = 'Get Installation';
sGetInstallationSummaryDesc = ' |' + slineBreak + ' Used to retrieve all data from a specific `Installation` (registered device). **id** is the unique RAD Server Installation identifier (InstallationID) in the RAD Server database.';
sGetInstallationsSummaryTitle = 'Get Installations';
sGetInstallationsSummaryDesc = ' |' + slineBreak + ' Used to retrieve all data from `Installation`.' + slineBreak +
' Optional query param of **skip, limit, order, where** determines ' + slineBreak +
' size of returned array, filtered and order by.';
sGetInstallationFieldsSummaryTitle = 'Get Fields';
sGetInstallationFieldsSummaryDesc = ' |' + slineBreak + ' Used to retrieve all the `field names` of the RAD Server Installation (including the custom fields).';
sGetInstallationChannelsSummaryTitle = 'Get Installation Channels';
sGetInstallationChannelsSummaryDesc = ' |' + slineBreak + ' Used to retrieve the available channels to which the device has subscribed. **id** is the unique RAD Server Installation identifier (InstallationID) in the RAD Server database.';
sPostInstallationSummaryTitle = 'Add Installation';
sPostInstallationSummaryDesc = ' |' + slineBreak + ' Used to add a new `Installation` object to the RAD Server database.';
sPutInstallationSummaryTitle = 'Update Installation';
sPutInstallationSummaryDesc = ' |' + slineBreak + ' Used to update an `Installation`. **id** is the unique RAD Server Installation identifier (IID) in the RAD Server database.';
sDeleteInstallationSummaryTitle = 'Delete Installation';
sDeleteInstallationSummaryDesc = ' |' + slineBreak + ' Used to delete an `Installation`. **id** is the unique RAD Server Installation identifier (IID) in the RAD Server database.';
sInstallationPathParamItemDesc = 'A Installation ID';
sResponseInstallationExist = 'Installation already exists';
sInstallationUpdateFields = 'Installation fields to update';
//Push Resource
sPostSendPushTitle = 'Send Push';
sPostSendPushDesc = 'Used to send a push notification message to a registered device';
sPushBodyParamDesc = 'Object containing the Push Message data structure';
//Module Resource
sResponseModulexist = 'Module already exist';
sGetModuleSummaryTitle = 'Get Module';
sGetModuleSummaryDesc = ' |' + slineBreak + ' Used to retrieve all data from `EdgeModule` (registered device). **mname** is the unique RAD Server EdgeModule identifier (MID) in the RAD Server database.';
sGetModulesSummaryTitle = 'Get Module';
sGetModulesSummaryDesc = ' |' + slineBreak + ' Used to retrieve all data from `EdgeModule`.' + slineBreak +
' Optional query param of **skip, limit, order, where** determines ' + slineBreak +
' size of returned array, filtered and order by.';
sGetModuleFieldsSummaryTitle = 'Get Fields';
sGetModuleFieldsSummaryDesc = ' |' + slineBreak + ' Used to retrieve all the `field names` of the RAD Server EdgeModule (including the custom fields).';
sGetModuleResourcesFieldsSummaryTitle = 'Get Resource Fields';
sGetModuleResourcesFieldsSummaryDesc = ' |' + slineBreak + ' Used to retrieve the `field names` of all the resources of the RAD Server EdgeModule (including the custom fields).';
sGetModulesResourcesSummaryTitle = 'Get EdgeModules Resources';
sGetModulesResourcesSummaryDesc = ' |' + slineBreak + ' Used to retrieve all data from the resources of all EdgeModules.';
sGetModuleResourcesSummaryTitle = 'Get EdgeModule Resources';
sGetModuleResourcesSummaryDesc = ' |' + slineBreak + ' Used to retrieve all data from the resources of an EdgeModule.';
sGetModuleResourceSummaryTitle = 'Get EdgeModule Resource';
sGetModuleResourceSummaryDesc = ' |' + slineBreak + ' Used to retrieve all data from a resource of an EdgeModule. **mname** is the unique RAD Server EdgeModule identifier in the RAD Server database. **resourcename** is the name of the resource.';
sPostModuleSummaryTitle = 'Add Module';
sPostModuleSummaryDesc = ' |' + slineBreak + ' Used to add a new `EdgeModule` object to the RAD Server database.';
sPostModuleResourceSummaryTitle = 'Add Module Resource';
sPostModuleResourceSummaryDesc = ' |' + slineBreak + ' Used to register a new resource from an RAD Server EdgeModule. **mname** is the unique RAD Server EdgeModule identifier in the RAD Server database.';
sPutModuleSummaryTitle = 'Update Module';
sPutModuleSummaryDesc = ' |' + slineBreak + ' Used to update an `EdgeModule`. **mname** is the unique RAD Server EdgeModule identifier (MID) in the RAD Server database.';
sPutModuleResourceSummaryTitle = 'Update Module Resource';
sPutModuleResourceSummaryDesc = ' |' + slineBreak + ' Used to update an `EdgeModule`. **mname** is the unique RAD Server EdgeModule identifier (MID) in the RAD Server database.';
sDeleteModuleSummaryTitle = 'Delete Module';
sDeleteModuleSummaryDesc = ' |' + slineBreak + ' Used to delete an `EdgeModule Resource`. **mname** is the unique RAD Server EdgeModule identifier (MID) in the RAD Server database. **resourcename** is the name of the resource.';
sDeleteModuleResourceSummaryTitle = 'Delete Module Resource';
sDeleteModuleResourceSummaryDesc = ' |' + slineBreak + ' Used to delete an `EdgeModule Resource`. **mname** is the unique RAD Server EdgeModule identifier (MID) in the RAD Server database. **resourcename** is the name of the resource.';
sInvokeGetModuleResourceSummaryTitle = 'Invoke Resource Get Method';
sInvokeGetModuleResourceSummaryDesc = 'Used to invoke the GET method of the resource from an existing RAD Server EdgeModule.';
sInvokeWildGetModuleResourceSummaryTitle = 'Invoke Resource/* Get Method';
sInvokeWildGetModuleResourceSummaryDesc = 'Used to invoke the GET method of the resource from an existing RAD Server EdgeModule.';
sInvokePutModuleResourceSummaryTitle = 'Invoke Resource Put Method';
sInvokePutModuleResourceSummaryDesc = 'Used to invoke the PUT method of the resource from an existing RAD Server EdgeModule.';
sInvokeWildPutModuleResourceSummaryTitle = 'Invoke Resource/* Put Method';
sInvokeWildPutModuleResourceSummaryDesc = 'Used to invoke the PUT method of the resource from an existing RAD Server EdgeModule.';
sInvokePostModuleResourceSummaryTitle = 'Invoke Resource Post Method';
sInvokePostModuleResourceSummaryDesc = 'Used to invoke the POST method of the resource from an existing RAD Server EdgeModule.';
sInvokeWildPostModuleResourceSummaryTitle = 'Invoke Resource/* Post Method';
sInvokeWildPostModuleResourceSummaryDesc = 'Used to invoke the POST method of the resource from an existing RAD Server EdgeModule.';
sInvokePatchModuleResourceSummaryTitle = 'Invoke Resource Patch Method';
sInvokePatchModuleResourceSummaryDesc = 'Used to invoke the PATCH method of the resource from an existing RAD Server EdgeModule.';
sInvokeWildPatchModuleResourceSummaryTitle = 'Invoke Resource/* Patch Method';
sInvokeWildPatchModuleResourceSummaryDesc = 'Used to invoke the PATCH method of the resource from an existing RAD Server EdgeModule.';
sInvokeDeleteModuleResourceSummaryTitle = 'Invoke Resource Delete Method';
sInvokeDeleteModuleResourceSummaryDesc = 'Used to invoke the DELETE method of the resource from an existing RAD Server EdgeModule.';
sInvokeWildDeleteModuleResourceSummaryTitle = 'Invoke Resource/* Delete Method';
sInvokeWildDeleteModuleResourceSummaryDesc = 'Used to invoke the DELETE method of the resource from an existing RAD Server EdgeModule.';
sEdgeModuleIdParam = 'Is the unique RAD Server EdgeModule identifier';
sEdgeModuleResourceNameParam = 'Is the unique RAD Server EdgeModule Resource name';
sEdgeModuleResourceWildCard = 'Is the Wild card part of the URL';
sEdgeModuleResourceBodyObject = 'Body Object';
sEdgeModuleAddObject = 'EdgeModule object to add. protocolprops example string {\"port\":8082,\"host\":\"10.150.40.52\"}';
sEdgeModuleResourceAddObject = 'EdgModule Resource add object. protocolprops string example {\"port\":8082,\"host\":\"10.150.40.52\"}';
//Module Resource Invoke
sEdgeModuleNameParam = 'Is the RAD Server EdgeModule name';
const
cUsersTag = 'Users';
cGroupsTag = 'Groups';
cInstallationsTag = 'Installations';
cPushTag = 'Push';
cAPIDocTag = 'Api Doc';
cEdgeModulesTag = 'EdgeModules';
cEdgeModulesInvokersTag = 'EdgeModules Invokers';
cVersionTag = 'Version';
cApplicationJSON = 'application/json';
cBodyParamName = 'body';
cResponseBadRequestKey = 'sResponseBadRequest';
cResponseOK = 'sResponseOK';
cResponseNoContent = 'sResponseNoContent';
cResponseNotFound = 'sResponseNotFound';
cResponseUnexpextedRequestBody = 'sResponseUnexpextedRequestBody';
cResponseWrongCredentials = 'sResponseWrongCredentials';
cResponseUserNotFound = 'sResponseUserNotFound';
cResponseOpNotCompleted = 'sResponseOpNotCompleted';
cResponseRequestNotIdentify = 'sResponseRequestNotIdentify';
//Users Resource
cResponseUserCreated = 'sResponseUserCreated';
cResponseUserExist = 'sResponseUserExist';
cGetUserSummaryTitle = 'sGetUserSummaryTitle';
cGetUserSummaryDesc = 'sGetUserSummaryDesc';
cGetUsersSummaryTitle = 'sGetUsersSummaryTitle';
cGetUsersSummaryDesc = 'sGetUsersSummaryDesc';
cGetUserFieldsSummaryTitle = 'sGetUserFieldsSummaryTitle';
cGetUserFieldsSummaryDesc = 'sGetUserFieldsSummaryDesc';
cGetUserGroupsSummaryTitle = 'sGetUserGroupsSummaryTitle';
cGetUserGroupsSummaryDesc = 'sGetUserGroupsSummaryDesc';
cUserSignUpSummaryTitle = 'sUserSignUpSummaryTitle';
cUserSignUpSummaryDesc = 'sUserSignUpSummaryDesc';
cPostLoginSummaryTitle = 'sPostLoginSummaryTitle';
cPostLoginSummaryDesc = 'sPostLoginSummaryDesc';
cPostLogoutSummaryTitle = 'sPostLogoutSummaryTitle';
cPostLogoutSummaryDesc = 'sPostLogoutSummaryDesc';
cPostUserSummaryTitle = 'sPostUserSummaryTitle';
cPostUserSummaryDesc = 'sPostUserSummaryDesc';
cPutUserSummaryTitle = 'sPutUserSummaryTitle';
cPutUserSummaryDesc = 'sPutUserSummaryDesc';
cDeleteUserSummaryTitle = 'sDeleteUserSummaryTitle';
cDeleteUserSummaryDesc = 'sDeleteUserSummaryDesc';
cUserPathParamIDDesc = 'sUserPathParamIDDesc';
cLoginPathParamIDDesc = 'sLoginPathParamIDDesc';
cSignUpObject = 'sSignUpObject';
cAddObject = 'sAddObject';
cAddFieldName = 'sAddFieldName';
cUserReqParamSkipDesc = 'sUserReqParamSkipDesc';
cUserReqParamLimitDesc = 'sUserReqParamLimitDesc';
cUserReqParamOrderDesc = 'sUserReqParamOrderDesc';
cUserReqParamWhereDesc = 'sUserReqParamWhereDesc';
//Version Resource
cGetVersionSummaryTitle= 'sGetVersionSummaryTitle';
cGetVersionSummaryDesc = 'sGetVersionSummaryDesc';
cGetVersion200Response = 'sGetVersion200Response';
//APIDoc Resource
cGetAPITitle = 'sGetAPITitle';
cGetOneAPITitle = 'sGetOneAPITitle';
cGetOneAPIDesc = 'sGetOneAPIDesc';
cGetAPIDesc = 'sGetAPIDesc';
cEndPointPath = 'sEndPointPath';
cGetAPIYAMLTitle = 'sGetAPIYAMLTitle';
cGetAPIJSONTitle = 'sGetAPIJSONTitle';
cGetAPIYAMLDesc = 'sGetAPIYAMLDesc';
cGetAPIJSONDesc = 'sGetAPIJSONDesc';
//APIDoc Resource
cGetGroupSummaryTitle = 'sGetGroupSummaryTitle';
cGetGroupSummaryDesc = 'sGetGroupSummaryDesc';
cGetGroupsSummaryTitle = 'sGetGroupsSummaryTitle';
cGetGroupsSummaryDesc = 'sGetGroupsSummaryDesc';
cGetGroupFieldsSummaryTitle = 'sGetGroupFieldsSummaryTitle';
cGetGroupFieldsSummaryDesc = 'sGetGroupFieldsSummaryDesc';
cPostGroupSummaryTitle = 'sPostGroupSummaryTitle';
cPostGroupSummaryDesc = 'sPostGroupSummaryDesc';
cPutGroupSummaryTitle = 'sPutGroupSummaryTitle';
cPutGroupSummaryDesc = 'sPutGroupSummaryDesc';
cDeleteGroupSummaryTitle = 'sDeleteGroupSummaryTitle';
cDeleteGroupSummaryDesc = 'sDeleteGroupSummaryDesc';
cGroupPathParamItemDesc = 'sGroupPathParamItemDesc';
cResponseGroupNotFound = 'sResponseGroupNotFound';
cResponseGroupUserNotFound = 'sResponseGroupUserNotFound';
cResponseGroupExist = 'sResponseGroupExist';
//Intallations Resource
cGetInstallationSummaryTitle = 'sGetInstallationSummaryTitle';
cGetInstallationSummaryDesc = 'sGetInstallationSummaryDesc';
cGetInstallationsSummaryTitle = 'sGetInstallationsSummaryTitle';
cGetInstallationsSummaryDesc = 'sGetInstallationsSummaryDesc';
cGetInstallationFieldsSummaryTitle = 'sGetInstallationFieldsSummaryTitle';
cGetInstallationFieldsSummaryDesc = 'sGetInstallationFieldsSummaryDesc';
cGetInstallationChannelsSummaryTitle = 'sGetInstallationChannelsSummaryTitle';
cGetInstallationChannelsSummaryDesc = 'sGetInstallationChannelsSummaryDesc';
cPostInstallationSummaryTitle = 'sPostInstallationSummaryTitle';
cPostInstallationSummaryDesc = 'sPostInstallationSummaryDesc';
cPutInstallationSummaryTitle = 'sPutInstallationSummaryTitle';
cPutInstallationSummaryDesc = 'sPutInstallationSummaryDesc';
cDeleteInstallationSummaryTitle = 'sDeleteInstallationSummaryTitle';
cDeleteInstallationSummaryDesc = 'sDeleteInstallationSummaryDesc';
cInstallationPathParamItemDesc = 'sInstallationPathParamItemDesc';
cInstallationUpdateFields = 'sInstallationUpdateFields';
cResponseInstallationExist = 'sResponseInstallationExist';
//Push Resource
cPostSendPushTitle = 'sPostSendPushTitle';
cPostSendPushDesc = 'sPostSendPushDesc';
cPushBodyParamDesc = 'cPushBodyParamDesc';
//Module Resource
cResponseModulexist= 'sResponseModulexist';
cGetModulesSummaryTitle = 'sGetModulesSummaryTitle';
cGetModulesSummaryDesc = 'sGetModulesSummaryDesc';
cGetModuleSummaryTitle = 'sGetModuleSummaryTitle';
cGetModuleSummaryDesc = 'sGetModuleSummaryDesc';
cGetModuleFieldsSummaryTitle = 'sGetModuleFieldsSummaryTitle';
cGetModuleFieldsSummaryDesc = 'cGetModuleFieldsSummaryDesc';
cGetModuleResourcesFieldsSummaryTitle = 'sGetModuleResourcesFieldsSummaryTitle';
cGetModuleResourcesFieldsSummaryDesc = 'sGetModuleResourcesFieldsSummaryDesc';
cGetModuleResourcesSummaryTitle = 'sGetModuleResourcesSummaryTitle';
cGetModuleResourcesSummaryDesc = 'sGetModuleResourcesSummaryDesc';
cGetModulesResourcesSummaryTitle = 'sGetModulesResourcesSummaryTitle';
cGetModulesResourcesSummaryDesc = 'sGetModulesResourcesSummaryDesc';
cGetModuleResourceSummaryTitle = 'sGetModuleResourceSummaryTitle';
cGetModuleResourceSummaryDesc = 'sGetModuleResourceSummaryDesc';
cPostModuleSummaryTitle = 'sPostModuleSummaryTitle';
cPostModuleSummaryDesc = 'sPostModuleSummaryDesc';
cPostModuleResourceSummaryTitle = 'sPostModuleResourceSummaryTitle';
cPostModuleResourceSummaryDesc = 'cPostModuleResourceSummaryDesc';
cPutModuleSummaryTitle = 'sPutModuleSummaryTitle';
cPutModuleSummaryDesc = 'sPutModuleSummaryDesc';
cPutModuleResourceSummaryTitle = 'sPutModuleResourceSummaryTitle';
cPutModuleResourceSummaryDesc = 'sPutModuleResourceSummaryDesc';
cDeleteModuleSummaryTitle = 'sDeleteModuleSummaryTitle';
cDeleteModuleSummaryDesc = 'sDeleteModuleSummaryDesc';
cDeleteModuleResourceSummaryTitle = 'sDeleteModuleResourceSummaryTitle';
cDeleteModuleResourceSummaryDesc = 'sDeleteModuleResourceSummaryDesc';
cInvokeGetModuleResourceSummaryTitle = 'sInvokeGetModuleResourceSummaryTitle';
cInvokeGetModuleResourceSummaryDesc = 'sInvokeGetModuleResourceSummaryDesc';
cInvokeWildGetModuleResourceSummaryTitle = 'sInvokeWildGetModuleResourceSummaryTitle';
cInvokeWildGetModuleResourceSummaryDesc = 'sInvokeWildGetModuleResourceSummaryDesc';
cInvokePutModuleResourceSummaryTitle = 'sInvokePutModuleResourceSummaryTitle';
cInvokePutModuleResourceSummaryDesc = 'sInvokePutModuleResourceSummaryDesc';
cInvokeWildPutModuleResourceSummaryTitle = 'sInvokeWildPutModuleResourceSummaryTitle';
cInvokeWildPutModuleResourceSummaryDesc = 'sInvokeWildPutModuleResourceSummaryDesc';
cInvokePostModuleResourceSummaryTitle = 'sInvokePostModuleResourceSummaryTitle';
cInvokePostModuleResourceSummaryDesc = 'sInvokePostModuleResourceSummaryDesc';
cInvokeWildPostModuleResourceSummaryTitle = 'sInvokeWildPostModuleResourceSummaryTitle';
cInvokeWildPostModuleResourceSummaryDesc = 'sInvokeWildPostModuleResourceSummaryDesc';
cInvokePatchModuleResourceSummaryTitle = 'sInvokePatchModuleResourceSummaryTitle';
cInvokePatchModuleResourceSummaryDesc = 'sInvokePatchModuleResourceSummaryDesc';
cInvokeWildPatchModuleResourceSummaryTitle = 'sInvokeWildPatchModuleResourceSummaryTitle';
cInvokeWildPatchModuleResourceSummaryDesc = 'sInvokeWildPatchModuleResourceSummaryDesc';
cInvokeDeleteModuleResourceSummaryTitle = 'sInvokeDeleteModuleResourceSummaryTitle';
cInvokeDeleteModuleResourceSummaryDesc = 'sInvokeDeleteModuleResourceSummaryDesc';
cInvokeWildDeleteModuleResourceSummaryTitle = 'sInvokeWildDeleteModuleResourceSummaryTitle';
cInvokeWildDeleteModuleResourceSummaryDesc = 'sInvokeWildDeleteModuleResourceSummaryDesc';
cEdgeModuleIdParam = 'sEdgeModuleIdParam';
cEdgeModuleResourceNameParam = 'sEdgeModuleResourceNameParam';
cEdgeModuleResourceWildCard = 'sEdgeModuleResourceWildCard';
cEdgeModuleResourceBodyObject = 'sEdgeModuleResourceBodyObject';
cEdgeModuleAddObject = 'sEdgeModuleAddObject';
cEdgeModuleResourceAddObject = 'sEdgeModuleResourceAddObject';
//Module Resource Invoke
cEdgeModuleNameParam = 'sEdgeModuleNameParam';
//Object Definitions
VersionObjectsYMALDefinition =
'#' + sLineBreak +
' versionObject:' + sLineBreak +
' type: object' + sLineBreak +
' properties:' + sLineBreak +
' version:' + sLineBreak +
' type: string' + sLineBreak +
' server:' + sLineBreak +
' type: string' + sLineBreak;
VersionObjectsJSONDefinition =
'{' + sLineBreak +
' "versionObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "properties": {' + sLineBreak +
' "version": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "server": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
'}' + sLineBreak;
EdgeVersionObjectsYMALDefinition =
'#' + sLineBreak +
' versionEdgeObject:' + sLineBreak +
' type: object' + sLineBreak +
' properties:' + sLineBreak +
' moduleversion:' + sLineBreak +
' type: string' + sLineBreak +
' modulename:' + sLineBreak +
' type: string'+ sLineBreak;
EdgeVersionObjectsJSONDefinition =
'{' + sLineBreak +
' "versionEdgeObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "properties": {' + sLineBreak +
' "moduleversion": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "modulename": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
'}' + sLineBreak;
UserObjectsYMALDefinition =
'#' + sLineBreak +
' _metaObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - creator' + sLineBreak +
' - created' + sLineBreak +
' properties:' + sLineBreak +
' creator:' + sLineBreak +
' type: string' + sLineBreak +
' created:' + sLineBreak +
' type: string' + sLineBreak +
' updated:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' userObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - id' + sLineBreak +
' - username' + sLineBreak +
' - _meta' + sLineBreak +
' properties:' + sLineBreak +
' id:' + sLineBreak +
' type: string' + sLineBreak +
' username:' + sLineBreak +
' type: string' + sLineBreak +
' _meta:' + sLineBreak +
' $ref: ''#/definitions/_metaObject''' + sLineBreak +
' additionalProperties:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' userTokenObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - id' + sLineBreak +
' - username' + sLineBreak +
' - _meta' + sLineBreak +
' - sessiontoken' + sLineBreak +
' properties:' + sLineBreak +
' id:' + sLineBreak +
' type: string' + sLineBreak +
' username:' + sLineBreak +
' type: string' + sLineBreak +
' _meta:' + sLineBreak +
' $ref: ''#/definitions/_metaObject''' + sLineBreak +
' sessiontoken:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' userCredentialsObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - username' + sLineBreak +
' - password' + sLineBreak +
' properties:' + sLineBreak +
' username:' + sLineBreak +
' type: string' + sLineBreak +
' password:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' userSignUpResponseObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - _id' + sLineBreak +
' - sessionToken' + sLineBreak +
' properties:' + sLineBreak +
' _id:' + sLineBreak +
' type: string' + sLineBreak +
' sessionToken:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' useridObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - _id' + sLineBreak +
' properties:' + sLineBreak +
' _id:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' updateObject:' + sLineBreak +
' type: object' + sLineBreak +
' properties:' + sLineBreak +
' fieldName:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' updatedObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - updated' + sLineBreak +
' properties:' + sLineBreak +
' updated:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' groupName:' + sLineBreak +
' type: string' + sLineBreak +
'# ' + sLineBreak +
' fieldObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - name' + sLineBreak +
' properties:' + sLineBreak +
' name:' + sLineBreak +
' type: string' + sLineBreak +
' fields:' + sLineBreak +
' type: array' + sLineBreak +
' items:' + sLineBreak +
' type: object' + sLineBreak +
' properties:' + sLineBreak +
' name:' + sLineBreak +
' type: string' + sLineBreak +
' custom:' + sLineBreak +
' type: boolean'+ sLineBreak;
UserObjectsJSONDefinition =
'{' + sLineBreak +
' "_metaObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "creator",' + sLineBreak +
' "created"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "creator": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "created": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "updated": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "userObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "id",' + sLineBreak +
' "username",' + sLineBreak +
' "_meta"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "id": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "username": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "_meta": {' + sLineBreak +
' "$ref": "#/definitions/_metaObject"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "additionalProperties": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "userTokenObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "id",' + sLineBreak +
' "username",' + sLineBreak +
' "_meta",' + sLineBreak +
' "sessiontoken"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "id": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "username": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "_meta": {' + sLineBreak +
' "$ref": "#/definitions/_metaObject"' + sLineBreak +
' },' + sLineBreak +
' "sessiontoken": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "userCredentialsObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "username",' + sLineBreak +
' "password"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "username": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "password": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "userSignUpResponseObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "_id",' + sLineBreak +
' "sessionToken"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "_id": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "sessionToken": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "useridObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "_id"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "_id": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "updateObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "properties": {' + sLineBreak +
' "fieldName": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "updatedObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "updated"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "updated": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "groupName": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "fieldObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "name"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "name": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "fields": {' + sLineBreak +
' "type": "array",' + sLineBreak +
' "items": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "properties": {' + sLineBreak +
' "name": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "custom": {' + sLineBreak +
' "type": "boolean"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
'}' + sLineBreak;
GroupsObjectsYMALDefinition =
'#' + sLineBreak +
' _metaGroupObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - creator' + sLineBreak +
' - created' + sLineBreak +
' properties:' + sLineBreak +
' creator:' + sLineBreak +
' type: string' + sLineBreak +
' created:' + sLineBreak +
' type: string' + sLineBreak +
' updated:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' groupObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - name' + sLineBreak +
' - _meta' + sLineBreak +
' properties:' + sLineBreak +
' name:' + sLineBreak +
' type: string' + sLineBreak +
' _meta:' + sLineBreak +
' $ref: ''#/definitions/_metaGroupObject''' + sLineBreak +
' users:' + sLineBreak +
' type: array' + sLineBreak +
' items:' + sLineBreak +
' type: string' + sLineBreak +
' additionalProperties:' + sLineBreak +
' type: string' + sLineBreak +
'# ' + sLineBreak +
' groupAddObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - groupname' + sLineBreak +
' properties:' + sLineBreak +
' groupname:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' updateGroupObject:' + sLineBreak +
' type: object' + sLineBreak +
' properties:' + sLineBreak +
' fieldName:' + sLineBreak +
' type: string' + sLineBreak +
' users:' + sLineBreak +
' type: array' + sLineBreak +
' items:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' updatedGroupObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - updated' + sLineBreak +
' properties:' + sLineBreak +
' updated:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' fieldGroupObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - name' + sLineBreak +
' properties:' + sLineBreak +
' name:' + sLineBreak +
' type: string' + sLineBreak +
' fields:' + sLineBreak +
' type: array' + sLineBreak +
' items:' + sLineBreak +
' type: object' + sLineBreak +
' properties:' + sLineBreak +
' name:' + sLineBreak +
' type: string' + sLineBreak +
' custom:' + sLineBreak +
' type: boolean'+ sLineBreak;
GroupsObjectsJSONDefinition =
'{' + sLineBreak +
' "_metaGroupObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "creator",' + sLineBreak +
' "created"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "creator": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "created": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "updated": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "groupObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "name",' + sLineBreak +
' "_meta"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "name": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "_meta": {' + sLineBreak +
' "$ref": "#/definitions/_metaGroupObject"' + sLineBreak +
' },' + sLineBreak +
' "users": {' + sLineBreak +
' "type": "array",' + sLineBreak +
' "items": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "additionalProperties": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "groupAddObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "groupname"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "groupname": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "updateGroupObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "properties": {' + sLineBreak +
' "fieldName": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "users": {' + sLineBreak +
' "type": "array",' + sLineBreak +
' "items": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "updatedGroupObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "updated"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "updated": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "fieldGroupObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "name"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "name": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "fields": {' + sLineBreak +
' "type": "array",' + sLineBreak +
' "items": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "properties": {' + sLineBreak +
' "name": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "custom": {' + sLineBreak +
' "type": "boolean"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
'}' + sLineBreak;
InstallationsObjectsYMALDefinition =
'#' + sLineBreak +
' _metaInstallationObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - creator' + sLineBreak +
' - created' + sLineBreak +
' properties:' + sLineBreak +
' creator:' + sLineBreak +
' type: string' + sLineBreak +
' created:' + sLineBreak +
' type: string' + sLineBreak +
' updated:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' installationObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - _id' + sLineBreak +
' - deviceToken' + sLineBreak +
' - deviceType' + sLineBreak +
' - _meta' + sLineBreak +
' properties:' + sLineBreak +
' _id:' + sLineBreak +
' type: string' + sLineBreak +
' deviceToken:' + sLineBreak +
' type: string' + sLineBreak +
' deviceType:' + sLineBreak +
' type: string' + sLineBreak +
' enum:' + sLineBreak +
' - ios' + sLineBreak +
' - android' + sLineBreak +
' _meta:' + sLineBreak +
' $ref: ''#/definitions/_metaInstallationObject''' + sLineBreak +
' channels:' + sLineBreak +
' type: array' + sLineBreak +
' items:' + sLineBreak +
' type: string' + sLineBreak +
' additionalProperties:' + sLineBreak +
' type: string' + sLineBreak +
'# ' + sLineBreak +
' installationAddObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - deviceToken' + sLineBreak +
' - deviceType' + sLineBreak +
' properties:' + sLineBreak +
' deviceToken:' + sLineBreak +
' type: string' + sLineBreak +
' deviceType:' + sLineBreak +
' type: string' + sLineBreak +
' channels:' + sLineBreak +
' type: array' + sLineBreak +
' items:' + sLineBreak +
' type: string' + sLineBreak +
' additionalProperties:' + sLineBreak +
' type: string' + sLineBreak +
'# ' + sLineBreak +
' installationAddedObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - _id' + sLineBreak +
' properties:' + sLineBreak +
' _id:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' updateInstallationObject:' + sLineBreak +
' type: object' + sLineBreak +
' properties:' + sLineBreak +
' channels:' + sLineBreak +
' type: array' + sLineBreak +
' items:' + sLineBreak +
' type: string' + sLineBreak +
' additionalProperties:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' updatedInstallationObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - updated' + sLineBreak +
' properties:' + sLineBreak +
' updated:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' channelName:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' fieldInstallationObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - name' + sLineBreak +
' properties:' + sLineBreak +
' name:' + sLineBreak +
' type: string' + sLineBreak +
' fields:' + sLineBreak +
' type: array' + sLineBreak +
' items:' + sLineBreak +
' type: object' + sLineBreak +
' properties:' + sLineBreak +
' name:' + sLineBreak +
' type: string' + sLineBreak +
' custom:' + sLineBreak +
' type: boolean'+ sLineBreak;
InstallationsObjectsJSONDefinition =
'{' + sLineBreak +
' "_metaInstallationObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "creator",' + sLineBreak +
' "created"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "creator": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "created": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "updated": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "installationObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "_id",' + sLineBreak +
' "deviceToken",' + sLineBreak +
' "deviceType",' + sLineBreak +
' "_meta"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "_id": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "deviceToken": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "deviceType": {' + sLineBreak +
' "type": "string",' + sLineBreak +
' "enum": [' + sLineBreak +
' "ios",' + sLineBreak +
' "android"' + sLineBreak +
' ]' + sLineBreak +
' },' + sLineBreak +
' "_meta": {' + sLineBreak +
' "$ref": "#/definitions/_metaInstallationObject"' + sLineBreak +
' },' + sLineBreak +
' "channels": {' + sLineBreak +
' "type": "array",' + sLineBreak +
' "items": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "additionalProperties": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "installationAddObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "deviceToken",' + sLineBreak +
' "deviceType"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "deviceToken": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "deviceType": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "channels": {' + sLineBreak +
' "type": "array",' + sLineBreak +
' "items": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "additionalProperties": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "installationAddedObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "_id"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "_id": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "updateInstallationObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "properties": {' + sLineBreak +
' "channels": {' + sLineBreak +
' "type": "array",' + sLineBreak +
' "items": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "additionalProperties": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "updatedInstallationObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "updated"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "updated": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "channelName": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "fieldInstallationObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "name"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "name": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "fields": {' + sLineBreak +
' "type": "array",' + sLineBreak +
' "items": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "properties": {' + sLineBreak +
' "name": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "custom": {' + sLineBreak +
' "type": "boolean"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
'}' + sLineBreak;
PushObjectsYMALDefinition =
'#' + sLineBreak +
' pushObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - data' + sLineBreak +
' - where' + sLineBreak +
' properties:' + sLineBreak +
' data:' + sLineBreak +
' $ref: ''#/definitions/pushDataObject''' + sLineBreak +
' channels:' + sLineBreak +
' type: array' + sLineBreak +
' items:' + sLineBreak +
' type: string' + sLineBreak +
' where:' + sLineBreak +
' $ref: ''#/definitions/pushWhereObject''' + sLineBreak +
'#' + sLineBreak +
' pushDataObject:' + sLineBreak +
' type: object' + sLineBreak +
' properties:' + sLineBreak +
' gcm:' + sLineBreak +
' type: object' + sLineBreak +
' properties:' + sLineBreak +
' message:' + sLineBreak +
' type: string' + sLineBreak +
' title:' + sLineBreak +
' type: string' + sLineBreak +
' aps:' + sLineBreak +
' type: object' + sLineBreak +
' properties:' + sLineBreak +
' alert:' + sLineBreak +
' type: string' + sLineBreak +
' badge:' + sLineBreak +
' type: string' + sLineBreak +
' sound:' + sLineBreak +
' type: string' + sLineBreak +
' extras:' + sLineBreak +
' type: object' + sLineBreak +
' properties:' + sLineBreak +
' message:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' pushWhereObject:' + sLineBreak +
' type: object' + sLineBreak +
' properties:' + sLineBreak +
' deviceType:' + sLineBreak +
' type: string' + sLineBreak +
' enum:' + sLineBreak +
' - ios' + sLineBreak +
' - android' + sLineBreak +
' deviceToken:' + sLineBreak +
' type: object' + sLineBreak +
' description : ''$in''' + sLineBreak +
' required:' + sLineBreak +
' - $in' + sLineBreak +
' properties:' + sLineBreak +
' $in:' + sLineBreak +
' type: array' + sLineBreak +
' items:' + sLineBreak +
' type: string' + sLineBreak;
PushObjectsJSONDefinition =
'{' + sLineBreak +
' "pushObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "data",' + sLineBreak +
' "where"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "data": {' + sLineBreak +
' "$ref": "#/definitions/pushDataObject"' + sLineBreak +
' },' + sLineBreak +
' "channels": {' + sLineBreak +
' "type": "array",' + sLineBreak +
' "items": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "where": {' + sLineBreak +
' "$ref": "#/definitions/pushWhereObject"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "pushDataObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "properties": {' + sLineBreak +
' "gcm": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "properties": {' + sLineBreak +
' "message": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "title": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "aps": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "properties": {' + sLineBreak +
' "alert": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "badge": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "sound": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "extras": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "properties": {' + sLineBreak +
' "message": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "pushWhereObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "properties": {' + sLineBreak +
' "deviceType": {' + sLineBreak +
' "type": "string",' + sLineBreak +
' "enum": [' + sLineBreak +
' "ios",' + sLineBreak +
' "android"' + sLineBreak +
' ]' + sLineBreak +
' },' + sLineBreak +
' "deviceToken": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "description": "$in",' + sLineBreak +
' "required": [' + sLineBreak +
' "$in"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "$in": {' + sLineBreak +
' "type": "array",' + sLineBreak +
' "items": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
'}' + sLineBreak;
ModuleObjectsYMALDefinition =
'#' + sLineBreak +
' _metaEdgeModuleObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - creator' + sLineBreak +
' - created' + sLineBreak +
' properties:' + sLineBreak +
' creator:' + sLineBreak +
' type: string' + sLineBreak +
' created:' + sLineBreak +
' type: string' + sLineBreak +
' updated:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' edgeModuleObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - modulename' + sLineBreak +
' - _id' + sLineBreak +
' - protocol' + sLineBreak +
' - protocolprops' + sLineBreak +
' - _meta' + sLineBreak +
' properties:' + sLineBreak +
' modulename:' + sLineBreak +
' type: string' + sLineBreak +
' _id:' + sLineBreak +
' type: string' + sLineBreak +
' protocol:' + sLineBreak +
' type: string' + sLineBreak +
//' enum:' + sLineBreak +
//' - http' + sLineBreak +
//' - https' + sLineBreak +
' protocolprops:' + sLineBreak +
' type: string' + sLineBreak +
' pattern: \{\\"port\\":[0-9]{2,5},\\"host\\":\\"([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3})\\"\}' + sLineBreak +
' _meta:' + sLineBreak +
' $ref: ''#/definitions/_metaEdgeModuleObject''' + sLineBreak +
' additionalProperties:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' edgeModuleResourceObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - resourcename' + sLineBreak +
' - modulename' + sLineBreak +
' - moduleid' + sLineBreak +
' - _meta' + sLineBreak +
' properties:' + sLineBreak +
' resourcename:' + sLineBreak +
' type: string' + sLineBreak +
' modulename:' + sLineBreak +
' type: string' + sLineBreak +
' moduleid:' + sLineBreak +
' type: string' + sLineBreak +
' _meta:' + sLineBreak +
' $ref: ''#/definitions/_metaEdgeModuleObject''' + sLineBreak +
' additionalProperties:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' edgeModuleAddObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - modulename' + sLineBreak +
' - protocol' + sLineBreak +
' - protocolprops' + sLineBreak +
' properties:' + sLineBreak +
' modulename:' + sLineBreak +
' type: string' + sLineBreak +
' protocol:' + sLineBreak +
' type: string' + sLineBreak +
' protocolprops:' + sLineBreak +
' type: string' + sLineBreak +
' pattern: \{\\"port\\":[0-9]{2,5},\\"host\\":\\"([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3})\\"\}' + sLineBreak +
' additionalProperties:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' edgeModuleAddedObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - _id' + sLineBreak +
' - modulename' + sLineBreak +
' properties:' + sLineBreak +
' _id:' + sLineBreak +
' type: string' + sLineBreak +
' modulename:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' edgeModuleResourceAddObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - resourcename' + sLineBreak +
' properties:' + sLineBreak +
' resourcename:' + sLineBreak +
' type: string' + sLineBreak +
' additionalProperties:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' edgeModuleResourceAddedObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - resourcename' + sLineBreak +
' properties:' + sLineBreak +
' resourcename:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' edgeModuleUpdateObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - modulename' + sLineBreak +
' - protocol' + sLineBreak +
' - protocolprops' + sLineBreak +
' properties:' + sLineBreak +
' modulename:' + sLineBreak +
' type: string' + sLineBreak +
' protocol:' + sLineBreak +
' type: string' + sLineBreak +
' protocolprops:' + sLineBreak +
' type: string' + sLineBreak +
' pattern: \{\\"port\\":[0-9]{2,5},\\"host\\":\\"([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3})\\"\}' + sLineBreak +
' additionalProperties:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' edgeModuleUpdatedObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - updated' + sLineBreak +
' properties:' + sLineBreak +
' updated:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' edgeModuleResourceUpdateObject:' + sLineBreak +
' type: object' + sLineBreak +
' properties:' + sLineBreak +
' resourcename:' + sLineBreak +
' type: string' + sLineBreak +
' additionalProperties:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' edgeModuleResourceUpdatedObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - updated' + sLineBreak +
' properties:' + sLineBreak +
' updated:' + sLineBreak +
' type: string' + sLineBreak +
'#' + sLineBreak +
' fieldsEdgeModuleObject:' + sLineBreak +
' type: object' + sLineBreak +
' required:' + sLineBreak +
' - name' + sLineBreak +
' properties:' + sLineBreak +
' name:' + sLineBreak +
' type: string' + sLineBreak +
' fields:' + sLineBreak +
' type: array' + sLineBreak +
' items:' + sLineBreak +
' type: object' + sLineBreak +
' properties:' + sLineBreak +
' name:' + sLineBreak +
' type: string' + sLineBreak +
' custom:' + sLineBreak +
' type: boolean'+ sLineBreak;
ModuleObjectsJSONDefinition =
'{' + sLineBreak +
' "_metaEdgeModuleObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "creator",' + sLineBreak +
' "created"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "creator": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "created": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "updated": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "edgeModuleObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "modulename",' + sLineBreak +
' "_id",' + sLineBreak +
' "protocol",' + sLineBreak +
' "protocolprops",' + sLineBreak +
' "_meta"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "modulename": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "_id": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "protocol": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "protocolprops": {' + sLineBreak +
' "type": "string",' + sLineBreak +
' "pattern": "\\{\\\\\"port\\\\\":[0-9]{2,5},\\\\\"host\\\\\":\\\\\"([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3})\\\\\"\\}"' + sLineBreak +
' },' + sLineBreak +
' "_meta": {' + sLineBreak +
' "$ref": "#/definitions/_metaEdgeModuleObject"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "additionalProperties": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "edgeModuleResourceObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "resourcename",' + sLineBreak +
' "modulename",' + sLineBreak +
' "moduleid",' + sLineBreak +
' "_meta"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "resourcename": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "modulename": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "moduleid": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "_meta": {' + sLineBreak +
' "$ref": "#/definitions/_metaEdgeModuleObject"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "additionalProperties": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "edgeModuleAddObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "modulename",' + sLineBreak +
' "protocol",' + sLineBreak +
' "protocolprops"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "modulename": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "protocol": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "protocolprops": {' + sLineBreak +
' "type": "string",' + sLineBreak +
' "pattern": "\\{\\\\\"port\\\\\":[0-9]{2,5},\\\\\"host\\\\\":\\\\\"([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3})\\\\\"\\}"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "additionalProperties": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "edgeModuleAddedObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "_id",' + sLineBreak +
' "modulename"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "_id": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "modulename": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "edgeModuleResourceAddObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "resourcename"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "resourcename": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "additionalProperties": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "edgeModuleResourceAddedObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "resourcename"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "resourcename": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "edgeModuleUpdateObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "modulename",' + sLineBreak +
' "protocol",' + sLineBreak +
' "protocolprops"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "modulename": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "protocol": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "protocolprops": {' + sLineBreak +
' "type": "string",' + sLineBreak +
' "pattern": "\\{\\\\\"port\\\\\":[0-9]{2,5},\\\\\"host\\\\\":\\\\\"([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3})\\\\\"\\}"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "additionalProperties": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "edgeModuleUpdatedObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "updated"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "updated": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "edgeModuleResourceUpdateObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "properties": {' + sLineBreak +
' "resourcename": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "additionalProperties": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "edgeModuleResourceUpdatedObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "updated"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "updated": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "fieldsEdgeModuleObject": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "required": [' + sLineBreak +
' "name"' + sLineBreak +
' ],' + sLineBreak +
' "properties": {' + sLineBreak +
' "name": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' },' + sLineBreak +
' "fields": {' + sLineBreak +
' "type": "array",' + sLineBreak +
' "items": {' + sLineBreak +
' "type": "object",' + sLineBreak +
' "properties": {' + sLineBreak +
' "name": {' + sLineBreak +
' "type": "string"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' },' + sLineBreak +
' "custom": {' + sLineBreak +
' "type": "boolean"' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
' }' + sLineBreak +
'}' + sLineBreak;
implementation
end.
|
unit WasmSample_Multi;
interface
uses
System.SysUtils
, Wasm
{$ifndef USE_WASMER}
, Wasmtime
{$else}
, Wasmer
{$ifend}
;
function MultiSample() : Boolean;
implementation
// A function to be called from Wasm code.
function callback(const args : PWasmValVec; results : PWasmValVec) : PWasmTrap; cdecl;
begin
writeln('Calling back...');
write('> ');
writeln( Format('> %u %u %u %u', [
args.Items[0].i32, args.Items[1].i64,
args.Items[2].i64, args.Items[3].i32]));
writeln('');
TWasm.val_copy(results.Items.Pointers[0], args.Items.Pointers[3]);
TWasm.val_copy(results.Items.Pointers[1], args.Items.Pointers[1]);
TWasm.val_copy(results.Items.Pointers[2], args.Items.Pointers[2]);
TWasm.val_copy(results.Items.Pointers[3], args.Items.Pointers[0]);
result := nil;
end;
// A function closure.
function closure_callback(env : Pointer; const args : PWasmValVec; results : PWasmValVec) : PWasmTrap; cdecl;
begin
var i := PInteger(env)^;
writeln('Calling back closure...');
writeln('>'+IntToStr(i));
var d := Default(TWasmVal);
d.kind := WASM_I32;
d.i32 := i;
results.Items[0] := d;
result := nil;
end;
function MultiSample() : Boolean;
begin
// Initialize.
writeln('Initializing...');
{$ifdef USE_WASMER}
var features := TWasmerFeatures.New();
(+features).MultiValue(true); // Probably true by default, but test for wasmer_features_xxx
var config := TWasmConfig.New();
(+config).SetFeatures(features);
var engine := TWasmEngine.NewWithConfig(config);
{$else}
var engine := TWasmEngine.New();
{$endif}
var store := TWasmStore.New(+engine);
// Load binary.
writeln('Loading binary...');
var binary := TWasmByteVec.NewEmpty;
{$ifdef USE_WASMFILE}
binary.Unwrap.LoadFromFile('multi.wasm');
{$else}
var wat :=
'(module'+
' (func $f (import "" "f") (param i32 i64 i64 i32) (result i32 i64 i64 i32))'+
''+
' (func $g (export "g") (param i32 i64 i64 i32) (result i32 i64 i64 i32)'+
' (call $f (local.get 0) (local.get 2) (local.get 1) (local.get 3))'+
' )'+
')';
binary.Unwrap.Wat2Wasm(wat);
{$ifend}
// Compile.
writeln('Compiling module...');
var module := TWasmModule.New(+store, +binary);
if module.IsNone then
begin
writeln('> Error compiling module!');
exit(false)
end;
// Create external print functions.
writeln('Creating callback...');
var callback_func := TWasmFunc.New(+store, +TWasmFunctype.New([WASM_I32, WASM_I64, WASM_I64, WASM_I32], [WASM_I32, WASM_I64, WASM_I64, WASM_I32]), callback);
// Instantiate.
writeln('Instantiating module...');
var imports := TWasmExternVec.Create([ (+callback_func).AsExtern ]);
var instance := TWasmInstance.New(+store, +module, @imports);
if instance.IsNone then
begin
writeln('> Error instantiating module!');
exit(false);
end;
// Extract export.
writeln('Extracting export...');
var export_s := (+instance).GetExports;
if export_s.Unwrap.size = 0 then
begin
writeln('> Error accessing exports!');
exit(false);
end;
var run_func := export_s.Unwrap.Items[0].AsFunc;
if run_func = nil then
begin
writeln('> Error accessing export!');
exit(false);
end;
// Call.
writeln('Calling export...');
var vals := [
WASM_I32_VAL(1), WASM_I64_VAL(2), WASM_I64_VAL(3), WASM_I32_VAL(4)
];
var res := [
WASM_INIT_VAL, WASM_INIT_VAL, WASM_INIT_VAL, WASM_INIT_VAL
];
var args := TWasmValVec.Create(vals);
var results := TWasmValVec.Create(res);
if run_func.Call( @args, @results).IsError then
begin
writeln('> Error calling function!');
exit(false);
end;
// Print result.
writeln('Printing result...');
writeln( Format('> %u %u %u %u', [
res[0].i32, res[1].i64, res[2].i64, res[3].i32]));
assert(res[0].i32 = 4);
assert(res[1].i64 = 3);
assert(res[2].i64 = 2);
assert(res[3].i32 = 1);
// Shut down.
writeln('Shutting down...');
// All done.
writeln('Done.');
result := true;
end;
end.
|
unit ejb_currencyconverter_s;
{This file was generated on 28 Feb 2001 10:06:55 GMT by version 03.03.03.C1.06}
{of the Inprise VisiBroker idl2pas CORBA IDL compiler. }
{Please do not edit the contents of this file. You should instead edit and }
{recompile the original IDL which was located in the file ejb.idl. }
{Delphi Pascal unit : ejb_currencyconverter_s }
{derived from IDL module : currencyconverter }
interface
uses
CORBA,
ejb_currencyconverter_i,
ejb_currencyconverter_c;
type
TEuroConverterSkeleton = class;
TEuroConverterHomeSkeleton = class;
TEuroConverterSkeleton = class(CORBA.TCorbaObject, ejb_currencyconverter_i.EuroConverter)
private
FImplementation : EuroConverter;
public
constructor Create(const InstanceName: string; const Impl: EuroConverter);
destructor Destroy; override;
function GetImplementation : EuroConverter;
function hfl2float ( const arg0 : Single): Single;
function getEJBHome : ejb_sidl_javax_ejb_i.EJBHome;
function getPrimaryKey : ANY;
procedure remove ;
published
procedure _hfl2float(const _Input: CORBA.InputStream; _Cookie: Pointer);
procedure _getEJBHome(const _Input: CORBA.InputStream; _Cookie: Pointer);
procedure _getPrimaryKey(const _Input: CORBA.InputStream; _Cookie: Pointer);
procedure _remove(const _Input: CORBA.InputStream; _Cookie: Pointer);
end;
TEuroConverterHomeSkeleton = class(CORBA.TCorbaObject, ejb_currencyconverter_i.EuroConverterHome)
private
FImplementation : EuroConverterHome;
public
constructor Create(const InstanceName: string; const Impl: EuroConverterHome);
destructor Destroy; override;
function GetImplementation : EuroConverterHome;
function _create : ejb_currencyconverter_i.EuroConverter;
function getEJBMetaData : ejb_sidl_javax_ejb_i.EJBMetaData;
procedure remove ( const primaryKey : ANY);
function getSimplifiedIDL : AnsiString;
published
procedure __create(const _Input: CORBA.InputStream; _Cookie: Pointer);
procedure _getEJBMetaData(const _Input: CORBA.InputStream; _Cookie: Pointer);
procedure _remove(const _Input: CORBA.InputStream; _Cookie: Pointer);
procedure _getSimplifiedIDL(const _Input: CORBA.InputStream; _Cookie: Pointer);
end;
implementation
constructor TEuroConverterSkeleton.Create(const InstanceName : string; const Impl : ejb_currencyconverter_i.EuroConverter);
begin
inherited;
inherited CreateSkeleton(InstanceName, 'EuroConverter', 'IDL:currencyconverter/EuroConverter:1.0');
FImplementation := Impl;
end;
destructor TEuroConverterSkeleton.Destroy;
begin
FImplementation := nil;
inherited;
end;
function TEuroConverterSkeleton.GetImplementation : ejb_currencyconverter_i.EuroConverter;
begin
result := FImplementation as ejb_currencyconverter_i.EuroConverter;
end;
function TEuroConverterSkeleton.hfl2float ( const arg0 : Single): Single;
begin
Result := FImplementation.hfl2float( arg0);
end;
function TEuroConverterSkeleton.getEJBHome : ejb_sidl_javax_ejb_i.EJBHome;
begin
Result := FImplementation.getEJBHome;
end;
function TEuroConverterSkeleton.getPrimaryKey : ANY;
begin
Result := FImplementation.getPrimaryKey;
end;
procedure TEuroConverterSkeleton.remove ;
begin
FImplementation.remove;
end;
procedure TEuroConverterSkeleton._hfl2float(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_arg0 : Single;
_Result : Single;
begin
_Input.ReadFloat(_arg0);
_Result := hfl2float( _arg0);
GetReplyBuffer(_Cookie, _Output);
_Output.WriteFloat(_Result);
end;
procedure TEuroConverterSkeleton._getEJBHome(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_Result : ejb_sidl_javax_ejb_i.EJBHome;
begin
_Result := getEJBHome;
GetReplyBuffer(_Cookie, _Output);
ejb_sidl_javax_ejb_c.TEJBHomeHelper.Write(_Output, _Result);
end;
procedure TEuroConverterSkeleton._getPrimaryKey(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_Result : ANY;
begin
_Result := getPrimaryKey;
GetReplyBuffer(_Cookie, _Output);
_Output.WriteAny(_Result);
end;
procedure TEuroConverterSkeleton._remove(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
begin
remove;
GetReplyBuffer(_Cookie, _Output);
end;
constructor TEuroConverterHomeSkeleton.Create(const InstanceName : string; const Impl : ejb_currencyconverter_i.EuroConverterHome);
begin
inherited;
inherited CreateSkeleton(InstanceName, 'EuroConverterHome', 'IDL:currencyconverter/EuroConverterHome:1.0');
FImplementation := Impl;
end;
destructor TEuroConverterHomeSkeleton.Destroy;
begin
FImplementation := nil;
inherited;
end;
function TEuroConverterHomeSkeleton.GetImplementation : ejb_currencyconverter_i.EuroConverterHome;
begin
result := FImplementation as ejb_currencyconverter_i.EuroConverterHome;
end;
function TEuroConverterHomeSkeleton._create : ejb_currencyconverter_i.EuroConverter;
begin
Result := FImplementation._create;
end;
function TEuroConverterHomeSkeleton.getEJBMetaData : ejb_sidl_javax_ejb_i.EJBMetaData;
begin
Result := FImplementation.getEJBMetaData;
end;
procedure TEuroConverterHomeSkeleton.remove ( const primaryKey : ANY);
begin
FImplementation.remove( primaryKey);
end;
function TEuroConverterHomeSkeleton.getSimplifiedIDL : AnsiString;
begin
Result := FImplementation.getSimplifiedIDL;
end;
procedure TEuroConverterHomeSkeleton.__create(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_Result : ejb_currencyconverter_i.EuroConverter;
begin
try
_Result := _create;
except on E: UserException do
begin
GetExceptionReplyBuffer(_Cookie, _Output);
E.WriteExceptionInfo(_Output);
exit
end;
end;
GetReplyBuffer(_Cookie, _Output);
ejb_currencyconverter_c.TEuroConverterHelper.Write(_Output, _Result);
end;
procedure TEuroConverterHomeSkeleton._getEJBMetaData(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_Result : ejb_sidl_javax_ejb_i.EJBMetaData;
begin
_Result := getEJBMetaData;
GetReplyBuffer(_Cookie, _Output);
ejb_sidl_javax_ejb_c.TEJBMetaDataHelper.Write(_Output, _Result);
end;
procedure TEuroConverterHomeSkeleton._remove(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_primaryKey : ANY;
begin
_Input.ReadAny(_primaryKey);
remove( _primaryKey);
GetReplyBuffer(_Cookie, _Output);
end;
procedure TEuroConverterHomeSkeleton._getSimplifiedIDL(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_Result : AnsiString;
begin
_Result := getSimplifiedIDL;
GetReplyBuffer(_Cookie, _Output);
_Output.WriteString(_Result);
end;
initialization
end. |
unit IdEchoUDP;
interface
uses classes, IdAssignedNumbers, IdUDPBase, IdUDPClient;
type
TIdEchoUDP = class(TIdUDPClient)
protected
FEchoTime: Cardinal;
public
constructor Create(AOwner: TComponent); override;
{This sends Text to the peer and returns the reply from the peer}
Function Echo(AText: String): String;
{Time taken to send and receive data}
Property EchoTime: Cardinal read FEchoTime;
published
property Port default IdPORT_ECHO;
end;
implementation
uses IdGlobal;
{ TIdIdEchoUDP }
constructor TIdEchoUDP.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Port := IdPORT_ECHO;
end;
function TIdEchoUDP.Echo(AText: String): String;
var
StartTime: Cardinal;
begin
StartTime := IdGlobal.GetTickCount;
Send(AText);
Result := ReceiveString;
{This is just in case the TickCount rolled back to zero}
FEchoTime := GetTickDiff(StartTime,IdGlobal.GetTickCount);
end;
end.
|
UNIT KaffeeautomatMod;
INTERFACE
TYPE Coins = RECORD
OneEuro: integer;
FiftyCent: integer;
TenCent: integer;
END;
VAR errNotEnoughChange: integer;
coinsInput: Coins;
coinsOutput: Coins;
PROCEDURE ResetMachine;
PROCEDURE CoffeeButtonPressed(input: Coins; var change: Coins);
IMPLEMENTATION
const coffeePrize = 40;
var totalChange: Coins;
totalCredit: integer;
changeBank: Coins;
PROCEDURE ResetMachine;
BEGIN
coinsInput.OneEuro := 0;
coinsInput.FiftyCent := 0;
coinsInput.TenCent := 0;
totalChange.OneEuro := 0;
totalChange.FiftyCent := 0;
totalChange.TenCent := 0;
totalCredit := 0;
END;
FUNCTION CalculateChange(credit: integer): Coins;
var returnCoins: Coins;
BEGIN (* CalculateChange *)
returnCoins.OneEuro := 0;
returnCoins.FiftyCent := 0;
returnCoins.TenCent := 0;
if credit < coffeePrize then BEGIN
WriteLn('Not enough credit. Please input at least ', (coffeePrize / 100):1:2, ' EUR.');
CalculateChange := coinsInput;
end else BEGIN
credit := credit - coffeePrize; (* Removes the prize for one coffe from the total credits *)
while (credit >= 100) AND (changeBank.OneEuro > 0) do BEGIN
Inc(returnCoins.OneEuro);
Dec(changeBank.OneEuro);
credit := credit - 100;
END; (* WHILE *)
while (credit >= 50) AND (changeBank.FiftyCent > 0) do BEGIN
Inc(returnCoins.FiftyCent);
Dec(changeBank.FiftyCent);
credit := credit - 50;
END; (* WHILE *)
while (credit >= 10) AND (changeBank.TenCent > 0) do BEGIN
Inc(returnCoins.TenCent);
Dec(changeBank.TenCent);
credit := credit - 10;
END; (* WHILE *)
if credit > 0 then BEGIN
Write('Machine has not enough change! ');
Inc(errNotEnoughChange);
CalculateChange := coinsInput;
end else BEGIN
CalculateChange := returnCoins;
END; (* IF *)
END; (* IF *)
END; (* CalculateChange *)
PROCEDURE CoffeeButtonPressed(input: Coins; var change: Coins);
BEGIN
totalCredit := input.OneEuro * 100;
totalCredit := totalCredit + input.FiftyCent * 50;
totalCredit := totalCredit + input.TenCent * 10;
changeBank.OneEuro := changeBank.OneEuro + input.OneEuro;
changeBank.FiftyCent := changeBank.FiftyCent + input.FiftyCent;
changeBank.TenCent := changeBank.TenCent + input.TenCent;
if totalCredit <> coffeePrize then BEGIN
totalChange := CalculateChange(totalCredit);
if (totalChange.OneEuro <> input.OneEuro) OR (totalChange.FiftyCent <> input.FiftyCent)
OR (totalChange.TenCent <> input.TenCent) then
WriteLn('Thank you, enjoy your coffee!');
Write('You get ');
if totalChange.OneEuro > 0 then
Write(totalChange.OneEuro, ' One Euro Coin(s) ');
if totalChange.FiftyCent > 0 then
Write(totalChange.FiftyCent, ' Fifty Cent Coin(s) ');
if totalChange.TenCent > 0 then
Write(totalChange.TenCent, ' Ten Cent Coin(s) ');
Write('in change.');
end else BEGIN
WriteLn('Thank you, enjoy your coffee!');
END; (* IF *)
END;
BEGIN (* KaffeeautomatMod *)
changeBank.OneEuro := 0;
changeBank.FiftyCent := 5;
changeBank.TenCent := 10;
coinsInput.OneEuro := 0;
coinsInput.FiftyCent := 0;
coinsInput.TenCent := 0;
totalChange.OneEuro := 0;
totalChange.FiftyCent := 0;
totalChange.TenCent := 0;
totalCredit := 0;
errNotEnoughChange := 0;
END. (* KaffeeautomatMod *) |
unit U_Param_Con_Mod;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, U_Param_Mod, StdCtrls, Buttons, U_MyFunction, DateUtils;
type
TF_Param_Con_Mod = class(TF_Param_Mod)
procedure btn_stop_plcClick(Sender: TObject);
procedure btn_resume_plcClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
m_dataUnit:array[0..2047] of Byte;
m_bResp_con:Boolean;
function WaitForResp_con(Sender: TObject;AFN,Fn:Byte):Boolean;
public
{ Public declarations }
function MakeFrame(AFN,Fn:Byte; pDataUnit:PByte=nil; len:Integer=0; Pn:Word=0; IS_COMM_MODULE_ID_PLC:Boolean=False):PByte;override;
function GetDataUnit():PByte;override;
function GetDataUnitLen():Integer;override;
function GetAFN():Byte;override;
function GetFn():Byte;override;
procedure ParseData(pCommEntity:Pointer=nil);override;
function Test():Byte;
end;
var
F_Param_Con_Mod: TF_Param_Con_Mod;
implementation
{$R *.dfm}
uses
U_Protocol,U_Protocol_con, U_Protocol_645, U_Main, U_ParamReadWrite;
function TF_Param_Con_Mod.Test():Byte;
begin
ShowMessage('22222');
end;
function TF_Param_Con_Mod.MakeFrame(AFN,Fn:Byte; pDataUnit:PByte=nil; len:Integer=0; Pn:Word=0; IS_COMM_MODULE_ID_PLC:Boolean=False):PByte;
var pParam:PDataTranParam;
begin
O_ProTx_Mod.MakeFrame(AFN, Fn, pDataUnit, len, Pn, IS_COMM_MODULE_ID_PLC);
pParam := @m_dataUnit[0];
pParam.nPort := PLC_PORT_NO;
pParam.tranCtrl := 0;
pParam.nFrameTimeout := $80 or (g_timeout div 1000);
pParam.nByteTimeout := 1;
pParam.nTranLen := O_ProTx_Mod.GetFrameLen();
MoveMemory(@pParam.data[0], O_ProTx_Mod.GetFrameBuf(), O_ProTx_Mod.GetFrameLen());
Result := O_ProTx.MakeFrame(AFN_TRANS,F1,@(pParam^),O_ProTx_Mod.GetFrameLen()+sizeof(TDataTranParam)-sizeof(pParam.data));
end;
function TF_Param_Con_Mod.GetDataUnit():PByte;
begin
Result := O_ProRx_Mod.GetDataUnit();
end;
function TF_Param_Con_Mod.GetDataUnitLen():Integer;
begin
Result := O_ProRx_Mod.GetDataUnitLen();
end;
function TF_Param_Con_Mod.GetAFN():Byte;
begin
Result := O_ProRx_Mod.GetAFN();
end;
function TF_Param_Con_Mod.GetFn():Byte;
begin
Result := O_ProRx_Mod.GetFn();
end;
procedure TF_Param_Con_Mod.ParseData(pCommEntity:Pointer=nil);
begin
m_bResp_con := True;
if O_ProRx_Mod.CheckFrame(O_ProRx.GetDataUnit(), O_ProRx.GetDataUnitLen()) then
begin
m_bResp := True;
end;
end;
function TF_Param_Con_Mod.WaitForResp_con(Sender: TObject;AFN,Fn:Byte):Boolean;
var beginWait:TDateTime;
clr:TColor;
nWaitTime:Integer;
begin
m_bResp_con := False;
Result := False;
beginWait := Now;
nWaitTime := 12000;
nWaitTime := nWaitTime + 2000*(O_ProTx.GetRelayLevel());
if Sender is TCheckBox then TCheckBox(Sender).Font.Color := clBlack;
if Sender is TButton then TButton(Sender).Font.Color := clBlack;
while (not m_bResp_con)and (Abs(MilliSecondsBetween(Now,beginWait))<nWaitTime) do
begin
Delay(100);
end;
if (m_bResp_con) then
begin
if (O_ProRx.GetAFN()=AFN)and(O_ProRx.GetFn()=Fn) then
begin
Result := True;
end;
end;
if Result then
begin
clr := clSucced;
end
else
begin
clr := clFailed;
end;
if Sender is TCheckBox then TCheckBox(Sender).Font.Color := clr;
if Sender is TButton then TButton(Sender).Font.Color :=clr;
end;
procedure TF_Param_Con_Mod.btn_stop_plcClick(Sender: TObject);
var dataUnit:array[0..127]of Byte;
begin
//inherited;
TButton(Sender).Enabled := False;
g_bStop := False;
dataUnit[0] := 31;
O_ProTx.MakeFrame(AFN_CTRL,F49,@dataUnit[0],1);
if F_Main.SendDataAuto()
and WaitForResp_con(Sender,AFN_CONFIRM,F1)
then;
TButton(Sender).Enabled := True;
end;
procedure TF_Param_Con_Mod.btn_resume_plcClick(Sender: TObject);
var dataUnit:array[0..127]of Byte;
begin
//inherited;
TButton(Sender).Enabled := False;
g_bStop := False;
dataUnit[0] := 31;
O_ProTx.MakeFrame(AFN_CTRL,F50,@dataUnit[0],1);
if F_Main.SendDataAuto()
and WaitForResp_con(Sender,AFN_CONFIRM,F1)
then;
TButton(Sender).Enabled := True;
end;
procedure TF_Param_Con_Mod.FormCreate(Sender: TObject);
begin
inherited;
m_bResp_con := False;
end;
end.
|
unit vr_variant;
{$IFDEF fpc}{$mode objfpc}{$ENDIF} {$H+}
{$I vrode.inc}
interface
uses
SysUtils, Classes, vr_types, vr_intfs;
type
IVariant = interface;
TIVariantProc = procedure(const AVar: IVariant);
TIVariantMethod = procedure(const AVar: IVariant) of object;
TIVariantKind = (ivkEmpty,
ivkInteger, ivkDouble, ivkString, ivkBoolean,
ivkInterface,
ivkObject, //ivar_Obj(obj, Own); overloading assignment operator -> Own=False
ivkError, //ivar_Err('Error', 0): IVariant.Str-Error;.Int=Code
ivkArray, //see TIArrayVariant<T>
ivkCustom //see TICustomVariant<T>,
);
IVariant = interface
['{6ACD0A3A-D173-4299-9349-56D17D19CF02}']
function Int(const ADefault: Int64 = 0): Int64;
function Float(const ADefault: Extended = 0): Extended;
function Str(const ADefault: string = ''): string;
function WStr(const ADefault: WideString = ''): WideString;
function Bool(const ADefault: Boolean = False): Boolean;
function Intf: IUnknown;
function Obj: TObject;
function Memory: Pointer;
function Kind: TIVariantKind;
function Copy: IVariant;
end;
function ivar_Obj(const AObject: TObject; const AOwn: Boolean= False): IVariant; inline;
function ivar_Err(const AError: string; const ACode: Integer = 0): IVariant; inline;
function ivar_Intf(const AUnknown: IUnknown): IVariant; inline;
{%Region Operator Overloading}
operator := (v : Int64) z : IVariant;
operator := (v : Extended) z : IVariant;
operator := (v : string) z : IVariant;
operator := (v : WideString) z : IVariant;
operator := (v : Boolean) z : IVariant;
operator := (v : TObject) z : IVariant;
//operator := (v : IUnknown) z : IVariant; //TComponent assigned as IUnknown
operator := (v : IFPObject) z : IVariant;
operator := (v : IVariantObject) z : IVariant;
operator := (v : IInterfaceList) z : IVariant;
//operator := (v : Variant) z : IVariant; //Compiler Error
operator := (v : IVariant) z : Int64;
operator := (v : IVariant) z : Extended;
operator := (v : IVariant) z : string;
operator := (v : IVariant) z : WideString;
operator := (v : IVariant) z : Boolean;
operator := (v : IVariant) z : TObject;
//operator := (v : IVariant) z : IUnknown; //Compiler Error
{%EndRegion Operator Overloading}
type
{ TIVariant }
TIVariant = class(TInterfacedObject, IVariant)
public
function Int(const ADefault: Int64 = 0): Int64; virtual;
function Str(const ADefault: string = ''): string; virtual;
function WStr(const ADefault: WideString = ''): WideString;
function Bool(const ADefault: Boolean = False): Boolean; virtual;
function Float(const ADefault: Extended = 0): Extended; virtual;
function Intf: IUnknown; virtual;
function Obj: TObject; virtual;
function Memory: Pointer; virtual;
function Kind: TIVariantKind; virtual;
function Copy: IVariant; virtual;
end;
{ TIIntegerVariant }
TIIntegerVariant = class(TIVariant)
private
FInt: Int64;
public
constructor Create(const AInt: Int64);
function Int(const {%H-}ADefault: Int64 = 0): Int64; override;
function Str(const {%H-}ADefault: string = ''): string; override;
function Bool(const {%H-}ADefault: Boolean = False): Boolean; override;
function Float(const {%H-}ADefault: Extended = 0): Extended; override;
function Kind: TIVariantKind; override;
function Copy: IVariant; override;
end;
{ TIFloatVariant }
TIFloatVariant = class(TIVariant)
private
FFloat: Extended;
public
constructor Create(const AFloat: Extended);
function Bool(const {%H-}ADefault: Boolean = False): Boolean; override;
function Int(const {%H-}ADefault: Int64 = 0): Int64; override;
function Str(const {%H-}ADefault: string = ''): string; override;
function Float(const {%H-}ADefault: Extended = 0): Extended; override;
function Kind: TIVariantKind; override;
function Copy: IVariant; override;
end;
{ TIStringVariant }
TIStringVariant = class(TIVariant)
private
FStr: string;
public
constructor Create(const AStr: string);
function Int(const ADefault: Int64 = 0): Int64; override;
function Str(const {%H-}ADefault: string = ''): string; override;
function Bool(const ADefault: Boolean = False): Boolean; override;
function Float(const ADefault: Extended = 0): Extended; override;
function Kind: TIVariantKind; override;
function Copy: IVariant; override;
end;
{ TIBooleanVariant }
TIBooleanVariant = class(TIVariant)
private
FBool: Boolean;
public
constructor Create(const ABool: Boolean);
function Bool(const {%H-}ADefault: Boolean = False): Boolean; override;
function Int(const {%H-}ADefault: Int64 = 0): Int64; override;
function Str(const {%H-}ADefault: string = ''): string; override;
function Float(const {%H-}ADefault: Extended = 0): Extended; override;
function Kind: TIVariantKind; override;
function Copy: IVariant; override;
end;
{ TIInterfaceVariant }
TIInterfaceVariant = class(TIVariant)
private
FIntf: IUnknown;
public
constructor Create(const AIntf: IUnknown);
function Intf: IUnknown; override;
function Kind: TIVariantKind; override;
//function Copy: IVariant; override;
end;
{ TIObjectVariant }
TIObjectVariant = class(TIVariant)
private
FObj: TObject;
FOwn: Boolean;
public
constructor Create(const AObj: TObject; const AOwn: Boolean = False);
destructor Destroy; override;
function Obj: TObject; override;
function Kind: TIVariantKind; override;
function Copy: IVariant; override;
end;
{ TIErrorVariant }
TIErrorVariant = class(TIVariant)
private
FErr: string;
FCode: Integer;
public
constructor Create(const AErr: string; const ACode: Integer = 0);
function Int(const {%H-}ADefault: Int64 = 0): Int64; override;
function Str(const {%H-}ADefault: string = ''): string; override;
function Kind: TIVariantKind; override;
function Copy: IVariant; override;
end;
{ TICustomVariant }
{**
type
TMyDataVariant = TICustomVariant<TMyData>;
var
v: IVariant;
obj: TMyDataVariant;
rec: TMyData;
begin
//v := TMyDataVariant.Create(rec);
if Supports(v, TMyDataVariant, obj) then //safe
rec := obj.Data;
rec := TMyData(v.Memory^); //unsafe
end; }
generic TICustomVariant<T> = class(TIVariant)
private
FData: T;
public
constructor Create(constref AData: T);
function Memory: Pointer; override;
function Kind: TIVariantKind; override;
function Copy: IVariant; override;
property Data: T read FData;
end;
{ TIArrayVariant }
{**
type
TMyArrVariant = TIArrayVariant<TMyRec>;
TMyRecArray = array of TMyRec;
var
v: IVariant;
arr: TMyRecArray;
obj: TMyArrVariant;
begin
//v := TMyArrVariant.Create(arr);
if Supports(v, TMyArrVariant, obj) then //safe
arr := obj.Arr;
arr := TMyRecArray(v.Memory^); //unsafe
end; }
generic TIArrayVariant<T> = class(TIVariant)
type
TArrayType = array of T;
private
FArr: TArrayType;
public
constructor Create(constref Arr: TArrayType);
function Memory: Pointer; override;
function Kind: TIVariantKind; override;
function Copy: IVariant; override;
property Arr: TArrayType read FArr;
end;
implementation
operator := (v: Int64)z: IVariant;
begin
Result := TIIntegerVariant.Create(v);
end;
operator := (v: Extended)z: IVariant;
begin
Result := TIFloatVariant.Create(v);
end;
operator := (v : string) z : IVariant;
begin
Result := TIStringVariant.Create(v);
end;
operator := (v: WideString)z: IVariant;
begin
Result := TIStringVariant.Create(UTF8Encode(v));
end;
operator := (v: Boolean)z: IVariant;
begin
Result := TIBooleanVariant.Create(v);
end;
operator := (v: TObject)z: IVariant;
begin
Result := TIObjectVariant.Create(v, False);
end;
//operator := (v: IUnknown)z: IVariant;
//begin
// Result := TIInterfaceVariant.Create(v);
//end;
operator := (v : IFPObject) z : IVariant;
begin
Result := TIInterfaceVariant.Create(v);
end;
operator := (v : IVariantObject) z : IVariant;
begin
Result := TIInterfaceVariant.Create(v);
end;
operator := (v : IInterfaceList) z : IVariant;
begin
Result := TIInterfaceVariant.Create(v);
end;
operator := (v: IVariant)z: Int64;
begin
Result := v.Int(0);
end;
operator := (v: IVariant)z: Extended;
begin
Result := v.Float(0);
end;
operator := (v: IVariant)z: string;
begin
Result := v.Str('');
end;
operator := (v : IVariant) z : WideString;
begin
Result := v.WStr('');
end;
operator := (v: IVariant)z: Boolean;
begin
Result := v.Bool(False);
end;
operator := (v: IVariant)z: TObject;
begin
Result := v.Obj;
end;
//operator := (v : IVariant) z : IUnknown;
//begin
// Result := v.Intf;
//end;
function ivar_Obj(const AObject: TObject; const AOwn: Boolean): IVariant;
begin
Result := TIObjectVariant.Create(AObject, AOwn);
end;
function ivar_Err(const AError: string; const ACode: Integer): IVariant;
begin
Result := TIErrorVariant.Create(AError, ACode);
end;
function ivar_Intf(const AUnknown: IUnknown): IVariant;
begin
Result := TIInterfaceVariant.Create(AUnknown);
end;
{ TIErrorVariant }
constructor TIErrorVariant.Create(const AErr: string; const ACode: Integer);
begin
FErr := AErr;
FCode := ACode;
end;
function TIErrorVariant.Int(const ADefault: Int64): Int64;
begin
Result := FCode;
end;
function TIErrorVariant.Str(const ADefault: string): string;
begin
Result := FErr;
end;
function TIErrorVariant.Kind: TIVariantKind;
begin
Result := ivkError;
end;
function TIErrorVariant.Copy: IVariant;
begin
Result := TIErrorVariant.Create(FErr, FCode);
end;
{ TIArrayVariant }
constructor TIArrayVariant.Create(constref Arr: TArrayType);
begin
FArr := Arr;
end;
function TIArrayVariant.Memory: Pointer;
begin
Result := @FArr;
end;
function TIArrayVariant.Kind: TIVariantKind;
begin
Result := ivkArray;
end;
function TIArrayVariant.Copy: IVariant;
var
a: TArrayType;
i: Integer;
begin
SetLength(a, Length(FArr));
for i := 0 to Length(a) - 1 do
a[i] := FArr[i];
Result := TIArrayVariant.Create(a);
end;
{ TICustomVariant }
constructor TICustomVariant.Create(constref AData: T);
begin
FData := AData;
end;
function TICustomVariant.Memory: Pointer;
begin
Result := @FData;
end;
function TICustomVariant.Kind: TIVariantKind;
begin
Result := ivkCustom;
end;
function TICustomVariant.Copy: IVariant;
begin
Result := TICustomVariant.Create(FData);
end;
{ TIObjectVariant }
constructor TIObjectVariant.Create(const AObj: TObject; const AOwn: Boolean);
begin
if AObj <> nil then
begin
FObj := AObj;
FOwn := AOwn;
end
else
begin
FObj := TObject.Create;
FOwn := True;
end;
end;
destructor TIObjectVariant.Destroy;
begin
if FOwn then
FObj.Free;
inherited Destroy;
end;
function TIObjectVariant.Kind: TIVariantKind;
begin
Result := ivkObject;
end;
function TIObjectVariant.Copy: IVariant;
function _TryCopy(out AVar: IVariant): Boolean;
var
obj_: TObject = nil;
begin
Result := False;
try
if not (FObj is TPersistent) then Exit;
obj_ := FObj.newinstance;
TPersistent(obj_).Assign(TPersistent(FObj));
AVar := TIObjectVariant.Create(obj_, True);
except
if obj_ <> nil then
obj_.Free;
end;
end;
begin
if not _TryCopy(Result) then
Result := inherited Copy;
end;
function TIObjectVariant.Obj: TObject;
begin
Result := FObj;
end;
{ TIFloatVariant }
constructor TIFloatVariant.Create(const AFloat: Extended);
begin
FFloat := AFloat;
end;
function TIFloatVariant.Kind: TIVariantKind;
begin
Result := ivkDouble;
end;
function TIFloatVariant.Bool(const ADefault: Boolean): Boolean;
begin
Result := Boolean(Round(FFloat));
end;
function TIFloatVariant.Int(const ADefault: Int64): Int64;
begin
Result := Round(FFloat);
end;
function TIFloatVariant.Str(const ADefault: string): string;
begin
Result := FloatToStr(FFloat);
end;
function TIFloatVariant.Float(const ADefault: Extended): Extended;
begin
Result := FFloat;
end;
function TIFloatVariant.Copy: IVariant;
begin
Result := TIFloatVariant.Create(FFloat);
end;
{ TIInterfaceVariant }
constructor TIInterfaceVariant.Create(const AIntf: IUnknown);
begin
if AIntf <> nil then
FIntf := AIntf
else
FIntf := TInterfacedObject.Create;
end;
function TIInterfaceVariant.Kind: TIVariantKind;
begin
Result := ivkInterface;
end;
function TIInterfaceVariant.Intf: IUnknown;
begin
Result := FIntf;
end;
{ TIBooleanVariant }
constructor TIBooleanVariant.Create(const ABool: Boolean);
begin
FBool := ABool;
end;
function TIBooleanVariant.Kind: TIVariantKind;
begin
Result := ivkBoolean;
end;
function TIBooleanVariant.Bool(const ADefault: Boolean): Boolean;
begin
Result := FBool;
end;
function TIBooleanVariant.Int(const ADefault: Int64): Int64;
begin
Result := Ord(FBool);
end;
function TIBooleanVariant.Str(const ADefault: string): string;
begin
Result := BoolToStr(FBool, True);
end;
function TIBooleanVariant.Float(const ADefault: Extended): Extended;
begin
Result := Ord(FBool);
end;
function TIBooleanVariant.Copy: IVariant;
begin
Result := TIBooleanVariant.Create(FBool);
end;
{ TIIntegerVariant }
constructor TIIntegerVariant.Create(const AInt: Int64);
begin
FInt := AInt;
end;
function TIIntegerVariant.Kind: TIVariantKind;
begin
Result := ivkInteger;
end;
function TIIntegerVariant.Bool(const ADefault: Boolean): Boolean;
begin
Result := Boolean(FInt);
end;
function TIIntegerVariant.Float(const ADefault: Extended): Extended;
begin
Result := FInt;
end;
function TIIntegerVariant.Int(const ADefault: Int64): Int64;
begin
Result := FInt;
end;
function TIIntegerVariant.Str(const ADefault: string): string;
begin
Result := IntToStr(FInt);
end;
function TIIntegerVariant.Copy: IVariant;
begin
Result := TIIntegerVariant.Create(FInt);
end;
{ TIStringVariant }
constructor TIStringVariant.Create(const AStr: string);
begin
FStr := AStr;
end;
function TIStringVariant.Kind: TIVariantKind;
begin
Result := ivkString;
end;
function TIStringVariant.Int(const ADefault: Int64): Int64;
begin
Result := StrToInt64Def(FStr, ADefault);
end;
function TIStringVariant.Str(const ADefault: string): string;
begin
Result := FStr;
end;
function TIStringVariant.Bool(const ADefault: Boolean): Boolean;
begin
Result := StrToBoolDef(FStr, ADefault);
end;
function TIStringVariant.Float(const ADefault: Extended): Extended;
begin
Result := StrToFloatDef(FStr, ADefault);
end;
function TIStringVariant.Copy: IVariant;
begin
Result := TIStringVariant.Create(FStr);
end;
{ TIVariant }
function TIVariant.Kind: TIVariantKind;
begin
Result := ivkEmpty;
end;
function TIVariant.Int(const ADefault: Int64): Int64;
begin
Result := ADefault;
end;
function TIVariant.Str(const ADefault: string): string;
begin
Result := ADefault;
end;
function TIVariant.WStr(const ADefault: WideString): WideString;
begin
Result := UTF8Decode(Str(UTF8Encode(ADefault)));
end;
function TIVariant.Bool(const ADefault: Boolean): Boolean;
begin
Result := ADefault;
end;
function TIVariant.Float(const ADefault: Extended): Extended;
begin
Result := ADefault;
end;
function TIVariant.Intf: IUnknown;
begin
Result := TInterfacedObject.Create;
end;
function TIVariant.Obj: TObject;
begin
Result := nil;
end;
function TIVariant.Memory: Pointer;
begin
Result := nil;{$IFDEF TEST_MODE}
raise Exception.Create('IVariant.Memory(): not allowed for this type');{$ENDIF}
end;
function TIVariant.Copy: IVariant;
begin
Result := nil;{$IFDEF TEST_MODE}
raise Exception.Create('IVariant.Copy(): not allowed for this type');{$ENDIF}
end;
end.
|
unit array_open_1;
interface
implementation
var
GL, G0, G1, G2, G3: Int32;
procedure P1(Values: openarray of Int32);
begin
GL := Length(Values);
G0 := Values[0];
G1 := Values[1];
G2 := Values[2];
G3 := Values[3];
end;
procedure Test;
begin
P1([11, 22, 33, 44]);
end;
initialization
Test();
finalization
Assert(GL = 4);
Assert(G0 = 11);
Assert(G1 = 22);
Assert(G2 = 33);
Assert(G3 = 44);
end. |
(* ShapeUnit: MM, 2020-06-03 *)
(* ------ *)
(* Unit for simple geometric shapes *)
(* ========================================================================= *)
UNIT ShapeUnit;
INTERFACE
USES WinGraph, Windows;
TYPE
Shape = ^ShapeObj;
ShapeObj = OBJECT
PUBLIC
CONSTRUCTOR Init;
DESTRUCTOR Done; VIRTUAL;
PROCEDURE Describe(name: STRING; indent: INTEGER);
PROCEDURE Draw(dc: HDC); VIRTUAL;
PROCEDURE Erase(dc: HDC); VIRTUAL;
PROCEDURE MoveBy(dc: HDC; dx, dy: INTEGER); VIRTUAL;
PRIVATE
visible: BOOLEAN;
END; (* ShapeObj *)
Line = ^LineObj;
LineObj = OBJECT(ShapeObj)
PUBLIC
CONSTRUCTOR Init(x1, y1, x2, y2: INTEGER);
DESTRUCTOR Done; VIRTUAL;
PROCEDURE Describe(name: STRING; indent: INTEGER);
PROCEDURE Draw(dc: HDC); VIRTUAL;
PROCEDURE Erase(dc: HDC); VIRTUAL;
PROCEDURE MoveBy(dc: HDC; dx, dy: INTEGER); VIRTUAL;
PRIVATE
x1, y1, x2, y2: INTEGER;
END; (* LineObj *)
IMPLEMENTATION
CONSTRUCTOR ShapeObj.Init;
BEGIN (* ShapeObj.Init *)
visible := FALSE;
END;(* ShapeObj.Init *)
DESTRUCTOR ShapeObj.Done;
BEGIN (* ShapeObj.Done *)
END;(* ShapeObj.Done *)
PROCEDURE ShapeObj.Describe(name: STRING; indent: INTEGER);
BEGIN (* ShapeObj.Describe *)
Write('':indent, '''', name, ': ');
IF (visible) THEN BEGIN
Write('visible ');
END ELSE BEGIN
Write('invisible ');
END; (* IF *)
END; (* ShapeObj.Describe *)
PROCEDURE ShapeObj.Draw(dc: HDC);
BEGIN (* ShapeObj.Draw *)
visible := TRUE;
END; (* ShapeObj.Draw *)
PROCEDURE ShapeObj.Erase(dc: HDC);
BEGIN (* ShapeObj.Erase *)
visible := FALSE;
END; (* ShapeObj.Erase *)
PROCEDURE ShapeObj.MoveBy(dc: HDC; dx, dy: INTEGER);
BEGIN (* ShapeObj.MoveBy *)
WriteLn('ERROR: ShapeObj.MoveBy is abstract.'); HALT;
END; (* ShapeObj.MoveBy *)
(* ------ LineObj Methods ------------------------------------- *)
CONSTRUCTOR LineObj.Init(x1, y1, x2, y2: INTEGER);
BEGIN (* LineObj.Init *)
INHERITED Init;
SELF.x1 := x1;
SELF.y1 := y1;
SELF.x2 := x2;
SELF.y2 := y2;
END;(* LineObj.Init *)
DESTRUCTOR LineObj.Done;
BEGIN (* LineObj.Done *)
END;(* LineObj.Done *)
PROCEDURE LineObj.Describe(name: STRING; indent: INTEGER);
BEGIN (* LineObj.Describe *)
INHERITED Describe(name, indent);
WriteLn('Line from (', x1, ', ', y1, ') to (', x2, ', ', y2, ')');
END; (* LineObj.Describe *)
PROCEDURE LineObj.Draw(dc: HDC);
BEGIN (* LineObj.Draw *)
MoveTo(dc, x1, y1);
LineTo(dc, x2, y2);
INHERITED Draw(dc);
END; (* LineObj.Draw *)
PROCEDURE LineObj.Erase(dc: HDC);
BEGIN (* LineObj.Erase *)
IF (visible) THEN BEGIN
INHERITED Erase(dc);
SelectObject(dc, GetStockObject(WHITE_PEN));
MoveTo(dc, x1, y1);
LineTo(dc, x2, y2);
SelectObject(dc, GetStockObject(BLACK_PEN));
END; (* IF *)
END; (* LineObj.Erase *)
PROCEDURE LineObj.MoveBy(dc: HDC; dx, dy: INTEGER);
VAR vis: BOOLEAN;
BEGIN (* LineObj.MoveBy *)
vis := SELF.visible;
IF (vis) THEN BEGIN
Erase(dc);
END;
x1 := x1 + dx;
y1 := y1 + dy;
x2 := x2 + dx;
y2 := y2 + dy;
IF (vis) THEN BEGIN
Draw(dc);
END;
END; (* LineObj.MoveBy *)
END. (* ShapeUnit *) |
unit PascalCoin.Utility.Interfaces;
interface
type
IPascalCoinList<T> = Interface
['{18B01A91-8F0E-440E-A6C2-B4B7D4ABA473}']
function GetItem(const Index: Integer): T;
function Count: Integer;
function Add(Item: T): Integer;
property Item[const Index: Integer]: T read GetItem; default;
End;
implementation
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.