text stringlengths 14 6.51M |
|---|
unit bFile;
interface
uses winapi.windows, system.SysUtils, shellapi, classes, variants, vEnv, inifiles;
type
TFile = class
public
class function Move(pSource, pDestination: string): string;
class function Copy(pSource, pDestination: string): string;
class procedure Open(pFile: string);
class procedure Delete(pFile: string);
class function Rename(pOldName, pNewName: string): string;
class function Create(AbsoluteFileName: string): TFile;
class procedure writeInFile(fileName, data: string);
class function exists(pathfilename: string): boolean;
private
class procedure PathWork(Origem, Destino: string; work: integer); overload;
class procedure PathWork(Origem: string; work: integer = FO_DELETE); overload;
class function quotedPath(path: string): string;
end;
implementation
class function TFile.Move(pSource, pDestination: string): string;
begin
if not SameFileName(pSource, tenv.system.exepath) then
begin
if ExtractFileExt(pDestination) <> '' then
begin
if FileExists(pDestination) then
self.Delete(quotedPath(pDestination));
winapi.windows.MoveFile(pchar(pSource), pchar(pDestination));
end
else
PathWork(pSource, pDestination, FO_MOVE);
result := pDestination;
end;
end;
class procedure TFile.Open(pFile: string);
begin
if not FileExists(pFile) then
raise Exception.Create(Format('Arquivo [%s] não encontrado!', [pFile]));
ShellExecute(0, 'open', pchar(quotedPath(pFile)), nil, nil, SW_SHOWNORMAL);
end;
class procedure TFile.PathWork(Origem: string; work: integer);
var
fos: TSHFileOpStruct;
begin
ZeroMemory(@fos, SizeOf(fos));
with fos do
begin
wFunc := work;
fFlags := FOF_NOCONFIRMATION + FOF_NOCONFIRMMKDIR + FOF_NO_UI + FOF_RENAMEONCOLLISION + FOF_SILENT;
pFrom := pchar(Origem + #0);
end;
ShFileOperation(fos);
end;
class function TFile.quotedPath(path: string): string;
begin
result := '"' + path + '"';
end;
class procedure TFile.PathWork(Origem, Destino: string; work: integer);
var
fos: TSHFileOpStruct;
begin
ZeroMemory(@fos, SizeOf(fos));
with fos do
begin
wFunc := work;
fFlags := FOF_NOCONFIRMATION + FOF_NOCONFIRMMKDIR + FOF_NO_UI + FOF_RENAMEONCOLLISION + FOF_SILENT;
pFrom := pchar(Origem + #0);
pTo := pchar(Destino)
end;
ShFileOperation(fos);
end;
class function TFile.Rename(pOldName, pNewName: string): string;
var
b: boolean;
begin
if not SameFileName(pOldName, tenv.system.exepath) then
begin
if ExtractFileExt(pOldName) <> '' then
begin
if FileExists(pOldName) then
b := RenameFile(pOldName, pNewName);
end
else
self.PathWork(quotedPath(pOldName), quotedPath(pNewName), FO_RENAME);
result := pNewName;
end;
end;
class procedure TFile.writeInFile(fileName, data: string);
var
log: TStringList;
begin
try
log := TStringList.Create;
if not FileExists(fileName) then
TFile.Create(fileName);
log.LoadFromFile(fileName);
log.Add(data);
log.SaveToFile(fileName);
except
exit
end;
end;
class procedure TFile.Delete(pFile: string);
begin
if not SameFileName(pFile, tenv.system.exepath) then
PathWork(pFile, FO_DELETE);
end;
class function TFile.exists(pathfilename: string): boolean;
begin
result := FileExists(pathfilename);
end;
class function TFile.Copy(pSource, pDestination: string): string;
begin
if ExtractFileExt(pDestination) <> '' then
begin
if FileExists(pDestination) then
self.Delete(quotedPath(pDestination));
winapi.windows.CopyFile(pchar(pSource), pchar(pDestination), true);
end
else
self.PathWork(pSource, pDestination, FO_COPY);
result := pDestination;
end;
class function TFile.Create(AbsoluteFileName: string): TFile;
begin
if ExtractFileExt(AbsoluteFileName) <> '' then
TStringList.Create.SaveToFile(AbsoluteFileName)
else
begin
if not DirectoryExists(AbsoluteFileName) then
ForceDirectories(StringToOleStr(AbsoluteFileName));
end;
result := self.ClassInfo;
end;
end.
|
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// 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.
//
{$POINTERMATH ON}
unit RN_DetourNavMeshBuilder;
interface
type
PPByte = ^PByte;
/// Represents the source data used to build an navigation mesh tile.
/// @ingroup detour
PdtNavMeshCreateParams = ^TdtNavMeshCreateParams;
TdtNavMeshCreateParams = record
/// @name Polygon Mesh Attributes
/// Used to create the base navigation graph.
/// See #rcPolyMesh for details related to these attributes.
/// @{
verts: PWord; ///< The polygon mesh vertices. [(x, y, z) * #vertCount] [Unit: vx]
vertCount: Integer; ///< The number vertices in the polygon mesh. [Limit: >= 3]
polys: PWord; ///< The polygon data. [Size: #polyCount * 2 * #nvp]
polyFlags: PWord; ///< The user defined flags assigned to each polygon. [Size: #polyCount]
polyAreas: PByte; ///< The user defined area ids assigned to each polygon. [Size: #polyCount]
polyCount: Integer; ///< Number of polygons in the mesh. [Limit: >= 1]
nvp: Integer; ///< Number maximum number of vertices per polygon. [Limit: >= 3]
/// @}
/// @name Height Detail Attributes (Optional)
/// See #rcPolyMeshDetail for details related to these attributes.
/// @{
detailMeshes: PCardinal; ///< The height detail sub-mesh data. [Size: 4 * #polyCount]
detailVerts: PSingle; ///< The detail mesh vertices. [Size: 3 * #detailVertsCount] [Unit: wu]
detailVertsCount: Integer; ///< The number of vertices in the detail mesh.
detailTris: PByte; ///< The detail mesh triangles. [Size: 4 * #detailTriCount]
detailTriCount: Integer; ///< The number of triangles in the detail mesh.
/// @}
/// @name Off-Mesh Connections Attributes (Optional)
/// Used to define a custom point-to-point edge within the navigation graph, an
/// off-mesh connection is a user defined traversable connection made up to two vertices,
/// at least one of which resides within a navigation mesh polygon.
/// @{
/// Off-mesh connection vertices. [(ax, ay, az, bx, by, bz) * #offMeshConCount] [Unit: wu]
offMeshConVerts: PSingle;
/// Off-mesh connection radii. [Size: #offMeshConCount] [Unit: wu]
offMeshConRad: PSingle;
/// User defined flags assigned to the off-mesh connections. [Size: #offMeshConCount]
offMeshConFlags: PWord;
/// User defined area ids assigned to the off-mesh connections. [Size: #offMeshConCount]
offMeshConAreas: PByte;
/// The permitted travel direction of the off-mesh connections. [Size: #offMeshConCount]
///
/// 0 = Travel only from endpoint A to endpoint B.<br/>
/// #DT_OFFMESH_CON_BIDIR = Bidirectional travel.
offMeshConDir: PByte;
/// The user defined ids of the off-mesh connection. [Size: #offMeshConCount]
offMeshConUserID: PCardinal;
/// The number of off-mesh connections. [Limit: >= 0]
offMeshConCount: Integer;
/// @}
/// @name Tile Attributes
/// @note The tile grid/layer data can be left at zero if the destination is a single tile mesh.
/// @{
userId: Cardinal; ///< The user defined id of the tile.
tileX: Integer; ///< The tile's x-grid location within the multi-tile destination mesh. (Along the x-axis.)
tileY: Integer; ///< The tile's y-grid location within the multi-tile desitation mesh. (Along the z-axis.)
tileLayer: Integer; ///< The tile's layer within the layered destination mesh. [Limit: >= 0] (Along the y-axis.)
bmin: array [0..2] of Single; ///< The minimum bounds of the tile. [(x, y, z)] [Unit: wu]
bmax: array [0..2] of Single; ///< The maximum bounds of the tile. [(x, y, z)] [Unit: wu]
/// @}
/// @name General Configuration Attributes
/// @{
walkableHeight: Single; ///< The agent height. [Unit: wu]
walkableRadius: Single; ///< The agent radius. [Unit: wu]
walkableClimb: Single; ///< The agent maximum traversable ledge. (Up/Down) [Unit: wu]
cs: Single; ///< The xz-plane cell size of the polygon mesh. [Limit: > 0] [Unit: wu]
ch: Single; ///< The y-axis cell height of the polygon mesh. [Limit: > 0] [Unit: wu]
/// True if a bounding volume tree should be built for the tile.
/// @note The BVTree is not normally needed for layered navigation meshes.
buildBvTree: Boolean;
/// @}
end;
/// Builds navigation mesh tile data from the provided tile creation data.
/// @ingroup detour
/// @param[in] params Tile creation data.
/// @param[out] outData The resulting tile data.
/// @param[out] outDataSize The size of the tile data array.
/// @return True if the tile data was successfully created.
function dtCreateNavMeshData(params: PdtNavMeshCreateParams; outData: PPByte; outDataSize: PInteger): Boolean;
/// Swaps the endianess of the tile data's header (#dtMeshHeader).
/// @param[in,out] data The tile data array.
/// @param[in] dataSize The size of the data array.
//function dtNavMeshHeaderSwapEndian(data: PByte; dataSize: Integer): Boolean;
/// Swaps endianess of the tile data.
/// @param[in,out] data The tile data array.
/// @param[in] dataSize The size of the data array.
//function dtNavMeshDataSwapEndian(data: PByte; dataSize: Integer): Boolean;
// This section contains detailed documentation for members that don't have
// a source file. It reduces clutter in the main section of the header.
(**
@struct dtNavMeshCreateParams
@par
This structure is used to marshal data between the Recast mesh generation pipeline and Detour navigation components.
See the rcPolyMesh and rcPolyMeshDetail documentation for detailed information related to mesh structure.
Units are usually in voxels (vx) or world units (wu). The units for voxels, grid size, and cell size
are all based on the values of #cs and #ch.
The standard navigation mesh build process is to create tile data using dtCreateNavMeshData, then add the tile
to a navigation mesh using either the dtNavMesh single tile <tt>init()</tt> function or the dtNavMesh::addTile()
function.
@see dtCreateNavMeshData
*)
implementation
uses Math, RN_DetourCommon, RN_DetourNavMesh, RN_Helper;
const
MESH_NULL_IDX = $ffff;
type
PBVItem = ^TBVItem;
TBVItem = record
bmin: array [0..2] of Word;
bmax: array [0..2] of Word;
i: Integer;
end;
function compareItemX(const va, vb: Pointer): Integer;
var a,b: PBVItem;
begin
a := PBVItem(va);
b := PBVItem(vb);
if (a.bmin[0] < b.bmin[0]) then
Exit(-1);
if (a.bmin[0] > b.bmin[0]) then
Exit(1);
Result := 0;
end;
function compareItemY(const va, vb: Pointer): Integer;
var a,b: PBVItem;
begin
a := PBVItem(va);
b := PBVItem(vb);
if (a.bmin[1] < b.bmin[1]) then
Exit(-1);
if (a.bmin[1] > b.bmin[1]) then
Exit(1);
Result := 0;
end;
function compareItemZ(const va, vb: Pointer): Integer;
var a,b: PBVItem;
begin
a := PBVItem(va);
b := PBVItem(vb);
if (a.bmin[2] < b.bmin[2]) then
Exit(-1);
if (a.bmin[2] > b.bmin[2]) then
Exit(1);
Result := 0;
end;
procedure calcExtends(items: PBVItem; nitems: Integer; imin, imax: Integer; bmin, bmax: PWord);
var i: Integer; it: PBVItem;
begin
bmin[0] := items[imin].bmin[0];
bmin[1] := items[imin].bmin[1];
bmin[2] := items[imin].bmin[2];
bmax[0] := items[imin].bmax[0];
bmax[1] := items[imin].bmax[1];
bmax[2] := items[imin].bmax[2];
for i := imin+1 to imax - 1 do
begin
it := @items[i];
if (it.bmin[0] < bmin[0]) then bmin[0] := it.bmin[0];
if (it.bmin[1] < bmin[1]) then bmin[1] := it.bmin[1];
if (it.bmin[2] < bmin[2]) then bmin[2] := it.bmin[2];
if (it.bmax[0] > bmax[0]) then bmax[0] := it.bmax[0];
if (it.bmax[1] > bmax[1]) then bmax[1] := it.bmax[1];
if (it.bmax[2] > bmax[2]) then bmax[2] := it.bmax[2];
end;
end;
function longestAxis(x,y,z: Word): Integer;
var axis: Integer; maxVal: Word;
begin
axis := 0;
maxVal := x;
if (y > maxVal) then
begin
axis := 1;
maxVal := y;
end;
if (z > maxVal) then
begin
axis := 2;
maxVal := z;
end;
Result := axis;
end;
procedure subdivide(items: PBVItem; nitems, imin, imax: Integer; curNode: PInteger; nodes: PdtBVNode);
var inum,icur,axis,isplit,iescape: Integer; node: PdtBVNode;
begin
inum := imax - imin;
icur := curNode^;
node := @nodes[curNode^];
Inc(curNode^);
if (inum = 1) then
begin
// Leaf
node.bmin[0] := items[imin].bmin[0];
node.bmin[1] := items[imin].bmin[1];
node.bmin[2] := items[imin].bmin[2];
node.bmax[0] := items[imin].bmax[0];
node.bmax[1] := items[imin].bmax[1];
node.bmax[2] := items[imin].bmax[2];
node.i := items[imin].i;
end
else
begin
// Split
calcExtends(items, nitems, imin, imax, @node.bmin, @node.bmax[0]);
axis := longestAxis(node.bmax[0] - node.bmin[0],
node.bmax[1] - node.bmin[1],
node.bmax[2] - node.bmin[2]);
if (axis = 0) then
begin
// Sort along x-axis
qsort(items+imin, inum, sizeof(TBVItem), compareItemX);
end
else if (axis = 1) then
begin
// Sort along y-axis
qsort(items+imin, inum, sizeof(TBVItem), compareItemY);
end
else
begin
// Sort along z-axis
qsort(items+imin, inum, sizeof(TBVItem), compareItemZ);
end;
isplit := imin+inum div 2;
// Left
subdivide(items, nitems, imin, isplit, curNode, nodes);
// Right
subdivide(items, nitems, isplit, imax, curNode, nodes);
iescape := curNode^ - icur;
// Negative index means escape.
node.i := -iescape;
end;
end;
function createBVTree(verts: PWord; nverts: Integer;
polys: PWord; npolys, nvp: Integer;
cs, ch: Single;
nnodes: Integer; nodes: PdtBVNode): Integer;
var items: PBVItem; i,j: Integer; it: PBVItem; p: PWord; x,y,z: Word; curNode: Integer;
begin
// Build tree
GetMem(items, sizeof(TBVItem)*npolys);
for i := 0 to npolys - 1 do
begin
it := @items[i];
it.i := i;
// Calc polygon bounds.
p := @polys[i*nvp*2];
it.bmin[0] := verts[p[0]*3+0]; it.bmax[0] := verts[p[0]*3+0];
it.bmin[1] := verts[p[0]*3+1]; it.bmax[1] := verts[p[0]*3+1];
it.bmin[2] := verts[p[0]*3+2]; it.bmax[2] := verts[p[0]*3+2];
for j := 1 to nvp - 1 do
begin
if (p[j] = MESH_NULL_IDX) then break;
x := verts[p[j]*3+0];
y := verts[p[j]*3+1];
z := verts[p[j]*3+2];
if (x < it.bmin[0]) then it.bmin[0] := x;
if (y < it.bmin[1]) then it.bmin[1] := y;
if (z < it.bmin[2]) then it.bmin[2] := z;
if (x > it.bmax[0]) then it.bmax[0] := x;
if (y > it.bmax[1]) then it.bmax[1] := y;
if (z > it.bmax[2]) then it.bmax[2] := z;
end;
// Remap y
it.bmin[1] := Floor(it.bmin[1]*ch/cs);
it.bmax[1] := Ceil(it.bmax[1]*ch/cs);
end;
curNode := 0;
subdivide(items, npolys, 0, npolys, @curNode, nodes);
FreeMem(items);
Result := curNode;
end;
function classifyOffMeshPoint(pt, bmin, bmax: PSingle): Byte;
const XP = 1 shl 0;
const ZP = 1 shl 1;
const XM = 1 shl 2;
const ZM = 1 shl 3;
var outcode: Byte;
begin
outcode := 0;
outcode := outcode or IfThen(pt[0] >= bmax[0], XP, 0);
outcode := outcode or IfThen(pt[2] >= bmax[2], ZP, 0);
outcode := outcode or IfThen(pt[0] < bmin[0], XM, 0);
outcode := outcode or IfThen(pt[2] < bmin[2], ZM, 0);
case (outcode) of
XP: Exit(0);
XP or ZP: Exit(1);
ZP: Exit(2);
XM or ZP: Exit(3);
XM: Exit(4);
XM or ZM: Exit(5);
ZM: Exit(6);
XP or ZM: Exit(7);
end;;
Result := $ff;
end;
// TODO: Better error handling.
/// @par
///
/// The output data array is allocated using the detour allocator (dtAlloc()). The method
/// used to free the memory will be determined by how the tile is added to the navigation
/// mesh.
///
/// @see dtNavMesh, dtNavMesh::addTile()
function dtCreateNavMeshData(params: PdtNavMeshCreateParams; outData: PPByte; outDataSize: PInteger): Boolean;
var nvp: Integer; offMeshConClass: PByte; storedOffMeshConCount,offMeshConLinkCount: Integer; hmin,hmax,h: Single;
i,j: Integer; iv,p: PWord; bmin,bmax: array [0..2] of Single; p0,p1: PSingle; totPolyCount, totVertCount: Integer;
edgeCount, portalCount: Integer; dir: Word; maxLinkCount, uniqueDetailVertCount, detailTriCount,ndv,nv: Integer;
headerSize,vertsSize,polysSize,linksSize,detailMeshesSize,detailVertsSize,detailTrisSize,bvTreeSize,offMeshConsSize,dataSize: Integer;
data,d: PByte; header: PdtMeshHeader; navVerts: PSingle; navPolys: PdtPoly; navDMeshes: PdtPolyDetail; navDVerts: PSingle;
navDTris: PByte; navBvtree: PdtBVNode; offMeshCons: PdtOffMeshConnection; offMeshVertsBase, offMeshPolyBase: Integer;
v,linkv: PSingle; n: Integer; src: PWord; pp: PdtPoly; vbase: Word; dtl: PdtPolyDetail; vb,tbase: Integer; t: PByte;
con: PdtOffMeshConnection; endPts: PSingle;
begin
if (params.nvp > DT_VERTS_PER_POLYGON) then
Exit(false);
if (params.vertCount >= $ffff) then
Exit(false);
if (params.vertCount = 0) or (params.verts = nil) then
Exit(false);
if (params.polyCount = 0) or (params.polys = nil) then
Exit(false);
nvp := params.nvp;
// Classify off-mesh connection points. We store only the connections
// whose start point is inside the tile.
offMeshConClass := nil;
storedOffMeshConCount := 0;
offMeshConLinkCount := 0;
if (params.offMeshConCount > 0) then
begin
GetMem(offMeshConClass, sizeof(Byte)*params.offMeshConCount*2);
// Find tight heigh bounds, used for culling out off-mesh start locations.
hmin := MaxSingle;
hmax := -MaxSingle;
if (params.detailVerts <> nil) and (params.detailVertsCount <> 0) then
begin
for i := 0 to params.detailVertsCount - 1 do
begin
h := params.detailVerts[i*3+1];
hmin := dtMin(hmin,h);
hmax := dtMax(hmax,h);
end;
end
else
begin
for i := 0 to params.vertCount - 1 do
begin
iv := @params.verts[i*3];
h := params.bmin[1] + iv[1] * params.ch;
hmin := dtMin(hmin,h);
hmax := dtMax(hmax,h);
end;
end;
hmin := hmin - params.walkableClimb;
hmax := hmax + params.walkableClimb;
dtVcopy(@bmin[0], @params.bmin[0]);
dtVcopy(@bmax[0], @params.bmax[0]);
bmin[1] := hmin;
bmax[1] := hmax;
for i := 0 to params.offMeshConCount - 1 do
begin
p0 := @params.offMeshConVerts[(i*2+0)*3];
p1 := @params.offMeshConVerts[(i*2+1)*3];
offMeshConClass[i*2+0] := classifyOffMeshPoint(p0, @bmin[0], @bmax[0]);
offMeshConClass[i*2+1] := classifyOffMeshPoint(p1, @bmin[0], @bmax[0]);
// Zero out off-mesh start positions which are not even potentially touching the mesh.
if (offMeshConClass[i*2+0] = $ff) then
begin
if (p0[1] < bmin[1]) or (p0[1] > bmax[1]) then
offMeshConClass[i*2+0] := 0;
end;
// Cound how many links should be allocated for off-mesh connections.
if (offMeshConClass[i*2+0] = $ff) then
Inc(offMeshConLinkCount);
if (offMeshConClass[i*2+1] = $ff) then
Inc(offMeshConLinkCount);
if (offMeshConClass[i*2+0] = $ff) then
Inc(storedOffMeshConCount);
end;
end;
// Off-mesh connectionss are stored as polygons, adjust values.
totPolyCount := params.polyCount + storedOffMeshConCount;
totVertCount := params.vertCount + storedOffMeshConCount*2;
// Find portal edges which are at tile borders.
edgeCount := 0;
portalCount := 0;
for i := 0 to params.polyCount - 1 do
begin
p := @params.polys[i*2*nvp];
for j := 0 to nvp - 1 do
begin
if (p[j] = MESH_NULL_IDX) then break;
Inc(edgeCount);
if (p[nvp+j] and $8000) <> 0 then
begin
dir := p[nvp+j] and $f;
if (dir <> $f) then
Inc(portalCount);
end;
end;
end;
maxLinkCount := edgeCount + portalCount*2 + offMeshConLinkCount*2;
// Find unique detail vertices.
uniqueDetailVertCount := 0;
detailTriCount := 0;
if (params.detailMeshes <> nil) then
begin
// Has detail mesh, count unique detail vertex count and use input detail tri count.
detailTriCount := params.detailTriCount;
for i := 0 to params.polyCount - 1 do
begin
p := @params.polys[i*nvp*2];
ndv := params.detailMeshes[i*4+1];
nv := 0;
for j := 0 to nvp - 1 do
begin
if (p[j] = MESH_NULL_IDX) then break;
Inc(nv);
end;
Dec(ndv, nv);
Inc(uniqueDetailVertCount, ndv);
end;
end
else
begin
// No input detail mesh, build detail mesh from nav polys.
uniqueDetailVertCount := 0; // No extra detail verts.
detailTriCount := 0;
for i := 0 to params.polyCount - 1 do
begin
p := @params.polys[i*nvp*2];
nv := 0;
for j := 0 to nvp - 1 do
begin
if (p[j] = MESH_NULL_IDX) then break;
Inc(nv);
end;
Inc(detailTriCount, nv-2);
end;
end;
// Calculate data size
headerSize := dtAlign4(sizeof(TdtMeshHeader));
vertsSize := dtAlign4(sizeof(Single)*3*totVertCount);
polysSize := dtAlign4(sizeof(TdtPoly)*totPolyCount);
linksSize := dtAlign4(sizeof(TdtLink)*maxLinkCount);
detailMeshesSize := dtAlign4(sizeof(TdtPolyDetail)*params.polyCount);
detailVertsSize := dtAlign4(sizeof(Single)*3*uniqueDetailVertCount);
detailTrisSize := dtAlign4(sizeof(Byte)*4*detailTriCount);
bvTreeSize := IfThen(params.buildBvTree, dtAlign4(sizeof(TdtBVNode)*params.polyCount*2), 0);
offMeshConsSize := dtAlign4(sizeof(TdtOffMeshConnection)*storedOffMeshConCount);
dataSize := headerSize + vertsSize + polysSize + linksSize +
detailMeshesSize + detailVertsSize + detailTrisSize +
bvTreeSize + offMeshConsSize;
GetMem(data, sizeof(Byte)*dataSize);
FillChar(data[0], dataSize, 0);
d := data;
header := PdtMeshHeader(d); Inc(d, headerSize);
navVerts := PSingle(d); Inc(d, vertsSize);
navPolys := PdtPoly(d); Inc(d, polysSize);
Inc(d, linksSize);
navDMeshes := PdtPolyDetail(d); Inc(d, detailMeshesSize);
navDVerts := PSingle(d); Inc(d, detailVertsSize);
navDTris := PByte(d); Inc(d, detailTrisSize);
navBvtree := PdtBVNode(d); Inc(d, bvTreeSize);
offMeshCons := PdtOffMeshConnection(d); Inc(d, offMeshConsSize);
// Store header
header.magic := DT_NAVMESH_MAGIC;
header.version := DT_NAVMESH_VERSION;
header.x := params.tileX;
header.y := params.tileY;
header.layer := params.tileLayer;
header.userId := params.userId;
header.polyCount := totPolyCount;
header.vertCount := totVertCount;
header.maxLinkCount := maxLinkCount;
dtVcopy(@header.bmin[0], @params.bmin[0]);
dtVcopy(@header.bmax[0], @params.bmax[0]);
header.detailMeshCount := params.polyCount;
header.detailVertCount := uniqueDetailVertCount;
header.detailTriCount := detailTriCount;
header.bvQuantFactor := 1.0 / params.cs;
header.offMeshBase := params.polyCount;
header.walkableHeight := params.walkableHeight;
header.walkableRadius := params.walkableRadius;
header.walkableClimb := params.walkableClimb;
header.offMeshConCount := storedOffMeshConCount;
header.bvNodeCount := IfThen(params.buildBvTree, params.polyCount*2, 0);
offMeshVertsBase := params.vertCount;
offMeshPolyBase := params.polyCount;
// Store vertices
// Mesh vertices
for i := 0 to params.vertCount - 1 do
begin
iv := @params.verts[i*3];
v := @navVerts[i*3];
v[0] := params.bmin[0] + iv[0] * params.cs;
v[1] := params.bmin[1] + iv[1] * params.ch;
v[2] := params.bmin[2] + iv[2] * params.cs;
end;
// Off-mesh link vertices.
n := 0;
for i := 0 to params.offMeshConCount - 1 do
begin
// Only store connections which start from this tile.
if (offMeshConClass[i*2+0] = $ff) then
begin
linkv := @params.offMeshConVerts[i*2*3];
v := @navVerts[(offMeshVertsBase + n*2)*3];
dtVcopy(@v[0], @linkv[0]);
dtVcopy(@v[3], @linkv[3]);
Inc(n);
end;
end;
// Store polygons
// Mesh polys
src := params.polys;
for i := 0 to params.polyCount - 1 do
begin
pp := @navPolys[i];
pp.vertCount := 0;
pp.flags := params.polyFlags[i];
pp.setArea(params.polyAreas[i]);
pp.setType(DT_POLYTYPE_GROUND);
for j := 0 to nvp - 1 do
begin
if (src[j] = MESH_NULL_IDX) then break;
pp.verts[j] := src[j];
if (src[nvp+j] and $8000) <> 0 then
begin
// Border or portal edge.
dir := src[nvp+j] and $f;
if (dir = $f) then // Border
pp.neis[j] := 0
else if (dir = 0) then // Portal x-
pp.neis[j] := DT_EXT_LINK or 4
else if (dir = 1) then // Portal z+
pp.neis[j] := DT_EXT_LINK or 2
else if (dir = 2) then // Portal x+
pp.neis[j] := DT_EXT_LINK or 0
else if (dir = 3) then // Portal z-
pp.neis[j] := DT_EXT_LINK or 6;
end
else
begin
// Normal connection
pp.neis[j] := src[nvp+j]+1;
end;
Inc(pp.vertCount);
end;
Inc(src, nvp*2);
end;
// Off-mesh connection vertices.
n := 0;
for i := 0 to params.offMeshConCount - 1 do
begin
// Only store connections which start from this tile.
if (offMeshConClass[i*2+0] = $ff) then
begin
pp := @navPolys[offMeshPolyBase+n];
pp.vertCount := 2;
pp.verts[0] := (offMeshVertsBase + n*2+0);
pp.verts[1] := (offMeshVertsBase + n*2+1);
pp.flags := params.offMeshConFlags[i];
pp.setArea(params.offMeshConAreas[i]);
pp.setType(DT_POLYTYPE_OFFMESH_CONNECTION);
Inc(n);
end;
end;
// Store detail meshes and vertices.
// The nav polygon vertices are stored as the first vertices on each mesh.
// We compress the mesh data by skipping them and using the navmesh coordinates.
if (params.detailMeshes <> nil) then
begin
vbase := 0;
for i := 0 to params.polyCount - 1 do
begin
dtl := @navDMeshes[i];
vb := params.detailMeshes[i*4+0];
ndv := params.detailMeshes[i*4+1];
nv := navPolys[i].vertCount;
dtl.vertBase := vbase;
dtl.vertCount := (ndv-nv);
dtl.triBase := params.detailMeshes[i*4+2];
dtl.triCount := params.detailMeshes[i*4+3];
// Copy vertices except the first 'nv' verts which are equal to nav poly verts.
if (ndv-nv) <> 0 then
begin
Move(params.detailVerts[(vb+nv)*3], navDVerts[vbase*3], sizeof(Single)*3*(ndv-nv));
Inc(vbase, (ndv-nv));
end;
end;
// Store triangles.
Move(params.detailTris[0], navDTris[0], sizeof(Byte)*4*params.detailTriCount);
end
else
begin
// Create dummy detail mesh by triangulating polys.
tbase := 0;
for i := 0 to params.polyCount - 1 do
begin
dtl := @navDMeshes[i];
nv := navPolys[i].vertCount;
dtl.vertBase := 0;
dtl.vertCount := 0;
dtl.triBase := tbase;
dtl.triCount := (nv-2);
// Triangulate polygon (local indices).
for j := 2 to nv - 1 do
begin
t := @navDTris[tbase*4];
t[0] := 0;
t[1] := (j-1);
t[2] := j;
// Bit for each edge that belongs to poly boundary.
t[3] := (1 shl 2);
if (j = 2) then t[3] := t[3] or (1 shl 0);
if (j = nv-1) then t[3] := t[3] or (1 shl 4);
Inc(tbase);
end;
end;
end;
// Store and create BVtree.
// TODO: take detail mesh into account! use byte per bbox extent?
if (params.buildBvTree) then
begin
createBVTree(params.verts, params.vertCount, params.polys, params.polyCount,
nvp, params.cs, params.ch, params.polyCount*2, navBvtree);
end;
// Store Off-Mesh connections.
n := 0;
for i := 0 to params.offMeshConCount - 1 do
begin
// Only store connections which start from this tile.
if (offMeshConClass[i*2+0] = $ff) then
begin
con := @offMeshCons[n];
con.poly := (offMeshPolyBase + n);
// Copy connection end-points.
endPts := @params.offMeshConVerts[i*2*3];
dtVcopy(@con.pos[0], @endPts[0]);
dtVcopy(@con.pos[3], @endPts[3]);
con.rad := params.offMeshConRad[i];
con.flags := IfThen(params.offMeshConDir[i] <> 0, DT_OFFMESH_CON_BIDIR, 0);
con.side := offMeshConClass[i*2+1];
if (params.offMeshConUserID <> nil) then
con.userId := params.offMeshConUserID[i];
Inc(n);
end;
end;
FreeMem(offMeshConClass);
outData^ := data;
outDataSize^ := dataSize;
Result := true;
end;
{function dtNavMeshHeaderSwapEndian(data: PByte; dataSize: Integer): Boolean;
var header: PdtMeshHeader; swappedMagic,swappedVersion: Integer;
begin
header := PdtMeshHeader(data);
swappedMagic := DT_NAVMESH_MAGIC;
swappedVersion := DT_NAVMESH_VERSION;
dtSwapEndian(PInteger(@swappedMagic));
dtSwapEndian(PInteger(@swappedVersion));
if ((header.magic <> DT_NAVMESH_MAGIC) or (header.version <> DT_NAVMESH_VERSION) and
(header.magic <> swappedMagic) or (header.version <> swappedVersion)) then
begin
Exit(false);
end;
dtSwapEndian(PInteger(@header.magic));
dtSwapEndian(PInteger(@header.version));
dtSwapEndian(PInteger(@header.x));
dtSwapEndian(PInteger(@header.y));
dtSwapEndian(PInteger(@header.layer));
dtSwapEndian(PCardinal(@header.userId));
dtSwapEndian(PInteger(@header.polyCount));
dtSwapEndian(PInteger(@header.vertCount));
dtSwapEndian(PInteger(@header.maxLinkCount));
dtSwapEndian(PInteger(@header.detailMeshCount));
dtSwapEndian(PInteger(@header.detailVertCount));
dtSwapEndian(PInteger(@header.detailTriCount));
dtSwapEndian(PInteger(@header.bvNodeCount));
dtSwapEndian(PInteger(@header.offMeshConCount));
dtSwapEndian(PInteger(@header.offMeshBase));
dtSwapEndian(PSingle(@&header.walkableHeight));
dtSwapEndian(PSingle(@header.walkableRadius));
dtSwapEndian(PSingle(@header.walkableClimb));
dtSwapEndian(PSingle(@header.bmin[0]));
dtSwapEndian(PSingle(@header.bmin[1]));
dtSwapEndian(PSingle(@header.bmin[2]));
dtSwapEndian(PSingle(@header.bmax[0]));
dtSwapEndian(PSingle(@header.bmax[1]));
dtSwapEndian(PSingle(@header.bmax[2]));
dtSwapEndian(PSingle(@header.bvQuantFactor));
// Freelist index and pointers are updated when tile is added, no need to swap.
Result := true;
end;}
/// @par
///
/// @warning This function assumes that the header is in the correct endianess already.
/// Call #dtNavMeshHeaderSwapEndian() first on the data if the data is expected to be in wrong endianess
/// to start with. Call #dtNavMeshHeaderSwapEndian() after the data has been swapped if converting from
/// native to foreign endianess.
{function dtNavMeshDataSwapEndian(data: PByte; dataSize: Integer): Boolean;
begin
// Make sure the data is in right format.
dtMeshHeader* header := (dtMeshHeader*)data;
if (header.magic != DT_NAVMESH_MAGIC)
return false;
if (header.version != DT_NAVMESH_VERSION)
return false;
// Patch header pointers.
const int headerSize := dtAlign4(sizeof(dtMeshHeader));
const int vertsSize := dtAlign4(sizeof(float)*3*header.vertCount);
const int polysSize := dtAlign4(sizeof(dtPoly)*header.polyCount);
const int linksSize := dtAlign4(sizeof(dtLink)*(header.maxLinkCount));
const int detailMeshesSize := dtAlign4(sizeof(dtPolyDetail)*header.detailMeshCount);
const int detailVertsSize := dtAlign4(sizeof(float)*3*header.detailVertCount);
const int detailTrisSize := dtAlign4(sizeof(unsigned char)*4*header.detailTriCount);
const int bvtreeSize := dtAlign4(sizeof(dtBVNode)*header.bvNodeCount);
const int offMeshLinksSize := dtAlign4(sizeof(dtOffMeshConnection)*header.offMeshConCount);
unsigned char* d := data + headerSize;
float* verts := (float*)d; d += vertsSize;
dtPoly* polys := (dtPoly*)d; d += polysSize;
/*dtLink* links := (dtLink*)d;*/ d += linksSize;
dtPolyDetail* detailMeshes := (dtPolyDetail*)d; d += detailMeshesSize;
float* detailVerts := (float*)d; d += detailVertsSize;
/*unsigned char* detailTris := (unsigned char*)d;*/ d += detailTrisSize;
dtBVNode* bvTree := (dtBVNode*)d; d += bvtreeSize;
dtOffMeshConnection* offMeshCons := (dtOffMeshConnection*)d; d += offMeshLinksSize;
// Vertices
for (int i := 0; i < header.vertCount*3; ++i)
begin
dtSwapEndian(&verts[i]);
end;
// Polys
for (int i := 0; i < header.polyCount; ++i)
begin
dtPoly* p := &polys[i];
// poly.firstLink is update when tile is added, no need to swap.
for (int j := 0; j < DT_VERTS_PER_POLYGON; ++j)
begin
dtSwapEndian(&p.verts[j]);
dtSwapEndian(&p.neis[j]);
end;
dtSwapEndian(&p.flags);
end;
// Links are rebuild when tile is added, no need to swap.
// Detail meshes
for (int i := 0; i < header.detailMeshCount; ++i)
begin
dtPolyDetail* pd := &detailMeshes[i];
dtSwapEndian(&pd.vertBase);
dtSwapEndian(&pd.triBase);
end;
// Detail verts
for (int i := 0; i < header.detailVertCount*3; ++i)
begin
dtSwapEndian(&detailVerts[i]);
end;
// BV-tree
for (int i := 0; i < header.bvNodeCount; ++i)
begin
dtBVNode* node := &bvTree[i];
for (int j := 0; j < 3; ++j)
begin
dtSwapEndian(&node.bmin[j]);
dtSwapEndian(&node.bmax[j]);
end;
dtSwapEndian(&node.i);
end;
// Off-mesh Connections.
for (int i := 0; i < header.offMeshConCount; ++i)
begin
dtOffMeshConnection* con := &offMeshCons[i];
for (int j := 0; j < 6; ++j)
dtSwapEndian(&con.pos[j]);
dtSwapEndian(&con.rad);
dtSwapEndian(&con.poly);
end;
Result := true;
end;}
end.
|
unit ncMWNex;
// =========================================================================
// kbmMW - An advanced and extendable middleware framework.
// by Components4Developers (http://www.components4developers.com)
//
// Service generated by kbmMW service wizard.
//
// INSTRUCTIONS FOR REGISTRATION/USAGE
// -----------------------------------
// Please update the uses clause of the datamodule/form the TkbmMWServer is placed on by adding
// kbmMWQueryService to it. Eg.
//
// uses ...,kbmMWServer,kbmMWQueryService;
//
// Somewhere in your application, make sure to register the serviceclass to the TkbmMWServer instance. Eg.
//
// var
// sd:TkbmMWCustomServiceDefinition;
// ..
// sd:=kbmMWServer1.RegisterService(yourserviceclassname,false);
//
// Set the last parameter to true if this is the default service.
//
{$I kbmMW.inc}
interface
uses
SysUtils, Variants, Windows, kbmMemTable, kbmMWStreamFormat,
kbmMWBinaryStreamFormat, DB, kbmMWCustomConnectionPool, Dialogs,
kbmMWCustomDataset, kbmMWNexusDB, Classes, kbmMWResolvers,
kbmMWSecurity, idTCPServer,
kbmMWGlobal,
kbmMWServer,
kbmMWQueryService, kbmMWX, ncClassesBase;
type
TmwNex = class(TkbmMWQueryService)
private
{ Private declarations }
function ObtemSenhaCli(const Args: Array of Variant): Variant;
function SalvaCredTempo(const Args: Array of variant): Variant;
function SalvaMovEst(const Args: Array of variant): Variant;
function SalvaDebito(const Args: Array of variant): Variant;
function SalvaLancExtra(const Args: Array of variant): Variant;
function SalvaDebTempo(const Args: Array of variant): Variant;
function SalvaImpressao(const Args: Array of variant): Variant;
function AbreCaixa(const Args: Array of variant): Variant;
function ObtemSitesBloqueados: Variant;
function ObtemPastaServ: Variant;
function SalvaLogAppUrl(const Args: Array of variant): Variant;
function SalvaStreamObj(const Args: Array of variant): Variant;
function ObtemStreamAvisos: Variant;
function ObtemStreamConfig: Variant;
function ObtemStreamListaObj(const Args: Array of variant): Variant;
function Login(const Args: Array of variant; aIP: String; aThreadID: Cardinal): Variant;
function LoginMaq(const Args: Array of variant): Variant;
function AlteraSessao(const Args: Array of variant): Variant;
function SalvaProcessos(const Args: Array of variant): Variant;
function ObtemPatrocinios(const Args: Array of variant): Variant;
function CapturaTelaMaq(const Args: Array of variant): Variant;
function SalvaTelaMaq(const Args: Array of variant): Variant;
function ObtemVersaoGuard: Variant;
protected
{ Private declarations }
function ProcessRequest(const Func:string; const ClientIdent:TkbmMWClientIdentity; const Args:array of Variant):Variant; override;
public
{ Public declarations }
{$IFNDEF CPP}class{$ENDIF} function GetPrefServiceName:string; override;
{$IFNDEF CPP}class{$ENDIF} function GetFlags:TkbmMWServiceFlags; override;
{$IFNDEF CPP}class{$ENDIF} function GetVersion:string; override;
end;
var
Servidor : TncServidorBase;
implementation
uses
ncServBase,
ncSessao,
ncCredTempo,
ncDebTempo,
ncImpressao,
ncLancExtra,
ncMovEst,
ncDebito, ncMWServer, ncDebug;
{$R *.dfm}
// Service definitions.
//---------------------
function TmwNex.AbreCaixa(const Args: array of variant): Variant;
var NovoCx: Integer;
begin
Result := VarArrayOf([Servidor.AbreCaixa(Args[0], NovoCx), NovoCx]);
end;
function TmwNex.AlteraSessao(const Args: array of variant): Variant;
var
S: TStream;
Sessao: TncSessao;
begin
S := TMemoryStream.Create;
try
kbmmwVariantToStream(Args[0], S);
S.Position := 0;
Sessao := TncSessao.Create(False);
try
Sessao.LeStream(S);
Servidor.AlteraSessao(Sessao);
finally
Sessao.Free;
end;
finally
S.Free;
end;
end;
function TmwNex.CapturaTelaMaq(const Args: array of variant): Variant;
var
S: TMemoryStream;
Erro: Integer;
V: Variant;
begin
S := TMemoryStream.Create;
try
Erro := Servidor.CapturaTelaMaq(Args[0]);
if Erro=0 then begin
V := kbmMWStreamToVariant(S);
Result := VarArrayOf([0, V]);
end else
Result := Erro;
finally
S.Free;
end;
end;
class function TmwNex.GetFlags: TkbmMWServiceFlags;
begin
end;
class function TmwNex.GetPrefServiceName:string;
begin
Result:='NexServ';
end;
class function TmwNex.GetVersion: string;
begin
Result := '1';
end;
function TmwNex.Login(const Args: array of variant; aIP: String; aThreadID: Cardinal): Variant;
var aHandle: Integer;
begin
Result := VarArrayOf([Servidor.Login(Args[0], Args[1], Args[2], Args[3], Args[4], Args[5], Args[6], aThreadID, 0, aIP, aHandle), aHandle]);
end;
function TmwNex.LoginMaq(const Args: array of variant): Variant;
var
S: TStream;
Sessao: TncSessao;
begin
S := TMemoryStream.Create;
try
kbmmwVariantToStream(Args[0], S);
S.Position := 0;
Sessao := TncSessao.Create(False);
try
Sessao.LeStream(S);
Result := Servidor.LoginMaq(Sessao);
finally
Sessao.Free;
end;
finally
S.Free;
end;
end;
function TmwNex.ObtemPastaServ: Variant;
var Pasta: String;
begin
Result := VarArrayOf([Servidor.ObtemPastaServ(Pasta), Pasta]);
end;
function TmwNex.ObtemPatrocinios(const Args: array of variant): Variant;
var SL: TStrings;
begin
SL := TStringList.Create;
try
Result := VarArrayOf([Servidor.ObtemPatrocinios(SL), SL.Text]);
finally
SL.Free;
end;
end;
function TmwNex.ObtemSenhaCli(const Args: array of Variant): Variant;
var Senha : String;
begin
Senha := '';
Result := VarArrayOf([Servidor.ObtemSenhaCli(Args[0], Senha), Senha]);
end;
function TmwNex.ObtemSitesBloqueados: Variant;
var S: String;
begin
S := '';
Result := VarArrayOf([Servidor.ObtemSitesBloqueados(S), S]);
end;
function TmwNex.ObtemStreamAvisos: Variant;
var
S: TStream;
Erro: Integer;
begin
S := TMemoryStream.Create;
try
Erro := Servidor.ObtemStreamAvisos(S);
if Erro=0 then
Result := VarArrayOf([0, kbmMWStreamToVariant(S)]) else
Result := Erro;
finally
S.Free;
end;
end;
function TmwNex.ObtemStreamConfig: Variant;
var
S: TStream;
Erro: Integer;
begin
S := TMemoryStream.Create;
try
Erro := Servidor.ObtemStreamConfig(S);
if Erro=0 then
Result := VarArrayOf([0, kbmMWStreamToVariant(S)]) else
Result := Erro;
finally
S.Free;
end;
end;
function TmwNex.ObtemStreamListaObj(const Args: array of variant): Variant;
var
S : TMemoryStream;
Erro : Integer;
begin
S := TMemoryStream.Create;
try
Erro := Servidor.ObtemStreamListaObj(Args[0], Args[1], S);
if Erro=0 then
Result := VarArrayOf([0, kbmMWStreamToVariant(S)]) else
Result := Erro;
finally
S.Free;
end;
end;
function TmwNex.ObtemVersaoGuard: Variant;
var Versao: Integer;
begin
Result := VarArrayOf([Servidor.ObtemVersaoGuard(Versao), Versao]);
end;
function TmwNex.ProcessRequest(const Func: string;
const ClientIdent: TkbmMWClientIdentity;
const Args: array of Variant): Variant;
var
C: Cardinal;
Cli: TncCliente;
Maq : Integer;
begin
if SameText(Func, 'KeepAlive') then begin
Result := 0;
Exit;
end;
DebugMsg('LOCK - ' + Func);
TncServidor(Servidor).Lock;
try
DebugMsg('LOCK - OK');
try
C := TidPeerThread(TkbmMWServerTransportInfo(RequestTransportStream.Info).Client).ThreadID;
Cli := Servidor.ObtemClientePorSocket(C);
except
on E: Exception do begin
Cli := nil;
DebugMsg('TmwNex.ProcessRequest - Exception: ' + E.Message);
end;
end;
if Cli<>nil then begin
HandleCliAtual := Cli.Handle;
Maq := Cli.Maquina;
UsernameAtual := Cli.UserName;
end else begin
HandleCliAtual := 0;
Maq := 0;
UsernameAtual := '';
end;
DebugMsg('TmwNex.ProcessRequest - ThreadID: ' + IntToStr(C) +
' - Handle: ' + IntToStr(HandleCliAtual) +
' - Maq: ' + IntToStr(Maq) + ' - IP: ' + ClientIdent.RemoteLocation);
if SameText(Func, 'ArqFundoEnviado') then begin
dmMWServer.mwFilePool.GarbageCollect;
Result := Servidor.ArqFundoEnviado(Args[0]);
end else
if SameText(Func, 'ObtemSenhaCli') then
Result := ObtemSenhaCli(Args)
else
if SameText(Func, 'SalvaSenhaCli') then
Result := Servidor.SalvaSenhaCli(Args[0], Args[1])
else
if SameText(Func, 'LimpaFundo') then
Result := Servidor.LimpaFundo(Args[0])
else
if SameText(Func, 'SalvaCredTempo') then
Result := SalvaCredTempo(Args[0])
else
if SameText(Func, 'SalvaMovEst') then
Result := SalvaMovEst(Args[0])
else
if SameText(Func, 'SalvaDebito') then
Result := SalvaDebito(Args[0])
else
if SameText(Func, 'SalvaLancExtra') then
Result := SalvaLancExtra(Args[0])
else
if SameText(Func, 'SalvaDebTempo') then
Result := SalvaDebTempo(Args[0])
else
if SameText(Func, 'SalvaImpressao') then
Result := SalvaImpressao(Args[0])
else
if SameText(Func, 'AbreCaixa') then
Result := AbreCaixa(Args)
else
if SameText(Func, 'FechaCaixa') then
Result := Servidor.FechaCaixa(Args[0], Args[1])
else
if SameText(Func, 'ReprocCaixa') then
Result := Servidor.ReprocCaixa(Args[0], Args[1])
else
if SameText(Func, 'CorrigeDataCaixa') then
Result := Servidor.CorrigeDataCaixa(Args[0], Args[1], Args[2], Args[3])
else
if SameText(Func, 'AjustaPontosFid') then
Result := Servidor.AjustaPontosFid(Args[0], Args[1], Args[2], Args[3], Args[4])
else
if SameText(Func, 'ObtemSitesBloqueados') then
Result := ObtemSitesBloqueados
else
if SameText(Func, 'SalvaLogAppUrl') then
Result := SalvaLogAppUrl(Args[0])
else
if SameText(Func, 'SalvaStreamObj') then
Result := SalvaStreamObj(Args)
else
if SameText(Func, 'ObtemStreamAvisos') then
Result := ObtemStreamAvisos
else
if SameText(Func, 'ObtemStreamConfig') then
Result := ObtemStreamConfig
else
if SameText(Func, 'ObtemStreamListaObj') then
Result := ObtemStreamListaObj(Args)
else
if SameText(Func, 'ApagaObj') then
Result := Servidor.ApagaObj(Args[0], Args[1], Args[2])
else
if SameText(Func, 'Login') then begin
Result := Login(Args, Copy(ClientIdent.RemoteLocation, 1, Pos(':', ClientIdent.RemoteLocation)-1), C);
end else
if SameText(Func, 'LoginMaq') then
Result := Self.LoginMaq(Args)
else
if SameText(Func, 'AlteraSessao') then
Result := AlteraSessao(Args)
else
if SameText(Func, 'CancelaTran') then
Result := Servidor.CancelaTran(Args[0], Args[1])
else
if SameText(Func, 'ObtemPastaServ') then
Result := ObtemPastaServ
else
if SameText(Func, 'ObtemProcessos') then
Result := Servidor.ObtemProcessos(Args[0], Args[1], Args[2])
else
if SameText(Func, 'FinalizaProcesso') then
Result := Servidor.FinalizaProcesso(Args[0], Args[1])
else
if SameText(Func, 'SalvaProcessos') then
Result := SalvaProcessos(Args)
else
if SameText(Func, 'ForceRefreshSessao') then
Result := Servidor.ForceRefreshSessao(Args[0])
else
if SameText(Func, 'SalvaLic') then
Result := Servidor.SalvaLic(Args[0])
else
if SameText(Func, 'ObtemPatrocinios') then
Result := ObtemPatrocinios(Args)
else
if SameText(Func, 'RefreshEspera') then
Result := Servidor.RefreshEspera
else
if SameText(Func, 'PermitirDownload') then
Result := Servidor.PermitirDownload(Args[0], Args[1])
else
if SameText(Func, 'AdicionaPassaporte') then
Result := Servidor.AdicionaPassaporte(Args[0], Args[1])
else
if SameText(Func, 'RegistraPaginasImpressas') then
Result := Servidor.RegistraPaginasImpressas(Args[0], Args[1], ARgs[2], Args[3])
else
if SameText(Func, 'PararTempoMaq') then
Result := Servidor.PararTempoMaq(Args[0], Args[1])
else
if SameText(Func, 'TransferirMaq') then
Result := Servidor.TransferirMaq(Args[0], Args[1])
else
if SameText(Func, 'ModoManutencao') then
Result := Servidor.ModoManutencao(Args[0], Args[1], Args[2], Args[3])
else
if SameText(Func, 'SuporteRem') then
Result := Servidor.SuporteRem(Args[0], Args[1])
else
if SameText(Func, 'LogoutMaq') then
Result := Servidor.LogoutMaq(Args[0])
else
if SameText(Func, 'PreLogoutMaq') then
Result := Servidor.PreLogoutMaq(Args[0])
else
if SameText(Func, 'CancLogoutMaq') then
Result := Servidor.CancLogoutMaq(Args[0])
else
if SameText(Func, 'ObtemVersaoGuard') then
Result := ObtemVersaoGuard
else
if SameText(Func, 'CapturaTelaMaq') then
Result := CapturaTelaMaq(Args)
else
if SameText(Func, 'SalvaTelaMaq') then
Result := SalvaTelaMaq(Args)
else
if SameText(Func, 'RefreshPrecos') then
Result := Servidor.RefreshPrecos
else
if SameText(Func, 'ShutdownMaq') then
Result := Servidor.ShutdownMaq(Args[0], Args[1])
else
if SameText(Func, 'EnviarMsg') then
Result := Servidor.EnviarMsg(Args[0], Args[1], Args[2])
else
Result:= inherited ProcessRequest(Func, ClientIdent, Args);
finally
DebugMsg('UNLOCK - ' + Func);
TncServidor(Servidor).Unlock;
end;
end;
function TmwNex.SalvaCredTempo(const Args: array of variant): Variant;
var
CT: TncCredTempo;
S: TMemoryStream;
begin
CT := TncCredTempo.Create;
try
S := TMemoryStream.Create;
try
kbmMWVariantToStream(Args[0], S);
CT.LoadFromStream(S);
Result := Servidor.SalvaCredTempo(CT);
finally
S.Free;
end;
finally
CT.Free;
end;
end;
function TmwNex.SalvaDebito(const Args: array of variant): Variant;
var
D: TncDebito;
S: TMemoryStream;
begin
D := TncDebito.Create;
try
S := TMemoryStream.Create;
try
kbmMWVariantToStream(Args[0], S);
D.LeStream(S);
Result := Servidor.SalvaDebito(D);
finally
S.Free;
end;
finally
D.Free;
end;
end;
function TmwNex.SalvaDebTempo(const Args: array of variant): Variant;
var
D: TncDebTempo;
S: TMemoryStream;
begin
D := TncDebTempo.Create;
try
S := TMemoryStream.Create;
try
kbmMWVariantToStream(Args[0], S);
D.LeStream(S);
Result := Servidor.SalvaDebTempo(D);
finally
S.Free;
end;
finally
D.Free;
end;
end;
function TmwNex.SalvaImpressao(const Args: array of variant): Variant;
var
I: TncImpressao;
S: TMemoryStream;
begin
I := TncImpressao.Create;
try
S := TMemoryStream.Create;
try
kbmMWVariantToStream(Args[0], S);
I.LoadFromStream(S);
Result := Servidor.SalvaImpressao(I);
finally
S.Free;
end;
finally
I.Free;
end;
end;
function TmwNex.SalvaLancExtra(const Args: array of variant): Variant;
var
LE: TncLancExtra;
S: TMemoryStream;
begin
LE := TncLancExtra.Create;
try
S := TMemoryStream.Create;
try
kbmMWVariantToStream(Args[0], S);
LE.LeStream(S);
Result := Servidor.SalvaLancExtra(LE);
finally
S.Free;
end;
finally
LE.Free;
end;
end;
function TmwNex.SalvaLogAppUrl(const Args: array of variant): Variant;
var S: TStream;
begin
S := TMemoryStream.Create;
try
kbmMWVariantToStream(Args[0], S);
S.Position := 0;
Result := Servidor.SalvaLogAppUrl(S);
finally
S.Free;
end;
end;
function TmwNex.SalvaMovEst(const Args: array of variant): Variant;
var
ME: TncMovEst;
S: TMemoryStream;
begin
ME := TncMovEst.Create;
try
S := TMemoryStream.Create;
try
kbmMWVariantToStream(Args[0], S);
ME.LeStream(S);
Result := Servidor.SalvaMovEst(ME);
finally
S.Free;
end;
finally
ME.Free;
end;
end;
function TmwNex.SalvaProcessos(const Args: array of variant): Variant;
var SL: TStrings;
begin
SL := TStringList.Create;
try
SL.Text := Args[2];
Result := Servidor.SalvaProcessos(Args[0], Args[1], SL);
finally
SL.Free;
end;
end;
function TmwNex.SalvaStreamObj(const Args: array of variant): Variant;
var S: TMemoryStream;
begin
S := TMemoryStream.Create;
try
kbmMWVariantToStream(Args[1], S);
S.Position := 0;
Result := Servidor.SalvaStreamObj(Args[0], S);
finally
S.Free;
end;
end;
function TmwNex.SalvaTelaMaq(const Args: array of variant): Variant;
var
S : TMemoryStream;
Maq : Byte;
begin
S := TMemoryStream.Create;
try
kbmMWVariantToStream(Args[1], S);
S.Position := 0;
Result := Servidor.SalvaTelaMaq(Args[0], S);
finally
S.Free;
end;
end;
end.
|
unit Test.RemoteServer;
interface
uses Windows, TestFrameWork, GMGlobals, GMConst, StdResponce, ConnParamsStorage, ClientResponce;
type
TRemoteServerTest = class(TTestCase)
private
processor: TClientResponce;
protected
resp: IXMLGMIOResponceType;
procedure SetUp; override;
procedure TearDown; override;
published
procedure Structure();
end;
implementation
{ TRemoteServerTest }
procedure TRemoteServerTest.SetUp;
begin
inherited;
processor := TClientResponce.Create(nil);
end;
procedure TRemoteServerTest.Structure;
begin
resp := processor.DBStructure();
Check(resp <> nil, 'nil');
// resp.OwnerDocument.SaveToFile('c:\remote.xml');
end;
procedure TRemoteServerTest.TearDown;
begin
resp := nil;
processor.Free();
inherited;
end;
initialization
RegisterTest('GMIOPSrv/RemoteServer', TRemoteServerTest.Suite);
end.
|
unit LittleTest26;
{ AFS August 2003
This unit compiles but is not semantically meaningfull
it is test cases for the code formatting utility
Test the "packed" keyword }
interface
type
TFooRecord = packed record
Soy: integer;
Monkey: integer;
Shatner: integer;
McFlurry: integer;
end;
type aPackedArray = Packed array[0..4] of integer;
type aPackedClass = Packed class
Soy: integer;
Monkey: integer;
end;
const
MyFooRecord: TFooRecord = (
Soy: 0;
Monkey: 0;
Shatner: 0;
);
implementation
end.
|
unit rEventHooks;
interface
uses
Classes, ORNet;
function GetPatientChangeGUIDs: string;
function GetOrderAcceptGUIDs(DisplayGroup: integer): string;
function GetAllActiveCOMObjects: TStrings;
function GetCOMObjectDetails(IEN: integer): string;
implementation
function GetPatientChangeGUIDs: string;
begin
Result := sCallV('ORWCOM PTOBJ', []);
end;
function GetOrderAcceptGUIDs(DisplayGroup: integer): string;
begin
Result := sCallV('ORWCOM ORDEROBJ', [DisplayGroup]);
end;
function GetAllActiveCOMObjects: TStrings;
begin
CallV('ORWCOM GETOBJS', []);
Result := RPCBrokerV.Results;
end;
function GetCOMObjectDetails(IEN: integer): string;
begin
Result := sCallV('ORWCOM DETAILS', [IEN]);
end;
end.
|
// Logger Demo
//
// Description: The ApacheOnLogger handler gets called for every request
// made on the webServer. You can use this handler to log
// Server Activity. In this example a simple ap_log_error call is
// made. Don't forget to return 'AP_OK' so that
// other handlers after you will continue executing.
unit Logger_u;
interface
uses
SysUtils, Classes, HTTPApp, HTTPD, ApacheApp;
type
TWebModule1 = class(TWebModule)
private
{ Private declarations }
public
{ Public declarations }
end;
var
WebModule1: TWebModule1;
implementation
uses WebReq;
{$IFDEF LINUX}{$R *.xfm}{$ENDIF}
{$IFDEF MSWINDOWS} {$R *.dfm}{$ENDIF}
function Apache_OnLogger(Req: Prequest_rec): integer;
var
Msg : String;
begin
// change the flags as needed
// this message will written to the error log
// For EVERY request, when this module is loaded
Msg := 'The Logger Says: Request from IP=' + Req.connection.remote_ip +
' Content-Type: ' + Req.content_type;
ap_log_error(Req.server.error_fname , APLOG_INFO, APLOG_NOTICE, Req.server,
PChar(Msg));
result := AP_OK;
end;
initialization
//WebRequestHandler.WebModuleClass := TWebModule1;
ApacheOnLogger := Apache_OnLogger;
end. |
{
AD.A.P.T. Library
Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved
Original Source Location: https://github.com/LaKraven/ADAPT
Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md
}
unit ADAPT.Math.Averagers.Intf;
{$I ADAPT.inc}
interface
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes,
{$ELSE}
Classes,
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
ADAPT, ADAPT.Intf,
ADAPT.Collections.Intf;
{$I ADAPT_RTTI.inc}
type
/// <summary><c>An Averagering Algorithm for a Series of Values of the given Type.</c></summary>
IADAverager<T> = interface(IADInterface)
// Management Methods
/// <returns><c>The Calculated Average for the given Series.</c></returns>
function CalculateAverage(const ASeries: IADListReader<T>): T; overload;
/// <returns><c>The Calculated Average for the given Series.</c></returns>
function CalculateAverage(const ASeries: Array of T; const ASortedState: TADSortedState): T; overload;
end;
/// <summary><c>An Object containing an Averager.</c></summary>
IADAveragable<T> = interface(IADInterface)
['{B3B4B967-F6EB-42CC-BD81-A39FA71A5209}']
// Getters
/// <returns>The Averager used by this Object.</c></returns>
function GetAverager: IADAverager<T>;
// Setters
/// <summary><c>Defines the Averager to be used by this Object.</c></summary>
procedure SetAverager(const AAverager: IADAverager<T>);
// Properties
/// <summary><c>Defines the Averager to be used by this Object.</c></summary>
/// <returns>The Averager used by this Object.</c></returns>
property Averager: IADAverager<T> read GetAverager write SetAverager;
end;
implementation
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit InetExpertsTemplateProperties;
interface
const
sIsapiSource = 'IsapiSource';
sDBXTerminateThreads = 'DBXTerminateThreads';
sSetWebModuleClass = 'SetWebModuleClass';
sCGISource = 'CGISource';
sIndyConsoleProjectSource = 'IndyConsoleProjectSource';
sIndyFormConsoleSource = 'IndyFormConsoleSource';
sIndyFormConsoleIntf = 'IndyFormConsoleIntf';
sIndyFormConsoleDFMSource = 'IndyFormConsoleDFMSource';
sIndyFormProjectSource = 'IndyFormProjectSource';
sWebModuleSource = 'WebModuleSource';
sWebModuleIntf = 'WebModuleIntf';
sWebModuleDFMSource = 'WebModuleDFMSource';
sHTTPPort = 'HTTPPort';
sHTTPS = 'HTTPS';
sTrue = 'TRUE';
sFalse = 'FALSE';
sKeyFilePassword = 'KeyFilePassword';
sRootCertFile = 'RootCertFile';
sCertFile = 'CertFile';
sKeyFile = 'KeyFile';
implementation
end.
|
unit JSONHelpersTests;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, TestFramework, fpjson;
type
{ TIndexOfTestCase }
TIndexOfTestCase = class(TTestCase)
private
FArray: TJSONArray;
procedure CreateArray(const Items: array of const);
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure SearchNull;
procedure SearchPrimitiveTypes;
procedure SearchJSONData;
procedure SearchObjectItems;
end;
implementation
uses
LuiJSONHelpers, variants;
{ TIndexOfTestCase }
procedure TIndexOfTestCase.CreateArray(const Items: array of const);
begin
FArray.Free;
FArray := TJSONArray.Create(Items);
end;
procedure TIndexOfTestCase.SetUp;
begin
end;
procedure TIndexOfTestCase.TearDown;
begin
FreeAndNil(FArray);
inherited TearDown;
end;
procedure TIndexOfTestCase.SearchNull;
var
V: Variant;
begin
CreateArray([1, nil, 2, nil]);
CheckEquals(1, FArray.IndexOf(Null));
V := nil;
CheckEquals(1, FArray.IndexOf(V));
CreateArray([0, '', 1]);
CheckEquals(-1, FArray.IndexOf(Null));
V := nil;
CheckEquals(-1, FArray.IndexOf(nil));
end;
procedure TIndexOfTestCase.SearchPrimitiveTypes;
begin
CreateArray([1, TJSONIntegerNumber.Create(1),'x',TJSONIntegerNumber.Create(2), 2, '', true, '2']);
CheckEquals(0, FArray.IndexOf(1));
CheckEquals(2, FArray.IndexOf('x'));
CheckEquals(3, FArray.IndexOf(2));
CheckEquals(5, FArray.IndexOf(''));
CheckEquals(6, FArray.IndexOf(True));
CheckEquals(7, FArray.IndexOf('2'));
end;
procedure TIndexOfTestCase.SearchJSONData;
var
NumData, OtherNumData: TJSONNumber;
ObjData: TJSONObject;
begin
//ensure no conflicts with TJSONArray method
NumData := TJSONIntegerNumber.Create(1);
OtherNumData := TJSONIntegerNumber.Create(1);
ObjData := TJSONObject.Create(['x', 1]);
CreateArray([1, 2, NumData, '', ObjData, '2']);
CheckEquals(-1, FArray.IndexOf(OtherNumData));
CheckEquals(2, FArray.IndexOf(NumData));
CheckEquals(4, FArray.IndexOf(ObjData));
OtherNumData.Destroy;
end;
procedure TIndexOfTestCase.SearchObjectItems;
begin
CreateArray([
TJSONObject.Create(['prop', 1]),
TJSONArray.Create(['prop']),
TJSONIntegerNumber.Create(2),
'prop',
2,
TJSONObject.Create(['x', 1, 'prop', 2]),
TJSONObject.Create(['prop', 3])
]);
CheckEquals(0, FArray.IndexOf(['prop', 1]));
CheckEquals(5, FArray.IndexOf(['prop', 2]));
CheckEquals(-1, FArray.IndexOf(['unknownprop', 2]));
CheckEquals(-1, FArray.IndexOf(['prop', '2']));
end;
initialization
ProjectRegisterTests('JSONHelpers', [TIndexOfTestCase.Suite]);
end.
|
{ ****************************************************************************** }
{ * machine Learn, writen by QQ 600585@qq.com * }
{ * https://zpascal.net * }
{ * https://github.com/PassByYou888/zAI * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/PascalString * }
{ * https://github.com/PassByYou888/zRasterization * }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zChinese * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/FFMPEG-Header * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/InfiniteIoT * }
{ * https://github.com/PassByYou888/FastMD5 * }
{ ****************************************************************************** }
unit Learn;
{$INCLUDE zDefine.inc}
interface
uses Math, CoreClasses, UnicodeMixedLib, PascalStrings, KDTree, LearnTypes, MemoryStream64, DataFrameEngine, ListEngine,
Geometry2DUnit, Geometry3DUnit;
{$REGION 'Class'}
type
TLearn = class;
TLearnState_Call = procedure(const LSender: TLearn; const State: Boolean);
TLearnState_Method = procedure(const LSender: TLearn; const State: Boolean) of object;
{$IFDEF FPC}
TLearnState_Proc = procedure(const LSender: TLearn; const State: Boolean) is nested;
{$ELSE FPC}
TLearnState_Proc = reference to procedure(const LSender: TLearn; const State: Boolean);
{$ENDIF FPC}
TLearnMemory = record
m_in, m_out: TLVec;
token: TPascalString;
end;
PLearnMemory = ^TLearnMemory;
TLearn = class(TCoreClassInterfacedObject)
public type
TLearnKDT = record
K: TKDTree;
end;
PLearnKDT = ^TLearnKDT;
THideLayerDepth = (hld0, hld1, hld2);
private
FRandomNumber: Boolean;
FInSize, FOutSize: TLInt;
FMemorySource: TCoreClassList;
FTokenCache: THashList;
FKDToken: TKDTree;
FLearnType: TLearnType;
FLearnData: Pointer;
FClassifier: Boolean;
FHideLayerDepth: THideLayerDepth;
FLastTrainMaxInValue, FLastTrainMaxOutValue: TLFloat;
FInfo: TPascalString;
FIsTraining: Boolean;
FTrainingThreadRuning: Boolean;
FUserData: Pointer;
FUserObject: TCoreClassObject;
procedure KDInput(const IndexFor: NativeInt; var Source: TKDTree_Source; const Data: Pointer);
procedure TokenInput(const IndexFor: NativeInt; var Source: TKDTree_Source; const Data: Pointer);
procedure FreeLearnData;
procedure CreateLearnData(const isTrainingTime: Boolean);
public
{ regression style }
class function CreateRegression(const lt: TLearnType; const InDataLen, OutDataLen: TLInt): TLearn;
{ regression style of level 1 }
class function CreateRegression1(const lt: TLearnType; const InDataLen, OutDataLen: TLInt): TLearn;
{ regression style of level 2 }
class function CreateRegression2(const lt: TLearnType; const InDataLen, OutDataLen: TLInt): TLearn;
{ classifier style }
class function CreateClassifier(const lt: TLearnType; const InDataLen: TLInt): TLearn;
{ classifier style of level 1 }
class function CreateClassifier1(const lt: TLearnType; const InDataLen: TLInt): TLearn;
{ classifier style of level 2 }
class function CreateClassifier2(const lt: TLearnType; const InDataLen: TLInt): TLearn;
constructor Create; virtual;
destructor Destroy; override;
{ * random number * }
property RandomNumber: Boolean read FRandomNumber write FRandomNumber;
{ * clear * }
procedure Clear;
{ * parameter * }
function Count: TLInt;
property InSize: TLInt read FInSize;
property OutSize: TLInt read FOutSize;
property LearnType: TLearnType read FLearnType;
property Info: TPascalString read FInfo;
property TrainingThreadRuning: Boolean read FTrainingThreadRuning;
function GetMemorySource(const index: TLInt): PLearnMemory;
property MemorySource[const index: TLInt]: PLearnMemory read GetMemorySource; default;
property LastTrainMaxInValue: TLFloat read FLastTrainMaxInValue;
property LastTrainMaxOutValue: TLFloat read FLastTrainMaxOutValue;
{ * user parameter * }
property UserData: Pointer read FUserData write FUserData;
property UserObject: TCoreClassObject read FUserObject write FUserObject;
{ * sampler * }
function AddMemory(const f_In, f_Out: TLVec; f_token: TPascalString): PLearnMemory; overload;
function AddMemory(const f_In: TLVec; f_token: TPascalString): PLearnMemory; overload;
function AddMemory(const f_In, f_Out: TLVec): PLearnMemory; overload;
function AddMemory(const s_In, s_Out: TPascalString): PLearnMemory; overload;
function AddMemory(const s_In, s_Out, s_token: TPascalString): PLearnMemory; overload;
function AddMemory(const s: TPascalString): PLearnMemory; overload;
procedure AddSampler(const f_In, f_Out: TLVec); overload;
procedure AddSampler(const s_In, s_Out: TPascalString); overload;
procedure AddSampler(const s: TPascalString); overload;
procedure AddMatrix(const m_in: TLMatrix; const f_Out: TLVec); overload;
procedure AddMatrix(const m_in: TLMatrix; const f_Out: TLVec; const f_token: TPascalString); overload;
{ * kdtree * }
procedure AddKDTree(kd: TKDTreeDataList);
{ * normal Training * }
function Training(const TrainDepth: TLInt): Boolean; overload;
function Training: Boolean; overload;
{ * Training with thread * }
procedure Training_MT; overload;
procedure Training_MT(const TrainDepth: TLInt); overload;
procedure TrainingC(const TrainDepth: TLInt; const OnResult: TLearnState_Call);
procedure TrainingM(const TrainDepth: TLInt; const OnResult: TLearnState_Method);
procedure TrainingP(const TrainDepth: TLInt; const OnResult: TLearnState_Proc);
{ wait thread }
procedure WaitTraining;
{ token }
function SearchToken(const v: TLVec): TPascalString;
function SearchOutVecToken(const v: TLVec): TPascalString;
function FindTokenIndex(const token_: TPascalString): Integer;
function FindTokenData(const token_: TPascalString): PLearnMemory;
{ data input/output }
function Process(const p_in, p_out: PLVec): Boolean; overload;
function Process(const ProcessIn: PLVec): TPascalString; overload;
function Process(const ProcessIn: TLVec): TPascalString; overload;
function Process(const ProcessIn: TPascalString): TPascalString; overload;
function ProcessMatrix(const p_in: PLMatrix; const p_out: PLVec): Boolean; overload;
function ProcessToken(const ProcessIn: PLVec): TPascalString; overload;
function ProcessToken(const ProcessIn: TLVec): TPascalString; overload;
{ result max value }
function ProcessMax(const ProcessIn: TLVec): TLFloat; overload;
function ProcessMax(const ProcessIn: TLMatrix): TLFloat; overload;
function ProcessMaxToken(const ProcessIn: TLVec): TPascalString; overload;
function ProcessMaxToken(const ProcessIn: TLMatrix): TPascalString; overload;
{ result max index }
function ProcessMaxIndex(const ProcessIn: TLVec): TLInt; overload;
function ProcessMaxIndex(const ProcessIn: TLMatrix): TLInt; overload;
function ProcessMaxIndexToken(const ProcessIn: TLVec): TPascalString; overload;
function ProcessMaxIndexToken(const ProcessIn: TLMatrix): TPascalString; overload;
function ProcessMaxIndexCandidate(const ProcessIn: TLVec): TLIVec; overload;
function ProcessMaxIndexCandidate(const ProcessIn: TLMatrix): TLIVec; overload;
{ result min value }
function ProcessMin(const ProcessIn: TLVec): TLFloat; overload;
function ProcessMin(const ProcessIn: TLMatrix): TLFloat; overload;
function ProcessMinToken(const ProcessIn: TLVec): TPascalString; overload;
function ProcessMinToken(const ProcessIn: TLMatrix): TPascalString; overload;
{ result min index }
function ProcessMinIndex(const ProcessIn: TLVec): TLInt; overload;
function ProcessMinIndex(const ProcessIn: TLMatrix): TLInt; overload;
function ProcessMinIndexToken(const ProcessIn: TLVec): TPascalString; overload;
function ProcessMinIndexToken(const ProcessIn: TLMatrix): TPascalString; overload;
function ProcessMinIndexCandidate(const ProcessIn: TLVec): TLIVec; overload;
function ProcessMinIndexCandidate(const ProcessIn: TLMatrix): TLIVec; overload;
{ result first value }
function ProcessFV(const ProcessIn: TLVec): TLFloat; overload;
function ProcessFV(const ProcessIn: TLMatrix): TLFloat; overload;
function ProcessFV(const ProcessIn: TPascalString): TLFloat; overload;
{ result last value }
function ProcessLV(const ProcessIn: TLVec): TLFloat; overload;
function ProcessLV(const ProcessIn: TLMatrix): TLFloat; overload;
function ProcessLV(const ProcessIn: TPascalString): TLFloat; overload;
{ search with Pearson }
function SearchMemoryPearson(const ProcessIn: TLVec): TLInt; overload;
procedure SearchMemoryPearson(const ProcessIn: TLVec; out List: TLIVec); overload;
{ search with Spearman }
function SearchMemorySpearman(const ProcessIn: TLVec): TLInt; overload;
procedure SearchMemorySpearman(const ProcessIn: TLVec; out List: TLIVec); overload;
{ search with euclidean metric:K }
function SearchMemoryDistance(const ProcessIn: TLVec): TLInt; overload;
procedure SearchMemoryDistance(const ProcessIn: TLVec; out List: TLIVec); overload;
{ build input Vector to KDTree }
function BuildKDTree: TKDTree;
{ * fast binary store * }
procedure SaveToDF(df: TDataFrameEngine);
procedure LoadFromDF(df: TDataFrameEngine);
{ store support }
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: TPascalString);
procedure LoadFromFile(FileName: TPascalString);
{$IFNDEF FPC}
{ * json store support * }
procedure SaveToJsonStream(stream: TCoreClassStream);
procedure LoadFromJsonStream(stream: TCoreClassStream);
procedure SaveToJsonFile(FileName: TPascalString);
procedure LoadFromJsonFile(FileName: TPascalString);
{$ENDIF FPC}
end;
TLearnRandom = class(TMT19937Random)
public
property RandReal: Double read RandD;
end;
{$ENDREGION 'Class'}
{$REGION 'LearnAPI'}
procedure LAdd(var f: TLFloat; const Value: TLFloat);
procedure LSub(var f: TLFloat; const Value: TLFloat);
procedure LMul(var f: TLFloat; const Value: TLFloat);
procedure LDiv(var f: TLFloat; const Value: TLFloat);
function LSafeDivF(const s, d: TLFloat): TLFloat;
procedure LSetVec(var v: TLVec; const VDef: TLFloat); overload;
procedure LSetVec(var v: TLIVec; const VDef: TLInt); overload;
procedure LSetVec(var v: TLBVec; const VDef: Boolean); overload;
procedure LSetMatrix(var M: TLMatrix; const VDef: TLFloat); overload;
procedure LSetMatrix(var M: TLIMatrix; const VDef: TLInt); overload;
procedure LSetMatrix(var M: TLBMatrix; const VDef: Boolean); overload;
function LVecCopy(const v: TLVec): TLVec; overload;
function LVecCopy(const v: TLVec; const index, Count: TLInt): TLVec; overload;
function LVecCopy(const v: TLIVec): TLIVec; overload;
function LVecCopy(const v: TLIVec; const index, Count: TLInt): TLIVec; overload;
function LVecCopy(const v: TLBVec): TLBVec; overload;
function LVecCopy(const v: TLBVec; const index, Count: TLInt): TLBVec; overload;
function LMatrixCopy(const v: TLMatrix): TLMatrix; overload;
function LMatrixCopy(const v: TLIMatrix): TLIMatrix; overload;
function LMatrixCopy(const v: TLBMatrix): TLBMatrix; overload;
function LVec(): TLVec; overload;
function LVec(const veclen: TLInt; const VDef: TLFloat): TLVec; overload;
function LVec(const veclen: TLInt): TLVec; overload;
function LVec(const v: TLVec): TPascalString; overload;
function LVec(const M: TLMatrix; const veclen: TLInt): TLVec; overload;
function LVec(const M: TLMatrix): TLVec; overload;
function LVec(const s: TPascalString): TLVec; overload;
function LVec(const s: TPascalString; const veclen: TLInt): TLVec; overload;
function LVec(const v: TLVec; const ShortFloat: Boolean): TPascalString; overload;
function LVec(const M: TLBMatrix; const veclen: TLInt): TLBVec; overload;
function LVec(const M: TLBMatrix): TLBVec; overload;
function LVec(const M: TLIMatrix; const veclen: TLInt): TLIVec; overload;
function LVec(const M: TLIMatrix): TLIVec; overload;
function ExpressionToLVec(const s: TPascalString; const_vl: THashVariantList): TLVec; overload;
function ExpressionToLVec(const s: TPascalString): TLVec; overload;
function ExpLVec(const s: TPascalString; const_vl: THashVariantList): TLVec; overload;
function ExpLVec(const s: TPascalString): TLVec; overload;
function ExpressionToLIVec(const s: TPascalString; const_vl: THashVariantList): TLIVec; overload;
function ExpressionToLIVec(const s: TPascalString): TLIVec; overload;
function ExpLIVec(const s: TPascalString; const_vl: THashVariantList): TLIVec; overload;
function ExpLIVec(const s: TPascalString): TLIVec; overload;
function LSpearmanVec(const M: TLMatrix; const veclen: TLInt): TLVec;
function LAbsMaxVec(const v: TLVec): TLFloat;
function LMaxVec(const v: TLVec): TLFloat; overload;
function LMaxVec(const v: TLIVec): TLInt; overload;
function LMaxVec(const v: TLMatrix): TLFloat; overload;
function LMaxVec(const v: TLIMatrix): TLInt; overload;
function LMinVec(const v: TLVec): TLFloat; overload;
function LMinVec(const v: TLIVec): TLInt; overload;
function LMinVec(const v: TLMatrix): TLFloat; overload;
function LMinVec(const v: TLIMatrix): TLInt; overload;
function LMaxVecIndex(const v: TLVec): TLInt;
function LMinVecIndex(const v: TLVec): TLInt;
function LDistance(const v1, v2: TLVec): TLFloat;
function LHamming(const v1, v2: TLVec): TLInt; overload;
function LHamming(const v1, v2: TLIVec): TLInt; overload;
procedure LClampF(var v: TLFloat; const min_, max_: TLFloat); overload;
procedure LClampI(var v: TLInt; const min_, max_: TLInt); overload;
function LClamp(const v: TLFloat; const min_, max_: TLFloat): TLFloat; overload;
function LClamp(const v: TLInt; const min_, max_: TLInt): TLInt; overload;
function LComplex(X, Y: TLFloat): TLComplex; overload;
function LComplex(f: TLFloat): TLComplex; overload;
{ * sampler support * }
procedure LZoomMatrix(var Source, dest: TLMatrix; const DestWidth, DestHeight: TLInt); overload;
procedure LZoomMatrix(var Source, dest: TLIMatrix; const DestWidth, DestHeight: TLInt); overload;
procedure LZoomMatrix(var Source, dest: TLBMatrix; const DestWidth, DestHeight: TLInt); overload;
{ matrix as stream }
procedure LSaveMatrix(var Source: TLMatrix; dest: TCoreClassStream); overload;
procedure LLoadMatrix(Source: TCoreClassStream; var dest: TLMatrix); overload;
procedure LSaveMatrix(var Source: TLIMatrix; dest: TCoreClassStream); overload;
procedure LLoadMatrix(Source: TCoreClassStream; var dest: TLIMatrix); overload;
procedure LSaveMatrix(var Source: TLBMatrix; dest: TCoreClassStream); overload;
procedure LLoadMatrix(Source: TCoreClassStream; var dest: TLBMatrix); overload;
{ * linear discriminant analysis support * }
function LDA(const M: TLMatrix; const cv: TLVec; const Nclass: TLInt; var sInfo: TPascalString; var output: TLMatrix): Boolean; overload;
function LDA(const M: TLMatrix; const cv: TLVec; const Nclass: TLInt; var sInfo: TPascalString; var output: TLVec): Boolean; overload;
procedure FisherLDAN(const xy: TLMatrix; NPoints: TLInt; NVars: TLInt; NClasses: TLInt; var Info: TLInt; var w: TLMatrix);
procedure FisherLDA(const xy: TLMatrix; NPoints: TLInt; NVars: TLInt; NClasses: TLInt; var Info: TLInt; var w: TLVec);
{ * principal component analysis support * }
(*
return code:
* -4, if SVD subroutine haven't converged
* -1, if wrong parameters has been passed (NPoints<0, NVars<1)
* 1, if task is solved
*)
function PCA(const buff: TLMatrix; const NPoints, NVars: TLInt; var v: TLVec; var M: TLMatrix): TLInt; overload;
function PCA(const buff: TLMatrix; const NPoints, NVars: TLInt; var M: TLMatrix): TLInt; overload;
procedure PCABuildBasis(const X: TLMatrix; NPoints: TLInt; NVars: TLInt; var Info: TLInt; var s2: TLVec; var v: TLMatrix);
{ * k-means++ clusterization support * }
function KMeans(const Source: TLMatrix; const NVars, K: TLInt; var KArray: TLMatrix; var kIndex: TLIVec): Boolean;
{ * init Matrix * }
function LMatrix(const L1, l2: TLInt): TLMatrix; overload;
function LBMatrix(const L1, l2: TLInt): TLBMatrix; overload;
function LIMatrix(const L1, l2: TLInt): TLIMatrix; overload;
function ExpressionToLMatrix(w, h: TLInt; const s: TPascalString; const_vl: THashVariantList): TLMatrix; overload;
function ExpressionToLMatrix(w, h: TLInt; const s: TPascalString): TLMatrix; overload;
{$ENDREGION 'LearnAPI'}
{$REGION 'FloatAPI'}
function AbsReal(X: TLFloat): TLFloat;
function AbsInt(i: TLInt): TLInt;
function RandomReal(): TLFloat;
function RandomInteger(i: TLInt): TLInt;
function Sign(X: TLFloat): TLInt;
function AP_Sqr(X: TLFloat): TLFloat;
function DynamicArrayCopy(const a: TLIVec): TLIVec; overload;
function DynamicArrayCopy(const a: TLVec): TLVec; overload;
function DynamicArrayCopy(const a: TLComplexVec): TLComplexVec; overload;
function DynamicArrayCopy(const a: TLBVec): TLBVec; overload;
function DynamicArrayCopy(const a: TLIMatrix): TLIMatrix; overload;
function DynamicArrayCopy(const a: TLMatrix): TLMatrix; overload;
function DynamicArrayCopy(const a: TLComplexMatrix): TLComplexMatrix; overload;
function DynamicArrayCopy(const a: TLBMatrix): TLBMatrix; overload;
function AbsComplex(const z: TLComplex): TLFloat;
function Conj(const z: TLComplex): TLComplex;
function CSqr(const z: TLComplex): TLComplex;
function C_Complex(const X: TLFloat): TLComplex;
function C_Opposite(const z: TLComplex): TLComplex;
function C_Add(const z1: TLComplex; const z2: TLComplex): TLComplex;
function C_Mul(const z1: TLComplex; const z2: TLComplex): TLComplex;
function C_AddR(const z1: TLComplex; const r: TLFloat): TLComplex;
function C_MulR(const z1: TLComplex; const r: TLFloat): TLComplex;
function C_Sub(const z1: TLComplex; const z2: TLComplex): TLComplex;
function C_SubR(const z1: TLComplex; const r: TLFloat): TLComplex;
function C_RSub(const r: TLFloat; const z1: TLComplex): TLComplex;
function C_Div(const z1: TLComplex; const z2: TLComplex): TLComplex;
function C_DivR(const z1: TLComplex; const r: TLFloat): TLComplex;
function C_RDiv(const r: TLFloat; const z2: TLComplex): TLComplex;
function C_Equal(const z1: TLComplex; const z2: TLComplex): Boolean;
function C_NotEqual(const z1: TLComplex; const z2: TLComplex): Boolean;
function C_EqualR(const z1: TLComplex; const r: TLFloat): Boolean;
function C_NotEqualR(const z1: TLComplex; const r: TLFloat): Boolean;
function APVDotProduct(v1: PLFloat; i11, i12: TLInt; v2: PLFloat; i21, i22: TLInt): TLFloat;
procedure APVMove(VDst: PLFloat; i11, i12: TLInt; vSrc: PLFloat; i21, i22: TLInt); overload;
procedure APVMove(VDst: PLFloat; i11, i12: TLInt; vSrc: PLFloat; i21, i22: TLInt; s: TLFloat); overload;
procedure APVMoveNeg(VDst: PLFloat; i11, i12: TLInt; vSrc: PLFloat; i21, i22: TLInt);
procedure APVAdd(VDst: PLFloat; i11, i12: TLInt; vSrc: PLFloat; i21, i22: TLInt); overload;
procedure APVAdd(VDst: PLFloat; i11, i12: TLInt; vSrc: PLFloat; i21, i22: TLInt; s: TLFloat); overload;
procedure APVSub(VDst: PLFloat; i11, i12: TLInt; vSrc: PLFloat; i21, i22: TLInt); overload;
procedure APVSub(VDst: PLFloat; i11, i12: TLInt; vSrc: PLFloat; i21, i22: TLInt; s: TLFloat); overload;
procedure APVMul(VOp: PLFloat; i1, i2: TLInt; s: TLFloat);
procedure APVFillValue(VOp: PLFloat; i1, i2: TLInt; s: TLFloat);
function AP_Float(X: TLFloat): TLFloat;
function AP_FP_Eq(X: TLFloat; Y: TLFloat): Boolean;
function AP_FP_NEq(X: TLFloat; Y: TLFloat): Boolean;
function AP_FP_Less(X: TLFloat; Y: TLFloat): Boolean;
function AP_FP_Less_Eq(X: TLFloat; Y: TLFloat): Boolean;
function AP_FP_Greater(X: TLFloat; Y: TLFloat): Boolean;
function AP_FP_Greater_Eq(X: TLFloat; Y: TLFloat): Boolean;
procedure TagSort(var a: TLVec; const n: TLInt; var p1: TLIVec; var p2: TLIVec);
procedure TagSortFastI(var a: TLVec; var b: TLIVec; n: TLInt);
procedure TagSortFastR(var a: TLVec; var b: TLVec; n: TLInt);
procedure TagSortFast(var a: TLVec; const n: TLInt);
procedure TagHeapPushI(var a: TLVec; var b: TLIVec; var n: TLInt; const VA: TLFloat; const VB: TLInt);
procedure TagHeapReplaceTopI(var a: TLVec; var b: TLIVec; const n: TLInt; const VA: TLFloat; const VB: TLInt);
procedure TagHeapPopI(var a: TLVec; var b: TLIVec; var n: TLInt);
(* ************************************************************************
More precise dot-product. Absolute error of subroutine result is about
1 ulp of max(MX,V), where:
MX = max( |a[i]*b[i]| )
V = |(a,b)|
INPUT PARAMETERS
A - array[0..N-1], vector 1
B - array[0..N-1], vector 2
N - vectors length, N<2^29.
Temp - array[0..N-1], pre-allocated temporary storage
OUTPUT PARAMETERS
R - (A,B)
RErr - estimate of error. This estimate accounts for both errors
during calculation of (A,B) and errors introduced by
rounding of A and B to fit in TLFloat (about 1 ulp).
************************************************************************ *)
procedure XDot(const a: TLVec; const b: TLVec; n: TLInt; var Temp: TLVec; var r: TLFloat; var RErr: TLFloat);
(* ************************************************************************
Internal subroutine for extra-precise calculation of SUM(w[i]).
INPUT PARAMETERS:
W - array[0..N-1], values to be added W is modified during calculations.
MX - max(W[i])
N - array size
OUTPUT PARAMETERS:
R - SUM(w[i])
RErr- error estimate for R
************************************************************************ *)
procedure XSum(var w: TLVec; mx: TLFloat; n: TLInt; var r: TLFloat; var RErr: TLFloat);
(* ************************************************************************
Fast Pow
************************************************************************ *)
function XFastPow(r: TLFloat; n: TLInt): TLFloat;
{$ENDREGION 'FloatAPI'}
{$REGION 'LowLevelMatrix'}
{ matrix base }
function VectorNorm2(const X: TLVec; const i1, i2: TLInt): TLFloat;
function VectorIdxAbsMax(const X: TLVec; const i1, i2: TLInt): TLInt;
function ColumnIdxAbsMax(const X: TLMatrix; const i1, i2, j: TLInt): TLInt;
function RowIdxAbsMax(const X: TLMatrix; const j1, j2, i: TLInt): TLInt;
function UpperHessenberg1Norm(const a: TLMatrix; const i1, i2, j1, j2: TLInt; var Work: TLVec): TLFloat;
procedure CopyMatrix(const a: TLMatrix; const IS1, IS2, JS1, JS2: TLInt;
var b: TLMatrix; const ID1, id2, JD1, JD2: TLInt);
procedure InplaceTranspose(var a: TLMatrix; const i1, i2, j1, j2: TLInt; var Work: TLVec);
procedure CopyAndTranspose(const a: TLMatrix; IS1, IS2, JS1, JS2: TLInt;
var b: TLMatrix; ID1, id2, JD1, JD2: TLInt);
procedure MatrixVectorMultiply(const a: TLMatrix; const i1, i2, j1, j2: TLInt; const Trans: Boolean;
const X: TLVec; const IX1, IX2: TLInt; const alpha: TLFloat;
var Y: TLVec; const IY1, IY2: TLInt; const beta: TLFloat);
function Pythag2(X: TLFloat; Y: TLFloat): TLFloat;
procedure MatrixMatrixMultiply(const a: TLMatrix; const AI1, AI2, AJ1, AJ2: TLInt; const TransA: Boolean;
const b: TLMatrix; const BI1, BI2, BJ1, BJ2: TLInt; const TransB: Boolean;
const alpha: TLFloat;
var c: TLMatrix; const CI1, CI2, CJ1, CJ2: TLInt;
const beta: TLFloat;
var Work: TLVec);
{ Level 2 and Level 3 BLAS operations }
procedure ABLASSplitLength(const a: TLMatrix; n: TLInt; var n1: TLInt; var n2: TLInt);
procedure ABLASComplexSplitLength(const a: TLComplexMatrix; n: TLInt; var n1: TLInt; var n2: TLInt);
function ABLASBlockSize(const a: TLMatrix): TLInt;
function ABLASComplexBlockSize(const a: TLComplexMatrix): TLInt;
function ABLASMicroBlockSize(): TLInt;
procedure CMatrixTranspose(M: TLInt; n: TLInt; const a: TLComplexMatrix; IA: TLInt; ja: TLInt; var b: TLComplexMatrix; IB: TLInt; JB: TLInt);
procedure RMatrixTranspose(M: TLInt; n: TLInt; const a: TLMatrix; IA: TLInt; ja: TLInt; var b: TLMatrix; IB: TLInt; JB: TLInt);
procedure CMatrixCopy(M: TLInt; n: TLInt; const a: TLComplexMatrix; IA: TLInt; ja: TLInt; var b: TLComplexMatrix; IB: TLInt; JB: TLInt);
procedure RMatrixCopy(M: TLInt; n: TLInt; const a: TLMatrix; IA: TLInt; ja: TLInt; var b: TLMatrix; IB: TLInt; JB: TLInt);
procedure CMatrixRank1(M: TLInt; n: TLInt; var a: TLComplexMatrix; IA: TLInt; ja: TLInt; var u: TLComplexVec; IU: TLInt; var v: TLComplexVec; IV: TLInt);
procedure RMatrixRank1(M: TLInt; n: TLInt; var a: TLMatrix; IA: TLInt; ja: TLInt; var u: TLVec; IU: TLInt; var v: TLVec; IV: TLInt);
procedure CMatrixMV(M: TLInt; n: TLInt; var a: TLComplexMatrix; IA: TLInt; ja: TLInt; OpA: TLInt; var X: TLComplexVec; ix: TLInt; var Y: TLComplexVec; iy: TLInt);
procedure RMatrixMV(M: TLInt; n: TLInt; var a: TLMatrix; IA: TLInt; ja: TLInt; OpA: TLInt; var X: TLVec; ix: TLInt; var Y: TLVec; iy: TLInt);
procedure CMatrixRightTRSM(M: TLInt; n: TLInt;
const a: TLComplexMatrix; i1: TLInt; j1: TLInt;
IsUpper: Boolean; IsUnit: Boolean; OpType: TLInt;
var X: TLComplexMatrix; i2: TLInt; j2: TLInt);
procedure CMatrixLeftTRSM(M: TLInt; n: TLInt;
const a: TLComplexMatrix; i1: TLInt; j1: TLInt;
IsUpper: Boolean; IsUnit: Boolean; OpType: TLInt;
var X: TLComplexMatrix; i2: TLInt; j2: TLInt);
procedure RMatrixRightTRSM(M: TLInt; n: TLInt;
const a: TLMatrix; i1: TLInt; j1: TLInt; IsUpper: Boolean;
IsUnit: Boolean; OpType: TLInt; var X: TLMatrix; i2: TLInt; j2: TLInt);
procedure RMatrixLeftTRSM(M: TLInt; n: TLInt;
const a: TLMatrix; i1: TLInt; j1: TLInt; IsUpper: Boolean;
IsUnit: Boolean; OpType: TLInt; var X: TLMatrix; i2: TLInt; j2: TLInt);
procedure CMatrixSYRK(n: TLInt; K: TLInt; alpha: TLFloat;
const a: TLComplexMatrix; IA: TLInt; ja: TLInt; OpTypeA: TLInt;
beta: TLFloat; var c: TLComplexMatrix; IC: TLInt; JC: TLInt; IsUpper: Boolean);
procedure RMatrixSYRK(n: TLInt; K: TLInt; alpha: TLFloat;
const a: TLMatrix; IA: TLInt; ja: TLInt; OpTypeA: TLInt;
beta: TLFloat; var c: TLMatrix; IC: TLInt; JC: TLInt; IsUpper: Boolean);
procedure CMatrixGEMM(M: TLInt; n: TLInt; K: TLInt; alpha: TLComplex;
const a: TLComplexMatrix; IA: TLInt; ja: TLInt; OpTypeA: TLInt;
const b: TLComplexMatrix; IB: TLInt; JB: TLInt; OpTypeB: TLInt;
beta: TLComplex; var c: TLComplexMatrix; IC: TLInt; JC: TLInt);
procedure RMatrixGEMM(M: TLInt; n: TLInt; K: TLInt; alpha: TLFloat;
const a: TLMatrix; IA: TLInt; ja: TLInt; OpTypeA: TLInt;
const b: TLMatrix; IB: TLInt; JB: TLInt; OpTypeB: TLInt;
beta: TLFloat; var c: TLMatrix; IC: TLInt; JC: TLInt);
{ LU and Cholesky decompositions }
procedure RMatrixLU(var a: TLMatrix; M: TLInt; n: TLInt; var Pivots: TLIVec);
procedure CMatrixLU(var a: TLComplexMatrix; M: TLInt; n: TLInt; var Pivots: TLIVec);
function HPDMatrixCholesky(var a: TLComplexMatrix; n: TLInt; IsUpper: Boolean): Boolean;
function SPDMatrixCholesky(var a: TLMatrix; n: TLInt; IsUpper: Boolean): Boolean;
procedure RMatrixLUP(var a: TLMatrix; M: TLInt; n: TLInt; var Pivots: TLIVec);
procedure CMatrixLUP(var a: TLComplexMatrix; M: TLInt; n: TLInt; var Pivots: TLIVec);
procedure RMatrixPLU(var a: TLMatrix; M: TLInt; n: TLInt; var Pivots: TLIVec);
procedure CMatrixPLU(var a: TLComplexMatrix; M: TLInt; n: TLInt; var Pivots: TLIVec);
{ matrix safe }
function RMatrixScaledTRSafeSolve(const a: TLMatrix; SA: TLFloat;
n: TLInt; var X: TLVec; IsUpper: Boolean; Trans: TLInt;
IsUnit: Boolean; MaxGrowth: TLFloat): Boolean;
function CMatrixScaledTRSafeSolve(const a: TLComplexMatrix; SA: TLFloat;
n: TLInt; var X: TLComplexVec; IsUpper: Boolean;
Trans: TLInt; IsUnit: Boolean; MaxGrowth: TLFloat): Boolean;
{ * Condition number estimate support * }
function RMatrixRCond1(a: TLMatrix; n: TLInt): TLFloat;
function RMatrixRCondInf(a: TLMatrix; n: TLInt): TLFloat;
function SPDMatrixRCond(a: TLMatrix; n: TLInt; IsUpper: Boolean): TLFloat;
function RMatrixTRRCond1(const a: TLMatrix; n: TLInt; IsUpper: Boolean; IsUnit: Boolean): TLFloat;
function RMatrixTRRCondInf(const a: TLMatrix; n: TLInt; IsUpper: Boolean; IsUnit: Boolean): TLFloat;
function HPDMatrixRCond(a: TLComplexMatrix; n: TLInt; IsUpper: Boolean): TLFloat;
function CMatrixRCond1(a: TLComplexMatrix; n: TLInt): TLFloat;
function CMatrixRCondInf(a: TLComplexMatrix; n: TLInt): TLFloat;
function RMatrixLURCond1(const LUA: TLMatrix; n: TLInt): TLFloat;
function RMatrixLURCondInf(const LUA: TLMatrix; n: TLInt): TLFloat;
function SPDMatrixCholeskyRCond(const a: TLMatrix; n: TLInt; IsUpper: Boolean): TLFloat;
function HPDMatrixCholeskyRCond(const a: TLComplexMatrix; n: TLInt; IsUpper: Boolean): TLFloat;
function CMatrixLURCond1(const LUA: TLComplexMatrix; n: TLInt): TLFloat;
function CMatrixLURCondInf(const LUA: TLComplexMatrix; n: TLInt): TLFloat;
function CMatrixTRRCond1(const a: TLComplexMatrix; n: TLInt; IsUpper: Boolean; IsUnit: Boolean): TLFloat;
function CMatrixTRRCondInf(const a: TLComplexMatrix; n: TLInt; IsUpper: Boolean; IsUnit: Boolean): TLFloat;
function RCondThreshold(): TLFloat;
{ Matrix inverse }
procedure RMatrixLUInverse(var a: TLMatrix; const Pivots: TLIVec; n: TLInt; var Info: TLInt; var Rep: TMatInvReport);
procedure RMatrixInverse(var a: TLMatrix; n: TLInt; var Info: TLInt; var Rep: TMatInvReport);
procedure CMatrixLUInverse(var a: TLComplexMatrix; const Pivots: TLIVec; n: TLInt; var Info: TLInt; var Rep: TMatInvReport);
procedure CMatrixInverse(var a: TLComplexMatrix; n: TLInt; var Info: TLInt; var Rep: TMatInvReport);
procedure SPDMatrixCholeskyInverse(var a: TLMatrix; n: TLInt; IsUpper: Boolean; var Info: TLInt; var Rep: TMatInvReport);
procedure SPDMatrixInverse(var a: TLMatrix; n: TLInt; IsUpper: Boolean; var Info: TLInt; var Rep: TMatInvReport);
procedure HPDMatrixCholeskyInverse(var a: TLComplexMatrix; n: TLInt; IsUpper: Boolean; var Info: TLInt; var Rep: TMatInvReport);
procedure HPDMatrixInverse(var a: TLComplexMatrix; n: TLInt; IsUpper: Boolean; var Info: TLInt; var Rep: TMatInvReport);
procedure RMatrixTRInverse(var a: TLMatrix; n: TLInt; IsUpper: Boolean; IsUnit: Boolean; var Info: TLInt; var Rep: TMatInvReport);
procedure CMatrixTRInverse(var a: TLComplexMatrix; n: TLInt; IsUpper: Boolean; IsUnit: Boolean; var Info: TLInt; var Rep: TMatInvReport);
{ matrix rotations }
procedure ApplyRotationsFromTheLeft(IsForward: Boolean; m1: TLInt; m2: TLInt; n1: TLInt; n2: TLInt;
const c: TLVec; const s: TLVec; var a: TLMatrix; var Work: TLVec);
procedure ApplyRotationsFromTheRight(IsForward: Boolean; m1: TLInt; m2: TLInt; n1: TLInt; n2: TLInt;
const c: TLVec; const s: TLVec; var a: TLMatrix; var Work: TLVec);
procedure GenerateRotation(f: TLFloat; g: TLFloat; var cs: TLFloat; var sn: TLFloat; var r: TLFloat);
{ Bidiagonal SVD }
function RMatrixBDSVD(var d: TLVec; E: TLVec; n: TLInt; IsUpper: Boolean; IsFractionalAccuracyRequired: Boolean;
var u: TLMatrix; NRU: TLInt; var c: TLMatrix; NCC: TLInt; var VT: TLMatrix; NCVT: TLInt): Boolean;
function BidiagonalSVDDecomposition(var d: TLVec; E: TLVec; n: TLInt; IsUpper: Boolean; IsFractionalAccuracyRequired: Boolean;
var u: TLMatrix; NRU: TLInt; var c: TLMatrix; NCC: TLInt; var VT: TLMatrix; NCVT: TLInt): Boolean;
(* ************************************************************************
Singular value decomposition of a rectangular matrix.
The algorithm calculates the singular value decomposition of a matrix of
size MxN: A = U * S * V^T
The algorithm finds the singular values and, optionally, matrices U and V^T.
The algorithm can find both first min(M,N) columns of matrix U and rows of
matrix V^T (singular vectors), and matrices U and V^T wholly (of sizes MxM
and NxN respectively).
Take into account that the subroutine does not return matrix V but V^T.
Input parameters:
A - matrix to be decomposed.
Array whose indexes range within [0..M-1, 0..N-1].
M - number of rows in matrix A.
N - number of columns in matrix A.
UNeeded - 0, 1 or 2. See the description of the parameter U.
VTNeeded - 0, 1 or 2. See the description of the parameter VT.
AdditionalMemory -
If the parameter:
* equals 0, the algorithm dont use additional memory (lower requirements, lower performance).
* equals 1, the algorithm uses additional memory of size min(M,N)*min(M,N) of real numbers. It often speeds up the algorithm.
* equals 2, the algorithm uses additional memory of size M*min(M,N) of real numbers.
It allows to get a maximum performance. The recommended value of the parameter is 2.
Output parameters:
W - contains singular values in descending order.
U - if UNeeded=0, U isn't changed, the left singular vectors are not calculated.
if Uneeded=1, U contains left singular vectors (first min(M,N) columns of matrix U). Array whose indexes range within [0..M-1, 0..Min(M,N)-1].
if UNeeded=2, U contains matrix U wholly. Array whose indexes range within [0..M-1, 0..M-1].
VT - if VTNeeded=0, VT isnę?changed, the right singular vectors are not calculated.
if VTNeeded=1, VT contains right singular vectors (first min(M,N) rows of matrix V^T). Array whose indexes range within [0..min(M,N)-1, 0..N-1].
if VTNeeded=2, VT contains matrix V^T wholly. Array whose indexes range within [0..N-1, 0..N-1].
************************************************************************ *)
function RMatrixSVD(a: TLMatrix; const M, n, UNeeded, VTNeeded, AdditionalMemory: TLInt; var w: TLVec; var u: TLMatrix; var VT: TLMatrix): Boolean;
{ Eigensolvers }
function SMatrixEVD(a: TLMatrix; n: TLInt; ZNeeded: TLInt; IsUpper: Boolean; var d: TLVec; var z: TLMatrix): Boolean;
function SMatrixEVDR(a: TLMatrix; n: TLInt; ZNeeded: TLInt;
IsUpper: Boolean; b1: TLFloat; b2: TLFloat; var M: TLInt;
var w: TLVec; var z: TLMatrix): Boolean;
function SMatrixEVDI(a: TLMatrix; n: TLInt; ZNeeded: TLInt;
IsUpper: Boolean; i1: TLInt; i2: TLInt;
var w: TLVec; var z: TLMatrix): Boolean;
function HMatrixEVD(a: TLComplexMatrix; n: TLInt; ZNeeded: TLInt; IsUpper: Boolean;
var d: TLVec; var z: TLComplexMatrix): Boolean;
function HMatrixEVDR(a: TLComplexMatrix; n: TLInt;
ZNeeded: TLInt; IsUpper: Boolean; b1: TLFloat; b2: TLFloat;
var M: TLInt; var w: TLVec; var z: TLComplexMatrix): Boolean;
function HMatrixEVDI(a: TLComplexMatrix; n: TLInt;
ZNeeded: TLInt; IsUpper: Boolean; i1: TLInt;
i2: TLInt; var w: TLVec; var z: TLComplexMatrix): Boolean;
function SMatrixTDEVD(var d: TLVec; E: TLVec; n: TLInt; ZNeeded: TLInt; var z: TLMatrix): Boolean;
function SMatrixTDEVDR(var d: TLVec; const E: TLVec;
n: TLInt; ZNeeded: TLInt; a: TLFloat; b: TLFloat;
var M: TLInt; var z: TLMatrix): Boolean;
function SMatrixTDEVDI(var d: TLVec; const E: TLVec;
n: TLInt; ZNeeded: TLInt; i1: TLInt;
i2: TLInt; var z: TLMatrix): Boolean;
function RMatrixEVD(a: TLMatrix; n: TLInt; VNeeded: TLInt;
var WR: TLVec; var WI: TLVec; var vl: TLMatrix;
var vr: TLMatrix): Boolean;
function InternalBisectionEigenValues(d: TLVec; E: TLVec;
n: TLInt; IRANGE: TLInt; IORDER: TLInt;
vl: TLFloat; VU: TLFloat; IL: TLInt; IU: TLInt;
ABSTOL: TLFloat; var w: TLVec; var M: TLInt;
var NSPLIT: TLInt; var IBLOCK: TLIVec;
var ISPLIT: TLIVec; var ErrorCode: TLInt): Boolean;
procedure InternalDSTEIN(const n: TLInt; const d: TLVec;
E: TLVec; const M: TLInt; w: TLVec;
const IBLOCK: TLIVec; const ISPLIT: TLIVec;
var z: TLMatrix; var IFAIL: TLIVec; var Info: TLInt);
{ Schur decomposition }
function RMatrixSchur(var a: TLMatrix; n: TLInt; var s: TLMatrix): Boolean;
function UpperHessenbergSchurDecomposition(var h: TLMatrix; n: TLInt; var s: TLMatrix): Boolean;
{$ENDREGION 'LowLevelMatrix'}
{$REGION 'LowlevelDistribution'}
{ Normal distribution support }
function NormalDistribution(const X: TLFloat): TLFloat;
function InvNormalDistribution(const y0: TLFloat): TLFloat;
{ statistics base }
function Log1P(const X: TLFloat): TLFloat;
function ExpM1(const X: TLFloat): TLFloat;
function CosM1(const X: TLFloat): TLFloat;
{ Gamma support }
function Gamma(const X: TLFloat): TLFloat;
{ Natural logarithm of gamma function }
function LnGamma(const X: TLFloat; var SgnGam: TLFloat): TLFloat;
{ Incomplete gamma integral }
function IncompleteGamma(const a, X: TLFloat): TLFloat;
{ Complemented incomplete gamma integral }
function IncompleteGammaC(const a, X: TLFloat): TLFloat;
{ Inverse of complemented imcomplete gamma integral }
function InvIncompleteGammaC(const a, y0: TLFloat): TLFloat;
{ Poisson distribution }
function PoissonDistribution(K: TLInt; M: TLFloat): TLFloat;
{ Complemented Poisson distribution }
function PoissonCDistribution(K: TLInt; M: TLFloat): TLFloat;
{ Inverse Poisson distribution }
function InvPoissonDistribution(K: TLInt; Y: TLFloat): TLFloat;
{ Incomplete beta integral support }
function IncompleteBeta(a, b, X: TLFloat): TLFloat;
{ Inverse of imcomplete beta integral }
function InvIncompleteBeta(const a, b, Y: TLFloat): TLFloat;
{ F distribution support }
function FDistribution(const a: TLInt; const b: TLInt; const X: TLFloat): TLFloat;
{ Complemented F distribution }
function FCDistribution(const a: TLInt; const b: TLInt; const X: TLFloat): TLFloat;
{ Inverse of complemented F distribution }
function InvFDistribution(const a: TLInt; const b: TLInt; const Y: TLFloat): TLFloat;
{ Two-sample F-test }
procedure FTest(const X: TLVec; n: TLInt; const Y: TLVec; M: TLInt; var BothTails, LeftTail, RightTail: TLFloat);
{ Binomial distribution support }
function BinomialDistribution(const K, n: TLInt; const p: TLFloat): TLFloat;
{ Complemented binomial distribution }
function BinomialCDistribution(const K, n: TLInt; const p: TLFloat): TLFloat;
{ Inverse binomial distribution }
function InvBinomialDistribution(const K, n: TLInt; const Y: TLFloat): TLFloat;
{ Sign test }
procedure OneSampleSignTest(const X: TLVec; n: TLInt; Median: TLFloat; var BothTails, LeftTail, RightTail: TLFloat);
{ Chi-square distribution support }
function ChiSquareDistribution(const v, X: TLFloat): TLFloat;
{ Complemented Chi-square distribution }
function ChiSquareCDistribution(const v, X: TLFloat): TLFloat;
{ Inverse of complemented Chi-square distribution }
function InvChiSquareDistribution(const v, Y: TLFloat): TLFloat;
{ One-sample chi-square test }
procedure OneSampleVarianceTest(const X: TLVec; n: TLInt; Variance: TLFloat; var BothTails, LeftTail, RightTail: TLFloat);
{ Student's t distribution support }
function StudentTDistribution(const K: TLInt; const t: TLFloat): TLFloat;
{ Functional inverse of Student's t distribution }
function InvStudentTDistribution(const K: TLInt; p: TLFloat): TLFloat;
{ One-sample t-test }
procedure StudentTTest1(const X: TLVec; n: TLInt; Mean: TLFloat; var BothTails, LeftTail, RightTail: TLFloat);
{ Two-sample pooled test }
procedure StudentTTest2(const X: TLVec; n: TLInt; const Y: TLVec; M: TLInt; var BothTails, LeftTail, RightTail: TLFloat);
{ Two-sample unpooled test }
procedure UnequalVarianceTTest(const X: TLVec; n: TLInt; const Y: TLVec; M: TLInt; var BothTails, LeftTail, RightTail: TLFloat);
{ Pearson and Spearman distribution support }
{ Pearson product-moment correlation coefficient }
function PearsonCorrelation(const X, Y: TLVec; const n: TLInt): TLFloat;
{ Spearman's rank correlation coefficient }
function SpearmanRankCorrelation(const X, Y: TLVec; const n: TLInt): TLFloat;
procedure SpearmanRank(var X: TLVec; n: TLInt);
{ Pearson's correlation coefficient significance test }
procedure PearsonCorrelationSignificance(const r: TLFloat; const n: TLInt; var BothTails, LeftTail, RightTail: TLFloat);
{ Spearman's rank correlation coefficient significance test }
procedure SpearmanRankCorrelationSignificance(const r: TLFloat; const n: TLInt; var BothTails, LeftTail, RightTail: TLFloat);
{ Jarque-Bera test }
procedure JarqueBeraTest(const X: TLVec; const n: TLInt; var p: TLFloat);
{ Mann-Whitney U-test }
procedure MannWhitneyUTest(const X: TLVec; n: TLInt; const Y: TLVec; M: TLInt; var BothTails, LeftTail, RightTail: TLFloat);
{ Wilcoxon signed-rank test }
procedure WilcoxonSignedRankTest(const X: TLVec; n: TLInt; E: TLFloat; var BothTails, LeftTail, RightTail: TLFloat);
{$ENDREGION 'LowlevelDistribution'}
{$REGION 'LowLevelGauss'}
{
Computation of nodes and weights for a Gauss quadrature formula
The algorithm generates the N-point Gauss quadrature formula with weight
function given by coefficients alpha and beta of a recurrence relation
which generates a system of orthogonal polynomials:
P-1(x) = 0
P0(x) = 1
Pn+1(x) = (x-alpha(n))*Pn(x) - beta(n)*Pn-1(x)
and zeroth moment Mu0
Mu0 = integral(W(x)dx,a,b)
}
procedure GaussQuadratureGenerateRec(const alpha, beta: TLVec; const Mu0: TLFloat; n: TLInt; var Info: TLInt; var X: TLVec; var w: TLVec);
{
Computation of nodes and weights for a Gauss-Lobatto quadrature formula
The algorithm generates the N-point Gauss-Lobatto quadrature formula with
weight function given by coefficients alpha and beta of a recurrence which
generates a system of orthogonal polynomials.
P-1(x) = 0
P0(x) = 1
Pn+1(x) = (x-alpha(n))*Pn(x) - beta(n)*Pn-1(x)
and zeroth moment Mu0
Mu0 = integral(W(x)dx,a,b)
}
procedure GaussQuadratureGenerateGaussLobattoRec(const alpha, beta: TLVec; const Mu0, a, b: TLFloat; n: TLInt; var Info: TLInt; var X: TLVec; var w: TLVec);
{
Computation of nodes and weights for a Gauss-Radau quadrature formula
The algorithm generates the N-point Gauss-Radau quadrature formula with
weight function given by the coefficients alpha and beta of a recurrence
which generates a system of orthogonal polynomials.
P-1(x) = 0
P0(x) = 1
Pn+1(x) = (x-alpha(n))*Pn(x) - beta(n)*Pn-1(x)
and zeroth moment Mu0
Mu0 = integral(W(x)dx,a,b)
}
procedure GaussQuadratureGenerateGaussRadauRec(const alpha, beta: TLVec; const Mu0, a: TLFloat; n: TLInt; var Info: TLInt; var X: TLVec; var w: TLVec);
{ Returns nodes/weights for Gauss-Legendre quadrature on [-1,1] with N nodes }
procedure GaussQuadratureGenerateGaussLegendre(const n: TLInt; var Info: TLInt; var X: TLVec; var w: TLVec);
{ Returns nodes/weights for Gauss-Jacobi quadrature on [-1,1] with weight function W(x)=Power(1-x,Alpha)*Power(1+x,Beta) }
procedure GaussQuadratureGenerateGaussJacobi(const n: TLInt; const alpha, beta: TLFloat; var Info: TLInt; var X: TLVec; var w: TLVec);
{ Returns nodes/weights for Gauss-Laguerre quadrature on (0,+inf) with weight function W(x)=Power(x,Alpha)*Exp(-x) }
procedure GaussQuadratureGenerateGaussLaguerre(const n: TLInt; const alpha: TLFloat; var Info: TLInt; var X: TLVec; var w: TLVec);
{ Returns nodes/weights for Gauss-Hermite quadrature on (-inf,+inf) with weight function W(x)=Exp(-x*x) }
procedure GaussQuadratureGenerateGaussHermite(const n: TLInt; var Info: TLInt; var X: TLVec; var w: TLVec);
{
Computation of nodes and weights of a Gauss-Kronrod quadrature formula
The algorithm generates the N-point Gauss-Kronrod quadrature formula with
weight function given by coefficients alpha and beta of a recurrence
relation which generates a system of orthogonal polynomials:
P-1(x) = 0
P0(x) = 1
Pn+1(x) = (x-alpha(n))*Pn(x) - beta(n)*Pn-1(x)
and zero moment Mu0
Mu0 = integral(W(x)dx,a,b)
}
procedure GaussKronrodQuadratureGenerateRec(const alpha, beta: TLVec; const Mu0: TLFloat; n: TLInt; var Info: TLInt; var X, WKronrod, WGauss: TLVec);
{
Returns Gauss and Gauss-Kronrod nodes/weights for Gauss-Legendre quadrature with N points.
GKQLegendreCalc (calculation) or GKQLegendreTbl (precomputed table) is used depending on machine precision and number of nodes.
}
procedure GaussKronrodQuadratureGenerateGaussLegendre(const n: TLInt; var Info: TLInt; var X, WKronrod, WGauss: TLVec);
{
Returns Gauss and Gauss-Kronrod nodes/weights for Gauss-Jacobi quadrature on [-1,1] with weight function
W(x)=Power(1-x,Alpha)*Power(1+x,Beta).
}
procedure GaussKronrodQuadratureGenerateGaussJacobi(const n: TLInt; const alpha, beta: TLFloat; var Info: TLInt; var X, WKronrod, WGauss: TLVec);
{
Returns Gauss and Gauss-Kronrod nodes for quadrature with N points.
Reduction to tridiagonal eigenproblem is used.
}
procedure GaussKronrodQuadratureLegendreCalc(const n: TLInt; var Info: TLInt; var X, WKronrod, WGauss: TLVec);
{
Returns Gauss and Gauss-Kronrod nodes for quadrature with N points using pre-calculated table. Nodes/weights were computed with accuracy up to 1.0E-32.
In standard TLFloat precision accuracy reduces to something about 2.0E-16 (depending on your compiler's handling of long floating point constants).
}
procedure GaussKronrodQuadratureLegendreTbl(const n: TLInt; var X, WKronrod, WGauss: TLVec; var Eps: TLFloat);
{$ENDREGION 'LowLevelGauss'}
{$REGION 'Limited memory BFGS optimizer'}
procedure MinLBFGSCreate(n: TLInt; M: TLInt; const X: TLVec; var State: TMinLBFGSState);
procedure MinLBFGSSetCond(var State: TMinLBFGSState; EpsG: TLFloat; EpsF: TLFloat; EpsX: TLFloat; MAXITS: TLInt);
procedure MinLBFGSSetXRep(var State: TMinLBFGSState; NeedXRep: Boolean);
procedure MinLBFGSSetStpMax(var State: TMinLBFGSState; StpMax: TLFloat);
procedure MinLBFGSCreateX(n: TLInt; M: TLInt; const X: TLVec; Flags: TLInt; var State: TMinLBFGSState);
function MinLBFGSIteration(var State: TMinLBFGSState): Boolean;
procedure MinLBFGSResults(const State: TMinLBFGSState; var X: TLVec; var Rep: TMinLBFGSReport);
procedure MinLBFGSFree(var X: TLVec; var State: TMinLBFGSState);
{$ENDREGION 'Limited memory BFGS optimizer'}
{$REGION 'Improved Levenberg-Marquardt optimizer'}
procedure MinLMCreateFGH(const n: TLInt; const X: TLVec; var State: TMinLMState);
procedure MinLMCreateFGJ(const n: TLInt; const M: TLInt; const X: TLVec; var State: TMinLMState);
procedure MinLMCreateFJ(const n: TLInt; const M: TLInt; const X: TLVec; var State: TMinLMState);
procedure MinLMSetCond(var State: TMinLMState; EpsG: TLFloat; EpsF: TLFloat; EpsX: TLFloat; MAXITS: TLInt);
procedure MinLMSetXRep(var State: TMinLMState; NeedXRep: Boolean);
procedure MinLMSetStpMax(var State: TMinLMState; StpMax: TLFloat);
function MinLMIteration(var State: TMinLMState): Boolean;
procedure MinLMResults(const State: TMinLMState; var X: TLVec; var Rep: TMinLMReport);
{$ENDREGION 'Improved Levenberg-Marquardt optimizer'}
{$REGION 'neural network'}
procedure MLPCreate0(NIn, NOut: TLInt; var Network: TMultiLayerPerceptron);
procedure MLPCreate1(NIn, NHid, NOut: TLInt; var Network: TMultiLayerPerceptron);
procedure MLPCreate2(NIn, NHid1, NHid2, NOut: TLInt; var Network: TMultiLayerPerceptron);
procedure MLPCreateB0(NIn, NOut: TLInt; b, d: TLFloat; var Network: TMultiLayerPerceptron);
procedure MLPCreateB1(NIn, NHid, NOut: TLInt; b, d: TLFloat; var Network: TMultiLayerPerceptron);
procedure MLPCreateB2(NIn, NHid1, NHid2, NOut: TLInt; b, d: TLFloat; var Network: TMultiLayerPerceptron);
procedure MLPCreateR0(NIn, NOut: TLInt; a, b: TLFloat; var Network: TMultiLayerPerceptron);
procedure MLPCreateR1(NIn, NHid, NOut: TLInt; a, b: TLFloat; var Network: TMultiLayerPerceptron);
procedure MLPCreateR2(NIn, NHid1, NHid2, NOut: TLInt; a, b: TLFloat; var Network: TMultiLayerPerceptron);
procedure MLPCreateC0(NIn, NOut: TLInt; var Network: TMultiLayerPerceptron);
procedure MLPCreateC1(NIn, NHid, NOut: TLInt; var Network: TMultiLayerPerceptron);
procedure MLPCreateC2(NIn, NHid1, NHid2, NOut: TLInt; var Network: TMultiLayerPerceptron);
procedure MLPFree(var Network: TMultiLayerPerceptron);
procedure MLPCopy(const Network1: TMultiLayerPerceptron; var Network2: TMultiLayerPerceptron);
procedure MLPSerialize(const Network: TMultiLayerPerceptron; var ResArry: TLVec; var RLen: TLInt);
procedure MLPUNSerialize(const ResArry: TLVec; var Network: TMultiLayerPerceptron);
procedure MLPRandomize(var Network: TMultiLayerPerceptron); overload;
procedure MLPRandomize(var Network: TMultiLayerPerceptron; const Diameter: TLFloat); overload;
procedure MLPRandomize(var Network: TMultiLayerPerceptron; const WBest: TLVec; const Diameter: TLFloat); overload;
procedure MLPRandomizeFull(var Network: TMultiLayerPerceptron);
procedure MLPInitPreprocessor(var Network: TMultiLayerPerceptron; const xy: TLMatrix; SSize: TLInt);
procedure MLPProperties(const Network: TMultiLayerPerceptron; var NIn: TLInt; var NOut: TLInt; var WCount: TLInt);
function MLPIsSoftmax(const Network: TMultiLayerPerceptron): Boolean;
procedure MLPProcess(var Network: TMultiLayerPerceptron; const X: TLVec; var Y: TLVec);
function MLPError(var Network: TMultiLayerPerceptron; const xy: TLMatrix; SSize: TLInt): TLFloat;
function MLPErrorN(var Network: TMultiLayerPerceptron; const xy: TLMatrix; SSize: TLInt): TLFloat;
function MLPClsError(var Network: TMultiLayerPerceptron; const xy: TLMatrix; SSize: TLInt): TLInt;
function MLPRelClsError(var Network: TMultiLayerPerceptron; const xy: TLMatrix; NPoints: TLInt): TLFloat;
function MLPAvgCE(var Network: TMultiLayerPerceptron; const xy: TLMatrix; NPoints: TLInt): TLFloat;
function MLPRMSError(var Network: TMultiLayerPerceptron; const xy: TLMatrix; NPoints: TLInt): TLFloat;
function MLPAvgError(var Network: TMultiLayerPerceptron; const xy: TLMatrix; NPoints: TLInt): TLFloat;
function MLPAvgRelError(var Network: TMultiLayerPerceptron; const xy: TLMatrix; NPoints: TLInt): TLFloat;
procedure MLPGrad(var Network: TMultiLayerPerceptron; const X: TLVec; const DesiredY: TLVec; var E: TLFloat; var Grad: TLVec);
procedure MLPGradN(var Network: TMultiLayerPerceptron; const X: TLVec; const DesiredY: TLVec; var E: TLFloat; var Grad: TLVec);
procedure MLPGradBatch(var Network: TMultiLayerPerceptron; const xy: TLMatrix; SSize: TLInt; var E: TLFloat; var Grad: TLVec);
procedure MLPGradNBatch(var Network: TMultiLayerPerceptron; const xy: TLMatrix; SSize: TLInt; var E: TLFloat; var Grad: TLVec);
procedure MLPHessianNBatch(var Network: TMultiLayerPerceptron; const xy: TLMatrix; SSize: TLInt; var E: TLFloat; var Grad: TLVec; var h: TLMatrix);
procedure MLPHessianBatch(var Network: TMultiLayerPerceptron; const xy: TLMatrix; SSize: TLInt; var E: TLFloat; var Grad: TLVec; var h: TLMatrix);
procedure MLPInternalProcessVector(const StructInfo: TLIVec;
const Weights: TLVec; const ColumnMeans: TLVec;
const ColumnSigmas: TLVec; var Neurons: TLVec;
var DFDNET: TLVec; const X: TLVec; var Y: TLVec);
procedure MLPTrainLM(var Network: TMultiLayerPerceptron; const xy: TLMatrix;
NPoints: TLInt; Decay: TLFloat; Restarts: TLInt;
var Info: TLInt; var Rep: TMLPReport);
procedure MLPTrainLM_MT(var Network: TMultiLayerPerceptron; const xy: TLMatrix;
NPoints: TLInt; Decay: TLFloat; Restarts: TLInt;
var Info: TLInt; var Rep: TMLPReport);
procedure MLPTrainLBFGS(var Network: TMultiLayerPerceptron;
const xy: TLMatrix; NPoints: TLInt; Decay: TLFloat;
Restarts: TLInt; WStep: TLFloat; MAXITS: TLInt;
var Info: TLInt; var Rep: TMLPReport; IsTerminated: PBoolean;
out EBest: TLFloat);
procedure MLPTrainLBFGS_MT(var Network: TMultiLayerPerceptron;
const xy: TLMatrix; NPoints: TLInt; Decay: TLFloat;
Restarts: TLInt; WStep: TLFloat; MAXITS: TLInt;
var Info: TLInt; var Rep: TMLPReport);
procedure MLPTrainLBFGS_MT_Mod(var Network: TMultiLayerPerceptron;
const xy: TLMatrix; NPoints: TLInt; Restarts: TLInt;
WStep, Diameter: TLFloat; MAXITS: TLInt;
var Info: TLInt; var Rep: TMLPReport);
procedure MLPTrainMonteCarlo(var Network: TMultiLayerPerceptron; const xy: TLMatrix; NPoints: TLInt;
const MainRestarts, SubRestarts: TLInt; const MinError: TLFloat;
Diameter: TLFloat; var Info: TLInt; var Rep: TMLPReport);
procedure MLPKFoldCVLBFGS(const Network: TMultiLayerPerceptron;
const xy: TLMatrix; NPoints: TLInt; Decay: TLFloat;
Restarts: TLInt; WStep: TLFloat; MAXITS: TLInt;
FoldsCount: TLInt; var Info: TLInt; var Rep: TMLPReport;
var CVRep: TMLPCVReport);
procedure MLPKFoldCVLM(const Network: TMultiLayerPerceptron;
const xy: TLMatrix; NPoints: TLInt; Decay: TLFloat;
Restarts: TLInt; FoldsCount: TLInt; var Info: TLInt;
var Rep: TMLPReport; var CVRep: TMLPCVReport);
{$ENDREGION 'neural network'}
{$REGION 'Neural networks ensemble'}
procedure MLPECreate0(NIn, NOut, EnsembleSize: TLInt; var Ensemble: TMLPEnsemble);
procedure MLPECreate1(NIn, NHid, NOut, EnsembleSize: TLInt; var Ensemble: TMLPEnsemble);
procedure MLPECreate2(NIn, NHid1, NHid2, NOut, EnsembleSize: TLInt; var Ensemble: TMLPEnsemble);
procedure MLPECreateB0(NIn, NOut: TLInt; b, d: TLFloat; EnsembleSize: TLInt; var Ensemble: TMLPEnsemble);
procedure MLPECreateB1(NIn, NHid, NOut: TLInt; b, d: TLFloat; EnsembleSize: TLInt; var Ensemble: TMLPEnsemble);
procedure MLPECreateB2(NIn, NHid1, NHid2, NOut: TLInt; b, d: TLFloat; EnsembleSize: TLInt; var Ensemble: TMLPEnsemble);
procedure MLPECreateR0(NIn, NOut: TLInt; a, b: TLFloat; EnsembleSize: TLInt; var Ensemble: TMLPEnsemble);
procedure MLPECreateR1(NIn, NHid, NOut: TLInt; a, b: TLFloat; EnsembleSize: TLInt; var Ensemble: TMLPEnsemble);
procedure MLPECreateR2(NIn, NHid1, NHid2, NOut: TLInt; a, b: TLFloat; EnsembleSize: TLInt; var Ensemble: TMLPEnsemble);
procedure MLPECreateC0(NIn, NOut, EnsembleSize: TLInt; var Ensemble: TMLPEnsemble);
procedure MLPECreateC1(NIn, NHid, NOut, EnsembleSize: TLInt; var Ensemble: TMLPEnsemble);
procedure MLPECreateC2(NIn, NHid1, NHid2, NOut, EnsembleSize: TLInt; var Ensemble: TMLPEnsemble);
procedure MLPECreateFromNetwork(const Network: TMultiLayerPerceptron; EnsembleSize: TLInt; var Ensemble: TMLPEnsemble);
procedure MLPECopy(const Ensemble1: TMLPEnsemble; var Ensemble2: TMLPEnsemble);
procedure MLPESerialize(var Ensemble: TMLPEnsemble; var ResArry: TLVec; var RLen: TLInt);
procedure MLPEUNSerialize(const ResArry: TLVec; var Ensemble: TMLPEnsemble);
procedure MLPERandomize(var Ensemble: TMLPEnsemble);
procedure MLPEProperties(const Ensemble: TMLPEnsemble; var NIn: TLInt; var NOut: TLInt);
function MLPEIsSoftmax(const Ensemble: TMLPEnsemble): Boolean;
procedure MLPEProcess(var Ensemble: TMLPEnsemble; const X: TLVec; var Y: TLVec);
function MLPERelClsError(var Ensemble: TMLPEnsemble; const xy: TLMatrix; NPoints: TLInt): TLFloat;
function MLPEAvgCE(var Ensemble: TMLPEnsemble; const xy: TLMatrix; NPoints: TLInt): TLFloat;
function MLPERMSError(var Ensemble: TMLPEnsemble; const xy: TLMatrix; NPoints: TLInt): TLFloat;
function MLPEAvgError(var Ensemble: TMLPEnsemble; const xy: TLMatrix; NPoints: TLInt): TLFloat;
function MLPEAvgRelError(var Ensemble: TMLPEnsemble; const xy: TLMatrix; NPoints: TLInt): TLFloat;
procedure MLPEBaggingLM(const MultiThread: Boolean; var Ensemble: TMLPEnsemble; const xy: TLMatrix;
NPoints: TLInt; Decay: TLFloat; Restarts: TLInt;
var Info: TLInt; var Rep: TMLPReport; var OOBErrors: TMLPCVReport);
procedure MLPEBaggingLBFGS(const MultiThread: Boolean; var Ensemble: TMLPEnsemble; const xy: TLMatrix;
NPoints: TLInt; Decay: TLFloat; Restarts: TLInt;
WStep: TLFloat; MAXITS: TLInt; var Info: TLInt;
var Rep: TMLPReport; var OOBErrors: TMLPCVReport);
{$ENDREGION 'Neural networks ensemble'}
{$REGION 'Random Decision Forest'}
procedure DFBuildRandomDecisionForest(const xy: TLMatrix; NPoints, NVars, NClasses, NTrees: TLInt; r: TLFloat; var Info: TLInt; var df: TDecisionForest; var Rep: TDFReport);
procedure DFProcess(const df: TDecisionForest; const X: TLVec; var Y: TLVec);
function DFRelClsError(const df: TDecisionForest; const xy: TLMatrix; NPoints: TLInt): TLFloat;
function DFAvgCE(const df: TDecisionForest; const xy: TLMatrix; NPoints: TLInt): TLFloat;
function DFRMSError(const df: TDecisionForest; const xy: TLMatrix; NPoints: TLInt): TLFloat;
function DFAvgError(const df: TDecisionForest; const xy: TLMatrix; NPoints: TLInt): TLFloat;
function DFAvgRelError(const df: TDecisionForest; const xy: TLMatrix; NPoints: TLInt): TLFloat;
procedure DFCopy(const DF1: TDecisionForest; var DF2: TDecisionForest);
procedure DFSerialize(const df: TDecisionForest; var ResArry: TLVec; var RLen: TLInt);
procedure DFUnserialize(const ResArry: TLVec; var df: TDecisionForest);
{$ENDREGION 'Random Decision Forest'}
{$REGION 'LogitModel'}
procedure MNLTrainH(const xy: TLMatrix; NPoints: TLInt; NVars: TLInt; NClasses: TLInt; var Info: TLInt; var LM: TLogitModel; var Rep: TMNLReport);
procedure MNLProcess(var LM: TLogitModel; const X: TLVec; var Y: TLVec);
procedure MNLUnpack(const LM: TLogitModel; var a: TLMatrix; var NVars: TLInt; var NClasses: TLInt);
procedure MNLPack(const a: TLMatrix; NVars: TLInt; NClasses: TLInt; var LM: TLogitModel);
procedure MNLCopy(const LM1: TLogitModel; var LM2: TLogitModel);
procedure MNLSerialize(const LM: TLogitModel; var ResArry: TLVec; var RLen: TLInt);
procedure MNLUnserialize(const ResArry: TLVec; var LM: TLogitModel);
function MNLAvgCE(var LM: TLogitModel; const xy: TLMatrix; NPoints: TLInt): TLFloat;
function MNLRelClsError(var LM: TLogitModel; const xy: TLMatrix; NPoints: TLInt): TLFloat;
function MNLRMSError(var LM: TLogitModel; const xy: TLMatrix; NPoints: TLInt): TLFloat;
function MNLAvgError(var LM: TLogitModel; const xy: TLMatrix; NPoints: TLInt): TLFloat;
function MNLAvgRelError(var LM: TLogitModel; const xy: TLMatrix; SSize: TLInt): TLFloat;
function MNLClsError(var LM: TLogitModel; const xy: TLMatrix; NPoints: TLInt): TLInt;
{$ENDREGION 'LogitModel'}
{$REGION 'fitting'}
{ Least squares fitting }
procedure LSFitLinearW(Y: TLVec; w: TLVec; FMatrix: TLMatrix; n: TLInt; M: TLInt; var Info: TLInt; var c: TLVec; var Rep: TLSFitReport);
procedure LSFitLinearWC(Y: TLVec; w: TLVec; FMatrix: TLMatrix; CMatrix: TLMatrix; n: TLInt; M: TLInt; K: TLInt; var Info: TLInt; var c: TLVec; var Rep: TLSFitReport);
procedure LSFitLinear(Y: TLVec; FMatrix: TLMatrix; n: TLInt; M: TLInt; var Info: TLInt; var c: TLVec; var Rep: TLSFitReport);
procedure LSFitLinearC(Y: TLVec; FMatrix: TLMatrix; CMatrix: TLMatrix; n: TLInt; M: TLInt; K: TLInt; var Info: TLInt; var c: TLVec; var Rep: TLSFitReport);
procedure LSFitNonlinearWFG(X: TLMatrix; Y: TLVec; w: TLVec; c: TLVec; n: TLInt; M: TLInt; K: TLInt; CheapFG: Boolean; var State: TLSFitState);
procedure LSFitNonlinearFG(X: TLMatrix; Y: TLVec; c: TLVec; n: TLInt; M: TLInt; K: TLInt; CheapFG: Boolean; var State: TLSFitState);
procedure LSFitNonlinearWFGH(X: TLMatrix; Y: TLVec; w: TLVec; c: TLVec; n: TLInt; M: TLInt; K: TLInt; var State: TLSFitState);
procedure LSFitNonlinearFGH(X: TLMatrix; Y: TLVec; c: TLVec; n: TLInt; M: TLInt; K: TLInt; var State: TLSFitState);
procedure LSFitNonlinearSetCond(var State: TLSFitState; EpsF: TLFloat; EpsX: TLFloat; MAXITS: TLInt);
procedure LSFitNonlinearSetStpMax(var State: TLSFitState; StpMax: TLFloat);
function LSFitNonlinearIteration(var State: TLSFitState): Boolean;
procedure LSFitNonlinearResults(State: TLSFitState; var Info: TLInt; var c: TLVec; var Rep: TLSFitReport);
procedure LSFitScaleXY(var X, Y: TLVec; n: TLInt; var XC, YC: TLVec; DC: TLIVec; K: TLInt; var XA, XB, SA, SB: TLFloat; var XOriginal, YOriginal: TLVec);
{ Barycentric fitting }
function BarycentricCalc(b: TBarycentricInterpolant; t: TLFloat): TLFloat;
procedure BarycentricDiff1(b: TBarycentricInterpolant; t: TLFloat; var f: TLFloat; var df: TLFloat);
procedure BarycentricDiff2(b: TBarycentricInterpolant; t: TLFloat; var f: TLFloat; var df: TLFloat; var D2F: TLFloat);
procedure BarycentricLinTransX(var b: TBarycentricInterpolant; ca: TLFloat; CB: TLFloat);
procedure BarycentricLinTransY(var b: TBarycentricInterpolant; ca: TLFloat; CB: TLFloat);
procedure BarycentricUnpack(b: TBarycentricInterpolant; var n: TLInt; var X: TLVec; var Y: TLVec; var w: TLVec);
procedure BarycentricSerialize(b: TBarycentricInterpolant; var ResArry: TLVec; var ResLen: TLInt);
procedure BarycentricUnserialize(ResArry: TLVec; var b: TBarycentricInterpolant);
procedure BarycentricCopy(b: TBarycentricInterpolant; var b2: TBarycentricInterpolant);
procedure BarycentricBuildXYW(X, Y, w: TLVec; n: TLInt; var b: TBarycentricInterpolant);
procedure BarycentricBuildFloaterHormann(X, Y: TLVec; n: TLInt; d: TLInt; var b: TBarycentricInterpolant);
procedure BarycentricFitFloaterHormannWC(X, Y, w: TLVec; n: TLInt; XC, YC: TLVec; DC: TLIVec; K, M: TLInt; var Info: TLInt; var b: TBarycentricInterpolant; var Rep: TBarycentricFitReport);
procedure BarycentricFitFloaterHormann(X, Y: TLVec; n: TLInt; M: TLInt; var Info: TLInt; var b: TBarycentricInterpolant; var Rep: TBarycentricFitReport);
{ Polynomial fitting }
procedure PolynomialBuild(X, Y: TLVec; n: TLInt; var p: TBarycentricInterpolant);
procedure PolynomialBuildEqDist(a: TLFloat; b: TLFloat; Y: TLVec; n: TLInt; var p: TBarycentricInterpolant);
procedure PolynomialBuildCheb1(a: TLFloat; b: TLFloat; Y: TLVec; n: TLInt; var p: TBarycentricInterpolant);
procedure PolynomialBuildCheb2(a: TLFloat; b: TLFloat; Y: TLVec; n: TLInt; var p: TBarycentricInterpolant);
function PolynomialCalcEqDist(a: TLFloat; b: TLFloat; f: TLVec; n: TLInt; t: TLFloat): TLFloat;
function PolynomialCalcCheb1(a: TLFloat; b: TLFloat; f: TLVec; n: TLInt; t: TLFloat): TLFloat;
function PolynomialCalcCheb2(a: TLFloat; b: TLFloat; f: TLVec; n: TLInt; t: TLFloat): TLFloat;
procedure PolynomialFit(X, Y: TLVec; n, M: TLInt; var Info: TLInt; var p: TBarycentricInterpolant; var Rep: TPolynomialFitReport);
procedure PolynomialFitWC(X, Y, w: TLVec; n: TLInt; XC, YC: TLVec; DC: TLIVec; K: TLInt; M: TLInt; var Info: TLInt; var p: TBarycentricInterpolant; var Rep: TPolynomialFitReport);
{ Spline1D fitting }
procedure Spline1DBuildLinear(X, Y: TLVec; n: TLInt; var c: TSpline1DInterpolant);
procedure Spline1DBuildCubic(X, Y: TLVec; n: TLInt; BoundLType: TLInt; BoundL: TLFloat; BoundRType: TLInt; BoundR: TLFloat; var c: TSpline1DInterpolant);
procedure Spline1DBuildCatmullRom(X, Y: TLVec; n: TLInt; BoundType: TLInt; Tension: TLFloat; var c: TSpline1DInterpolant);
procedure Spline1DBuildHermite(X, Y: TLVec; d: TLVec; n: TLInt; var c: TSpline1DInterpolant);
procedure Spline1DBuildAkima(X, Y: TLVec; n: TLInt; var c: TSpline1DInterpolant);
procedure Spline1DFitCubicWC(X, Y, w: TLVec; n: TLInt; XC: TLVec; YC: TLVec; DC: TLIVec; K: TLInt; M: TLInt; var Info: TLInt; var s: TSpline1DInterpolant; var Rep: TSpline1DFitReport);
procedure Spline1DFitHermiteWC(X, Y, w: TLVec; n: TLInt; XC: TLVec; YC: TLVec; DC: TLIVec; K: TLInt; M: TLInt; var Info: TLInt; var s: TSpline1DInterpolant; var Rep: TSpline1DFitReport);
procedure Spline1DFitCubic(X, Y: TLVec; n: TLInt; M: TLInt; var Info: TLInt; var s: TSpline1DInterpolant; var Rep: TSpline1DFitReport);
procedure Spline1DFitHermite(X, Y: TLVec; n: TLInt; M: TLInt; var Info: TLInt; var s: TSpline1DInterpolant; var Rep: TSpline1DFitReport);
function Spline1DCalc(c: TSpline1DInterpolant; X: TLFloat): TLFloat;
procedure Spline1DDiff(c: TSpline1DInterpolant; X: TLFloat; var s: TLFloat; var DS: TLFloat; var D2S: TLFloat);
procedure Spline1DCopy(c: TSpline1DInterpolant; var CC: TSpline1DInterpolant);
procedure Spline1DUnpack(c: TSpline1DInterpolant; var n: TLInt; var Tbl: TLMatrix);
procedure Spline1DLinTransX(var c: TSpline1DInterpolant; a: TLFloat; b: TLFloat);
procedure Spline1DLinTransY(var c: TSpline1DInterpolant; a: TLFloat; b: TLFloat);
function Spline1DIntegrate(c: TSpline1DInterpolant; X: TLFloat): TLFloat;
{$ENDREGION 'fitting'}
{$REGION 'Portable high quality random number'}
procedure HQRNDRandomize(var State: THQRNDState);
procedure HQRNDSeed(const s1, s2: TLInt; var State: THQRNDState);
function HQRNDUniformR(var State: THQRNDState): TLFloat;
function HQRNDUniformI(const n: TLInt; var State: THQRNDState): TLInt;
function HQRNDNormal(var State: THQRNDState): TLFloat;
procedure HQRNDUnit2(var State: THQRNDState; var X: TLFloat; var Y: TLFloat);
procedure HQRNDNormal2(var State: THQRNDState; var x1: TLFloat; var x2: TLFloat);
function HQRNDExponential(const LAMBDA: TLFloat; var State: THQRNDState): TLFloat;
{$ENDREGION 'Portable high quality random number'}
{$REGION 'Generation of random matrix'}
procedure RMatrixRndOrthogonal(n: TLInt; var a: TLMatrix);
procedure RMatrixRndCond(n: TLInt; c: TLFloat; var a: TLMatrix);
procedure CMatrixRndOrthogonal(n: TLInt; var a: TLComplexMatrix);
procedure CMatrixRndCond(n: TLInt; c: TLFloat; var a: TLComplexMatrix);
procedure SMatrixRndCond(n: TLInt; c: TLFloat; var a: TLMatrix);
procedure SPDMatrixRndCond(n: TLInt; c: TLFloat; var a: TLMatrix);
procedure HMatrixRndCond(n: TLInt; c: TLFloat; var a: TLComplexMatrix);
procedure HPDMatrixRndCond(n: TLInt; c: TLFloat; var a: TLComplexMatrix);
procedure RMatrixRndOrthogonalFromTheRight(var a: TLMatrix; M: TLInt; n: TLInt);
procedure RMatrixRndOrthogonalFromTheLeft(var a: TLMatrix; M: TLInt; n: TLInt);
procedure CMatrixRndOrthogonalFromTheRight(var a: TLComplexMatrix; M: TLInt; n: TLInt);
procedure CMatrixRndOrthogonalFromTheLeft(var a: TLComplexMatrix; M: TLInt; n: TLInt);
procedure SMatrixRndMultiply(var a: TLMatrix; n: TLInt);
procedure HMatrixRndMultiply(var a: TLComplexMatrix; n: TLInt);
{$ENDREGION 'Generation of random matrix'}
{$REGION 'fft'}
{ generates FFT plan }
procedure FTBaseGenerateComplexFFTPlan(n: TLInt; var Plan: TFTPlan);
procedure FTBaseGenerateRealFFTPlan(n: TLInt; var Plan: TFTPlan);
procedure FTBaseGenerateRealFHTPlan(n: TLInt; var Plan: TFTPlan);
procedure FTBaseExecutePlan(var a: TLVec; AOffset: TLInt; n: TLInt; var Plan: TFTPlan);
procedure FTBaseExecutePlanRec(var a: TLVec; AOffset: TLInt; var Plan: TFTPlan; EntryOffset: TLInt; StackPtr: TLInt);
procedure FTBaseFactorize(n: TLInt; TaskType: TLInt; var n1: TLInt; var n2: TLInt);
function FTBaseIsSmooth(n: TLInt): Boolean;
function FTBaseFindSmooth(n: TLInt): TLInt;
function FTBaseFindSmoothEven(n: TLInt): TLInt;
function FTBaseGetFLOPEstimate(n: TLInt): TLFloat;
{ 1-dimensional TLComplex FFT. }
procedure FFTC1D(var a: TLComplexVec; n: TLInt);
{ 1-dimensional TLComplex inverse FFT. }
procedure FFTC1DInv(var a: TLComplexVec; n: TLInt);
{ 1-dimensional real FFT. }
procedure FFTR1D(const a: TLVec; n: TLInt; var f: TLComplexVec);
{ 1-dimensional real inverse FFT. }
procedure FFTR1DInv(const f: TLComplexVec; n: TLInt; var a: TLVec);
{$ENDREGION 'fft'}
{$REGION 'test'}
procedure LearnTest;
{$ENDREGION 'test'}
implementation
uses KM, DoStatusIO, TextParsing, zExpression, OpCode;
{$REGION 'Include'}
{$INCLUDE learn_base.inc}
{$INCLUDE learn_blas.inc}
{$INCLUDE learn_ablas.inc}
{$INCLUDE learn_trfac.inc}
{$INCLUDE learn_safesolve.inc}
{$INCLUDE learn_rcond.inc}
{$INCLUDE learn_matinv.inc}
{$INCLUDE learn_linmin.inc}
{$INCLUDE learn_lbfgs.inc}
{$INCLUDE learn_rotations.inc}
{$INCLUDE learn_ortfac.inc}
{$INCLUDE learn_bdsvd.inc}
{$INCLUDE learn_svd.inc}
{$INCLUDE learn_densesolver.inc}
{$INCLUDE learn_minlm.inc}
{$INCLUDE learn_trainbase.inc}
{$INCLUDE learn_train.inc}
{$INCLUDE learn_trainEnsemble.inc}
{$INCLUDE learn_schur.inc}
{$INCLUDE learn_evd.inc}
{$INCLUDE learn_PCA.inc}
{$INCLUDE learn_LDA.inc}
{$INCLUDE learn_forest.inc}
{$INCLUDE learn_logit.inc}
{$INCLUDE learn_statistics_normal_distribution.inc}
{$INCLUDE learn_statistics_base.inc}
{$INCLUDE learn_statistics_IncompleteBeta.inc}
{$INCLUDE learn_statistics_fdistribution.inc}
{$INCLUDE learn_statistics_binomial_distribution.inc}
{$INCLUDE learn_statistics_chisquare_distribution.inc}
{$INCLUDE learn_statistics_StudentsT_distribution.inc}
{$INCLUDE learn_statistics_Pearson_Spearman.inc}
{$INCLUDE learn_statistics_JarqueBeraTest.inc}
{$INCLUDE learn_statistics_MannWhitneyUTest.inc}
{$INCLUDE learn_statistics_Wilcoxon.inc}
{$INCLUDE learn_gaussintegral.inc}
{$INCLUDE learn_fitting.inc}
{$INCLUDE learn_quality_random.inc}
{$INCLUDE learn_matgen.inc}
{$INCLUDE learn_fft.inc}
{$INCLUDE learn_extAPI.inc}
{$INCLUDE learn_th.inc}
{$INCLUDE learn_class.inc}
{$INCLUDE learn_test.inc}
{$ENDREGION 'Include'}
end.
|
unit JvInterpreterCallFunctionFm;
interface
uses
SysUtils, Variants, Classes, Graphics, Controls, Forms,
StdCtrls, Dialogs, SynEdit, SynHighlighterPas, LCLVersion,
JvInterpreter;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Edit1: TEdit;
Label1: TLabel;
JvInterpreterProgram1: TJvInterpreterProgram;
SynPasSyn1: TSynPasSyn;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure JvInterpreterProgram1GetValue(Sender: TObject;
Identifier: String; var Value: Variant; Args: TJvInterpreterArgs;
var Done: Boolean);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
JvHLEditor: TSynEdit;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
procedure TForm1.Button1Click(Sender: TObject);
var
Args: TJvInterpreterArgs;
begin
{ before we get here, JvInterpreterProgram1.Pas is already set to show the text in the HLEditor. }
Assert(JvInterpreterProgram1.Pas.Count>0);
{ THIS IS ONLY ONE POSSIBLE WAY TO CALL CallFunction! Look at both ways please. }
{Args is a temporary argument data holder object}
Args := TJvInterpreterArgs.Create;
try
Args.Count := 1;
Args.Values[0] := 'SomeText';
JvInterpreterProgram1.CallFunction( 'MyFunction', Args, []);
{ show result to user:}
Edit1.Text := VarToStr( JvInterpreterProgram1.VResult );
finally
Args.Free;
end;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
{ move program text over to interpreter! }
JvInterpreterProgram1.Pas.Assign(JvHLEditor.Lines);
end;
procedure TForm1.JvInterpreterProgram1GetValue(Sender: TObject;
Identifier: String; var Value: Variant; Args: TJvInterpreterArgs;
var Done: Boolean);
begin
Identifier := UpperCase(Identifier);
if (Identifier='LENGTH') and (ARgs.Count=1) and (VarIsStr(Args.Values[0])) then
begin
Value := Length(ARgs.Values[0]);
Done := true;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
Param1,Param2:Variant;
begin
{ before we get here, JvInterpreterProgram1.Pas is already set to show the text in the HLEditor. }
Assert(JvInterpreterProgram1.Pas.Count>0);
{ Alternative method without creating/freeing JvInterpreter args is to use Params instead, but not Args:}
Param1 := 10;
Param2 := 20;
JvInterpreterProgram1.CallFunction( 'MyFunction2', nil, [Param1,Param2] );
{ show result to user:}
Edit1.Text := VarToStr( JvInterpreterProgram1.VResult );
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
JvHLEditor := TSynEdit.Create(self);
with JvHLEditor do
begin
Parent := self;
AnchorSideLeft.Control := self;
AnchorSideTop.Control := Button2;
AnchorSideTop.Side := asrBottom;
AnchorSideRight.Control := self;
AnchorSideRight.Side := asrBottom;
AnchorSideBottom.Control := Self;
AnchorSideBottom.Side := asrBottom;
BorderSpacing.Left := 12;
BorderSpacing.Top := 8;
BorderSpacing.Right := 12;
BorderSpacing.Bottom := 12;
Anchors := [akTop, akLeft, akRight, akBottom];
Lines.Add('unit UserFunctions;');
Lines.Add('');
Lines.Add('// sample of a user-created-library of jvinterpreter functions that your compiled');
Lines.Add('// program might access:');
Lines.Add('');
Lines.Add('');
Lines.Add('// notice that there is no interface/implementation section in this ');
Lines.Add('// interpreter-only unit.');
Lines.Add('');
Lines.Add('function MyFunction(B:String):Integer;');
Lines.Add('begin');
Lines.Add(' result := Length(B);');
Lines.Add('end;');
Lines.Add('');
Lines.Add('function MyFunction2(A,B:Integer):Integer;');
Lines.Add('begin');
Lines.Add(' result := A+B;');
Lines.Add('end;');
Lines.Add('');
Lines.Add('');
Lines.Add('end.');
Highlighter := SynPasSyn1;
end;
{$IF LCL_FullVersion >= 2010000}
JvHLEditor.ScrollOnEditLeftOptions.ScrollExtraMax := 10;
JvHLEditor.ScrollOnEditLeftOptions.ScrollExtraPercent := 20;
SynPasSyn1.Typehelpers := true;
{$ENDIF}
end;
end.
|
unit Winapi.ProcessThreadsApi;
{$MINENUMSIZE 4}
interface
uses
Winapi.WinNt, Winapi.WinBase;
const
// WinBase.573
DEBUG_PROCESS = $00000001;
DEBUG_ONLY_THIS_PROCESS = $00000002;
CREATE_SUSPENDED = $00000004;
DETACHED_PROCESS = $00000008;
CREATE_NEW_CONSOLE = $00000010;
CREATE_NEW_PROCESS_GROUP = $00000200;
CREATE_UNICODE_ENVIRONMENT = $00000400;
CREATE_PROTECTED_PROCESS = $00040000;
EXTENDED_STARTUPINFO_PRESENT = $00080000;
CREATE_SECURE_PROCESS = $00400000;
CREATE_BREAKAWAY_FROM_JOB = $01000000;
CREATE_DEFAULT_ERROR_MODE = $04000000;
CREATE_NO_WINDOW = $08000000;
PROFILE_USER = $10000000;
PROFILE_KERNEL = $20000000;
PROFILE_SERVER = $40000000;
CREATE_IGNORE_SYSTEM_DEFAULT = $80000000;
// WinBase.3010
STARTF_USESHOWWINDOW = $00000001;
STARTF_USESIZE = $00000002;
STARTF_USEPOSITION = $00000004;
STARTF_FORCEONFEEDBACK = $00000040;
STARTF_FORCEOFFFEEDBACK = $00000080;
STARTF_USESTDHANDLES = $00000100;
STARTF_UNTRUSTEDSOURCE = $00008000;
// WinBase.3398
PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = $20000;
PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY = $70000;
PROC_THREAD_ATTRIBUTE_CHILD_PROCESS_POLICY = $E0000;
// WinBase.3440, Win 7+
MITIGATION_POLICY_DEP_ENABLE = $01;
MITIGATION_POLICY_DEP_ATL_THUNK_ENABLE = $02;
MITIGATION_POLICY_SEHOP_ENABLE = $04;
// Win 8+
MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON = $100;
MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_OFF = $200;
MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON_REQ_RELOCS = $300;
MITIGATION_POLICY_HEAP_TERMINATE_ALWAYS_ON = $1000;
MITIGATION_POLICY_HEAP_TERMINATE_ALWAYS_OFF = $2000;
MITIGATION_POLICY_BOTTOM_UP_ASLR_ALWAYS_ON = $10000;
MITIGATION_POLICY_BOTTOM_UP_ASLR_ALWAYS_OFF = $20000;
MITIGATION_POLICY_HIGH_ENTROPY_ASLR_ALWAYS_ON = $100000;
MITIGATION_POLICY_HIGH_ENTROPY_ASLR_ALWAYS_OFF = $200000;
MITIGATION_POLICY_STRICT_HANDLE_CHECKS_ALWAYS_ON = $1000000;
MITIGATION_POLICY_STRICT_HANDLE_CHECKS_ALWAYS_OFF = $2000000;
MITIGATION_POLICY_WIN32K_SYSTEM_CALL_DISABLE_ALWAYS_ON = $10000000;
MITIGATION_POLICY_WIN32K_SYSTEM_CALL_DISABLE_ALWAYS_OFF = $20000000;
MITIGATION_POLICY_EXTENSION_POINT_DISABLE_ALWAYS_ON = $100000000;
MITIGATION_POLICY_EXTENSION_POINT_DISABLE_ALWAYS_OFF = $200000000;
MITIGATION_POLICY_EXTENSION_POINT_DISABLE_RESERVED = $300000000;
// WinBlue+
MITIGATION_POLICY_PROHIBIT_DYNAMIC_CODE_ALWAYS_ON = $1000000000;
MITIGATION_POLICY_PROHIBIT_DYNAMIC_CODE_ALWAYS_OFF = $2000000000;
MITIGATION_POLICY_PROHIBIT_DYNAMIC_CODE_ALWAYS_ON_ALLOW_OPT_OUT = $3000000000;
MITIGATION_POLICY_CONTROL_FLOW_GUARD_ALWAYS_ON = $10000000000;
MITIGATION_POLICY_CONTROL_FLOW_GUARD_ALWAYS_OFF = $20000000000;
MITIGATION_POLICY_CONTROL_FLOW_GUARD_EXPORT_SUPPRESSION = $30000000000;
MITIGATION_POLICY_BLOCK_NON_MICROSOFT_BINARIES_ALWAYS_ON = $100000000000;
MITIGATION_POLICY_BLOCK_NON_MICROSOFT_BINARIES_ALWAYS_OFF = $200000000000;
MITIGATION_POLICY_BLOCK_NON_MICROSOFT_BINARIES_ALLOW_STORE = $300000000000;
// Win 10 TH+
MITIGATION_POLICY_FONT_DISABLE_ALWAYS_ON = $1000000000000;
MITIGATION_POLICY_FONT_DISABLE_ALWAYS_OFF = $2000000000000;
MITIGATION_POLICY_AUDIT_NONSYSTEM_FONTS = $3000000000000;
MITIGATION_POLICY_IMAGE_LOAD_NO_REMOTE_ALWAYS_ON = $10000000000000;
MITIGATION_POLICY_IMAGE_LOAD_NO_REMOTE_ALWAYS_OFF = $20000000000000;
MITIGATION_POLICY_IMAGE_LOAD_NO_LOW_LABEL_ALWAYS_ON = $100000000000000;
MITIGATION_POLICY_IMAGE_LOAD_NO_LOW_LABEL_ALWAYS_OFF = $200000000000000;
MITIGATION_POLICY_IMAGE_LOAD_PREFER_SYSTEM32_ALWAYS_ON = $1000000000000000;
MITIGATION_POLICY_IMAGE_LOAD_PREFER_SYSTEM32_ALWAYS_OFF = $2000000000000000;
MITIGATION_POLICY2_LOADER_INTEGRITY_CONTINUITY_ALWAYS_ON = $10;
MITIGATION_POLICY2_LOADER_INTEGRITY_CONTINUITY_ALWAYS_OFF = $20;
MITIGATION_POLICY2_LOADER_INTEGRITY_CONTINUITY_AUDIT = $30;
MITIGATION_POLICY2_STRICT_CONTROL_FLOW_GUARD_ALWAYS_ON = $100;
MITIGATION_POLICY2_STRICT_CONTROL_FLOW_GUARD_ALWAYS_OFF = $200;
MITIGATION_POLICY2_MODULE_TAMPERING_PROTECTION_ALWAYS_ON = $1000;
MITIGATION_POLICY2_MODULE_TAMPERING_PROTECTION_ALWAYS_OFF = $2000;
MITIGATION_POLICY2_MODULE_TAMPERING_PROTECTION_NOINHERIT = $3000;
MITIGATION_POLICY2_RESTRICT_INDIRECT_BRANCH_PREDICTION_ALWAYS_ON = $10000;
MITIGATION_POLICY2_RESTRICT_INDIRECT_BRANCH_PREDICTION_ALWAYS_OFF = $20000;
MITIGATION_POLICY2_ALLOW_DOWNGRADE_DYNAMIC_CODE_POLICY_ALWAYS_ON = $100000;
MITIGATION_POLICY2_ALLOW_DOWNGRADE_DYNAMIC_CODE_POLICY_ALWAYS_OFF = $200000;
MITIGATION_POLICY2_SPECULATIVE_STORE_BYPASS_DISABLE_ALWAYS_ON = $1000000;
MITIGATION_POLICY2_SPECULATIVE_STORE_BYPASS_DISABLE_ALWAYS_OFF = $2000000;
// WinBase.3690, Win 10 TH+
PROCESS_CREATION_CHILD_PROCESS_RESTRICTED = $01;
PROCESS_CREATION_CHILD_PROCESS_OVERRIDE = $02;
PROCESS_CREATION_CHILD_PROCESS_RESTRICTED_UNLESS_SECURE = $04;
// WinBase.7268
LOGON_WITH_PROFILE = $00000001;
LOGON_NETCREDENTIALS_ONLY = $00000002;
LOGON_ZERO_PASSWORD_BUFFER = $80000000;
type
// 28
TProcessInformation = record
hProcess: THandle;
hThread: THandle;
dwProcessId: Cardinal;
dwThreadId: Cardinal;
end;
PProcessInformation = ^TProcessInformation;
// 55
TStartupInfoW = record
cb: Cardinal;
lpReserved: PWideChar;
lpDesktop: PWideChar;
lpTitle: PWideChar;
dwX: Cardinal;
dwY: Cardinal;
dwXSize: Cardinal;
dwYSize: Cardinal;
dwXCountChars: Cardinal;
dwYCountChars: Cardinal;
dwFillAttribute: Cardinal;
dwFlags: Cardinal;
wShowWindow: Word;
cbReserved2: Word;
lpReserved2: PByte;
hStdInput: THandle;
hStdOutput: THandle;
hStdError: THandle;
end;
PStartupInfoW = ^TStartupInfoW;
// 573
PProcThreadAttributeList = Pointer;
// WinBase.3038
TStartupInfoExW = record
StartupInfo: TStartupInfoW;
lpAttributeList: PProcThreadAttributeList;
end;
PStartupInfoExW = ^TStartupInfoExW;
// 377
function CreateProcessW(lpApplicationName: PWideChar;
lpCommandLine: PWideChar; lpProcessAttributes: PSecurityAttributes;
lpThreadAttributes: PSecurityAttributes; bInheritHandles: LongBool;
dwCreationFlags: Cardinal; lpEnvironment: Pointer;
lpCurrentDirectory: PWideChar; const StartupInfo: TStartupInfoExW;
out ProcessInformation: TProcessInformation): LongBool; stdcall;
external kernel32;
// 422
procedure GetStartupInfoW(out StartupInfo: TStartupInfoW); stdcall;
external kernel32;
// 433
function CreateProcessAsUserW(hToken: THandle; lpApplicationName: PWideChar;
lpCommandLine: PWideChar; lpProcessAttributes: PSecurityAttributes;
lpThreadAttributes: PSecurityAttributes; bInheritHandles: LongBool;
dwCreationFlags: Cardinal; lpEnvironment: Pointer;
lpCurrentDirectory: PWideChar; StartupInfo: PStartupInfoExW;
out ProcessInformation: TProcessInformation): LongBool; stdcall;
external advapi32;
// 637
function InitializeProcThreadAttributeList(
lpAttributeList: PProcThreadAttributeList; dwAttributeCount: Cardinal;
dwFlags: Cardinal; var lpSize: NativeUInt): LongBool; stdcall;
external kernel32;
// 648
procedure DeleteProcThreadAttributeList(
lpAttributeList: PProcThreadAttributeList); stdcall; external kernel32;
// 678
function UpdateProcThreadAttribute(
lpAttributeList: PProcThreadAttributeList; dwFlags: Cardinal;
Attribute: NativeUInt; lpValue: Pointer; cbSize: NativeUInt;
lpPreviousValue: Pointer = nil; lpReturnSize: PNativeUInt = nil): LongBool;
stdcall; external kernel32;
// WinBase.7276
function CreateProcessWithLogonW(lpUsername: PWideChar;
lpDomain: PWideChar; lpPassword: PWideChar; dwLogonFlags: Cardinal;
pApplicationName: PWideChar; lpCommandLine: PWideChar;
dwCreationFlags: Cardinal; lpEnvironment: Pointer;
lpCurrentDirectory: PWideChar; StartupInfo: PStartupInfoExW;
out ProcessInformation: TProcessInformation): LongBool; stdcall;
external advapi32;
// WinBase.7293
function CreateProcessWithTokenW(hToken: THandle; dwLogonFlags: Cardinal;
pApplicationName: PWideChar; lpCommandLine: PWideChar;
dwCreationFlags: Cardinal; lpEnvironment: Pointer;
lpCurrentDirectory: PWideChar; StartupInfo: PStartupInfoExW;
out ProcessInformation: TProcessInformation): LongBool; stdcall;
external advapi32;
implementation
end.
|
Unit CustomOutline;
// A minor enhancement to TOutline to remember which node was
// right clicked
// And also, has a SetAndShowSelectedItem method
Interface
Uses
Classes, Forms, OutLine;
{Declare new class}
Type
TCustomOutline=Class(TOutline)
Protected
FPopupNode: TOutlineNode;
Procedure ParentNotification(Var Msg:TMessage);Override;
Public
Procedure SetAndShowSelectedItem( NodeIndex: longint );
Property PopupNode: TOutlineNode read FPopupNode;
End;
Exports
TCustomOutline,'User','CustomOutline.bmp';
Implementation
Uses
PmStdDlg, PmWin;
Procedure TCustomOutline.SetAndShowSelectedItem( NodeIndex: longint );
Begin
SelectedItem:= NodeIndex;
// The only way I can find to actually show the selected node
// if its off screen!!!
// Send a cursor up + cursor down key stroke
if NodeIndex>1 then
begin
SendMsg( Handle,
WM_CHAR,
MPFROM2SHORT( KC_VIRTUALKEY, 0 ),
MPFROM2SHORT( 0, VK_UP ) );
SendMsg( Handle,
WM_CHAR,
MPFROM2SHORT( KC_VIRTUALKEY, 0 ),
MPFROM2SHORT( 0, VK_DOWN ) );
end
else
begin
// selecting root node
if ItemCount>1 then
begin
SendMsg( Handle,
WM_CHAR,
MPFROM2SHORT( KC_VIRTUALKEY, 0 ),
MPFROM2SHORT( 0, VK_DOWN ) );
SendMsg( Handle,
WM_CHAR,
MPFROM2SHORT( KC_VIRTUALKEY, 0 ),
MPFROM2SHORT( 0, VK_UP ) );
end;
end;
// Expand the selected node
SelectedNode.Expand;
End;
Procedure TCustomOutline.ParentNotification(Var Msg:TMessage);
Var
RecordCore:POutlineRecord;
Begin
Case Msg.Param1Hi Of
CN_CONTEXTMENU:
Begin
If Designed Then Exit;
RecordCore := Pointer(Msg.Param2);
If RecordCore = Nil Then Exit;
FPopupNode := RecordCore^.Node;
end;
end; // case
Inherited ParentNotification( Msg );
end;
Initialization
{Register classes}
RegisterClasses([TCustomOutline]);
End.
|
(*
Demonstration of a Parse Query Params Azure Functions App
Written by: Glenn Dufke
Copyright (c) 2021
Version 0.1
License: Apache 2.0
*)
unit DelphiAzure.WebModule;
interface
uses
System.SysUtils,
System.Classes,
Web.HTTPApp;
type
TwmAzureFunction = class(TWebModule)
procedure WebModule1DefaultHandlerAction(Sender: TObject;
Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
private
{ Private declarations }
public
{ Public declarations }
end;
var
WebModuleClass: TComponentClass = TwmAzureFunction;
FunctionRequested: Boolean = False;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
{$R *.dfm}
uses
System.JSON;
procedure TwmAzureFunction.WebModule1DefaultHandlerAction(Sender: TObject;
Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
const
cJSON = 'application/json';
var
LJSONObject: TJSONObject;
begin
LJSONObject := TJSONObject.Create;
try
if Request.PathInfo.Equals('/api/DelphiTrigger') then
begin
if Request.QueryFields.Count = 3 then
begin
LJSONObject.AddPair('PersonName', TJSONString.Create(Request.QueryFields.Values['Name']));
LJSONObject.AddPair('PersonAge', TJSONNumber.Create(Request.QueryFields.Values['Age'].ToDouble));
LJSONObject.AddPair('PersonIsAdult', TJSONBool.Create(Request.QueryFields.Values['Adult'].ToBoolean));
end
else
LJSONObject.AddPair('Error', 'Not enough parameters');
Response.ContentType := cJSON;
Response.Content := LJSONObject.ToJSON;
FunctionRequested := True;
end;
finally
LJSONObject.Free;
end;
end;
end.
|
unit AsyncSoundSynthesizer;
interface
uses
Windows, Messages, SysUtils, Classes, Generics.Collections, WaveStorage,
SoundSynthesizer;
type
TMessageType = (mtSentenceSynthesized, mtThreadEnded);
TAsyncSoundSynthesizer = class(TThread)
private
FHandle: THandle;
FSynthesizer: TSoundSynthesizer;
FText: String;
FVocalizedSentences: TList<TWave>;
FTerminated: Boolean;
private
function GetTerminated: Boolean;
procedure SetTerminated(const Value: Boolean);
public
constructor Create(const AHandle: THandle; const ASynthesizer: TSoundSynthesizer; const AText: String);
destructor Destroy(); override;
procedure Execute(); override;
published
property Terminated: Boolean read GetTerminated write SetTerminated;
end;
implementation
constructor TAsyncSoundSynthesizer.Create(const AHandle: THandle; const ASynthesizer: TSoundSynthesizer; const AText: String);
begin
FHandle := AHandle;
FSynthesizer := ASynthesizer;
FText := AText;
FVocalizedSentences := TList<TWave>.Create;
FTerminated := False;
FreeOnTerminate := True;
inherited Create(False);
end;
destructor TAsyncSoundSynthesizer.Destroy;
begin
inherited;
FreeAndNil(FVocalizedSentences);
end;
procedure TAsyncSoundSynthesizer.Execute;
var
i: Integer;
Sentences: TArray<String>;
begin
Sentences := FSynthesizer.Tokenizer.GetCleanSentences(FText);
for i := Low(Sentences) to High(Sentences) do
begin
if (Terminated) then
begin
break;
end;
FVocalizedSentences.Add(FSynthesizer.VocalizeSentence(Sentences[i]));
PostMessage(FHandle, WM_USER, Cardinal(FVocalizedSentences.Items[i]), Cardinal(mtSentenceSynthesized));
end;
SendMessage(FHandle, WM_USER, 0, Cardinal(mtThreadEnded));
end;
function TAsyncSoundSynthesizer.GetTerminated: Boolean;
begin
Result := FTerminated;
end;
procedure TAsyncSoundSynthesizer.SetTerminated(const Value: Boolean);
begin
FTerminated := Value;
end;
end.
|
unit PascalCoin.Test.Wallet;
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.Controls.Presentation, PascalCoin.Wallet.Interfaces, FMX.Layouts,
FMX.ListBox, FMX.ScrollBox, FMX.Memo, FMX.Edit;
type
TWalletFrame = class(TFrame)
LoadButton: TButton;
ListBox1: TListBox;
Memo1: TMemo;
PastedKeyEdit: TEdit;
KeyCompareLabel: TLabel;
ExportedKeyEdit: TEdit;
ScrollBox1: TScrollBox;
Layout1: TLayout;
StateLabel: TLabel;
procedure ListBox1ItemClick(const Sender: TCustomListBox; const Item:
TListBoxItem);
procedure LoadButtonClick(Sender: TObject);
procedure PastedKeyEditChange(Sender: TObject);
private
FWallet: IWallet;
procedure CompareExports;
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.fmx}
uses PascalCoin.Wallet.Classes,
PascalCoin.RPC.Interfaces, PascalCoin.RPC.Test.DM, Spring.Container;
procedure TWalletFrame.CompareExports;
begin
if (ExportedKeyEdit.Text = '') or (PastedKeyEdit.Text = '') then
begin
KeyCompareLabel.Text := 'nothing to compare';
end;
if (ExportedKeyEdit.Text = PastedKeyEdit.Text) then
KeyCompareLabel.Text := 'the keys are the same'
else
KeyCompareLabel.Text := 'the keys are different';
end;
procedure TWalletFrame.ListBox1ItemClick(const Sender: TCustomListBox; const
Item: TListBoxItem);
var lKey: IWalletKey;
lAPI: IPascalCoinAPI;
lAccounts: IPascalCoinAccounts;
I: Integer;
begin
Memo1.Lines.Clear;
lKey := FWallet[Item.Index];
Memo1.Lines.Add('=== Key Name ===');
Memo1.Lines.Add(lKey.Name);
Memo1.Lines.Add('');
Memo1.Lines.Add('=== Key Type ===');
Memo1.Lines.Add(lKey.PublicKey.KeyTypeAsStr);
Memo1.Lines.Add('');
Memo1.Lines.Add('=== Public As Hex ===');
Memo1.Lines.Add(lKey.PublicKey.AsHexStr);
Memo1.Lines.Add('');
ExportedKeyEdit.Text := lKey.PublicKey.AsBase58;
Memo1.Lines.Add('=== Public As Base58 ===');
Memo1.Lines.Add(ExportedKeyEdit.Text);
lAPI := GlobalContainer.Resolve<IPascalCoinAPI>.URI(DM.URI);
Memo1.Lines.Add('');
try
Memo1.Lines.Add('Number of Accounts: ' + lAPI.getwalletaccountscount(lKey.PublicKey.AsBase58, TKeyStyle.ksB58Key).ToString);
Memo1.Lines.Add('');
lAccounts := lAPI.getwalletaccounts(lKey.PublicKey.AsBase58, TKeyStyle.ksB58Key);
for I := 0 to lAccounts.Count - 1 do
begin
Memo1.Lines.Add(
lAccounts[I].account.ToString + ': ' + lAccounts[I].enc_pubkey);
end;
Except
on e: exception do
Memo1.Lines.Add(e.Message);
end;
CompareExports;
end;
procedure TWalletFrame.LoadButtonClick(Sender: TObject);
const
cState: array[TEncryptionState] of string = ('Plain Text', 'Encrypted', 'Decrypted');
var
I: Integer;
begin
FWallet := Nil;
FWallet := GlobalContainer.Resolve<IWallet>;
ListBox1.Clear;
StateLabel.Text := cState[FWallet.State];
for I := 0 to FWallet.Count -1 do
begin
ListBox1.Items.Add(FWallet[I].Name + ' (' + cState[FWallet[1].State] + ')');
end;
end;
procedure TWalletFrame.PastedKeyEditChange(Sender: TObject);
begin
CompareExports;
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Menus, StdCtrls, ComCtrls, Dropper;
type
TDemoForm = class(TForm)
StatusBar: TStatusBar;
ListBox1: TListBox;
MainMenu: TMainMenu;
FileMenu: TMenuItem;
ClearItem: TMenuItem;
N1: TMenuItem;
ExitItem: TMenuItem;
OptionsMenu: TMenuItem;
AllowDirItem: TMenuItem;
SubFolderItem: TMenuItem;
FileDropper1: TFileDropper;
procedure AllowDirItemClick(Sender: TObject);
procedure OptionsMenuClick(Sender: TObject);
procedure SubFolderItemClick(Sender: TObject);
procedure ExitItemClick(Sender: TObject);
procedure ClearItemClick(Sender: TObject);
procedure FileDropper1Drop(Sender: TObject; Filename: String);
private
{ Private declarations }
public
{ Public declarations }
end;
var
DemoForm: TDemoForm;
implementation
{$R *.DFM}
procedure TDemoForm.AllowDirItemClick(Sender: TObject);
begin
FileDropper1.AllowDir := not FileDropper1.AllowDir;
end;
procedure TDemoForm.OptionsMenuClick(Sender: TObject);
begin
AllowDirItem.Checked := FileDropper1.AllowDir;
SubFolderItem.Checked := FileDropper1.SubFolders;
end;
procedure TDemoForm.SubFolderItemClick(Sender: TObject);
begin
FileDropper1.SubFolders := not FileDropper1.SubFolders;
end;
procedure TDemoForm.ExitItemClick(Sender: TObject);
begin
Application.Terminate;
end;
procedure TDemoForm.ClearItemClick(Sender: TObject);
begin
ListBox1.Clear;
end;
procedure TDemoForm.FileDropper1Drop(Sender: TObject; Filename: String);
begin
ListBox1.Items.Add(Filename);
end;
end.
|
unit uGeraSql_Controller;
interface
uses
uIGeraSql_Interface, Vcl.StdCtrls, System.Classes;
type
TGeraSql = class(TInterfacedObject, IGeraSql)
private
FColunas : TMemo;
FTabela : TMemo;
FCondicoes : TMemo;
public
procedure SetColunas(Colunas: TMemo);
procedure SetTabela(Tabela: TMemo);
procedure SetCondicoes(Condicoes: TMemo);
function GeraSQL : TStringList;
end;
implementation
{ TGeraSql }
uses uspQuery;
function TGeraSql.GeraSQL: TStringList;
var
qryGeraSQL : TspQuery;
spColunas : TStringList;
spTabelas : TStringList;
spCondicoes : TStringList;
begin
qryGeraSQL := TspQuery.Create(nil);
spColunas := TStringList.Create;
spTabelas := TStringList.Create;
spCondicoes := TStringList.Create;
spColunas.AddStrings(FColunas.Lines);
spTabelas.AddStrings(FTabela.Lines);
spCondicoes.AddStrings(FCondicoes.Lines);
qryGeraSQL.spColunas := spColunas;
qryGeraSQL.spTabelas := spTabelas;
qryGeraSQL.spCondicoes := spCondicoes;
Result := qryGeraSQL.GeraSQL;
end;
procedure TGeraSql.SetColunas(Colunas: TMemo);
begin
FColunas := Colunas;
end;
procedure TGeraSql.SetCondicoes(Condicoes: TMemo);
begin
FCondicoes := Condicoes;
end;
procedure TGeraSql.SetTabela(Tabela: TMemo);
begin
FTabela := Tabela;
end;
end.
|
unit UsesClauseInsert;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is UsesClauseInsert.pas, released October 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
{ AFS 2 October 2003
- massage the uses clause. Insert units if they aren't already there
}
uses
{ delphi }
Classes,
{ local }
SourceToken,
SwitchableVisitor;
type
TUsesClauseInsert = class(TSwitchableVisitor)
private
fiCount: integer;
fbDoneInterface, fbDoneImplementation: boolean;
procedure SetDoneSection(const pbInterface: boolean);
procedure AddUses(const pcToken: TSourceToken; const psList: TStrings);
procedure CreateUses(const pcToken: TSourceToken; const pbInterface: boolean);
protected
function EnabledVisitSourceToken(const pcNode: TObject): Boolean; override;
public
constructor Create; override;
function IsIncludedInSettings: boolean; override;
function FinalSummary(out psMessage: string): boolean; override;
end;
implementation
uses
{ delphi }
SysUtils,
{ local }
JcfSettings,
Tokens,
FormatFlags,
ParseTreeNodeType,
ParseTreeNode,
TokenUtils;
constructor TUsesClauseInsert.Create;
begin
inherited;
FormatFlags := FormatFlags + [eFindReplaceUses];
fbDoneInterface := False;
fbDoneImplementation := False;
fiCount := 0;
end;
function TUsesClauseInsert.IsIncludedInSettings: boolean;
begin
Result := (JcfFormatSettings.UsesClause.InsertInterfaceEnabled or
JcfFormatSettings.UsesClause.InsertImplementationEnabled);
end;
function TUsesClauseInsert.EnabledVisitSourceToken(const pcNode: TObject): Boolean;
var
lcSourceToken: TSourceToken;
lbInterface, lbImplementation: boolean;
begin
Result := False;
if pcNode = nil then
exit;
lcSourceToken := TSourceToken(pcNode);
{ end of the unit }
if (lcSourceToken.TokenType = ttDot) and
(lcSourceToken.HasParentNode(TopOfFileSection, 1)) then
begin
// any uses clauses omitted that need to be here?
if ( not fbDoneInterface) and (JcfFormatSettings.UsesClause.InsertInterfaceEnabled) and
(JcfFormatSettings.UsesClause.InsertInterface.Count > 0) then
begin
CreateUses(lcSourceToken, True);
end;
if ( not fbDoneImplementation) and
(JcfFormatSettings.UsesClause.InsertImplementationEnabled) and
(JcfFormatSettings.UsesClause.InsertImplementation.Count > 0) then
begin
CreateUses(lcSourceToken, False);
end;
end;
{ only do this in a uses clause }
if not lcSourceToken.HasParentNode(nUses) then
exit;
lbInterface := lcSourceToken.HasParentNode(nInterfaceSection);
if lbInterface then
lbImplementation := False
else
lbImplementation := lcSourceToken.HasParentNode(nImplementationSection);
if not (lbImplementation or lbInterface) then
exit;
if (lcSourceToken.TokenType = ttSemiColon) then
begin
{ Reached the end - insert the rest }
if lbInterface then
AddUses(lcSourceToken, JcfFormatSettings.UsesClause.InsertInterface)
else
AddUses(lcSourceToken, JcfFormatSettings.UsesClause.InsertImplementation);
SetDoneSection(lbInterface);
end;
end;
function TUsesClauseInsert.FinalSummary(out psMessage: string): boolean;
begin
Result := (fiCount > 0);
if Result then
begin
psMessage := 'Uses clause insertion: ' + IntToStr(fiCount) + ' insertions were made';
end
else
begin
psMessage := '';
end;
end;
procedure TUsesClauseInsert.SetDoneSection(const pbInterface: boolean);
begin
if pbInterface then
fbDoneInterface := True
else
fbDoneImplementation := True;
end;
procedure TUsesClauseInsert.AddUses(const pcToken: TSourceToken; const psList: TStrings);
var
liLoop: integer;
ptNew, ptLast: TSourceToken;
begin
ptLast := pcToken.PriorToken;
for liLoop := 0 to psList.Count - 1 do
begin
ptNew := TSourceToken.Create;
ptNew.TokenType := ttComma;
ptNew.SourceCode := ',';
InsertTokenAfter(ptLast, ptNew);
ptLast := ptNew;
ptNew := TSourceToken.Create;
ptNew.TokenType := ttWord;
ptNew.SourceCode := psList[liLoop];
InsertTokenAfter(ptLast, ptNew);
ptLast := ptNew;
end;
end;
procedure TUsesClauseInsert.CreateUses(const pcToken: TSourceToken;
const pbInterface: boolean);
var
lcRoot, lcSection: TParseTreeNode;
lcKeyWord, lcNew: TSourceToken;
lcInserts: TStrings;
liLoop, liInsertPos: integer;
begin
lcRoot := pcToken.Root;
if pbInterface then
begin
lcSection := lcRoot.GetImmediateChild(nInterfaceSection);
lcInserts := JcfFormatSettings.UsesClause.InsertInterface;
end
else
begin
lcSection := lcRoot.GetImmediateChild(nImplementationSection);
lcInserts := JcfFormatSettings.UsesClause.InsertImplementation;
end;
{ could be a 'program', 'library' or 'package' file with no interface/impl sections }
if lcSection = nil then
exit;
{ find the 'interface' and 'implmentation' section }
lcKeyWord := TSourceToken(lcSection.FirstLeaf);
if pbInterface then
begin
while lcKeyWord.TokenType <> ttInterface do
lcKeyWord := lcKeyWord.NextToken;
end
else
begin
while lcKeyWord.TokenType <> ttImplementation do
lcKeyWord := lcKeyWord.NextToken;
end;
liInsertPos := lcSection.IndexOfChild(lcKeyWord) + 1;
lcNew := NewSpace(1);
lcSection.InsertChild(liInsertPos, lcNew);
Inc(liInsertPos);
lcNew := TSourceToken.Create;
lcNew.FileName := pcToken.FileName;
lcNew.TokenType := ttUses;
lcNew.SourceCode := 'uses';
lcSection.InsertChild(liInsertPos, lcNew);
Inc(liInsertPos);
for liLoop := 0 to lcInserts.Count - 1 do
begin
{ space }
lcNew := NewSpace(1);
lcSection.InsertChild(liInsertPos, lcNew);
Inc(liInsertPos);
{ uses item }
lcNew := TSourceToken.Create;
lcNew.FileName := pcToken.FileName;
lcNew.TokenType := ttIdentifier;
lcNew.SourceCode := lcInserts.Strings[liLoop];
lcSection.InsertChild(liInsertPos, lcNew);
Inc(liInsertPos);
{ , or ;}
lcNew := TSourceToken.Create;
lcNew.FileName := pcToken.FileName;
if liLoop = (lcInserts.Count - 1) then
begin
lcNew.TokenType := ttSemiColon;
lcNew.SourceCode := ';';
end
else
begin
lcNew.TokenType := ttComma;
lcNew.SourceCode := ',';
end;
lcSection.InsertChild(liInsertPos, lcNew);
Inc(liInsertPos);
end;
end;
end.
|
{ Program MAKE_LCASE
*
* One-off hack to create the LCASE.INS.DSPIC dsPIC assembler include file.
* This file creates lower case symbols for all the standard symbols created
* in the Microchip include file. A lower case version of a symbol is only
* created if the upper case version of it previously exists.
*
* The input file is assumed to be "ucase" in the current directory. It
* contains the symbols from the Microchip include file in the case they
* are defined in, one per line. Leading and trailing spaces are allowed.
*
* For each input symbol, if the symbol is not already all lower case
* with the first letter upper case, the appropriate assembler statements
* are written so that such a symbol is created if the symbol with the
* original case already exists.
*
* The output file is "lcase.ins.dspic" and will be written to the
* current directory.
}
program make_lcase;
%include 'base.ins.pas';
var
conn_in, conn_out: file_conn_t; {input and output file connections}
p: string_index_t; {parse index}
ibuf: {one line input buffer}
%include '(cog)lib/string80.ins.pas';
obuf: {one line output buffer}
%include '(cog)lib/string80.ins.pas';
symu, syml: {upper and lower case symbol names}
%include '(cog)lib/string80.ins.pas';
stat: sys_err_t; {completion status}
label
loop_iline, eof;
begin
file_open_read_text ( {open the input file}
string_v('ucase'), '', {file name and suffix}
conn_in, {returned connection to the file}
stat);
sys_error_abort (stat, '', '', nil, 0);
file_open_write_text ( {open the output file}
string_v('lcase.ins.dspic'), '', {file name and suffix}
conn_out, {returned connection to the output file}
stat);
sys_error_abort (stat, '', '', nil, 0);
loop_iline: {back here each new input line}
file_read_text (conn_in, ibuf, stat); {read next line from input file}
if file_eof(stat) then goto eof; {hit end of input file ?}
sys_error_abort (stat, '', '', nil, 0);
string_unpad (ibuf); {strip trailing blanks}
p := 1; {init input line parse index}
string_token (ibuf, p, symu, stat); {extract the input symbol name into SYMU}
if string_eos(stat) then goto loop_iline; {empty line, ignore and go on to next ?}
sys_error_abort (stat, '', '', nil, 0);
string_token (ibuf, p, syml, stat); {try to get another token}
if not string_eos(stat) then begin {not just end of string error ?}
sys_error_abort (stat, '', '', nil, 0);
writeln ('Extra crap on line ', conn_in.lnum);
sys_bomb;
end;
if symu.len <= 0 then goto loop_iline; {empty token, ignore this line ?}
{
* The next input symbol name to process is in SYMU.
}
if symu.str[1] = '_'
then begin {upper case name starts with underscore}
string_substr (symu, 2, symu.len, syml); {extract name after underscore}
end
else begin {no leading underscore}
string_copy (symu, syml); {make lower case version of the symbol}
end
;
string_downcase (syml);
syml.str[1] := string_upcase_char (syml.str[1]); {upcase only the first char}
if string_equal (syml, symu) {desired symbol already exists ?}
then goto loop_iline;
{
* The original symbol name is in SYMU and the all lower case version of it
* is in SYML, and the two are guaranteed to be different.
*
* Now write the assembler directives to create the lower case symbol equal
* to the upper case one if the upper case one already exists. The following
* directives will be written to the output file.
*
* .ifndef <syml>
* .ifdef <symu>
* .equiv <syml>, <symu>
* .endif
* .endif
}
string_vstring (obuf, '.ifndef '(0), -1);
string_append (obuf, syml);
file_write_text (obuf, conn_out, stat); sys_error_abort (stat, '', '', nil, 0);
string_vstring (obuf, ' .ifdef '(0), -1);
string_append (obuf, symu);
file_write_text (obuf, conn_out, stat); sys_error_abort (stat, '', '', nil, 0);
string_vstring (obuf, ' .equiv '(0), -1);
string_append (obuf, syml);
string_appends (obuf, ', '(0));
string_append (obuf, symu);
file_write_text (obuf, conn_out, stat); sys_error_abort (stat, '', '', nil, 0);
string_vstring (obuf, ' .endif'(0), -1);
file_write_text (obuf, conn_out, stat); sys_error_abort (stat, '', '', nil, 0);
string_vstring (obuf, ' .endif'(0), -1);
file_write_text (obuf, conn_out, stat); sys_error_abort (stat, '', '', nil, 0);
goto loop_iline;
{
* end of input file has been encountered.
}
eof:
file_close (conn_in);
file_close (conn_out);
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Androidapi.Log;
interface
(*$HPPEMIT '#include <android/log.h>' *)
{$I Androidapi.inc}
type
android_LogPriority = (
ANDROID_LOG_UNKNOWN,
ANDROID_LOG_DEFAULT,
ANDROID_LOG_VERBOSE,
ANDROID_LOG_DEBUG,
ANDROID_LOG_INFO,
ANDROID_LOG_WARN,
ANDROID_LOG_ERROR,
ANDROID_LOG_FATAL,
ANDROID_LOG_SILENT
);
{$EXTERNALSYM android_LogPriority}
function __android_log_write(Priority: android_LogPriority; const Tag, Text: MarshaledAString): Integer; cdecl;
external AndroidLogLib name '__android_log_write';
{$EXTERNALSYM android_LogPriority}
{ Helper functions }
function LOGI(Text: MarshaledAString): Integer;
function LOGW(Text: MarshaledAString): Integer;
function LOGE(Text: MarshaledAString): Integer;
function LOGF(Text: MarshaledAString): Integer;
implementation
function LOGI(Text: MarshaledAString): Integer;
begin
Result := __android_log_write(android_LogPriority.ANDROID_LOG_INFO, 'info', Text);
end;
function LOGW(Text: MarshaledAString): Integer;
begin
Result := __android_log_write(android_LogPriority.ANDROID_LOG_WARN, 'warning', Text);
end;
function LOGE(Text: MarshaledAString): Integer;
begin
Result := __android_log_write(android_LogPriority.ANDROID_LOG_ERROR, 'error', Text);
end;
function LOGF(Text: MarshaledAString): Integer;
begin
Result := __android_log_write(android_LogPriority.ANDROID_LOG_FATAL, 'fatal', Text);
end;
end.
|
unit cItemDePedido;
interface
type
ItemDePedido = class (TObject)
protected
codItemPed : integer;
qtdUnitItemPed : integer;
qtdPesoItemPed : real;
valPagItemPed : real;
public
Constructor Create (codItemPed:integer; qtdUnitItemPed:integer; qtdPesoItemPed:real;valPagItemPed:real);
Procedure setcodItemPed(codItemPed:integer);
Function getcodItemPed:integer;
Procedure setqtdUnitItemPed(qtdUnitItemPed:integer);
Function getqtdUnitItemPed:integer;
Procedure setqtdPesoItemPed(qtdPesoItemPed:real);
Function getqtdPesoItemPed:real;
Procedure setvalPagItemPed(valPagItemPed:real);
Function getvalPagItemPed:real;
end;
implementation
Constructor ItemDePedido.Create(codItemPed:integer; qtdUnitItemPed:integer; qtdPesoItemPed:real; valPagItemPed:real);
begin
self.codItemPed := codItemPed;
self.qtdUnitItemPed := qtdUnitItemPed;
self.qtdPesoItemPed := qtdPesoItemPed;
self.valPagItemPed := valPagItemPed;
end;
Procedure ItemDePedido.setcodItemPed(codItemPed:integer);
begin
self.codItemPed := codItemPed;
end;
Function ItemDePedido.getcodItemPed:integer;
begin
result := codItemPed;
end;
Procedure ItemDePedido.setqtdUnitItemPed(qtdUnitItemPed:integer);
begin
self.qtdUnitItemPed := qtdUnitItemPed;
end;
Function ItemDePedido.getqtdUnitItemPed:integer;
begin
result := qtdUnitItemPed;
end;
Procedure ItemDePedido.setqtdPesoItemPed(qtdPesoItemPed:real);
begin
self.qtdPesoItemPed := qtdPesoItemPed;
end;
Function ItemDePedido.getqtdPesoItemPed:real;
begin
result := qtdPesoItemPed;
end;
Procedure ItemDePedido.setvalPagItemPed(valPagItemPed:real);
begin
self.valPagItemPed := valPagItemPed;
end;
Function ItemDePedido.getvalPagItemPed:real;
begin
result := valPagItemPed;
end;
end.
|
{ Piping data from and to processes
Copyright (C) 1998-2005 Free Software Foundation, Inc.
Author: Frank Heckenbach <frank@pascal.gnu.de>
This file is part of GNU Pascal.
GNU Pascal is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2, or (at your
option) any later version.
GNU Pascal is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Pascal; see the file COPYING. If not, write to the
Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
As a special exception, if you link this file with files compiled
with a GNU compiler to produce an executable, this does not cause
the resulting executable to be covered by the GNU General Public
License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU
General Public License. }
{$gnu-pascal,I-}
{$if __GPC_RELEASE__ < 20030303}
{$error This unit requires GPC release 20030303 or newer.}
{$endif}
{ Keep this consistent with the one in pipesc.c }
{$if defined (MSDOS) or defined (__MINGW32__)}
{$define NOFORK}
{$endif}
unit Pipes;
interface
uses GPC;
const
PipeForking = {$ifdef NOFORK} False {$else} True {$endif};
type
TProcedure = procedure;
PWaitPIDResult = ^TWaitPIDResult;
TWaitPIDResult = (PIDNothing, PIDExited, PIDSignaled, PIDStopped, PIDUnknown);
PPipeProcess = ^TPipeProcess;
TPipeProcess = record
PID : Integer; { Process ID of process forked }
SignalPID: Integer; { Process ID to send the signal to.
Equals PID by default }
OpenPipes: Integer; { Number of pipes to/from the
process, for internal use }
Signal : Integer; { Send this signal (if not 0) to the
process after all pipes have been
closed after some time }
Seconds : Integer; { Wait so many seconds before
sending the signal if the process
has not terminated by itself }
Wait : Boolean; { Wait for the process, even longer
than Seconds seconds, after
sending the signal (if any) }
Result : PWaitPIDResult; { Default nil. If a pointer to a
variable is stored here, its
destination will contain the
information whether the process
terminated by itself, or was
terminated or stopped by a signal,
when waiting after closing the
pipes }
Status : ^Integer; { Default nil. If a pointer to a
variable is stored here, its
destination will contain the exit
status if the process terminated
by itself, or the number of the
signal otherwise, when waiting
after closing the pipes }
end;
var
{ Default values for TPipeProcess records created by Pipe }
DefaultPipeSignal : Integer = 0;
DefaultPipeSeconds: Integer = 0;
DefaultPipeWait : Boolean = True;
{ The procedure Pipe starts a process whose name is given by
ProcessName, with the given parameters (can be Null if no
parameters) and environment, and create pipes from and/or to the
process' standard input/output/error. ProcessName is searched for
in the PATH with FSearchExecutable. Any of ToInputFile,
FromOutputFile and FromStdErrFile can be Null if the corresponding
pipe is not wanted. FromOutputFile and FromStdErrFile may be
identical, in which case standard output and standard error are
redirected to the same pipe. The behaviour of other pairs of files
being identical is undefined, and useless, anyway. The files are
Assigned and Reset or Rewritten as appropriate. Errors are
returned in IOResult. If Process is not Null, a pointer to a
record is stored there, from which the PID of the process created
can be read, and by writing to which the action after all pipes
have been closed can be changed. (The record is automatically
Dispose'd of after all pipes have been closed.) If automatic
waiting is turned off, the caller should get the PID from the
record before it's Dispose'd of, and wait for the process sometime
in order to avoid zombies. If no redirections are performed (i.e.,
all 3 files are Null), the caller should wait for the process with
WaitPipeProcess. When an error occurs, Process is not assigned to,
and the state of the files is undefined, so be sure to check
IOResult before going on.
ChildProc, if not nil, is called in the child process after
forking and redirecting I/O, but before executing the new process.
It can even be called instead of executing a new process
(ProcessName can be empty then).
The procedure even works under Dos, but, of course, in a limited
sense: if ToInputFile is used, the process will not actually be
started until ToInputFile is closed. Signal, Seconds and Wait of
TPipeProcess are ignored, and PID and SignalPID do not contain a
Process ID, but an internal value without any meaning to the
caller. Result will always be PIDExited. So, Status is the only
interesting field (but Result should also be checked). Since there
is no forking under Dos, ChildProc, if not nil, is called in the
main process before spawning the program. So, to be portable, it
should not do any things that would influence the process after
the return of the Pipe function.
The only portable way to use "pipes" in both directions is to call
`Pipe', write all the Input data to ToInputFile, close
ToInputFile, and then read the Output and StdErr data from
FromOutputFile and FromStdErrFile. However, since the capacity of
pipes is limited, one should also check for Data from
FromOutputFile and FromStdErrFile (using CanRead, IOSelect or
IOSelectRead) while writing the Input data (under Dos, there
simply won't be any data then, but checking for data doesn't do
any harm). Please see pipedemo.pas for an example. }
procedure Pipe (var ToInputFile, FromOutputFile, FromStdErrFile: AnyFile; const ProcessName: String; protected var Parameters: TPStrings; ProcessEnvironment: PCStrings; var Process: PPipeProcess; ChildProc: TProcedure); attribute (iocritical);
{ Waits for a process created by Pipe as determined in the Process
record. (Process is Dispose'd of afterwards.) Returns True if
successful. }
function WaitPipeProcess (Process: PPipeProcess): Boolean; attribute (ignorable);
{ Alternative interface from PExecute }
const
PExecute_First = 1;
PExecute_Last = 2;
PExecute_One = PExecute_First or PExecute_Last;
PExecute_Search = 4;
PExecute_Verbose = 8;
{ PExecute: execute a chain of processes.
Program and Arguments are the arguments to execv/execvp.
Flags and PExecute_Search is non-zero if $PATH should be searched.
Flags and PExecute_First is nonzero for the first process in
chain. Flags and PExecute_Last is nonzero for the last process in
chain.
The result is the pid on systems like Unix where we fork/exec and
on systems like MS-Windows and OS2 where we use spawn. It is up to
the caller to wait for the child.
The result is the exit code on systems like MSDOS where we spawn
and wait for the child here.
Upon failure, ErrMsg is set to the text of the error message,
and -1 is returned. `errno' is available to the caller to use.
PWait: cover function for wait.
PID is the process id of the task to wait for. Status is the
`status' argument to wait. Flags is currently unused (allows
future enhancement without breaking upward compatibility). Pass 0
for now.
The result is the process ID of the child reaped, or -1 for
failure.
On systems that don't support waiting for a particular child, PID
is ignored. On systems like MSDOS that don't really multitask
PWait is just a mechanism to provide a consistent interface for
the caller. }
function PExecute (ProgramName: CString; Arguments: PCStrings; var ErrMsg: String; Flags: Integer): Integer; attribute (ignorable);
function PWait (PID: Integer; var Status: Integer; Flags: Integer): Integer; attribute (ignorable);
implementation
{$L pipesc.c}
{$ifndef NOFORK}
type
PCInteger = ^CInteger;
PFileProcess = ^TFileProcess;
TFileProcess = record
FilePtr: PAnyFile;
OldCloseProc: TCloseProc;
ProcessPtr: PPipeProcess
end;
function CPipe (Path: CString; CProcessParameters, ProcessEnvironment: PCStrings; PPipeStdIn, PPipeStdOut, PPipeStdErr: PCInteger; ChildProc: TProcedure): CInteger; external name '_p_CPipe';
function WaitPipeProcess (Process: PPipeProcess): Boolean;
function DoWaitPID (Block: Boolean) = WPID: Integer;
var
Result: TWaitPIDResult;
WStatus: CInteger;
Status: Integer;
begin
WPID := WaitPID (Process^.PID, WStatus, Block);
if WPID <= 0 then
begin
Result := PIDNothing;
Status := 0
end
else if StatusExited (WStatus) then
begin
Result := PIDExited;
Status := StatusExitCode (WStatus)
end
else if StatusSignaled (WStatus) then
begin
Result := PIDSignaled;
Status := StatusTermSignal (WStatus)
end
else if StatusStopped (WStatus) then
begin
Result := PIDStopped;
Status := StatusStopSignal (WStatus)
end
else
begin
Result := PIDUnknown;
Status := 0
end;
if Process^.Result <> nil then Process^.Result^ := Result;
if Process^.Status <> nil then Process^.Status^ := Status
end;
begin
WaitPipeProcess := True;
with Process^ do
begin
while Seconds <> 0 do
begin
if DoWaitPID (False) = PID then
begin
Dispose (Process);
Exit
end;
Sleep (1);
Dec (Seconds)
end;
if Signal <> 0 then Discard (Kill (SignalPID, Signal));
if not Wait or (DoWaitPID (True) <= 0) then
WaitPipeProcess := False
else
Dispose (Process)
end
end;
procedure PipeTFDDClose (var PrivateData);
var
FileProcess: TFileProcess absolute PrivateData;
OpenProc: TOpenProc;
SelectFunc: TSelectFunc;
SelectProc: TSelectProc;
ReadFunc: TReadFunc;
WriteFunc: TWriteFunc;
FlushProc: TFlushProc;
DoneProc: TDoneProc;
FPrivateData: Pointer;
begin
with FileProcess do
begin
GetTFDD (FilePtr^, OpenProc, SelectFunc, SelectProc, ReadFunc, WriteFunc, FlushProc, Null, DoneProc, FPrivateData);
SetTFDD (FilePtr^, OpenProc, SelectFunc, SelectProc, ReadFunc, WriteFunc, FlushProc, OldCloseProc, DoneProc, FPrivateData);
Close (FilePtr^);
Dec (ProcessPtr^.OpenPipes);
if ProcessPtr^.OpenPipes = 0 then Discard (WaitPipeProcess (ProcessPtr))
end;
Dispose (@FileProcess)
end;
procedure SetCloseAction (var f: AnyFile; PProcess: PPipeProcess);
var
p: PFileProcess;
OpenProc: TOpenProc;
SelectFunc: TSelectFunc;
SelectProc: TSelectProc;
ReadFunc: TReadFunc;
WriteFunc: TWriteFunc;
FlushProc: TFlushProc;
DoneProc: TDoneProc;
PrivateData: Pointer;
begin
if InOutRes <> 0 then Exit;
New (p);
p^.FilePtr := @f;
p^.ProcessPtr := PProcess;
Inc (PProcess^.OpenPipes);
GetTFDD (f, OpenProc, SelectFunc, SelectProc, ReadFunc, WriteFunc, FlushProc, p^.OldCloseProc, DoneProc, PrivateData);
SetTFDD (f, OpenProc, SelectFunc, SelectProc, ReadFunc, WriteFunc, FlushProc, PipeTFDDClose, DoneProc, p)
end;
procedure Pipe (var ToInputFile, FromOutputFile, FromStdErrFile: AnyFile; const ProcessName: String; protected var Parameters: TPStrings; ProcessEnvironment: PCStrings; var Process: PPipeProcess; ChildProc: TProcedure);
var
ParameterCount, i: Cardinal;
PipeStdIn, PipeStdOut, PipeStdErr: CInteger;
PPipeStdIn, PPipeStdOut, PPipeStdErr: PCInteger;
PID: Integer;
PProcess: PPipeProcess;
ProcessPath: TString;
begin
if @Process <> nil then Process := nil;
if InOutRes <> 0 then Exit;
if @Parameters = nil then ParameterCount := 0 else ParameterCount := Parameters.Count;
if @ToInputFile = nil then PPipeStdIn := nil else PPipeStdIn := @PipeStdIn;
if @FromOutputFile = nil then PPipeStdOut := nil else PPipeStdOut := @PipeStdOut;
if @FromStdErrFile = nil then PPipeStdErr := nil else
if @FromStdErrFile = @FromOutputFile then PPipeStdErr := @PipeStdOut else PPipeStdErr := @PipeStdErr;
if ProcessName = '' then
ProcessPath := ''
else
ProcessPath := FSearchExecutable (ProcessName, GetEnv (PathEnvVar));
if (ProcessName <> '') and (ProcessPath = '') then
begin
IOErrorCString (EProgramNotFound, ProcessName, False);
Exit
end;
var CProcessParameters: array [0 .. ParameterCount + 1] of CString;
CProcessParameters[0] := ProcessName;
for i := 1 to ParameterCount do CProcessParameters[i] := Parameters[i]^;
CProcessParameters[ParameterCount + 1] := nil;
PID := CPipe (ProcessPath, PCStrings (@CProcessParameters), ProcessEnvironment, PPipeStdIn, PPipeStdOut, PPipeStdErr, ChildProc);
if PID <= 0 then
begin
case PID of
-2: IOErrorCString (EProgramNotExecutable, ProcessName, False);
-3: IOErrorCString (EPipe, ProcessName, True);
-4: IOErrorCString (ECannotFork, ProcessName, True);
-5: InternalError (EExitReturned);
else RuntimeError (EAssert)
end;
Exit
end;
SetReturnAddress (ReturnAddress (0));
New (PProcess);
PProcess^.PID := PID;
PProcess^.SignalPID := PID;
PProcess^.Signal := DefaultPipeSignal;
PProcess^.Seconds := DefaultPipeSeconds;
PProcess^.Wait := DefaultPipeWait;
PProcess^.OpenPipes := 0;
PProcess^.Result := nil;
PProcess^.Status := nil;
if @Process <> nil then Process := PProcess;
if @ToInputFile <> nil then
begin
AssignHandle (ToInputFile, PipeStdIn, True);
Rewrite (ToInputFile);
SetCloseAction (ToInputFile, PProcess)
end;
if @FromOutputFile <> nil then
begin
AssignHandle (FromOutputFile, PipeStdOut, True);
Reset (FromOutputFile);
SetCloseAction (FromOutputFile, PProcess)
end;
if (@FromStdErrFile <> nil) and (@FromStdErrFile <> @FromOutputFile) then
begin
AssignHandle (FromStdErrFile, PipeStdErr, True);
Reset (FromStdErrFile);
SetCloseAction (FromStdErrFile, PProcess)
end;
RestoreReturnAddress
end;
{$else}
{ NOTE: This emulation code is quite a mess! Be warned if you want
to understand it, and don't make any quick changes here unless you
fully understand it. }
function CPipe (Path: CString; CProcessParameters, ProcessEnvironment: PCStrings; NameStdIn, NameStdOut, NameStdErr: CString; ChildProc: TProcedure): CInteger; external name '_p_CPipe';
type
PPipeData = ^TPipeData;
TPipeData = record
ProcName, Path: CString;
ParameterCount: Cardinal;
CProcessParameters, CProcessEnvironment: PCStrings;
NameStdOut, NameStdErr, NameStdIn: TString;
CNameStdOut, CNameStdErr, CNameStdIn: CString;
PToInputFile, PFromOutputFile, PFromStdErrFile: ^AnyFile;
InternalToInputFile: Text;
aChildProc: TProcedure;
PipeProcess: TPipeProcess
end;
PFileProcess = ^TFileProcess;
TFileProcess = record
FilePtr: PAnyFile;
OldCloseProc: TCloseProc;
PipeDataPtr: PPipeData
end;
{ TPipeProcess.PID actually holds the exit status here }
function WaitPipeProcess (Process: PPipeProcess): Boolean;
begin
if Process^.Result <> nil then Process^.Result^ := PIDExited;
if Process^.Status <> nil then Process^.Status^ := Process^.PID;
WaitPipeProcess := Process^.PID >= 0
end;
procedure DoPipe (var PipeData: TPipeData);
var i: Cardinal;
begin
with PipeData do
begin
PipeProcess.PID := CPipe (Path, CProcessParameters, CProcessEnvironment, CNameStdIn, CNameStdOut, CNameStdErr, aChildProc);
PipeProcess.SignalPID := PipeProcess.PID;
if PToInputFile <> nil then Erase (InternalToInputFile);
if PipeProcess.PID < 0 then
if PipeProcess.PID = -2 then
IOErrorCString (EProgramNotExecutable, ProcName, False)
else
IOErrorCString (ECannotSpawn, ProcName, False);
Dispose (ProcName);
Dispose (Path);
for i := 0 to ParameterCount do Dispose (CProcessParameters^[i]);
Dispose (CProcessParameters);
Discard (WaitPipeProcess (@PipeProcess));
if PipeProcess.PID < 0 then Exit;
if PFromOutputFile <> nil then
begin
Reset (PFromOutputFile^, NameStdOut);
Erase (PFromOutputFile^)
end;
if (PFromStdErrFile <> nil) and (PFromStdErrFile <> PFromOutputFile) then
begin
Reset (PFromStdErrFile^, NameStdErr);
Erase (PFromStdErrFile^)
end
end
end;
function PipeInTFDDWrite (var PrivateData; const Buffer; Size: SizeType): SizeType;
var
Data: TPipeData absolute PrivateData;
CharBuffer: array [1 .. Size] of Char absolute Buffer;
begin
with Data do
Write (InternalToInputFile, CharBuffer);
PipeInTFDDWrite := Size
end;
procedure PipeInTFDDClose (var PrivateData);
var Data: TPipeData absolute PrivateData;
begin
with Data do
begin
Close (InternalToInputFile);
if PFromOutputFile <> nil then Close (PFromOutputFile^);
if (PFromStdErrFile <> nil) and (PFromStdErrFile <> PFromOutputFile) then Close (PFromStdErrFile^);
Dec (Data.PipeProcess.OpenPipes);
DoPipe (Data);
Dispose (@Data)
end
end;
procedure PipeOutTFDDClose (var PrivateData);
var
FileProcess: TFileProcess absolute PrivateData;
OpenProc: TOpenProc;
SelectFunc: TSelectFunc;
SelectProc: TSelectProc;
ReadFunc: TReadFunc;
WriteFunc: TWriteFunc;
FlushProc: TFlushProc;
DoneProc: TDoneProc;
FPrivateData: Pointer;
begin
with FileProcess do
begin
GetTFDD (FilePtr^, OpenProc, SelectFunc, SelectProc, ReadFunc, WriteFunc, FlushProc, Null, DoneProc, FPrivateData);
SetTFDD (FilePtr^, OpenProc, SelectFunc, SelectProc, ReadFunc, WriteFunc, FlushProc, OldCloseProc, DoneProc, FPrivateData);
Close (FilePtr^);
Dec (PipeDataPtr^.PipeProcess.OpenPipes);
if PipeDataPtr^.PipeProcess.OpenPipes = 0 then
begin
Discard (WaitPipeProcess (@PipeDataPtr^.PipeProcess));
Dispose (PipeDataPtr)
end
end;
Dispose (@FileProcess)
end;
procedure SetCloseAction (var f: AnyFile; PipeData: PPipeData);
var
p: PFileProcess;
OpenProc: TOpenProc;
SelectFunc: TSelectFunc;
SelectProc: TSelectProc;
ReadFunc: TReadFunc;
WriteFunc: TWriteFunc;
FlushProc: TFlushProc;
DoneProc: TDoneProc;
PrivateData: Pointer;
begin
if InOutRes <> 0 then Exit;
New (p);
p^.FilePtr := @f;
p^.PipeDataPtr := PipeData;
GetTFDD (f, OpenProc, SelectFunc, SelectProc, ReadFunc, WriteFunc, FlushProc, p^.OldCloseProc, DoneProc, PrivateData);
SetTFDD (f, OpenProc, SelectFunc, SelectProc, ReadFunc, WriteFunc, FlushProc, PipeOutTFDDClose, DoneProc, p)
end;
{ The "pipes" that come from the process are reset to nothing until the
process is started. Use a TFDD, not an empty file or the Null device,
so that IOSelect will not select these files. }
procedure ResetNothing (var f: AnyFile);
begin
AssignTFDD (f, nil, nil, nil, nil, nil, nil, nil, nil, nil);
Reset (f)
end;
procedure Pipe (var ToInputFile, FromOutputFile, FromStdErrFile: AnyFile; const ProcessName: String; protected var Parameters: TPStrings; ProcessEnvironment: PCStrings; var Process: PPipeProcess; ChildProc: TProcedure);
var
i: Cardinal;
PipeData: PPipeData;
ProcessPath: TString;
begin
if @Process <> nil then Process := nil;
if ProcessName = '' then
ProcessPath := ''
else
ProcessPath := FSearchExecutable (ProcessName, GetEnv (PathEnvVar));
if (ProcessName <> '') and (ProcessPath = '') then
begin
IOErrorCString (EProgramNotFound, ProcessName, False);
Exit
end;
SetReturnAddress (ReturnAddress (0));
New (PipeData);
with PipeData^ do
begin
aChildProc := ChildProc;
ProcName := NewCString (ProcessName);
Path := NewCString (ProcessPath);
if @Parameters = nil then ParameterCount := 0 else ParameterCount := Parameters.Count;
GetMem (CProcessParameters, (ParameterCount + 2) * SizeOf (CString));
CProcessParameters^[0] := NewCString (ProcessName);
for i := 1 to ParameterCount do CProcessParameters^[i] := NewCString (Parameters[i]^);
CProcessParameters^[ParameterCount + 1] := nil;
CProcessEnvironment := ProcessEnvironment;
PipeProcess.PID := -1;
PipeProcess.SignalPID := -1;
PipeProcess.Signal := DefaultPipeSignal;
PipeProcess.Seconds := DefaultPipeSeconds;
PipeProcess.Wait := DefaultPipeWait;
PipeProcess.OpenPipes := 0;
PipeProcess.Result := nil;
PipeProcess.Status := nil;
if @Process <> nil then Process := @PipeProcess;
PToInputFile := @ToInputFile;
PFromOutputFile := @FromOutputFile;
PFromStdErrFile := @FromStdErrFile;
if @FromOutputFile = nil then
CNameStdOut := nil
else
begin
Inc (PipeProcess.OpenPipes);
NameStdOut := GetTempFileName;
CNameStdOut := NameStdOut;
if @ToInputFile <> nil then ResetNothing (FromOutputFile)
end;
if @FromStdErrFile = nil then
CNameStdErr := nil
else if @FromStdErrFile = @FromOutputFile then
CNameStdErr := CNameStdOut
else
begin
Inc (PipeProcess.OpenPipes);
NameStdErr := GetTempFileName;
CNameStdErr := NameStdErr;
if @ToInputFile <> nil then ResetNothing (FromStdErrFile)
end;
if @ToInputFile = nil then
begin
CNameStdIn := nil;
DoPipe (PipeData^);
if @FromOutputFile <> nil then
SetCloseAction (FromOutputFile, PipeData);
if (@FromStdErrFile <> nil) and (@FromStdErrFile <> @FromOutputFile) then
SetCloseAction (FromStdErrFile, PipeData)
end
else
begin
Inc (PipeProcess.OpenPipes);
NameStdIn := GetTempFileName;
CNameStdIn := NameStdIn;
Rewrite (InternalToInputFile, NameStdIn);
AssignTFDD (ToInputFile, nil, nil, nil, nil, PipeInTFDDWrite, nil, PipeInTFDDClose, nil, PipeData);
Rewrite (ToInputFile)
end
end;
RestoreReturnAddress
end;
{$endif}
{ PExecute }
function PExecuteC (ProgramName: CString; ArgV: PCStrings; This_PName, Temp_Base: CString;
var ErrMsg_Fmt, ErrMsg_Arg: CString; Flags: CInteger): CInteger; external name 'pexecute';
function PWaitC (PID: CInteger; var Status: CInteger; Flags: CInteger): CInteger; external name 'pwait';
function PExecute (ProgramName: CString; Arguments: PCStrings; var ErrMsg: String; Flags: Integer): Integer;
var
ErrMsg_Fmt, ErrMsg_Arg: CString = nil;
i: Integer;
begin
SetReturnAddress (ReturnAddress (0));
PExecute := PExecuteC (ProgramName, Arguments, CParameters^[0],
GetTempDirectory + 'ccXXXXXX', ErrMsg_Fmt, ErrMsg_Arg, Flags);
RestoreReturnAddress;
if ErrMsg_Fmt = nil then
ErrMsg := ''
else
begin
ErrMsg := CString2String (ErrMsg_Fmt);
i := Pos ('%s', ErrMsg);
if (ErrMsg_Arg <> nil) and (i <> 0) then
begin
Delete (ErrMsg, i, 2);
Insert (CString2String (ErrMsg_Arg), ErrMsg, i)
end
end
end;
function PWait (PID: Integer; var Status: Integer; Flags: Integer): Integer;
var CStatus: CInteger;
begin
PWait := PWaitC (PID, CStatus, Flags);
Status := CStatus
end;
end.
|
unit ClassHuman;
interface
uses ClassBoard, ClassLetterBoard, ClassLetters, ClassLetterStack,
ClassPlayer, Classes, ExtCtrls;
type THuman = class( TPlayer )
private
FLtrBoard : TLetterBoard;
procedure OnBoardClick( X, Y : integer );
public
constructor Create( Letters : TLetters; Board : TBoard; LtrBoard : TLetterBoard );
procedure MakeMove( FirstMove : boolean ); override;
function EndMove : boolean; override;
procedure ChangeSomeLetters; override;
end;
implementation
constructor THuman.Create( Letters : TLetters; Board : TBoard; LtrBoard : TLetterBoard );
begin
inherited Create( Letters , Board );
FLtrBoard := LtrBoard;
end;
//==============================================================================
// P R I V A T E
//==============================================================================
procedure THuman.OnBoardClick( X, Y : integer );
var LegalMove : boolean;
I : integer;
J, K, L : integer;
Min : integer;
Ltr : TLetter;
begin
// Take back move
for I := 0 to Length( FLastMove )-1 do
if ((FLastMove[I].X = X) and
(FLastMove[I].Y = Y)) then
begin
FLtrBoard.UnMark;
FLtrBoard.TakeBack( FLastMove[I].Letter );
FBoard.RemoveLetter( FLastMove[I].X , FLastMove[I].Y );
for J := I to Length( FLastMove )-2 do
FLastMove[J] := FLastMove[J+1];
SetLength( FLastMove , Length( FLastMove ) - 1 );
exit;
end;
if (FLtrBoard.Marked.C <> #0) then
begin
if (Length( FLastMove ) = 0) then
LegalMove := true
else
begin
J := 0;
K := 0;
for I := 0 to Length( FLastMove )-1 do
if ((J = 0) and
(K = 0)) then
begin
J := FLastMove[I].X;
K := FLastMove[I].Y;
end
else
if (FLastMove[I].X = J) then
K := 0
else
J := 0;
LegalMove := false;
if (X = J) then
begin
Min := CNumRows;
for I := 0 to Length( FLastMove )-1 do
if (FLastMove[I].Y < Min) then
Min := FLastMove[I].Y;
if (Y < Min) then
Min := Y;
L := Length( FLastMove );
repeat
if ((FBoard.Letters[Min,X].Letter.C = #0) and
(Min <> Y)) then
break;
if ((FBoard.Letters[Min,X].ThisTurn) or
(Min = Y)) then
begin
Dec( L );
if (L = -1) then
begin
LegalMove := true;
break;
end;
end;
Inc( Min );
until (Min > CNumRows);
end;
if (Y = K) then
begin
Min := CNumCols;
for I := 0 to Length( FLastMove )-1 do
if (FLastMove[I].X < Min) then
Min := FLastMove[I].X;
if (X < Min) then
Min := X;
L := Length( FLastMove );
repeat
if ((FBoard.Letters[Y,Min].Letter.C = #0) and
(Min <> X)) then
break;
if ((FBoard.Letters[Y,Min].ThisTurn) or
(Min = X)) then
begin
Dec( L );
if (L = -1) then
begin
LegalMove := true;
break;
end;
end;
Inc( Min );
until (Min > CNumCols);
end;
end;
if (not LegalMove) then
exit;
Ltr := FLtrBoard.Marked;
if (FBoard.AddLetter( X , Y , Ltr )) then
begin
SetLength( FLastMove , Length( FLastMove ) + 1 );
FLastMove[Length( FLastMove )-1].Letter := Ltr;
FLastMove[Length( FLastMove )-1].X := X;
FLastMove[Length( FLastMove )-1].Y := Y;
FLtrStack.PopStack( [FLtrBoard.Marked] );
FLtrBoard.RemoveMarked;
end;
end;
end;
//==============================================================================
// P U B L I C
//==============================================================================
procedure THuman.MakeMove( FirstMove : boolean );
begin
SetLength( FLastMove , 0 );
FBoard.OnClick := OnBoardClick;
end;
function THuman.EndMove : boolean;
var I, Count : integer;
begin
FLtrStack.TakeNew;
FBoard.OnClick := nil;
FBoard.EndMove;
Count := 0;
for I := 1 to 7 do
if (FLtrStack.Stack[I].C <> #0) then
Inc( Count );
if (Count = 0) then
Result := true
else
Result := false;
end;
procedure THuman.ChangeSomeLetters;
begin
FLtrStack.ChangeSomeLetters( FLtrBoard.GetBottomTiles );
end;
end.
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2020-2020 Skybuck Flying
// Copyright (c) 2020-2020 The Delphicoin Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Bitcoin file: src/coins.h
// Bitcoin file: src/coins.cpp
// Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c
unit Unit_TCoinsViewErrorCatcher;
interface
/**
* This is a minimally invasive approach to shutdown on LevelDB read errors from the
* chainstate, while keeping user interface out of the common library, which is shared
* between bitcoind, and bitcoin-qt and non-server tools.
*
* Writes do not need similar protection, as failure to write is handled by the caller.
*/
class CCoinsViewErrorCatcher final : public CCoinsViewBacked
{
public:
explicit CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
void AddReadErrCallback(std::function<void()> f) {
m_err_callbacks.emplace_back(std::move(f));
}
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
private:
/** A list of callbacks to execute upon leveldb read error. */
std::vector<std::function<void()>> m_err_callbacks;
};
implementation
bool CCoinsViewErrorCatcher::GetCoin(const COutPoint &outpoint, Coin &coin) const {
try {
return CCoinsViewBacked::GetCoin(outpoint, coin);
} catch(const std::runtime_error& e) {
for (auto f : m_err_callbacks) {
f();
}
LogPrintf("Error reading from database: %s\n", e.what());
// Starting the shutdown sequence and returning false to the caller would be
// interpreted as 'entry not found' (as opposed to unable to read data), and
// could lead to invalid interpretation. Just exit immediately, as we can't
// continue anyway, and all writes should be atomic.
std::abort();
}
}
end.
|
{ ****************************************************************************** }
{ * ics support * }
{ * written by QQ 600585@qq.com * }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zRasterization * }
{ ****************************************************************************** }
(*
update history
*)
unit CommunicationFramework_Client_ICS;
{$INCLUDE ..\zDefine.inc}
interface
uses Windows, SysUtils, Classes, Messages,
PascalStrings,
OverByteIcsWSocket,
CommunicationFramework_Server_ICSCustomSocket,
CommunicationFramework, CoreClasses, DoStatusIO;
type
TCommunicationFramework_Client_ICS = class;
TICSClient_PeerIO = class(TPeerIO)
public
procedure CreateAfter; override;
destructor Destroy; override;
function Context: TCommunicationFramework_Client_ICS;
function Connected: Boolean; override;
procedure Disconnect; override;
procedure SendByteBuffer(const buff: PByte; const Size: NativeInt); override;
procedure WriteBufferOpen; override;
procedure WriteBufferFlush; override;
procedure WriteBufferClose; override;
function GetPeerIP: SystemString; override;
procedure ContinueResultSend; override;
end;
TClientICSContextIntf = class(TCustomICS)
end;
TCommunicationFramework_Client_ICS = class(TCommunicationFrameworkClient)
protected
FDriver: TClientICSContextIntf;
FClient: TICSClient_PeerIO;
FAsyncConnecting: Boolean;
FOnAsyncConnectNotifyCall: TStateCall;
FOnAsyncConnectNotifyMethod: TStateMethod;
FOnAsyncConnectNotifyProc: TStateProc;
procedure DataAvailable(Sender: TObject; ErrCode: Word);
procedure SessionClosed(Sender: TObject; ErrCode: Word);
procedure SessionConnectedAndCreateContext(Sender: TObject; ErrCode: Word);
procedure AsyncConnect(addr: SystemString; Port: Word; OnResultCall: TStateCall; OnResultMethod: TStateMethod; OnResultProc: TStateProc); overload;
public
constructor Create; override;
destructor Destroy; override;
procedure TriggerDoConnectFailed; override;
procedure TriggerDoConnectFinished; override;
procedure AsyncConnectC(addr: SystemString; Port: Word; OnResult: TStateCall); overload; override;
procedure AsyncConnectM(addr: SystemString; Port: Word; OnResult: TStateMethod); overload; override;
procedure AsyncConnectP(addr: SystemString; Port: Word; OnResult: TStateProc); overload; override;
function Connect(Host, Port: SystemString; AWaitTimeOut: TTimeTick): Boolean; overload;
function Connect(Host, Port: SystemString): Boolean; overload;
function Connect(addr: SystemString; Port: Word): Boolean; overload; override;
procedure Disconnect; override;
function Connected: Boolean; override;
function ClientIO: TPeerIO; override;
procedure TriggerQueueData(v: PQueueData); override;
procedure Progress; override;
end;
implementation
procedure TICSClient_PeerIO.CreateAfter;
begin
inherited CreateAfter;
end;
destructor TICSClient_PeerIO.Destroy;
begin
inherited Destroy;
end;
function TICSClient_PeerIO.Context: TCommunicationFramework_Client_ICS;
begin
Result := IOInterface as TCommunicationFramework_Client_ICS;
end;
function TICSClient_PeerIO.Connected: Boolean;
begin
Result := Context.Connected;
end;
procedure TICSClient_PeerIO.Disconnect;
begin
Context.Disconnect;
end;
procedure TICSClient_PeerIO.SendByteBuffer(const buff: PByte; const Size: NativeInt);
begin
if Connected then
Context.FDriver.Send(buff, Size);
end;
procedure TICSClient_PeerIO.WriteBufferOpen;
begin
end;
procedure TICSClient_PeerIO.WriteBufferFlush;
begin
if Connected then
Context.FDriver.TryToSend;
end;
procedure TICSClient_PeerIO.WriteBufferClose;
begin
end;
function TICSClient_PeerIO.GetPeerIP: SystemString;
begin
Result := Context.FDriver.addr;
end;
procedure TICSClient_PeerIO.ContinueResultSend;
begin
inherited ContinueResultSend;
ProcessAllSendCmd(nil, False, False);
end;
procedure TCommunicationFramework_Client_ICS.DataAvailable(Sender: TObject; ErrCode: Word);
var
BuffCount: Integer;
buff: PByte;
begin
// increment receive
BuffCount := FDriver.RcvdCount;
if BuffCount <= 0 then
BuffCount := 255 * 255;
buff := System.GetMemory(BuffCount);
BuffCount := FDriver.Receive(buff, BuffCount);
if BuffCount > 0 then
begin
try
FClient.SaveReceiveBuffer(buff, BuffCount);
FClient.FillRecvBuffer(nil, False, False);
except
FDriver.Close;
end;
end;
System.FreeMemory(buff);
end;
procedure TCommunicationFramework_Client_ICS.SessionClosed(Sender: TObject; ErrCode: Word);
begin
if FAsyncConnecting then
TriggerDoConnectFailed;
// FClient.Print('client disonnect for %s:%s', [FDriver.addr, FDriver.Port]);
DoDisconnect(FClient);
end;
procedure TCommunicationFramework_Client_ICS.SessionConnectedAndCreateContext(Sender: TObject; ErrCode: Word);
begin
// FClient.Print('client connected %s:%s', [FDriver.addr, FDriver.Port]);
DoConnected(FClient);
end;
procedure TCommunicationFramework_Client_ICS.AsyncConnect(addr: SystemString; Port: Word; OnResultCall: TStateCall; OnResultMethod: TStateMethod; OnResultProc: TStateProc);
begin
Disconnect;
FDriver.OnSessionConnected := SessionConnectedAndCreateContext;
FAsyncConnecting := True;
FOnAsyncConnectNotifyCall := OnResultCall;
FOnAsyncConnectNotifyMethod := OnResultMethod;
FOnAsyncConnectNotifyProc := OnResultProc;
FDriver.Proto := 'tcp';
FDriver.Port := IntToStr(Port);
FDriver.addr := addr;
try
FDriver.Connect;
except
TriggerDoConnectFailed;
end;
end;
constructor TCommunicationFramework_Client_ICS.Create;
begin
inherited Create;
FEnabledAtomicLockAndMultiThread := False;
FDriver := TClientICSContextIntf.Create(nil);
FDriver.MultiThreaded := False;
FDriver.KeepAliveOnOff := TSocketKeepAliveOnOff.wsKeepAliveOnCustom;
FDriver.KeepAliveTime := 1 * 1000;
FDriver.KeepAliveInterval := 1 * 1000;
FDriver.OnDataAvailable := DataAvailable;
FDriver.OnSessionClosed := SessionClosed;
FClient := TICSClient_PeerIO.Create(Self, Self);
FAsyncConnecting := False;
FOnAsyncConnectNotifyCall := nil;
FOnAsyncConnectNotifyMethod := nil;
FOnAsyncConnectNotifyProc := nil;
end;
destructor TCommunicationFramework_Client_ICS.Destroy;
begin
Disconnect;
DisposeObject(FDriver);
DisposeObject(FClient);
inherited Destroy;
end;
procedure TCommunicationFramework_Client_ICS.TriggerDoConnectFailed;
begin
inherited TriggerDoConnectFailed;
try
if Assigned(FOnAsyncConnectNotifyCall) then
FOnAsyncConnectNotifyCall(False);
if Assigned(FOnAsyncConnectNotifyMethod) then
FOnAsyncConnectNotifyMethod(False);
if Assigned(FOnAsyncConnectNotifyProc) then
FOnAsyncConnectNotifyProc(False);
except
end;
FOnAsyncConnectNotifyCall := nil;
FOnAsyncConnectNotifyMethod := nil;
FOnAsyncConnectNotifyProc := nil;
FDriver.OnSessionConnected := nil;
FAsyncConnecting := False;
end;
procedure TCommunicationFramework_Client_ICS.TriggerDoConnectFinished;
begin
inherited TriggerDoConnectFinished;
try
if Assigned(FOnAsyncConnectNotifyCall) then
FOnAsyncConnectNotifyCall(True);
if Assigned(FOnAsyncConnectNotifyMethod) then
FOnAsyncConnectNotifyMethod(True);
if Assigned(FOnAsyncConnectNotifyProc) then
FOnAsyncConnectNotifyProc(True);
except
end;
FOnAsyncConnectNotifyCall := nil;
FOnAsyncConnectNotifyMethod := nil;
FOnAsyncConnectNotifyProc := nil;
FDriver.OnSessionConnected := nil;
FAsyncConnecting := False;
end;
procedure TCommunicationFramework_Client_ICS.AsyncConnectC(addr: SystemString; Port: Word; OnResult: TStateCall);
begin
AsyncConnect(addr, Port, OnResult, nil, nil);
end;
procedure TCommunicationFramework_Client_ICS.AsyncConnectM(addr: SystemString; Port: Word; OnResult: TStateMethod);
begin
AsyncConnect(addr, Port, nil, OnResult, nil);
end;
procedure TCommunicationFramework_Client_ICS.AsyncConnectP(addr: SystemString; Port: Word; OnResult: TStateProc);
begin
AsyncConnect(addr, Port, nil, nil, OnResult);
end;
function TCommunicationFramework_Client_ICS.Connect(Host, Port: SystemString; AWaitTimeOut: TTimeTick): Boolean;
var
AStopTime: TTimeTick;
begin
Disconnect;
FDriver.OnSessionConnected := nil;
FAsyncConnecting := False;
FOnAsyncConnectNotifyCall := nil;
FOnAsyncConnectNotifyMethod := nil;
FOnAsyncConnectNotifyProc := nil;
FDriver.Proto := 'tcp';
FDriver.Port := Port;
FDriver.addr := Host;
try
FDriver.Connect;
except
Result := False;
exit;
end;
AStopTime := GetTimeTick + AWaitTimeOut;
while not(FDriver.State in [wsConnected]) do
begin
Progress;
if (GetTimeTick >= AStopTime) then
Break;
if FDriver.State in [wsClosed] then
Break;
TCoreClassThread.Sleep(1);
end;
Result := FDriver.State in [wsConnected];
if Result then
DoConnected(FClient);
while (not RemoteInited) and (FDriver.State in [wsConnected]) do
begin
Progress;
if (GetTimeTick >= AStopTime) then
begin
FDriver.Close;
Break;
end;
if FDriver.State in [wsClosed] then
Break;
TCoreClassThread.Sleep(1);
end;
Result := (RemoteInited);
if Result then
FClient.Print('client connected %s:%s', [FDriver.addr, FDriver.Port]);
end;
function TCommunicationFramework_Client_ICS.Connect(Host, Port: SystemString): Boolean;
begin
Result := Connect(Host, Port, 5000);
end;
function TCommunicationFramework_Client_ICS.Connect(addr: SystemString; Port: Word): Boolean;
begin
Result := Connect(addr, IntToStr(Port), 5000);
end;
procedure TCommunicationFramework_Client_ICS.Disconnect;
begin
FDriver.Close;
DisposeObject(FClient);
FClient := TICSClient_PeerIO.Create(Self, Self);
end;
function TCommunicationFramework_Client_ICS.Connected: Boolean;
begin
Result := (FDriver.State in [wsConnected]);
end;
function TCommunicationFramework_Client_ICS.ClientIO: TPeerIO;
begin
Result := FClient;
end;
procedure TCommunicationFramework_Client_ICS.TriggerQueueData(v: PQueueData);
begin
if not Connected then
begin
DisposeQueueData(v);
exit;
end;
FClient.PostQueueData(v);
FClient.ProcessAllSendCmd(nil, False, False);
inherited Progress;
end;
procedure TCommunicationFramework_Client_ICS.Progress;
begin
FClient.ProcessAllSendCmd(nil, False, False);
inherited Progress;
try
FDriver.ProcessMessages;
except
end;
end;
initialization
finalization
end.
|
Unit FUNC_Menu_Listados;
interface
uses
FUNC_REG_Pacientes, FUNC_REG_Estadisticas, ARCH_REG_Estadisticas, ARCH_REG_Pacientes;
procedure Menu_Listados(VAR ARCH_Personas: ARCHIVO_Pacientes; VAR ARCH_Estadisticas: ARCHIVO_Estadisticas;
VAR R_Persona: REG_Persona; VAR R_Estadisticas: REG_Estadisticas);
implementation
uses
wincrt, graph, Graph_Graficos,
FUNC_ARCH_REGITROS_PACIENTES_Y_ESTADISTICAS, Funciones_Ordenar, FUNC_REG_Provincias;
procedure Listado_ordenado_alfabeticamente(VAR ARCH_Personas: ARCHIVO_Pacientes; VAR ARCH_Estadisticas: ARCHIVO_Estadisticas;
VAR R_Persona: REG_Persona; VAR R_Estadisticas: REG_Estadisticas);
begin
Abrir_ARCHIVO_pacientes_y_Estadisticas(ARCH_Personas, ARCH_Estadisticas);
if IoResult <> 0 then
begin
Mostrar_MSJ('Error, archivo no encontrado', 'Presione una tecla para volver al menu principal');
Readkey;
Bar(3*15, 16*10, 57*16,16*16);
end
else
begin
insercion_alfabetica_de_nombres_De_Archivos(ARCH_Personas, ARCH_Estadisticas);
Cargar_datos_de_Archivo_pacientes_a_Registro_Paciente_y_Estadisticas_y_Mostrar_datos_de_los_paciente_Activos(ARCH_Personas, ARCH_Estadisticas, R_Persona, R_Estadisticas);
Cerrar_ARCHIVO_pacientes_y_Estadisticas(ARCH_Personas, ARCH_Estadisticas);
end;
end;
procedure Mostrar_Lista_ordenada_alfabeticamente_por_provincia(VAR ARCH_Personas: ARCHIVO_Pacientes; VAR ARCH_Estadisticas: ARCHIVO_Estadisticas;
VAR R_Persona: REG_Persona; VAR R_Estadisticas: REG_Estadisticas);
VAR
Opcion: Char;
Codigo_Provincia: Byte;
begin
Abrir_ARCHIVO_pacientes_y_Estadisticas(ARCH_Personas, ARCH_Estadisticas);
if IoResult <> 0 then
begin
Mostrar_MSJ('Error, archivo no encontrado', 'Presione una tecla para volver al menu principal');
Readkey;
Bar(3*15, 16*10, 57*16,16*16);
end
else
begin
Menu_provincias(Opcion);
Bar((3*16), (15*16), 57*16,(34*16));
Cargo_Codigo(Opcion, Codigo_Provincia);
insercion_alfabetica_de_nombres_De_Archivos(ARCH_Personas, ARCH_Estadisticas);
Cargar_datos_de_Archivo_pacientes_a_Registro_Paciente_y_Estadisticas_y_Mostrar_datos_de_los_paciente_de_una_provincia(ARCH_Personas, ARCH_Estadisticas, R_Persona, R_Estadisticas, Codigo_Provincia);
Cerrar_ARCHIVO_pacientes_y_Estadisticas(ARCH_Personas, ARCH_Estadisticas);
end;
end;
procedure Menu_Listados(VAR ARCH_Personas: ARCHIVO_Pacientes; VAR ARCH_Estadisticas: ARCHIVO_Estadisticas;
VAR R_Persona: REG_Persona; VAR R_Estadisticas: REG_Estadisticas);
Var
opcion: Char;
begin
cleardevice;
Rectangle(3*16,16*2, 43*16,16*7);
SetFillStyle(SolidFill, 92);
bar(3*16+1,16*2+1, 43*16-1,7*16-1);
SetFillStyle(SolidFill, 91);
OutTextXY(4*16, 16*3,'[1]-Listado de pacientes por provincia');
OutTextXY(4*16, 16*4,'[2]-Listado de pacientes de Argentina');
OutTextXY(4*16, 16*5,'[ESC]-Salir');
repeat
opcion:= upcase(readkey);
until ((opcion in ['1','2']) OR (opcion = #27));
CASE opcion OF
'1':
Mostrar_Lista_ordenada_alfabeticamente_por_provincia(ARCH_Personas, ARCH_Estadisticas, R_Persona, R_Estadisticas);
'2':
Listado_ordenado_alfabeticamente(ARCH_Personas, ARCH_Estadisticas, R_Persona, R_Estadisticas);
end;
end;
end. |
unit gParse;
interface
uses
SysUtils
, Classes
;
type
TgTokenClass = Class of TgToken;
EgParseClass = Class Of EgParse;
TgTokenRegistry = class;
TgSymbolString = class(TObject)
strict private
FSourceString: String;
FSourceStringIndex: Integer;
FSourceStringLength: Integer;
FSourceStringLineNumber: Integer;
FLastNewLine: Integer;
FSourceStringName: String;
FSymbolStringExceptionClass: EgParseClass;
function GetSourceStringColumnNumber: Integer;
function GetCurrentChar: Char;
function GetSourceStringName: String;
strict protected
property SymbolStringExceptionClass: EgParseClass read FSymbolStringExceptionClass write FSymbolStringExceptionClass;
public
constructor Create; virtual;
function Copy(AStart, ACount: Integer): string;
procedure Initialize(const AString: String);
procedure NewLine;
function Pos(const AString: String): Integer;
procedure RaiseException(const Msg: String; const Args: Array of Const);
property SourceString: String read FSourceString write FSourceString;
property SourceStringColumnNumber: Integer read GetSourceStringColumnNumber;
property SourceStringIndex: Integer read FSourceStringIndex write FSourceStringIndex;
property SourceStringLength: Integer read FSourceStringLength write FSourceStringLength;
property SourceStringLineNumber: Integer read FSourceStringLineNumber;
property CurrentChar: Char read GetCurrentChar;
property SourceStringName: String read GetSourceStringName write FSourceStringName;
end;
TgToken = class abstract(TObject)
strict private
FOwner: TgSymbolString;
FTokenStringIndex: Integer;
function GetSourceString: String;
function GetSourceStringIndex: Integer;
function GetSourceStringLength: Integer;
function GetSourceStringLineNumber: Integer;
procedure SetSourceStringIndex(const Value: Integer);
strict protected
class function TokenRegistry: TgTokenRegistry; virtual; abstract;
property Owner: TgSymbolString read FOwner;
public
constructor Create(AOwner: TgSymbolString); virtual;
procedure Parse(ASymbolLength: Integer); virtual;
class procedure Register(const ASymbol: String); virtual;
class function ValidSymbol(const ASymbolName: String): Boolean; virtual;
property SourceString: String read GetSourceString;
property SourceStringIndex: Integer read GetSourceStringIndex write SetSourceStringIndex;
property SourceStringLength: Integer read GetSourceStringLength;
property SourceStringLineNumber: Integer read GetSourceStringLineNumber;
End;
TgTokenRegistry = class(TStringList)
strict private
FUnknownTokenClass: TgTokenClass;
protected
function CompareStrings(const S1: string; const S2: string): Integer; override;
public
Constructor Create;
function ClassifyNextSymbol(const AString: String; AStringIndex: Integer; out ASymbol: String): TgTokenClass;
procedure RegisterToken(const ASymbol: String; ATokenClass: TgTokenClass);
property UnknownTokenClass: TgTokenClass read FUnknownTokenClass write FUnknownTokenClass;
End;
EgParse = class(Exception)
end;
implementation
uses
StrUtils
, Math
;
constructor TgSymbolString.Create;
begin
inherited Create;
SymbolStringExceptionClass := EgParse;
FSourceStringLineNumber := 1;
end;
function TgSymbolString.Copy(AStart, ACount: Integer): string;
begin
Result := System.Copy( SourceString, AStart, ACount );
end;
function TgSymbolString.GetSourceStringColumnNumber: Integer;
begin
Result := SourceStringIndex - FLastNewLine;
end;
procedure TgSymbolString.Initialize(const AString: String);
begin
SourceString := AString;
SourceStringIndex := 1;
SourceStringLength := Length( AString );
end;
procedure TgSymbolString.NewLine;
begin
Inc( FSourceStringLineNumber );
FLastNewLine := SourceStringIndex;
end;
function TgSymbolString.Pos(const AString: String): Integer;
begin
Result := PosEx( AString, SourceString, SourceStringIndex );
end;
procedure TgSymbolString.RaiseException(const Msg: String; const Args: Array of Const);
var
AppendString : String;
begin
AppendString := Format( 'On line %d at column %d of %s: ', [SourceStringLineNumber, SourceStringColumnNumber, SourceStringName] );
Raise SymbolStringExceptionClass.CreateFmt( AppendString + Msg, Args );
end;
function TgSymbolString.GetCurrentChar: Char;
begin
Result := FSourceString[FSourceStringIndex];
end;
function TgSymbolString.GetSourceStringName: String;
begin
If FSourceStringName > '' Then
Result := FSourceStringName
Else
Result := '{unknown}';
end;
constructor TgToken.Create(AOwner: TgSymbolString);
begin
Inherited Create;
FOwner := AOwner;
end;
function TgToken.GetSourceString: String;
begin
Result := Owner.SourceString;
end;
function TgToken.GetSourceStringIndex: Integer;
begin
Result := Owner.SourceStringIndex;
end;
function TgToken.GetSourceStringLength: Integer;
begin
Result := Owner.SourceStringLength;
end;
function TgToken.GetSourceStringLineNumber: Integer;
begin
Result := Owner.SourceStringLineNumber;
end;
procedure TgToken.Parse(ASymbolLength: Integer);
begin
FTokenStringIndex := SourceStringIndex;
SourceStringIndex := SourceStringIndex + ASymbolLength;
end;
{ TgToken }
class procedure TgToken.Register(const ASymbol: String);
begin
TokenRegistry.RegisterToken(UpperCase(ASymbol), Self);
end;
procedure TgToken.SetSourceStringIndex(const Value: Integer);
begin
Owner.SourceStringIndex := Value;
end;
class function TgToken.ValidSymbol(const ASymbolName: String): Boolean;
begin
Result := False;
end;
{ TgTokenRegistry }
constructor TgTokenRegistry.Create;
begin
Inherited;
CaseSensitive := False;
Sorted := True;
end;
function TgTokenRegistry.ClassifyNextSymbol(const AString: String; AStringIndex: Integer; out ASymbol: String): TgTokenClass;
Var
CanExit: Boolean;
Counter: Integer;
IsSystem: Boolean;
SymbolLength : Integer;
TempSymbol: string;
TempTokenIndex: Integer;
TokenIndex : Integer;
const
SPseudoSystemObject = 'SYSTEM.';
begin
IsSystem := StartsText( SPseudoSystemObject, Copy(AString, AStringIndex, Length(SPseudoSystemObject)));
If IsSystem Then
AStringIndex := AStringIndex + Length( SPseudoSystemObject );
Counter := 1;
CanExit := False;
Repeat
Repeat
while (AStringIndex+Counter < Length(AString)) and (AString[AStringIndex+Counter-1] in ['a'..'z','_','A'..'Z']) and (AString[AStringIndex+Counter] in ['a'..'z','_','A'..'Z']) do
Inc(Counter);
//Find the closest token
Find(UpperCase(Copy(AString, AStringIndex, Counter)), TokenIndex);
//If Find says we're at the end, then get out
If TokenIndex = Count Then
Begin
CanExit := True;
SymbolLength := 0;
Counter := 0;
Break;
End
Else
Begin
//Grab its symbol
ASymbol := Strings[TokenIndex];
SymbolLength := Length(ASymbol);
//Compare the next symbol in the string with the symbol in the list
Counter := 1;
While (Counter <= SymbolLength) And (UpperCase(AString[AStringIndex + Counter - 1]) = ASymbol[Counter]) Do
Inc(Counter);
//There is no match
If (Counter <= SymbolLength) And (UpperCase(AString[AStringIndex + Counter - 1]) < ASymbol[Counter]) Then
Begin
CanExit := True;
Break;
End;
End;
Until CanExit Or (Counter > SymbolLength);
//If we found a match check one more character
If (Counter > SymbolLength) Then
Begin
If ((AStringIndex + Counter - 1) <= Length(AString)) Then
Begin
Find(Copy(AString, AStringIndex, Counter), TempTokenIndex);
If TempTokenIndex < Count Then
TempSymbol := Strings[TempTokenIndex];
CanExit := (TempTokenIndex = Count) Or Not StartsText(TempSymbol, Copy(AString, AStringIndex, Length(TempSymbol)));
End
Else
CanExit := True;
End;
Until CanExit;
//If we matched the symbol, check one character past the symbol to see if we could be referring to a valid variable name
If Counter > SymbolLength Then
Begin
If (AStringIndex + Counter > Length(AString)) Or Not Assigned(UnknownTokenClass) Or Not UnknownTokenClass.ValidSymbol(Copy(AString, AStringIndex, Counter)) Then
Result := TgTokenClass(Objects[TokenIndex])
Else
Result := UnknownTokenClass;
End
Else
Begin
If Assigned(UnknownTokenClass) Then
Result := UnknownTokenClass
Else
Raise EgParse.CreateFmt('Symbol ''%s'' not found.', [Copy(AString, AStringIndex, 50)]);
End;
If IsSystem Then
ASymbol := 'System.' + ASymbol;
end;
function TgTokenRegistry.CompareStrings(const S1: string; const S2: string): Integer;
begin
If S1 = S2 Then
Result := 0
Else If S1 > S2 Then
Result := 1
Else
Result := -1;
end;
procedure TgTokenRegistry.RegisterToken(const ASymbol: String; ATokenClass: TgTokenClass);
Var
Index : Integer;
begin
Index := IndexOf(ASymbol);
If Index > -1 Then
Objects[Index] := TObject(ATokenClass)
Else
AddObject(UpperCase(ASymbol), TObject(ATokenClass));
end;
end.
|
unit uReservaDao;
interface
uses
FireDAC.Comp.Client, uConexao, uReservaModel, System.SysUtils;
type
TReservaDao = class
private
FConexao: TConexao;
public
constructor Create;
function Incluir(ReservaModel: TReservaModel): Boolean;
function Alterar(ReservaModel: TReservaModel): Boolean;
function Excluir(ReservaModel: TReservaModel): Boolean;
function Obter: TFDQuery;
function ObterSelecionadas(IdUsuario: string): TFDQuery;
end;
implementation
{ TReservaDao }
uses uSistemaControl, uUnidadeModel, uUsuarioModel, Vcl.Dialogs;
constructor TReservaDao.Create;
begin
FConexao := TSistemaControl.GetInstance().Conexao;
end;
function TReservaDao.Alterar(ReservaModel: TReservaModel): Boolean;
var
VQry: TFDQuery;
begin
VQry := FConexao.CriarQuery();
try
VQry.ExecSQL('UPDATE Reserva SET Fim = :fim WHERE (Id_Usuario = :idUsuario AND Id_Livro = :idLivro)', [ReservaModel.Fim, ReservaModel.IdUsuario, ReservaModel.IdLivro]);
Result := True;
finally
VQry.Free;
end;
end;
function TReservaDao.Excluir(ReservaModel: TReservaModel): Boolean;
var
VQry: TFDQuery;
begin
VQry := FConexao.CriarQuery();
try
VQry.ExecSQL('DELETE FROM Reserva WHERE (Id_Usuario = :idUsuario AND Id_Livro = :idLivro)', [ReservaModel.IdUsuario, ReservaModel.IdLivro]);
Result := True;
finally
VQry.Free;
end;
end;
function TReservaDao.Incluir(ReservaModel: TReservaModel): Boolean;
var
VQry: TFDQuery;
begin
VQry := FConexao.CriarQuery();
try
VQry.ExecSQL(' INSERT INTO Reserva VALUES (:inicio, :fim, :idUsuario, :idLivro, :hora) ', [ReservaModel.Inicio, ReservaModel.Fim, ReservaModel.IdUsuario, ReservaModel.IdLivro, ReservaModel.Hora]);
Result := True;
finally
VQry.Free;
end;
end;
function TReservaDao.Obter: TFDQuery;
var
VQry: TFDQuery;
begin
VQry := FConexao.CriarQuery();
VQry.Open(' SELECT * FROM Reserva order by 1 ');
Result := VQry;
end;
function TReservaDao.ObterSelecionadas(IdUsuario: string): TFDQuery;
var
VQry: TFDQuery;
begin
VQry := FConexao.CriarQuery();
VQry.Open(' SELECT r.Id_Livro AS Codigo, l.Titulo FROM Reserva r, Livro l WHERE (r.Id_Usuario = :idUsuario AND r.Id_Livro = l.Codigo) ', [IdUsuario]);
Result := VQry;
end;
end.
|
unit recursion_1;
interface
var G: Int32;
implementation
function FindNumber(StartValue, TargetValue: Int32): Int32;
begin
if StartValue = TargetValue then
Result := -StartValue
else begin
StartValue := StartValue + 1;
Result := FindNumber(StartValue, TargetValue);
end;
end;
procedure Test;
begin
G := FindNumber(0, 100);
end;
initialization
Test();
finalization
Assert(G = -100);
end. |
unit Pizza;
interface
type
TPizza = class
public
function PrepararPizza: string; virtual; abstract;
procedure Entregar;
end;
implementation
{ TPizza }
procedure TPizza.Entregar;
begin
Writeln('Pizza Saiu para entrega!');
end;
end.
|
unit UnitServices;
interface
uses
Windows, WinSvc, UnitFunctions, SysUtils;
function InstallService(ServiceName, DisplayName, FileName, Desc: string;
StartType: integer): Boolean;
implementation
function xStartService(ServiceName: string): Boolean;
var
SCManager: SC_Handle;
Service: SC_Handle;
ARgs: pchar;
begin
Result := False;
SetTokenPrivileges('SeDebugPrivilege');
SCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
try
Service := OpenService(SCManager, PChar(ServiceName), SERVICE_ALL_ACCESS);
Args := nil;
Result := winsvc.StartService(Service, 0, ARgs);
finally
CloseServiceHandle(SCManager);
end;
end;
function EditService(ServiceName, DisplayName, FileName, Desc: string;
StartType: Integer): Boolean;
var
SCManager: SC_Handle;
Service: SC_Handle;
begin
Result := false;
if (Trim(ServiceName) = '') and not FileExists(PChar(Filename)) then Exit;
SetTokenPrivileges('SeDebugPrivilege');
SCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
if SCManager = 0 then Exit;
try
Service := OpenService(SCManager,PChar(ServiceName),SERVICE_CHANGE_CONFIG);
Result := ChangeServiceConfig(Service, SERVICE_NO_CHANGE, StartType,
SERVICE_NO_CHANGE,PChar(FileName), nil, nil, nil, nil, nil, PChar(DisplayName));
if Result = True then
CreateKeyString(HKEY_LOCAL_MACHINE,
'SYSTEM\CurrentControlSet\Services\' + ServiceName,
'Description', Desc);
finally
CloseServiceHandle(SCManager);
end;
end;
function InstallService(ServiceName, DisplayName, FileName, Desc: string;
StartType: integer): Boolean;
var
SCManager: SC_Handle;
begin
Result := false;
if (Trim(ServiceName) = '') and not FileExists(PChar(Filename)) then Exit;
SetTokenPrivileges('SeDebugPrivilege');
SCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
if SCManager = 0 then Exit;
try
Result := CreateService(SCManager, PChar(ServiceName), PChar(DisplayName),
SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, STartType, SERVICE_ERROR_IGNORE, PChar(FileName), nil, nil, nil, nil, nil) <> 0;
if Result = True then
Result := EditService(ServiceName, DisplayName, FileName, Desc, StartType);
if Result = True then xStartService(ServiceName);
finally
CloseServiceHandle(SCManager);
end;
end;
end.
|
unit StringUtil;
interface
uses
SysUtils;
function CustomPad(St: String; Len: Word; Ch: Char; Left: Boolean): String;
function LeftPad(St: String; Len: Word): String;
function Pad(St: String; Len: Word): String;
function LeftPadCh(St: String; Len: Word; Ch: Char): String;
function PadCh(St: String; Len: Word; Ch: Char): String;
function IntLeftPad(I: Integer; Len: Word): String;
function IntPad(I: Integer; Len: Word): String;
function IntLeftPadCh(I: Integer; Len: Word; Ch: Char): String;
function IntPadCh(I: Integer; Len: Word; Ch: Char): String;
function IntZero(I: Integer; Len: Word): String;
function ByteFlagIsSet(Flag: Byte; Mask: Byte): Boolean;
implementation
function ByteFlagIsSet(Flag: Byte; Mask: Byte): Boolean;
begin
Result := ((Flag and Mask) = Mask);
end;
function CustomPad(St: String; Len: Word; Ch: Char; Left: Boolean): String;
begin
Result := St;
if Left then begin
while Length(Result)<Len do Result := Ch + Result;
end else begin
while Length(Result)<Len do Result := Result + Ch;
end;
end;
function LeftPad(St: String; Len: Word): String;
begin
Result := CustomPad(St, Len, ' ', True);
end;
function Pad(St: String; Len: Word): String;
begin
Result := CustomPad(St, Len, ' ', False);
end;
function LeftPadCh(St: String; Len: Word; Ch: Char): String;
begin
Result := CustomPad(St, Len, Ch, True);
end;
function PadCh(St: String; Len: Word; Ch: Char): String;
begin
Result := CustomPad(St, Len, Ch, False);
end;
function IntLeftPad(I: Integer; Len: Word): String;
begin
Result := CustomPad(IntToStr(I), Len, ' ', True);
end;
function IntPad(I: Integer; Len: Word): String;
begin
Result := CustomPad(IntToStr(I), Len, ' ', False);
end;
function IntLeftPadCh(I: Integer; Len: Word; Ch: Char): String;
begin
Result := CustomPad(IntToStr(I), Len, Ch, True);
end;
function IntPadCh(I: Integer; Len: Word; Ch: Char): String;
begin
Result := CustomPad(IntToStr(I), Len, Ch, False);
end;
function IntZero(I: Integer; Len: Word): String;
begin
Result := CustomPad(IntToStr(I), Len, '0', True);
end;
end.
|
(*
Name: keyman32_int
Copyright: Copyright (C) SIL International.
Documentation:
Description:
Create Date: 1 Aug 2006
Modified Date: 17 Aug 2012
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 01 Aug 2006 - mcdurdin - Add GetKeymanInstallPath function
14 Sep 2006 - mcdurdin - Retrieve Debug_Keyman32 path if assigned
18 Mar 2011 - mcdurdin - I2825 - Debug_Keyman32 override not working correctly
03 May 2011 - mcdurdin - I2890 - Record diagnostic data when encountering registry errors
17 Aug 2012 - mcdurdin - I3310 - V9.0 - Unicode in Delphi fixes
*)
unit keyman32_int;
interface
uses Windows, SysUtils, Forms, ErrorControlledRegistry, RegistryKeys; //, util;
function Keyman_Initialise(Handle: HWND; FSingleApp: Boolean): Boolean;
function Keyman_Exit: Boolean;
function Keyman_ForceKeyboard(const s: string): Boolean;
function Keyman_StopForcingKeyboard: Boolean;
implementation
uses DebugPaths, Dialogs, KLog;
type TKeyman_ForceKeyboard = function (s: PAnsiChar): Boolean; stdcall; // I3310
type TKeyman_StopForcingKeyboard = function: Boolean; stdcall;
type TKeyman_Initialise = function(h: THandle; FSingleApp: LongBool): Boolean; stdcall;
type TKeyman_Exit = function: Boolean; stdcall;
var
FInitKeyman: Boolean = False;
FKeyman32Path: string = '';
function GetKeymanInstallPath: string;
var
RootPath: string;
begin
RootPath := '';
with TRegistryErrorControlled.Create do // I2890
try
RootKey := HKEY_LOCAL_MACHINE;
if OpenKeyReadOnly(SRegKey_KeymanEngine) and ValueExists(SRegValue_RootPath) then
RootPath := ReadString(SRegValue_RootPath);
finally
Free;
end;
RootPath := GetDebugPath('Debug_Keyman32Path', RootPath); // I2825
if RootPath = '' then
begin
RootPath := ExtractFilePath(ParamStr(0));
end;
Result := IncludeTrailingPathDelimiter(RootPath);
if not FileExists(Result + 'keyman32.dll') then
raise Exception.Create( 'The executable keyman32.dll could not '+
'be found. You should reinstall.');
end;
function Keyman_Initialise(Handle: HWND; FSingleApp: Boolean): Boolean;
var
hkeyman: THandle;
FLoad: Boolean;
ki: TKeyman_Initialise;
s: string;
begin
Result := False;
FLoad := False;
hkeyman := GetModuleHandle('keyman32.dll');
if hkeyman = 0 then
begin
s := GetKeymanInstallPath;
hkeyman := LoadLibrary(PChar(s+'keyman32.dll'));
if hkeyman = 0 then
begin
KL.LogError('Keyman_Initialise: Unable to load '+s+'keyman32.dll: '+SysErrorMessage(GetLastError));
Exit;
end;
KL.Log('Keyman_Initialise: Loaded keyman32.dll');
FLoad := True;
end
else
KL.Log('Keyman_Initialise: Found keyman32.dll already loaded');
ki := TKeyman_Initialise(GetProcAddress(hkeyman, 'Keyman_Initialise'));
if not Assigned(@ki) then
begin
KL.LogError('Keyman_Initialise: Unable to find Keyman_Initialise in '+s+'keyman32.dll: '+SysErrorMessage(GetLastError));
if FLoad then FreeLibrary(hkeyman);
Exit;
end;
if not ki(Handle, FSingleApp) then
begin
KL.LogError('Keyman_Initialise: Call to Keyman_Initialise in '+s+'keyman32.dll failed: '+SysErrorMessage(GetLastError));
if FLoad then FreeLibrary(hkeyman);
Exit;
end;
KL.Log('Keyman_Initialise: Loaded successfully');
FInitKeyman := True;
Result := True;
end;
function Keyman_Exit: Boolean;
var
hkeyman: THandle;
ke: TKeyman_Exit;
begin
if not FInitKeyman then
begin
Result := True;
Exit;
end;
Result := False;
hkeyman := GetModuleHandle('keyman32.dll');
if hkeyman = 0 then Exit;
ke := TKeyman_Exit(GetProcAddress(hkeyman, 'Keyman_Exit'));
if not Assigned(@ke) then Exit;
if not ke then Exit;
if FInitKeyman then FreeLibrary(hkeyman);
FInitKeyman := False;
Result := True;
end;
function Keyman_ForceKeyboard(const s: string): Boolean;
var
hkeyman: THandle;
fk: TKeyman_ForceKeyboard;
begin
Result := False;
hkeyman := GetModuleHandle('keyman32.dll');
if hkeyman = 0 then
begin
KL.Log('Keyman_ForceKeyboard: Attempting to load keyman32.dll');
if not Keyman_Initialise(Application.MainForm.Handle, True) then
begin
KL.LogError('Keyman_ForceKeyboard: Unable to load keyman32.dll');
Exit;
end;
hkeyman := GetModuleHandle('keyman32.dll');
if hkeyman = 0 then Exit;
end;
fk := TKeyman_ForceKeyboard(GetProcAddress(hkeyman, 'Keyman_ForceKeyboard'));
if(Assigned(@fk)) then
begin
Result := fk(PAnsiChar(AnsiString(s))); // todo: k9: unicode // I3310
if not Result then KL.LogError('Keyman_ForceKeyboard in keyman32.dll failed: '+s)
else KL.Log('Keyman_ForceKeyboard: success');
end
else
KL.LogError('Keyman_ForceKeyboard: failed to find Keyman_ForceKeyboard in keyman32.dll');
end;
function Keyman_StopForcingKeyboard: Boolean;
var
hkeyman: THandle;
sfk: TKeyman_StopForcingKeyboard;
begin
Result := False;
hkeyman := GetModuleHandle('keyman32.dll');
if hkeyman = 0 then Exit;
sfk := TKeyman_StopForcingKeyboard(GetProcAddress(hkeyman, 'Keyman_StopForcingKeyboard'));
if(Assigned(@sfk)) then
Result := sfk;
end;
initialization
finalization
Keyman_Exit;
end.
|
unit func_ccreg_int_all;
interface
implementation
function F(a1: int8;
a2: uint8;
a3: int16;
a4: uint16;
a5: int32;
a6: uint32;
a7: int64;
a8: uint64;
a9: AnsiChar;
a10: Char): Int64; external 'CAT' name 'func_ccreg_int_all';
var G: Int64;
procedure Test;
var
c: AnsiChar = 'A';
begin
G := F(1, 2, 3, 4, 5, 6, 7, 8, C, 'B');
end;
var S: Int64;
initialization
Test();
finalization
s := 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + ord('A') + ord('B');
Assert(G = S);
end. |
unit ncaStrings;
interface
resourcestring
rsTamCodMax6Dig = 'O código gerado automaticamente pelo programa NEX deve no mínimo 2 e no máximo 6 dígitos';
rsRecursoProObsItem = 'A opção de adicionar um complemento/observação ao item é um recurso exclusivo para assinantes do plano PRO';
rsNecessarioFornecedor = 'É necessário informar o Fornecedor';
rsNovaMarca = 'nova marca';
rsCreditoTotal = 'Crédito Total';
rsPersonalizado = 'Personalizado';
rsMes = 'Mês';
rsMigrarFree = 'Migrar para o FREE';
rsConfirmaMigrarFree = 'Deseja realmente migrar para o plano FREE?';
rsSuportePremium = 'Suporte por Telefone, CHAT e Celular até 22hs';
rsUsoEmRede = 'Uso em Rede';
rsNotaFiscal = 'Emissão de Notas Fiscais (NF-e, NFC-e, CFe-SAT)';
rsNaoDefTranspEnt = 'Não definir um entregador ou transportadora';
rsAvancar = 'Avançar';
rsConcluir = 'Concluir';
rsEntregador = 'Entregador';
rsTransportadora = 'Transportadora';
rsSemEnderecos = 'Esse cliente não possui nenhum endereço cadastrado';
rsSemTranspEnt = 'É necessário cadastrar um entregador ou transportadora ou marcar a opção "Não definir entregador/transportadora"';
rsMultiploEndPRO = 'O cadastro de vários endereços para um mesmo cliente é um recurso disponível apenas para os assinantes do plano PRO e PREMIUM.';
rsEndCliGMapsPRO = 'A visualização do endereço do cliente no Mapa é um recurso disponível apenas para os assinantes do plano PRO e PREMIUM.';
rsEndEntregaPRO = 'O controle de entrega é um recurso disponível apenas para os assinantes do plano PRO e PREMIUM.';
rsPrincipal = 'Principal';
rsConfirmaCancelamentoTran = 'Deseja realmente cancelar essa transação?';
rsAbatDeb = 'Abatido de Débito';
rsConfirmaCancelamentoVenda = 'Deseja realmente cancelar essa venda?';
rsCadastreEndLoja =
'Informe o endereço da sua loja para que possa ser montado a rota.';
rsModoResumido = 'Modo Resumido';
rsModoDetalhado = 'Modo Detalhado';
rsProdEstoque = 'Produtos / Estoque';
rsOpcoesVendas = 'Opções para Vendas';
rsOpcoesTranEst = 'Opções para Transações de Estoque';
rsTransacoesEstoque = 'Transações de Estoque';
rsCadastrarIE = 'É necessário informar a Inscrição Estadual (IE) do cliente assinalar a opção de Isento de IE';
rsAcessoNaoAutorizado = 'Seu usuário não tem acesso a essa operação';
rsSemPermissaoAlterar = 'Você não tem permissão para alterar essa informação';
rsSemPermissao = 'O usuário logado no NEX não tem permissão para realizar essa operação';
rsConfirmaExclusao = 'Confirma a exclusão de';
rsConfirmaExcluir = 'Confirma a exclusão de %s?';
rsDescrObrig = 'É necessário informar a descrição (nome do produto)';
rsCodObrig = 'É necessário informar um código para o produto';
rsPrecoObrig = 'É necessário informar o preço de venda do produto';
rsCodRepetido = 'Já existe um produto cadastrado com esse código';
rsItens = 'itens';
rsItem = 'item';
rsEmailObrigatorio = 'É necessário informar o e-mail para o caso do usuário esquecer sua senha';
rsEmailDif = 'E-mails diferentes. O campo de E-mail e Confirmar E-mail devem conter endereços idênticos';
rsConfirmaExclusaoTrib = 'Deseja realmente apagar a taxa';
rsSomenteAdmin = 'Essa operação é restrita a usuários com direito de administrador do programa Nex';
rsConfirmaTribPadrao = 'Definir %s como padrão?';
rsPadrao = 'Padrão';
rsGrupo = 'Grupo';
rsNomeTribNecessario = 'É necessário informar um nome para essa taxa';
rsMarcarTaxa = 'É necessário marcar as taxas que fazem parte desse grupo';
rsInformarPerc = 'É necessário informar o percentual dessa taxa';
rsValor = 'Valor';
rsCaixa = 'Caixa';
rsHora = 'Hora';
rsQtd = 'Qtd';
rsConferirMeioPagto = 'Conferir Meio de Pagamento';
rsEstoque = 'Estoque';
rsNome = 'Nome';
rsBairro = 'Bairro';
rsCidade = 'Cidade';
rsCEP = 'CEP';
rsUF = 'UF';
rsTelefone = 'Telefone';
rsCelular = 'Celular';
rsDocID = 'Num.Ident.';
rsDesconto = 'Desconto';
rsObs = 'Obs';
rsEndereco = 'Endereço';
rsSexo = 'Sexo';
rsTel = 'Telefone';
rsPai = 'Pai';
rsCPF = 'CPF';
rsCNPJ = 'CNPJ';
rsRG = 'RG';
rsIE = 'I.E.';
rsCPF_CNPJ = 'CPF/CNPJ';
rsRG_IE = 'RG/I.E.';
rsFornecedorRepetido = 'Esse fornecedor já está na lista!';
rsFornecedor = 'Fornecedor';
implementation
end.
|
unit IdIdent;
interface
uses Classes, IdAssignedNumbers, IdException, IdTCPClient;
{ 2001 - Feb 12 - J. Peter Mugaas
started this client
This is the Ident client which is based on RFC 1413.
}
const
IdIdentQryTimeout = 60000;
type
EIdIdentException = class(EIdException);
EIdIdentReply = class(EIdIdentException);
EIdIdentInvalidPort = class(EIdIdentReply);
EIdIdentNoUser = class(EIdIdentReply);
EIdIdentHiddenUser = class(EIdIdentReply);
EIdIdentUnknownError = class(EIdIdentReply);
EIdIdentQueryTimeOut = class(EIdIdentReply);
TIdIdent = class(TIdTCPClient)
protected
FQueryTimeOut : Integer;
FReplyString : String;
function GetReplyCharset: String;
function GetReplyOS: String;
function GetReplyOther: String;
function GetReplyUserName: String;
function FetchUserReply : String;
function FetchOS : String;
Procedure ParseError;
public
Constructor Create(AOwner : TComponent); override;
Procedure Query(APortOnServer, APortOnClient : Word);
Property Reply : String read FReplyString;
Property ReplyCharset : String read GetReplyCharset;
Property ReplyOS : String read GetReplyOS;
Property ReplyOther : String read GetReplyOther;
Property ReplyUserName : String read GetReplyUserName;
published
property QueryTimeOut : Integer read FQueryTimeOut write FQueryTimeOut default IdIdentQryTimeout;
Property Port default IdPORT_AUTH;
end;
implementation
uses IdGlobal, IdResourceStrings, SysUtils;
const IdentErrorText : Array[0..3] of string =
('INVALID-PORT', 'NO-USER', 'HIDDEN-USER', 'UNKNOWN-ERROR'); {Do not Localize}
{ TIdIdent }
constructor TIdIdent.Create(AOwner: TComponent);
begin
inherited;
FQueryTimeOut := IdIdentQryTimeout;
Port := IdPORT_AUTH;
end;
function TIdIdent.FetchOS: String;
var Buf : String;
begin
Buf := FetchUserReply;
Result := Trim(Fetch(Buf,':')); {Do not Localize}
end;
function TIdIdent.FetchUserReply: String;
var Buf : String;
begin
Result := ''; {Do not Localize}
Buf := FReplyString;
Fetch(Buf,':'); {Do not Localize}
if UpperCase(Trim(Fetch(Buf,':'))) = 'USERID' then {Do not Localize}
Result := TrimLeft(Buf);
end;
function TIdIdent.GetReplyCharset: String;
var Buf : String;
begin
Buf := FetchOS;
if (Length(Buf) > 0) and (Pos(',',Buf)>0) then {Do not Localize}
begin
Result := Trim(Fetch(Buf,',')); {Do not Localize}
end
else
Result := 'US-ASCII'; {Do not Localize}
end;
function TIdIdent.GetReplyOS: String;
var Buf : String;
begin
Buf := FetchOS;
if Length(Buf) > 0 then
begin
Result := Trim(Fetch(Buf,',')); {Do not Localize}
end
else
Result := ''; {Do not Localize}
end;
function TIdIdent.GetReplyOther: String;
var Buf : String;
begin
if FetchOS = 'OTHER' then {Do not Localize}
begin
Buf := FetchUserReply;
Fetch(Buf,':'); {Do not Localize}
Result := TrimLeft(Buf);
end;
end;
function TIdIdent.GetReplyUserName: String;
var Buf : String;
begin
if FetchOS <> 'OTHER' then {Do not Localize}
begin
Buf := FetchUserReply;
{OS ID}
Fetch(Buf,':'); {Do not Localize}
Result := TrimLeft(Buf);
end;
end;
procedure TIdIdent.ParseError;
var Buf : String;
begin
Buf := FReplyString;
Fetch(Buf,':'); {Do not Localize}
if Trim(Fetch(Buf,':')) = 'ERROR' then {Do not Localize}
begin
case PosInStrArray(UpperCase(Trim(Buf)),IdentErrorText) of
{Invalid Port}
0 : Raise EIdIdentInvalidPort.Create(RSIdentInvalidPort);
{No user}
1 : Raise EIdIdentNoUser.Create(RSIdentNoUser);
{Hidden User}
2 : Raise EIdIdentHiddenUser.Create(RSIdentHiddenUser)
else {Unknwon or other error}
Raise EIdIdentUnknownError.Create(RSIdentUnknownError);
end;
end;
end;
procedure TIdIdent.Query(APortOnServer, APortOnClient: Word);
var RTO : Boolean;
begin
FReplyString := ''; {Do not Localize}
Connect;
try
WriteLn(IntToStr(APortOnServer)+', '+IntToStr(APortOnClient)); {Do not Localize}
FReplyString := ReadLn('',FQueryTimeOut); {Do not Localize}
{We check here and not return an exception at the moment so we can close our
connection before raising our exception if the read timed out}
RTO := ReadLnTimedOut;
finally
Disconnect;
end;
if RTO then
Raise EIdIdentQueryTimeOut.Create(RSIdentReplyTimeout)
else
ParseError;
end;
end.
|
unit Amazon.Interfaces;
interface
type
IAmazonRESTClient = interface
['{E6CD9C73-6C92-4996-AEC3-3EC836629E6D}']
function GetAccept: string;
procedure SetAccept(value: string);
function GetAcceptCharset: string;
procedure SetAcceptCharset(value: string);
function GetUserAgent: string;
procedure SetUserAgent(value:string);
function GetResponseCode: Integer;
function GetResponseText: String;
function GetContent_type: string;
function GetErrorCode: Integer;
procedure SetContent_type(value: string);
function GetErrorMessage: String;
procedure AddHeader(aName, aValue: UTF8String);
procedure Post(aUrl: string; aRequest: UTF8String;
var aResponse: UTF8String);
property ResponseCode: Integer read GetResponseCode;
property ResponseText: string read GetResponseText;
property Content_type: String read GetContent_type write SetContent_type;
property ErrorCode: Integer read GetErrorCode;
property ErrorMessage: String read GetErrorMessage;
property UserAgent: string read GetUserAgent write SetUserAgent;
property AcceptCharset: string read GetAcceptCharset write SetAcceptCharset;
property Accept: string read GetAccept write SetAccept;
end;
IAmazonClient = interface
['{24BF1E03-A208-4F7D-9FC7-875BC33D339F}']
end;
IAmazonMarshaller = interface
['{132F6BC1-8F07-4A2E-B763-02C4CF66008C}']
end;
IAmazonResponse = interface
['{022460F3-2D8A-4784-9207-825242851A12}']
procedure setresponsecode(value: Integer);
procedure setreponsetext(value: UTF8String);
procedure setreponse(value: UTF8String);
function GetResponseCode: Integer;
function getreponsetext: UTF8String;
function getreponse: UTF8String;
property ResponseText: UTF8String read getreponsetext write setreponsetext;
property ResponseCode: Integer read GetResponseCode write setresponsecode;
property Response: UTF8String read getreponse write setreponse;
end;
IAmazonRequest = interface
['{DA029A3F-05C2-4286-BF0B-4FE859AC8A64}']
function getsecret_key: UTF8String;
procedure setsecret_key(value: UTF8String);
function getaccess_key: UTF8String;
procedure setaccess_key(value: UTF8String);
function gettarget: UTF8String;
function gettargetPrefix: UTF8String;
procedure settargetPrefix(value: UTF8String);
function getservice: UTF8String;
procedure setservice(value: UTF8String);
function getregion: UTF8String;
procedure setregion(value: UTF8String);
function gethost: UTF8String;
procedure sethost(value: UTF8String);
function getamz_date: UTF8String;
procedure setamz_date(value: UTF8String);
function getdate_stamp: UTF8String;
procedure setdate_stamp(value: UTF8String);
function getendpoint: UTF8String;
procedure setendpoint(value: UTF8String);
function getoperationName: UTF8String;
procedure setoperationName(value: UTF8String);
function getauthorization_header: UTF8String;
procedure setauthorization_header(value: UTF8String);
function getrequest_parameters: UTF8String;
procedure setrequest_parameters(value: UTF8String);
property secret_key: UTF8String read getsecret_key write setsecret_key;
property access_key: UTF8String read getaccess_key write setaccess_key;
property targetPrefix: UTF8String read gettargetPrefix
write settargetPrefix;
property operationName: UTF8String read getoperationName
write setoperationName;
property service: UTF8String read getservice write setservice;
property region: UTF8String read getregion write setregion;
property host: UTF8String read gethost write sethost;
property endpoint: UTF8String read getendpoint write setendpoint;
property amz_date: UTF8String read getamz_date write setamz_date;
property date_stamp: UTF8String read getdate_stamp write setdate_stamp;
property target: UTF8String read gettarget;
property authorization_header: UTF8String read getauthorization_header
write setauthorization_header;
property request_parameters: UTF8String read getrequest_parameters
write setrequest_parameters;
end;
IAmazonSignature = interface
['{56901E5E-BA6C-49E4-B730-CA58AE7F8DCB}']
function getsignature: UTF8String;
function getauthorization_header: UTF8String;
function GetContent_type: UTF8String;
procedure Sign(aRequest: IAmazonRequest);
property Signature: UTF8String read getsignature;
property authorization_header: UTF8String read getauthorization_header;
end;
implementation
end.
|
unit Vigilante.Compilacao.Observer.Impl;
interface
uses
System.Generics.Collections, Vigilante.Compilacao.Observer,
Vigilante.Compilacao.Model;
type
TCompilacaoSubject = class(TInterfacedObject, ICompilacaoSubject)
private
FList: TList<ICompilacaoObserver>;
public
constructor Create;
destructor Destroy; override;
procedure Adicionar(const ACompilacaoObserver: ICompilacaoObserver);
procedure Notificar(const ACompilacao: ICompilacaoModel);
procedure Remover(const ACompilacaoObserver: ICompilacaoObserver);
end;
implementation
uses
System.SysUtils, System.Threading, System.Classes;
constructor TCompilacaoSubject.Create;
begin
FList := TList<ICompilacaoObserver>.Create;
end;
destructor TCompilacaoSubject.Destroy;
begin
FreeAndNil(FList);
end;
procedure TCompilacaoSubject.Adicionar(const ACompilacaoObserver
: ICompilacaoObserver);
begin
if FList.Contains(ACompilacaoObserver) then
Exit;
FList.Add(ACompilacaoObserver);
end;
procedure TCompilacaoSubject.Notificar(const ACompilacao: ICompilacaoModel);
begin
TParallel.&For(0, Pred(FList.Count),
procedure(i: integer)
begin
TThread.Queue(TThread.CurrentThread,
procedure
begin
FList.Items[i].NovaAtualizacao(ACompilacao);
end);
end);
end;
procedure TCompilacaoSubject.Remover(const ACompilacaoObserver
: ICompilacaoObserver);
begin
if FList.Contains(ACompilacaoObserver) then
FList.Remove(ACompilacaoObserver)
end;
end.
|
unit CachedUpdates;
interface
uses
{$IFDEF FPC}
LResources,
{$ENDIF}
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
DBCtrls, ExtCtrls, Db, Grids, DBGrids, StdCtrls, ToolWin, ComCtrls, Buttons,
{$IFNDEF FPC}
MemDS,
{$ELSE}
MemDataSet,
{$ENDIF}
DBAccess, Uni, UniDacVcl, DemoFrame, UniDacDemoForm;
type
TCachedUpdatesFrame = class(TDemoFrame)
DBGrid: TDBGrid;
DataSource: TDataSource;
UniQuery: TUniQuery;
Panel8: TPanel;
ToolBar: TPanel;
btOpen: TSpeedButton;
btClose: TSpeedButton;
RefreshRecord: TSpeedButton;
DBNavigator: TDBNavigator;
Panel1: TPanel;
Label2: TLabel;
Panel3: TPanel;
btApply: TSpeedButton;
btCommit: TSpeedButton;
btCancel: TSpeedButton;
btRevertRecord: TSpeedButton;
Panel2: TPanel;
cbCachedUpdates: TCheckBox;
cbCustomUpdate: TCheckBox;
Panel4: TPanel;
Label3: TLabel;
Panel5: TPanel;
btStartTrans: TSpeedButton;
btCommitTrans: TSpeedButton;
btRollBackTrans: TSpeedButton;
Panel6: TPanel;
Label1: TLabel;
cbDeleted: TCheckBox;
cbInserted: TCheckBox;
cbModified: TCheckBox;
cbUnmodified: TCheckBox;
Panel7: TPanel;
Label4: TLabel;
edUpdateBatchSize: TEdit;
procedure btOpenClick(Sender: TObject);
procedure btCloseClick(Sender: TObject);
procedure btApplyClick(Sender: TObject);
procedure btCancelClick(Sender: TObject);
procedure btStartTransClick(Sender: TObject);
procedure btCommitTransClick(Sender: TObject);
procedure btRollbackTransClick(Sender: TObject);
procedure cbCachedUpdatesClick(Sender: TObject);
procedure UniQueryUpdateError(DataSet: TDataSet; E: EDatabaseError;
UpdateKind: TUpdateKind; var UpdateAction: TUpdateAction);
procedure UniQueryUpdateRecord(DataSet: TDataSet;
UpdateKind: TUpdateKind; var UpdateAction: TUpdateAction);
procedure cbCustomUpdateClick(Sender: TObject);
procedure UniQueryCalcFields(DataSet: TDataSet);
procedure btCommitClick(Sender: TObject);
procedure cbUnmodifiedClick(Sender: TObject);
procedure cbModifiedClick(Sender: TObject);
procedure cbInsertedClick(Sender: TObject);
procedure cbDeletedClick(Sender: TObject);
procedure DataSourceDataChange(Sender: TObject; Field: TField);
procedure DataSourceStateChange(Sender: TObject);
procedure DBGridDrawDataCell(Sender: TObject; const Rect: TRect;
Field: TField; State: TGridDrawState);
procedure btRevertRecordClick(Sender: TObject);
procedure RefreshRecordClick(Sender: TObject);
private
{ Private declarations }
procedure ShowTrans;
procedure ShowPending;
procedure ShowUpdateRecordTypes;
public
destructor Destroy; override;
// Demo management
procedure Initialize; override;
procedure SetDebug(Value: boolean); override;
end;
implementation
uses
UpdateAction;
{$IFNDEF FPC}
{$IFDEF CLR}
{$R *.nfm}
{$ELSE}
{$R *.dfm}
{$ENDIF}
{$ENDIF}
procedure TCachedUpdatesFrame.ShowTrans;
begin
if UniQuery.Connection .InTransaction then
UniDACForm.StatusBar.Panels[2].Text := 'In Transaction'
else
UniDACForm.StatusBar.Panels[2].Text := '';
end;
procedure TCachedUpdatesFrame.ShowPending;
begin
if UniQuery.UpdatesPending then
UniDACForm.StatusBar.Panels[1].Text := 'Updates Pending'
else
UniDACForm.StatusBar.Panels[1].Text := '';
end;
procedure TCachedUpdatesFrame.ShowUpdateRecordTypes;
begin
if UniQuery.CachedUpdates then begin
cbUnmodified.Checked := rtUnmodified in UniQuery.UpdateRecordTypes;
cbModified.Checked := rtModified in UniQuery.UpdateRecordTypes;
cbInserted.Checked := rtInserted in UniQuery.UpdateRecordTypes;
cbDeleted.Checked := rtDeleted in UniQuery.UpdateRecordTypes;
end;
end;
procedure TCachedUpdatesFrame.btOpenClick(Sender: TObject);
begin
UniQuery.Open;
end;
procedure TCachedUpdatesFrame.btCloseClick(Sender: TObject);
begin
UniQuery.Close;
end;
procedure TCachedUpdatesFrame.btApplyClick(Sender: TObject);
begin
UniQuery.Options.UpdateBatchSize := StrToInt(edUpdateBatchSize.Text);
UniQuery.ApplyUpdates;
ShowPending;
end;
procedure TCachedUpdatesFrame.btCommitClick(Sender: TObject);
begin
UniQuery.CommitUpdates;
ShowPending;
end;
procedure TCachedUpdatesFrame.btCancelClick(Sender: TObject);
begin
UniQuery.CancelUpdates;
ShowPending;
end;
procedure TCachedUpdatesFrame.btStartTransClick(Sender: TObject);
begin
UniQuery.Connection.StartTransaction;
ShowTrans;
end;
procedure TCachedUpdatesFrame.btCommitTransClick(Sender: TObject);
begin
UniQuery.Connection.Commit;
ShowTrans;
end;
procedure TCachedUpdatesFrame.btRollbackTransClick(Sender: TObject);
begin
UniQuery.Connection.Rollback;
ShowTrans;
end;
destructor TCachedUpdatesFrame.Destroy;
begin
FreeAndNil(UpdateActionForm);
inherited;
end;
procedure TCachedUpdatesFrame.cbCachedUpdatesClick(Sender: TObject);
begin
try
UniQuery.CachedUpdates := cbCachedUpdates.Checked;
except
cbCachedUpdates.Checked := UniQuery.CachedUpdates;
raise;
end;
ShowUpdateRecordTypes;
end;
procedure TCachedUpdatesFrame.UniQueryUpdateError(DataSet: TDataSet; E: EDatabaseError;
UpdateKind: TUpdateKind; var UpdateAction: TUpdateAction);
begin
UpdateActionForm.rgAction.ItemIndex := Ord(UpdateAction);
UpdateActionForm.rgKind.ItemIndex := Ord(UpdateKind);
UpdateActionForm.lbField.Caption := String(DataSet.Fields[0].Value);
UpdateActionForm.lbMessage.Caption := E.Message;
UpdateActionForm.ShowModal;
UpdateAction := TUpdateAction(UpdateActionForm.rgAction.ItemIndex);
end;
procedure TCachedUpdatesFrame.UniQueryUpdateRecord(DataSet: TDataSet;
UpdateKind: TUpdateKind; var UpdateAction: TUpdateAction);
begin
UpdateActionForm.rgAction.ItemIndex := Ord(UpdateAction);
UpdateActionForm.rgKind.ItemIndex := Ord(UpdateKind);
UpdateActionForm.lbField.Caption := String(DataSet.Fields[0].NewValue);
UpdateActionForm.lbMessage.Caption := '';
UpdateActionForm.ShowModal;
UpdateAction := TUpdateAction(UpdateActionForm.rgAction.ItemIndex);
end;
procedure TCachedUpdatesFrame.cbCustomUpdateClick(Sender: TObject);
begin
if cbCustomUpdate.Checked then
UniQuery.OnUpdateRecord := UniQueryUpdateRecord
else
UniQuery.OnUpdateRecord := nil;
end;
procedure TCachedUpdatesFrame.UniQueryCalcFields(DataSet: TDataSet);
var
St:string;
begin
case Ord(TCustomUniDataSet(DataSet).UpdateStatus) of
0: St := 'Unmodified';
1: St := 'Modified';
2: St := 'Inserted';
3: St := 'Deleted';
end;
DataSet.FieldByName('Status').AsString := St;
{ case Ord(TUniDataSet(DataSet).UpdateResult) of
0: St := 'Fail';
1: St := 'Abort';
2: St := 'Skip';
3: St := 'Applied';
end;
DataSet.FieldByName('Result').AsString := St;}
end;
procedure TCachedUpdatesFrame.cbUnmodifiedClick(Sender: TObject);
begin
if cbUnmodified.Checked then
UniQuery.UpdateRecordTypes := UniQuery.UpdateRecordTypes + [rtUnmodified]
else
UniQuery.UpdateRecordTypes := UniQuery.UpdateRecordTypes - [rtUnmodified];
end;
procedure TCachedUpdatesFrame.cbModifiedClick(Sender: TObject);
begin
if cbModified.Checked then
UniQuery.UpdateRecordTypes := UniQuery.UpdateRecordTypes + [rtModified]
else
UniQuery.UpdateRecordTypes := UniQuery.UpdateRecordTypes - [rtModified];
end;
procedure TCachedUpdatesFrame.cbInsertedClick(Sender: TObject);
begin
if cbInserted.Checked then
UniQuery.UpdateRecordTypes := UniQuery.UpdateRecordTypes + [rtInserted]
else
UniQuery.UpdateRecordTypes := UniQuery.UpdateRecordTypes - [rtInserted];
end;
procedure TCachedUpdatesFrame.cbDeletedClick(Sender: TObject);
begin
if cbDeleted.Checked then
UniQuery.UpdateRecordTypes := UniQuery.UpdateRecordTypes + [rtDeleted]
else
UniQuery.UpdateRecordTypes := UniQuery.UpdateRecordTypes - [rtDeleted];
end;
procedure TCachedUpdatesFrame.DataSourceStateChange(Sender: TObject);
begin
ShowPending;
UniDACForm.StatusBar.Panels[3].Text := 'Record ' + IntToStr(UniQuery.RecNo) + ' of ' + IntToStr(UniQuery.RecordCount) ;
end;
procedure TCachedUpdatesFrame.DataSourceDataChange(Sender: TObject; Field: TField);
begin
DataSourceStateChange(nil);
end;
procedure TCachedUpdatesFrame.DBGridDrawDataCell(Sender: TObject; const Rect: TRect;
Field: TField; State: TGridDrawState);
begin
{$IFNDEF FPC}
if UniQuery.UpdateResult in [uaFail,uaSkip] then
TDBGrid(Sender).Canvas.Brush.Color := clRed
else
if UniQuery.UpdateStatus <> usUnmodified then
TDBGrid(Sender).Canvas.Brush.Color := clYellow;
TDBGrid(Sender).DefaultDrawDataCell(Rect, Field, State);
{$ENDIF}
end;
procedure TCachedUpdatesFrame.btRevertRecordClick(Sender: TObject);
begin
UniQuery.RevertRecord;
ShowPending;
end;
procedure TCachedUpdatesFrame.RefreshRecordClick(Sender: TObject);
begin
UniQuery.RefreshRecord;
end;
// Demo management
procedure TCachedUpdatesFrame.Initialize;
begin
inherited;
UniQuery.Connection := Connection as TUniConnection;
UpdateActionForm := TUpdateActionForm.Create(nil);
cbCachedUpdates.Checked := UniQuery.CachedUpdates;
ShowUpdateRecordTypes;
end;
procedure TCachedUpdatesFrame.SetDebug(Value: boolean);
begin
UniQuery.Debug := Value;
end;
{$IFDEF FPC}
initialization
{$i CachedUpdates.lrs}
{$ENDIF}
end.
|
//ALGORITHME : triangle_1
//BUT : faire un programme qui fait apparaître un traingle; les bordure du triangle est remplacé par des X et est rempli de O
//ENTREE : les fonctions
//SORTIE: le triangle
//CONSTANTE :
// MAX <== 20
// VAR
// i,j: ENTIER
// DEBUT
// POUR j <- 1 A MAX FAIRE
// DEBUT
// POUR i <- 1 A MAX FAIRE
// DEBUT
// SI i=j ALORS
// ECRIRE("X")
// SINON
// ECRIRE(" ")
// FINSI
// FIN
// ECRIRE
// FINPOUR
// FIN
// FINPOUR
// FIN
PROGRAM TP_triangle;
USES crt,math;
CONST
MAX=10;
VAR
i,j,x: INTEGER;
BEGIN
x:=0;
FOR i:=1 to MAX DO
BEGIN
FOR j:=1 to MAX DO
BEGIN
x:=x+1;
IF (x<i) AND (x>1) then
BEGIN
write('O');
END
ELSE
BEGIN
write(' ');
END;
IF j=1 then
BEGIN
write('X');
END
else
BEGIN
write(' ');
END;
IF i=MAX then
BEGIN
write('X');
END
else
BEGIN
write(' ');
END;
if (i=j) then
BEGIN
write('X'); //permet d'écrire le caractère
END
else
BEGIN
write(' '); //permet de faire les espaces.
END;
END;
writeln;
END;
readln; //permet d'afficher le triangle
END. |
unit Vigilante.Compilacao.Observer;
interface
uses
Vigilante.Compilacao.Model;
type
ICompilacaoObserver = interface(IInterface)
['{E02F4230-5052-4C3F-BC3B-719F9CC620A2}']
procedure NovaAtualizacao(const ACompilacao: ICompilacaoModel);
end;
ICompilacaoSubject = interface(IInterface)
['{7101ECE2-303D-40C5-83A6-52BFD3D92E3E}']
procedure Adicionar(const ACompilacaoObserver: ICompilacaoObserver);
procedure Remover(const ACompilacaoObserver: ICompilacaoObserver);
procedure Notificar(const ACompilacao: ICompilacaoModel);
end;
implementation
end.
|
unit uRedisConfig;
interface
type
TRedisConfig = class
private
FPort: Integer;
FHost: string;
public
property Host: string read FHost write FHost;
property Port: Integer read FPort write FPort;
constructor Create;
end;
implementation
uses
inifiles, System.SysUtils, Vcl.Forms;
{ TRedisConfig }
constructor TRedisConfig.Create;
var
AIni: TIniFile;
begin
AIni := TIniFile.Create(ChangeFileExt(Application.ExeName, '.INI'));
try
FHost := AIni.ReadString('Redis', 'Host', '127.0.0.1');
FPort := AIni.ReadInteger('Redis', 'Port', 6379);
finally
AIni.Free;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.Cloud.CloudAPI;
interface
uses System.Classes,
System.SysUtils,
System.Net.HTTPClient,
System.Net.URLClient,
System.Generics.Collections,
Xml.XMLIntf;
type
TCloudAuthentication = class;
/// <summary>Base connection info class for cloud services</summary>
/// <remarks>Provides account credential information for the cloud service.</remarks>
TCloudConnectionInfo = class(TComponent)
private
[Weak] FAuthentication: TCloudAuthentication;
function IsProtocolStored: Boolean;
procedure SetAccountKey(const AValue: string);
protected
/// <summary>The protocol to use as part of the service URL (http|https)</summary>
FProtocol: string;
/// <summary>The account name used for authentication with the service</summary>
FAccountName: string;
/// <summary>The account key/password used for authenticating the service</summary>
FAccountKey: string;
/// <summary>The proxy host to use for the HTTP requests to the cloud, or empty string to use none</summary>
FRequestProxyHost: string;
/// <summary>The proxy host's port to use for the HTTP requests to the cloud</summary>
FRequestProxyPort: Integer;
/// <summary>True to use the default service URLs, false to use custom ones.</summary>
FUseDefaultEndpoints: Boolean;
/// <summary>Returns the account name used for authentication with the service</summary>
function GetAccountName: string; virtual;
/// <summary>Returns the account key/password used for authenticating the service</summary>
function GetAccountKey: string; virtual;
public
/// <summary>Creates a new instance of this connection info class</summary>
/// <param name="AOwner">The component owner.</param>
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
/// <summary>The protocol to use as part of the service URL (http|https)</summary>
[Stored('IsProtocolStored'), nodefault]
property Protocol: string read FProtocol write FProtocol stored IsProtocolStored;
/// <summary>The account name used for authentication with the service</summary>
property AccountName: string read GetAccountName write FAccountName;
/// <summary>The account key/password used for authenticating the service</summary>
property AccountKey: string read GetAccountKey write SetAccountKey;
/// <summary>The proxy host to use for the HTTP requests to the cloud, or empty string to use none</summary>
property RequestProxyHost: string read FRequestProxyHost write FRequestProxyHost;
/// <summary>The proxy host's port to use for the HTTP requests to the cloud</summary>
[Default(0)]
property RequestProxyPort: Integer read FRequestProxyPort write FRequestProxyPort default 0;
/// <summary>True to use the default service URLs, false to use custom ones.</summary>
[Default(True)]
property UseDefaultEndpoints: Boolean read FUseDefaultEndpoints write FUseDefaultEndpoints default True;
end;
/// <summary>Base class for building a signed Authorization string</summary>
/// <remarks>Subclasses implement the signing algorithm, which is used on the 'StringToSign',
/// and then becomes part of the Authorization String
/// </remarks>
TCloudAuthentication = class abstract
protected
/// <summary>The connection info passed in from the constructor</summary>
[Weak] FConnectionInfo: TCloudConnectionInfo;
/// <summary>The Base64 decoded bytes of the FConnectionInfo.AccountKey</summary>
FSHAKey: TArray<Byte>;
/// <summary>Assigns the algorithm key to use, from the string representation.</summary>
/// <param name="AccountKey">The account key, in string representation.</param>
procedure AssignKey(const AccountKey: string); virtual;
/// <summary>Returns the authorization type to use in the value of the Authorization header</summary>
/// <remarks>If the Authorization header is to look like this:
/// Authorization: SharedKey [AccountName]:[Signature]
/// Then this function should be implemented in a subclass to return "SharedKey"
/// </remarks>
/// <returns>the authorization type to use</returns>
function GetAuthorizationType: string; virtual; abstract;
/// <summary>Signs the given string, for use in authentication with the cloud service</summary>
/// <param name="Signkey">The Key to use for signing</param>
/// <param name="StringToSign">The string to sign</param>
/// <returns>The signed string (as bytes), to use as part of the Authorization header in all requests.</returns>
function SignString(const Signkey: TBytes; const StringToSign: string): TBytes; virtual; abstract;
public
/// <summary>Creates a new instance of TCloudAuthentication with the given connection info.</summary>
// / <param name="ConnectionInfo">The connection info to get the required account info from when building the signed string.</param>
constructor Create(const ConnectionInfo: TCloudConnectionInfo);
destructor Destroy; override;
/// <summary>Builds the string to use as the value of the Authorization header of requests..</summary>
/// <remarks>The 'StringToSign' passed in is encoded using the 'ConnectionInfo' of this class, and the 'SignString' function of the subclass.
/// The result of this is then combined with the result returned by 'GetAuthorizationType' to build the value string to use with the
/// Authorization header of all requests to the cloud.
/// </remarks>
/// <param name="StringToSign">The string to sign and use in the Authorization header value</param>
function BuildAuthorizationString(const StringToSign: string): string; virtual;
end;
/// <summary>Implementation of TCloudAuthentication, specific to the SHA256 algorithm.</summary>
TCloudSHA256Authentication = class(TCloudAuthentication)
private
/// <summary>The AuthorizationType passed in from the Constructor, returned by GetAuthorizationType</summary>
FAuthorizationType: string;
protected
/// <summary>Returns the authorization type to use in the value of the Authorization header</summary>
/// <remarks> Implementation of the abstract function of the base class. Returns the value as specified
/// in the Constructor of this instance.
/// </remarks>
/// <returns>the authorization type to use</returns>
function GetAuthorizationType: string; override;
/// <summary>Signs the given string using the SHA256 algorithm</summary>
/// <param name="Signkey">The Key to use for signing</param>
/// <param name="StringToSign">The string to sign</param>
/// <returns>The SHA256 signed bytes of the given string</returns>
function SignString(const Signkey: TBytes; const StringToSign: string): TBytes; override;
public
/// <summary>Creates SHA256 hash in hex from a string</summary>
/// <param name="HashString">The string to hash</param>
/// <returns>The SHA256 hash in hex</returns>
class function GetHashSHA256Hex( HashString: string): string;
/// <summary>Creates SHA256 hash in hex from a Stream</summary>
/// <param name="content">The stream to hash</param>
/// <returns>The SHA256 hash in hex</returns>
class function GetStreamToHashSHA256Hex(const Content: TStream): string;
/// <summary>Creates a new instance of TCloudSHA256Authentication</summary>
// / <param name="ConnectionInfo">The connection info to use with string signing</param>
// / <param name="AuthorizationType">The authorization type to use</param>
constructor Create(const ConnectionInfo: TCloudConnectionInfo; AuthorizationType: string); overload;
end;
/// <summary>Implementation of TCloudAuthentication, specific to the SHA1 algorithm.</summary>
TCloudSHA1Authentication = class(TCloudAuthentication)
private
/// <summary>The AuthorizationType passed in from the Constructor, returned by GetAuthorizationType</summary>
FAuthorizationType: string;
protected
/// <summary>Returns the authorization type to use in the value of the Authorization header</summary>
/// <remarks> Implementation of the abstract function of the base class. Returns the value as specified
/// in the Constructor of this instance.
/// </remarks>
/// <returns>the authorization type to use</returns>
function GetAuthorizationType: string; override;
/// <summary>Signs the given string using the SHA1 algorithm</summary>
/// <param name="Signkey">The Key to use for signing</param>
/// <param name="StringToSign">The string to sign</param>
/// <returns>The SHA1 signed bytes of the given string</returns>
function SignString(const Signkey: TBytes; const StringToSign: string): TArray<Byte>; override;
public
/// <summary>Creates a new instance of TCloudSHA1Authentication</summary>
// / <param name="ConnectionInfo">The connection info to use with string signing</param>
// / <param name="AuthorizationType">The authorization type to use</param>
constructor Create(ConnectionInfo: TCloudConnectionInfo; AuthorizationType: string); overload;
end;
/// <summary> Provides HTTP client functionality </summary>
TCloudHTTP = class(TComponent)
private
FClient: THTTPClient;
FResponse: IHTTPResponse;
FOnAuthCallback: TCredentialsStorage.TCredentialAuthCallback;
procedure DoValidateServerCertificate(const Sender: TObject;
const ARequest: TURLRequest; const Certificate: TCertificate;
var Accepted: Boolean);
protected
function GetResponseCode: Integer;
function GetResponseText: string;
function GetResponse: IHTTPResponse;
function GetProxyParams: TProxySettings;
procedure SetProxyParams(const Value: TProxySettings);
public
/// <summary> Constructs a new instance of TCloudHTTP. </summary>
constructor Create; reintroduce; overload;
constructor Create(AOwner: TComponent); overload; override;
destructor Destroy; override;
/// <summary> Sends a DELETE command type request. </summary>
/// <param name="AURL">URL where the delete command is sent</param>
/// <returns>The response stream in string form</returns>
function Delete(AURL: string): string; overload;
function Get(AURL: string): string; overload;
/// <summary> Sends a GET command type request. </summary>
/// <param name="AURL">URL where the GET command is sent</param>
/// <param name="AResponseContent">The stream to collect the response in</param>
procedure Get(AURL: string; AResponseContent: TStream); overload;
function Post(AURL: string; Source: TStream): string;
/// <summary> Sends a DELETE command type request. </summary>
/// <param name="AURL">URL where the delete command is sent</param>
/// <param name="AResponseStream">The stream to collect the response in</param>
/// <returns>The response stream in string form</returns>
function Delete(AURL: string; AResponseStream: TStream): string; overload;
/// <summary> Sends a MERGE command type request. </summary>
/// <param name="AURL">URL where the merge command is sent</param>
/// <param name="RequestStream">The stream to send as the body of the request</param>
procedure Merge(AURL: string; RequestStream: TStream);
/// <summary> Sends a OPTIONS command type request. </summary>
/// <param name="AURL">URL where the OPTIONS command is sent</param>
/// <returns>The response string</returns>
function Options(const AURL: string): string; overload;
/// <summary> Sends a OPTIONS command type request. </summary>
/// <param name="AURL">URL where the OPTIONS command is sent</param>
/// <param name="AResponseContent">The stream to collect the response in</param>
/// <returns>The response string</returns>
procedure Options(const AURL: string; AResponseContent: TStream); overload;
/// <summary> Sends a HEAD command type request. </summary>
/// <param name="AURL">URL where the head command is sent</param>
/// <remarks> This TCloudHTTP instance will hold the resulting headers from the request. </remarks>
procedure Head(AURL: string);
/// <summary>PUT command with empty content</summary>
/// <param name="AURL">URL where the put command is sent</param>
/// <param name="Source">Source TStream for put request</param>
/// <returns>The response string</returns>
function Put(AURL: string; Source: TStream): string; overload;
function Put(AURL: string): string; overload;
/// <summary>Uses HTTP standard authentication protocols with the given credentials.</summary>
/// <remarks>This sets the Authorization header of this request,
/// With the properly formatted and encoded user/password pairing provided.
/// </remarks>
/// <param name="AUser">The user name to encode for Authorization</param>
/// <param name="APassword">The password to encode for Authorization</param>
procedure SetAuthentication(const AUser: string; const APassword: string);
property ResponseCode: Integer read GetResponseCode;
property ResponseText: string read GetResponseText;
property Response: IHTTPResponse read GetResponse;
property ProxyParams: TProxySettings read GetProxyParams write SetProxyParams;
/// <summary>Set or Get Credentials Authentication Callback</summary>
property OnAuthCallback: TCredentialsStorage.TCredentialAuthCallback read FOnAuthCallback write FOnAuthCallback;
/// <summary>HTTP client used to provide HTTP functionality</summary>
property Client: THTTPClient read FClient;
end;
/// <summary>Class meant to be populated with useful information from an HTTP response.</summary>
/// <remarks>Cloud Service API calls should be implemented to optionally populated an instance of
/// TCloudResponseInfo. This would then provide a way to see the HTTP response information
/// from the request, such as the status code and message.
/// </remarks>
TCloudResponseInfo = class
protected
/// <summary>The status code of the response</summary>
FStatusCode: Integer;
/// <summary>The status message of the response</summary>
FStatusMessage: string;
/// <summary>The headers of the response</summary>
FHeaders: TStrings;
/// <summary>Sets the list of headers to hold in this instance.</summary>
/// <remarks>This call also frees the previous header list</remarks>
/// <param name="NewHeaders">The new header list to use</param>
procedure SetHeaders(NewHeaders: TStrings);
public
/// <summary>Destroys the current instance and frees the headers.</summary>
destructor Destroy; override;
/// <summary>Copy the content of ASource into this instace</summary>
procedure Assign(const ASource: TObject);
/// <summary>The status code of the response</summary>
property StatusCode: Integer read FStatusCode write FStatusCode;
/// <summary>The status message of the response</summary>
property StatusMessage: string read FStatusMessage write FStatusMessage;
/// <summary>The headers of the response</summary>
property Headers: TStrings read FHeaders write SetHeaders;
end;
/// <summary>Represents a single cell of a cloud table service table.</summary>
/// <remarks>Some cloud table services don't support data types for columns,
/// and require all data to be strings. In these cases, DataType
/// will be empty.
/// </remarks>
TCloudTableColumn = class
protected
/// <summary>The name of the cell's column</summary>
FName: string;
/// <summary>The value held within the cell</summary>
FValue: string;
/// <summary>The name of the cell's datatype.</summary>
/// <remarks>Empty string to use the default type.</remarks>
FDataType: string;
public
/// <summary>The name of the cell's column</summary>
property Name: string read FName write FName;
/// <summary>The value held within the cell</summary>
property Value: string read FValue write FValue;
/// <summary>The name of the cell's datatype.</summary>
/// <remarks>Empty string to use the default type.</remarks>
property DataType: string read FDataType write FDataType;
end;
/// <summary>Represents a single row of a cloud table service table.</summary>
TCloudTableRow = class
protected
/// <summary>The columns of the row</summary>
FColumns: TList<TCloudTableColumn>;
/// <summary>True if the columns of this service support datatypes, false
/// to ignore the datatypes of the columns.
/// </summary>
FSupportsDataType: Boolean;
public
/// <summary>Constructs a new instance of TCloudTableRow</summary>
// / <param name="SupportsDataType">Sets the value of FSupportsDataType. Defaults to True.</param>
constructor Create(SupportsDataType: Boolean = True); virtual;
/// <summary>Frees the columns and destroys this instance.</summary>
destructor Destroy; override;
/// <summary>Adds the new column.</summary>
/// <remarks>Replaces the value and datatype of an existing column with the given name
/// if one is found.
///
/// If Replace is set to false and a column with the given name already exists, but
/// but the value isn't the one mentioned, then a new column is created for the
/// specified value. There will be two columns with the same name, but different values.
/// </remarks>
/// <param name="Name">Name of the column to add</param>
/// <param name="Value">Value to store in this row's cell for the column</param>
/// <param name="DataType">The name of the cell's datatype. Optional, defaults to empty string.</param>
/// <param name="Replace">True to replace previous value if it exists, false to create a second column.</param>
procedure SetColumn(const Name, Value: string; const DataType: string = ''; const Replace: Boolean = true);
/// <summary>Deletes the column with the given name, if found.</summary>
/// <param name="Name">The name of the column to delete</param>
/// <returns>true if the column had existed, false otherwise.</returns>
function DeleteColumn(const Name: string): Boolean;
/// <summary>Returns the first column instance with the given column name.</summary>
/// <param name="Name">The name of the column to get</param>
/// <returns>The first column with the given name, or nil if not found.</returns>
function GetColumn(const Name: string): TCloudTableColumn;
/// <summary>Gets the value of the column of this row with the given name.</summary>
/// <remarks>False is returned here to differentiate between an empty string value,
/// and a column name that doesn't exist.
/// </remarks>
/// <param name="Name">The name of the column to get the value for</param>
/// <param name="Value">The output parameter to store the value into</param>
/// <returns>true if the Value was returned successfully, false otherwise.</returns>
function GetColumnValue(const Name: string; out Value: string): Boolean;
/// <summary>The columns of the row</summary>
property Columns: TList<TCloudTableColumn> read FColumns;
/// <summary>True if the columns of this service support datatypes, false
/// to ignore the datatypes of the columns.
/// </summary>
property SupportsDataType: Boolean read FSupportsDataType;
end;
/// <summary>Identifier for a single queue.</summary>
TCloudQueue = record
/// <summary></summary>
Name: string;
/// <summary></summary>
URL: string;
/// <summary>Creates a new instance of TCloudQueue</summary>
/// <param name="Name">The queue's name</param>
/// <param name="URL">The queue's URL</param>
/// <returns>The new TCloudQueue instance</returns>
class function Create(Name, URL: string): TCloudQueue; overload; static;
/// <summary>Creates a new instance of TCloudQueue, parsing the Name from the given URL.</summary>
/// <param name="URL">The URL to set and parse the name from</param>
/// <returns>The new TCloudQueue instance</returns>
class function Create(URL: string): TCloudQueue; overload; static;
end;
TQueuePropertyArray = array of TPair<string, string>;
TCloudQueueMessageItem = record
/// <summary>Properties of the message</summary>
Properties: TQueuePropertyArray;
/// <summary>Unique Id of the message</summary>
MessageId: string;
/// <summary>Text of the message</summary>
MessageText: string;
/// <summary>Key required for deleting the message from the queue.</summary>
PopReceipt: string;
end;
/// <summary>Represents a single message in a Cloud Queue service's queue.</summary>
TCloudQueueMessage = class
private
/// <summary>Properties of the message</summary>
FProperties: TStrings;
/// <summary>Unique Id of the message</summary>
FMessageId: string;
/// <summary>Text of the message</summary>
FMessageText: string;
/// <summary>Key required for deleting the message from the queue.</summary>
FPopReceipt: string;
public
/// <summary>Creates a new instance of TCloudQueueMessage, with an empty property list.</summary>
// / <param name="MessageId">The value to set as the message's unique Id</param>
// / <param name="MessageText">The value to set as the message's text</param>
constructor Create(const MessageId, MessageText: string); overload;
/// <summary>Creates a new instance of TCloudQueueMessage, with the given property list.</summary>
/// <remarks>The properties specified will be owned by this instance</remarks>
// / <param name="MessageId">The value to set as the message's unique Id</param>
// / <param name="MessageText">The value to set as the message's text</param>
// / <param name="Properties">The properties to set on the message.</param>
constructor Create(const MessageId, MessageText: string; Properties: TStrings); overload;
class function CreateFromRecord(ACloudQueueMessage: TCloudQueueMessageItem): TCloudQueueMessage;
/// <summary>Frees the properties and destorys this instance.</summary>
destructor Destroy; override;
/// <summary>Properties of the message</summary>
property Properties: TStrings read FProperties;
/// <summary>Unique Id of the message</summary>
property MessageId: string read FMessageId;
/// <summary>Text of the message</summary>
property MessageText: string read FMessageText;
/// <summary>Key required for deleting the message from the queue.</summary>
property PopReceipt: string read FPopReceipt write FPopReceipt;
end;// deprecated 'use TCloudQueueMessageRecord instead';
/// <summary>Base Cloud Service class, providing useful common functionality.</summary>
/// <remarks>This class holds common functionality for building the authentication string,
/// And for issuing properly formatted requests. There are several abstract functions
/// which need to be implemented by subclasses, to provide service-specific functionality.
/// </remarks>
TCloudService = class abstract
protected
/// <summary>The authenticator to use when building the Authorization header value.</summary>
FAuthenticator: TCloudAuthentication;
/// <summary>The account connection info to use in connection and authentication</summary>
[Weak]FConnectionInfo: TCloudConnectionInfo;
/// <summary>The character to use to start the query string when building the StringToSign</summary>
/// <remarks>This, for example, is #10 for Azure, as the query section begins on a new line.
/// For other services, this could be a '?', for example. The default is set to '?'.
/// </remarks>
FQueryStartChar: Char;
/// <summary>The char to use to separate query parameter keys from their values</summary>
/// <remarks>This is only used when building the query string for the StringToSign.
/// This defaults to '=' but could be anything else. It is ':' in Azure, for example.
/// </remarks>
FQueryParamKeyValueSeparator: Char;
/// <summary>The char to use to separate query parameters from each other</summary>
/// <remarks>This is only used when building the query string for the StringToSign.
/// This defaults to '&' but could be anything else. It is #10 in Azure, for example.
/// </remarks>
FQueryParamSeparator: Char;
/// <summary>True to add headers to the StringToSign when building it, false otherwise.</summary>
FUseCanonicalizedHeaders: Boolean;
/// <summary>True to add query parameters to the StringToSign when building it, false otherwise.</summary>
FUseCanonicalizedResource: Boolean;
/// <summary>True to use the resource path in the StringToSign, false otherwise.</summary>
/// <remarks>This would say to take the part of the request URI up to (but not including) the query string and
/// use it in the StringToSign. It's default location would be directly after the prefix (protocol)
/// before the headers or query parameters.
/// </remarks>
FUseResourcePath: Boolean;
/// <summary>URL Encodes the param name and value.</summary>
/// <remarks>Can be extended by a subclass, to conditionally do encoding.</remarks>
/// <param name="ForURL">True if the parameter is for a URL, false if it is for a signature.</param>
/// <param name="ParamName">Name of the parameter</param>
/// <param name="ParamValue">Value of the parameter</param>
procedure URLEncodeQueryParams(const ForURL: Boolean; var ParamName, ParamValue: string); virtual;
/// <summary>List of header names, whose values (but not the names) must appear, in the given order,
/// in the StringToSign that gets built.
/// </summary>
/// <remarks>Note that the order matters. The headers must be returned in the exact order
/// they need to appear in the StringToSign for the cloud service in question.
/// </remarks>
/// <param name="InstanceOwner">Set to true if the caller should free the resulting list.</param>
/// <returns>The list of required header names.</returns>
function GetRequiredHeaderNames(out InstanceOwner: Boolean): TStrings; virtual; abstract;
/// <summary>Returns the prefix a header name starts with if it is to be included in the
/// CanonicalizedHeaders of the StringToSign.
/// </summary>
/// <remarks>For example, this is 'x-ms-' in Azure and 'x-amz-' in Amazon.</remarks>
/// <returns>The header prefix for names of CanonicalizedHeaders headers.</returns>
function GetCanonicalizedHeaderPrefix: string; virtual; abstract;
/// <summary>Sorts the given list of Query Parameters</summary>
/// <remarks>Extend this if you wish to modify how the list is sorted, or to modify its contents.</remarks>
/// <param name="QueryParameters">List of parameters to sort</param>
/// <param name="ForURL">True if these are used in a URL, false if they are used in a StringToSign</param>
procedure SortQueryParameters(const QueryParameters: TStringList; ForURL: Boolean); virtual;
/// <summary>Sorts the given list of Headers.</summary>
/// <remarks>Extend this if you wish to modify how the list is sorted.</remarks>
/// <param name="Headers">List of headers to sort.</param>
procedure SortHeaders(const Headers: TStringList); virtual;
/// <summary>Builds a string representation of the given Query Parameters and the given prefix.</summary>
/// <remarks>The parameters list will be lexicographically sorted if DoSort is set to true. The
/// characters used in the query string depend on the value of ForURL. If set to true,
/// '?' will be used after the prefix, '='
/// </remarks>
/// <param name="QueryPrefix">Value to prefix the result string with</param>
/// <param name="QueryParameters">List of parameters to build the result string from</param>
/// <param name="DoSort">True to sort the given QueryParameters list, false otherwise.</param>
/// <param name="ForURL">True to use default (URL) characters in the string, false to use the
/// characters specified by FQueryStartChar, FQueryParamKeyValueSeparator and FQueryParamSeparator.
/// </param>
/// <returns>The string representation of the query aprameters.</returns>
function BuildQueryParameterString(const QueryPrefix: string; QueryParameters: TStringList;
DoSort: Boolean = False; ForURL: Boolean = True): string; virtual;
/// <summary>Builds the StringToSign value, based on the given information.</summary>
/// <param name="HTTPVerb">The HTTP verb (eg: GET, POST) of the request type.</param>
/// <param name="Headers">The list of headers in the request, or nil</param>
/// <param name="QueryParameters">The list of query parameters for the request, or nil</param>
/// <param name="QueryPrefix">The string to prefix the query parameter string with.</param>
/// <param name="URL">The URL of the request.</param>
/// <returns>The StringToSign, which will be encoded and used for authentication.</returns>
function BuildStringToSign(const HTTPVerb: string; Headers, QueryParameters: TStringList;
const QueryPrefix, URL: string): string; virtual;
/// <summary>Takes in a URL and optionally uses it to parse the HTTPRequestURI</summary>
/// <remarks>By default, conditionally (based on the value of FUseResourcePath) the value returned
/// is the part after the host name, up until the beginning of the query parameters.
/// Returning, at minimum, a forward slash character.
/// </remarks>
/// <param name="URL">The URL of the request.</param>
/// <returns>The HTTPRequestURI, for use in a StringToSign, or Empty String</returns>
function BuildStringToSignResourcePath(const URL: string): string; virtual;
/// <summary>Optionally builds the CanonicalizedQueryString</summary>
/// <remarks>Based on the value of FUseCanonicalizedResource, this either builds the query string,
/// or returns empty string.
/// </remarks>
/// <param name="QueryPrefix">The prefix to use before the query parameters</param>
/// <param name="QueryParameters">The query parameters to build the string from</param>
/// <returns>The CanonicalizedQueryString, or Empty String if FUseCanonicalizedResource is false</returns>
function BuildStringToSignResources(QueryPrefix: string; QueryParameters: TStringList): string; virtual;
/// <summary>Takes in a URL and uses it to parse the HTTPRequestURI for a StringToSign</summary>
/// <remarks>By default, the value returns is the part after the host name, up until the
/// beginning of the query parameters. Returning, at minimum, a forward slash character.
/// </remarks>
/// <param name="URL">The URL of the request.</param>
/// <returns>The HTTPRequestURI, for use in a StringToSign.</returns>
function GetHTTPRequestURI(const URL: string): string; virtual;
/// <summary>Builds the first part of the StringToSign, including the HTTP Verb</summary>
/// <remarks>Subclasses can override this if they need to add to the stringToSign
/// before header and query parameter information is appended to it.
/// </remarks>
/// <param name="HTTPVerb">The HTTP verb (eg: GET, POST) of the request type.</param>
/// <returns>The first portion of the stringToSign, before headers and query parameters</returns>
function BuildStringToSignPrefix(const HTTPVerb: string): string; virtual;
/// <summary>Builds the StringToSign value's header part</summary>
/// <remarks>This will include both the required and optional headers, and end with a newline character.
/// </remarks>
/// <param name="Headers">The list of headers in the request, or nil</param>
/// <returns>The headers portion of the StringToSign</returns>
function BuildStringToSignHeaders(Headers: TStringList): string; virtual;
/// <summary>Helper method to set the request's date based on the string value.</summary>
/// <param name="Request">The request to add the date value to</param>
/// <param name="DateTimeAsString">The date, in string format</param>
procedure SetDateFromString(Request: THTTPClient; const DateTimeAsString: string); virtual;
/// <summary>Helper method to add the given key/value pair to the request's headers.</summary>
/// <remarks>This handles special cases, such as where the header being set is a field
/// in the request, instead of part of the custom header list.
/// </remarks>
/// <param name="Request">The request to add the header name/value pair to</param>
/// <param name="headers">list of string key values</param>
procedure AddHeaders(Request: THTTPClient; const headers: TStringList); virtual;
/// <summary>Handles the StringToSign after it is created.</summary>
/// <param name="HTTPVerb">The HTTP verb (eg: GET, POST) of the request.</param>
/// <param name="Headers">The header name/value pairs</param>
/// <param name="QueryParameters">The query parameter name/value pairs</param>
/// <param name="StringToSign">The StringToSign for the request</param>
/// <param name="URL">The URL of the request</param>
/// <param name="Request">The request object</param>
/// <param name="Content">The content stream of the request.</param>
procedure PrepareRequestSignature(const HTTPVerb: string;
const Headers, QueryParameters: TStringList;
const StringToSign: string;
var URL: string; Request: TCloudHTTP; var Content: TStream); virtual;
/// <summary>Creates a new request object ad populated the headers, including the Authorization header.
/// </summary>
/// <remarks>The caller owns the lists passed in, and can free them any time after the invocation ends.
/// </remarks>
/// <param name="HTTPVerb">The HTTP verb (eg: GET, POST) of the request.</param>
/// <param name="Headers">The header name/value pairs to populate the
/// request and build the StringToSign with.</param>
/// <param name="QueryParameters">The query parameter name/value pairs to
/// populate the request and build the StringToSign with.</param>
/// <param name="QueryPrefix">The string to prefix the query parameter string with, for the StringToSign.</param>
/// <param name="URL">The request's URL</param>
/// <param name="Content">The request content stream, or nil</param>
/// <returns>The initialized TCloudHTTP instance.</returns>
function PrepareRequest(const HTTPVerb: string; Headers, QueryParameters: TStringList;
const QueryPrefix: string; var URL: string; var Content: TStream): TCloudHTTP; overload; virtual;
/// <summary>Creates a new request object ad populated the headers, including the Authorization header.
/// </summary>
/// <remarks>The caller owns the lists passed in, and can free them any time after the invocation ends.
/// </remarks>
/// <param name="HTTPVerb">The HTTP verb (eg: GET, POST) of the request.</param>
/// <param name="Headers">The header name/value pairs to populate the
/// request and build the StringToSign with.</param>
/// <param name="QueryParameters">The query parameter name/value pairs to
/// populate the request and build the StringToSign with.</param>
/// <param name="QueryPrefix">The string to prefix the query parameter string with, for the StringToSign.</param>
/// <param name="URL">The request's URL</param>
/// <returns>The initialized TCloudHTTP instance.</returns>
function PrepareRequest(const HTTPVerb: string; Headers, QueryParameters: TStringList;
const QueryPrefix: string; var URL: string): TCloudHTTP; overload; virtual;
/// <summary>Populates the given ResponseInfo with appropriate information from the Response.</summary>
/// <remarks>Fills in the status code, status message, and response headers for the ResponseInfo object,
/// Based on the values stored in the given Response object.
/// </remarks>
/// <param name="ACloudHTTP">The response object to get the values from</param>
/// <param name="ResponseInfo">The ResponseInfo object to populate with information from the Response.</param>
procedure PopulateResponseInfo(ACloudHTTP: TCloudHTTP; ResponseInfo: TCloudResponseInfo); virtual;
/// <summary>Executes a HEAD request with the given parameters.</summary>
/// <param name="URL">The URL to issue the request to</param>
/// <param name="Headers">The header name/value pairs to use in the request and authentication.</param>
/// <param name="QueryParameters">The query parameter name/value pairs to use in the
/// request and authentication.</param>
/// <param name="QueryPrefix">The string to prefix the query string with when building the StringToSign</param>
/// <param name="ResponseInfo">The ResponseInfo instance to populate from the request's response, or nil</param>
/// <returns>The TCloudHTTP instance used to issue the request.</returns>
function IssueHeadRequest(URL: string; Headers: TStringList;
QueryParameters: TStringList; const QueryPrefix: string;
ResponseInfo: TCloudResponseInfo): TCloudHTTP; virtual;
/// <summary>Executes a GET request with the given parameters.</summary>
/// <remarks>Returns the response stream as well as the TCloudHTTP instance used in the request.</remarks>
/// <param name="URL">The URL to issue the request to</param>
/// <param name="Headers">The header name/value pairs to use in the request and authentication.</param>
/// <param name="QueryParameters">The query parameter name/value pairs to use in the
/// request and authentication.</param>
/// <param name="QueryPrefix">The string to prefix the query string with when building the StringToSign</param>
/// <param name="ResponseInfo">The ResponseInfo instance to populate from the request's response, or nil</param>
/// <param name="ResponseContent">Response stream, to use in the request being made.</param>
/// <returns>The TCloudHTTP instance used to issue the request.</returns>
function IssueGetRequest(URL: string; Headers: TStringList;
QueryParameters: TStringList; const QueryPrefix: string;
ResponseInfo: TCloudResponseInfo;
ResponseContent: TStream): TCloudHTTP; overload; virtual;
/// <summary>Executes a GET request with the given parameters.</summary>
/// <remarks>Returns the response body as a string, as well as the TCloudHTTP instance used in the request.
/// </remarks>
/// <param name="URL">The URL to issue the request to</param>
/// <param name="Headers">The header name/value pairs to use in the request and authentication.</param>
/// <param name="QueryParameters">The query parameter name/value pairs to use in the
/// request and authentication.</param>
/// <param name="QueryPrefix">The string to prefix the query string with when building the StringToSign</param>
/// <param name="ResponseInfo">The ResponseInfo instance to populate from the request's response, or nil</param>
/// <param name="ResponseString">Output parameter, set to the string content returned in the response.</param>
/// <returns>The TCloudHTTP instance used to issue the request.</returns>
function IssueGetRequest(URL: string; Headers: TStringList;
QueryParameters: TStringList; const QueryPrefix: string;
ResponseInfo: TCloudResponseInfo;
out ResponseString: string): TCloudHTTP; overload; virtual;
/// <summary>Executes a GET request with the given parameters.</summary>
/// <param name="URL">The URL to issue the request to</param>
/// <param name="Headers">The header name/value pairs to use in the request and authentication.</param>
/// <param name="QueryParameters">The query parameter name/value pairs to use in the
/// request and authentication.</param>
/// <param name="QueryPrefix">The string to prefix the query string with when building the StringToSign</param>
/// <param name="ResponseInfo">The ResponseInfo instance to populate from the request's response, or nil</param>
/// <returns>The TCloudHTTP instance used to issue the request.</returns>
function IssueGetRequest(URL: string; Headers: TStringList;
QueryParameters: TStringList; const QueryPrefix: string;
ResponseInfo: TCloudResponseInfo): TCloudHTTP; overload; virtual;
/// <summary>Executes a PUT request with the given parameters.</summary>
/// <remarks>Optionally takes a stream to use as the request body.</remarks>
/// <param name="URL">The URL to issue the request to</param>
/// <param name="Headers">The header name/value pairs to use in the request and authentication.</param>
/// <param name="QueryParameters">The query parameter name/value pairs to use in the
/// request and authentication.</param>
/// <param name="QueryPrefix">The string to prefix the query string with when building the StringToSign</param>
/// <param name="ResponseInfo">The ResponseInfo instance to populate from the request's response, or nil</param>
/// <param name="Content">The stream to send as the request content (optional)</param>
/// <returns>The TCloudHTTP instance used to issue the request.</returns>
function IssuePutRequest(URL: string; Headers: TStringList;
QueryParameters: TStringList; const QueryPrefix: string;
ResponseInfo: TCloudResponseInfo;
Content: TStream = nil): TCloudHTTP; overload; virtual;
/// <summary>Executes a PUT request with the given parameters.</summary>
/// <remarks>Optionally takes a stream to use as the request body.</remarks>
/// <param name="URL">The URL to issue the request to</param>
/// <param name="Headers">The header name/value pairs to use in the request and authentication.</param>
/// <param name="QueryParameters">The query parameter name/value pairs to use in the
/// request and authentication.</param>
/// <param name="QueryPrefix">The string to prefix the query string with when building the StringToSign</param>
/// <param name="ResponseInfo">The ResponseInfo instance to populate from the request's response, or nil</param>
/// <param name="Content">The stream to send as the request content, or nil</param>
/// <param name="ResponseString">Output parameter, set to the string content returned in the response.</param>
/// <returns>The TCloudHTTP instance used to issue the request.</returns>
function IssuePutRequest(URL: string; Headers: TStringList;
QueryParameters: TStringList; const QueryPrefix: string;
ResponseInfo: TCloudResponseInfo;
Content: TStream; out ResponseString: string): TCloudHTTP; overload; virtual;
/// <summary>Executes a MERGE request with the given parameters.</summary>
/// <remarks>Takes a stream to use as the request body</remarks>
/// <param name="URL">The URL to issue the request to</param>
/// <param name="Headers">The header name/value pairs to use in the request and authentication.</param>
/// <param name="QueryParameters">The query parameter name/value pairs to use in the
/// request and authentication.</param>
/// <param name="QueryPrefix">The string to prefix the query string with when building the StringToSign</param>
/// <param name="ResponseInfo">The ResponseInfo instance to populate from the request's response, or nil</param>
/// <param name="Content">The stream to send as the request content (required)</param>
/// <returns>The TCloudHTTP instance used to issue the request.</returns>
function IssueMergeRequest(URL: string; Headers: TStringList;
QueryParameters: TStringList; const QueryPrefix: string;
ResponseInfo: TCloudResponseInfo;
Content: TStream): TCloudHTTP; virtual;
/// <summary>Executes a POST request with the given parameters.</summary>
/// <remarks>Takes a stream to use as the request body</remarks>
/// <param name="URL">The URL to issue the request to</param>
/// <param name="Headers">The header name/value pairs to use in the request and authentication.</param>
/// <param name="QueryParameters">The query parameter name/value pairs to use in the
/// request and authentication.</param>
/// <param name="QueryPrefix">The string to prefix the query string with when building the StringToSign</param>
/// <param name="ResponseInfo">The ResponseInfo instance to populate from the request's response, or nil</param>
/// <param name="Content">The stream to send as the request content (required)</param>
/// <returns>The TCloudHTTP instance used to issue the request.</returns>
function IssuePostRequest(URL: string; Headers: TStringList;
QueryParameters: TStringList; const QueryPrefix: string;
ResponseInfo: TCloudResponseInfo;
Content: TStream): TCloudHTTP; overload; virtual;
/// <summary>Executes a POST request with the given parameters.</summary>
/// <remarks>Takes a stream to use as the request body</remarks>
/// <param name="URL">The URL to issue the request to</param>
/// <param name="Headers">The header name/value pairs to use in the request and authentication.</param>
/// <param name="QueryParameters">The query parameter name/value pairs to use in the
/// request and authentication.</param>
/// <param name="QueryPrefix">The string to prefix the query string with when building the StringToSign</param>
/// <param name="ResponseInfo">The ResponseInfo instance to populate from the request's response, or nil</param>
/// <param name="Content">The stream to send as the request content (required)</param>
/// <param name="Content">Output parameter, set to the string content returned in the response.</param>
/// <param name="ResponseString">Output parameter, set to the string content returned in the response.</param>
/// <returns>The TCloudHTTP instance used to issue the request.</returns>
function IssuePostRequest(URL: string; Headers: TStringList;
QueryParameters: TStringList; const QueryPrefix: string;
ResponseInfo: TCloudResponseInfo;
Content: TStream; out ResponseString: string): TCloudHTTP; overload; virtual;
/// <summary>Executes a DELETE request with the given parameters.</summary>
/// <param name="URL">The URL to issue the request to</param>
/// <param name="Headers">The header name/value pairs to use in the request and authentication.</param>
/// <param name="QueryParameters">The query parameter name/value pairs to use in the
/// request and authentication.</param>
/// <param name="QueryPrefix">The string to prefix the query string with when building the StringToSign</param>
/// <param name="ResponseInfo">The ResponseInfo instance to populate from the request's response, or nil</param>
/// <returns>The TCloudHTTP instance used to issue the request.</returns>
function IssueDeleteRequest(URL: string; Headers: TStringList;
QueryParameters: TStringList; const QueryPrefix: string;
ResponseInfo: TCloudResponseInfo): TCloudHTTP; overload; virtual;
/// <summary>Executes a DELETE request with the given parameters.</summary>
/// <param name="URL">The URL to issue the request to</param>
/// <param name="Headers">The header name/value pairs to use in the request and authentication.</param>
/// <param name="QueryParameters">The query parameter name/value pairs to use in the
/// request and authentication.</param>
/// <param name="QueryPrefix">The string to prefix the query string with when building the StringToSign</param>
/// <param name="ResponseInfo">The ResponseInfo instance to populate from the request's response, or nil</param>
/// <param name="ResponseString">Output parameter, set to the string content returned in the response.</param>
/// <returns>The TCloudHTTP instance used to issue the request.</returns>
function IssueDeleteRequest(URL: string; Headers: TStringList;
QueryParameters: TStringList; const QueryPrefix: string;
ResponseInfo: TCloudResponseInfo;
out ResponseString: string): TCloudHTTP; overload; virtual;
/// <summary>Executes a OPTIONS request with the given parameters.</summary>
/// <param name="AURL">The URL to issue the request to</param>
/// <param name="AHeaders">The header name/value pairs to use in the request and authentication.</param>
/// <param name="AQueryParameters">The query parameter name/value pairs to use in the request and authentication.</param>
/// <param name="AQueryPrefix">The string to prefix the query string with when building the StringToSign</param>
/// <param name="AResponseInfo">The ResponseInfo instance to populate from the request's response, or nil</param>
/// <returns>The TCloudHTTP instance used to issue the request.</returns>
function IssueOptionsRequest(AURL: string; const AHeaders, AQueryParameters: TStringList; const AQueryPrefix: string;
const AResponseInfo: TCloudResponseInfo): TCloudHTTP; overload; virtual;
/// <summary>Executes a OPTIONS request with the given parameters.</summary>
/// <param name="AURL">The URL to issue the request to</param>
/// <param name="AHeaders">The header name/value pairs to use in the request and authentication.</param>
/// <param name="AQueryParameters">The query parameter name/value pairs to use in the request and authentication.</param>
/// <param name="AQueryPrefix">The string to prefix the query string with when building the StringToSign</param>
/// <param name="AResponseInfo">The ResponseInfo instance to populate from the request's response, or nil</param>
/// <param name="AResponseString">Output parameter, set to the string content returned in the response.</param>
/// <returns>The TCloudHTTP instance used to issue the request.</returns>
function IssueOptionsRequest(AURL: string; const AHeaders, AQueryParameters: TStringList;
const AQueryPrefix: string; const AResponseInfo: TCloudResponseInfo;
out AResponseString: string): TCloudHTTP; overload; virtual;
/// <summary>URL encodes the given value.</summary>
/// <param name="Value">The string to URL encode</param>
/// <returns>The URL encoded value.</returns>
function URLEncodeValue(const Value: string): string; virtual;
public
/// <summary>Creates a new instance of the service class.</summary>
/// <remarks>Note that the ConnectionInfo is not freed when this instance is destructed,
/// but the Authenticator is.
/// </remarks>
// / <param name="ConnectionInfo">The service account connection/authentication information to use</param>
// / <param name="Authenticator">The authentication instance to use for authenticating requests</param>
constructor Create(const ConnectionInfo: TCloudConnectionInfo; const Authenticator: TCloudAuthentication);
/// <summary>Frees the Authenticator and destroys the instance.</summary>
/// <remarks>Note that the ConnectionInfo is not freed.</remarks>
destructor Destroy; override;
/// <summary> Reference to the ConnectionInfo held by this service, as specified in the constructor.
/// </summary>
property ConnectionInfo: TCloudConnectionInfo read FConnectionInfo;
end;
/// <summary>Escapes reserved XML characters in the string.</summary>
/// <param name="Str">The string to XML escape.</param>
/// <returns>The String with special XML characters escaped.</returns>
function XMLEscape(const Str: string): string; deprecated;
/// <summary>URL encodes the specified string</summary>
/// <param name="Str">The string to URL encode.</param>
/// <returns>The URL encoded version of the specified string.</returns>
function URLEncode(const Str: string): string; overload;
/// <summary>URL encodes the specified string</summary>
// / <param name="Str">The string to URL encode.</param>
// / <param name="EncodeChars">Additional non-standard characters to encode with their hex value.</param>
/// <returns>The URL encoded version of the specified string.</returns>
function URLEncode(const Str: string; const EncodeChars: array of Char): string; overload;
/// <summary>Base 64 Encodes the specified string</summary>
/// <param name="Str">The string to Base64 encode.</param>
/// <returns>The encoded version of the string.</returns>
function Encode64(Str: string): string; deprecated;
/// <summary>Decodes a Base64 encoded string</summary>
/// <param name="Str">The string to Base64 decode.</param>
/// <returns>The decoded version of the string.</returns>
function Decode64(Str: string): string; deprecated;
/// <summary>Base 64 Encodes the specified bytes</summary>
/// <param name="asBytes">The bytes to Base64 encode.</param>
/// <returns>The encoded version of the string.</returns>
function EncodeBytes64(asBytes: TArray<Byte>): string; deprecated;
/// <summary>Base 64 Decodes the specified string</summary>
/// <param name="Str">The string to Base64 decode.</param>
/// <returns>The decoded version of the string.</returns>
function DecodeBytes64(Str: string): TArray<Byte>; deprecated;
/// <summary>Helper function that returns the first child node of the given name.</summary>
/// <param name="Parent">The parent node to get the child nodes from.</param>
/// <param name="ChildName">The name of the child node to find.</param>
/// <returns>The first matching child node, or nil if none found.</returns>
function GetFirstMatchingChildNode(Parent: IXMLNode; ChildName: string): IXMLNode;
/// <summary>Populates the provided string list with Key-Value pairs.</summary>
/// <remarks>Each child node of the given node is checked. If its name is the same as the specified
/// value of 'PairNodeName', then it is checked to see if it has a text node name matching
/// the value of KeyNodeName, as well as ValueNodeName. The value of these two nodes are
/// used as a key-value pair, which is populated into the given list.
/// </remarks>
/// <param name="Parent">The node to iterate over</param>
/// <param name="PairList">The list to populate with key-value pairs</param>
/// <param name="PairNodeName">The name of the child node type to get a single pair from</param>
/// <param name="KeyNodeName">The name of the node containing the key information of a pair</param>
/// <param name="ValueNodeName">The name of the node containing the value information of a pair</param>
/// <returns>The first matching child node, or nil if none found.</returns>
procedure PopulateKeyValuePairs(Parent: IXMLNode; PairList: TStrings; const PairNodeName: string;
const KeyNodeName: string = 'Name';
const ValueNodeName: string = 'Value'); deprecated;
/// <summary>Returns the text contained within the child element.</summary>
/// <remarks>This finds the first matching child tag with the given name, and if it is a text element,
/// returns the text contained within it. If it isn't a text element, or it isn't found, then
/// empty string will be returned.
/// </remarks>
/// <param name="NodeName">The name of the child node to get the text for</param>
/// <param name="Parent">The parent node to get the child node for.</param>
/// <returns>The child element's text value.</returns>
function GetChildText(const NodeName: string; Parent: IXMLNode): string;
implementation
uses
{$IF defined(MSWINDOWS) and not defined(NEXTGEN)}
Xml.Win.msxmldom,
{$ELSE}
Xml.omnixmldom,
{$ENDIF}
System.DateUtils, System.StrUtils, System.Hash, Data.Cloud.CloudResStrs,
System.NetEncoding;
const
Codes64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
Pad = '=';
function XMLEscape(const Str: string): string;
begin
Result := TNetEncoding.HTML.Encode(Str);
end;
function EncodeBytes64(asBytes: TArray<Byte>): string;
begin
Result := TNetEncoding.Base64.EncodeBytesToString(asBytes);
end;
function Encode64(Str: string): string;
begin
Result := TNetEncoding.Base64.Encode(Str);
end;
function DecodeBytes64(Str: string): TArray<Byte>;
begin
Result := TNetEncoding.Base64.DecodeStringToBytes(Str);
end;
function Decode64(Str: string): string;
begin
Result := TNetEncoding.Base64.Decode(Str);
end;
function URLEncode(const Str: string): string;
begin
Result := URLEncode(Str, ['=']);
end;
function URLEncode(const Str: string; const EncodeChars: array of Char): string;
function IsHexChar(C: Byte): Boolean;
begin
case Char(C) of
'0'..'9', 'a'..'f', 'A'..'F': Result := True;
else
Result := False;
end;
end;
const
// Safe characters from on TIdURL.ParamsEncode
// '*<>#%"{}|\^[]`'
DefaultUnsafeChars: array[0..13] of Byte = (Ord('*'), Ord('<'), Ord('>'), Ord('#'),
Ord('%'), Ord('"'), Ord('{'), Ord('}'), Ord('|'), Ord('\'), Ord('^'), Ord('['), Ord(']'), Ord('`'));
XD: array[0..15] of char = ('0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
var
Buff: TBytes;
I, J: Integer;
IsUnsafe: Boolean;
begin
Result := '';
if Str <> '' then
begin
Buff := TEncoding.UTF8.GetBytes(Str);
I := 0;
while I < Length(Buff) do
begin
if (Buff[I] < 33) or (Buff[I] > 127) then
IsUnsafe := True
else
begin
IsUnsafe := False;
for J := 0 to Length(DefaultUnsafeChars) - 1 do
if Buff[I] = DefaultUnsafeChars[J] then
begin
IsUnsafe := True;
break;
end;
if not IsUnsafe then
for J := 0 to Length(EncodeChars) - 1 do
if Char(Buff[I]) = EncodeChars[J] then
begin
IsUnsafe := True;
break;
end;
end;
if IsUnsafe then
Result := Result + '%' + XD[(Buff[I] shr 4) and $0F] + XD[Buff[I] and $0F]
else
Result := Result + Char(Buff[I]);
Inc(I);
end;
end;
end;
function GetFirstMatchingChildNode(Parent: IXMLNode; ChildName: string): IXMLNode;
var
Child: IXMLNode;
begin
Result := nil;
if (Parent <> nil) and Parent.HasChildNodes and (ChildName <> EmptyStr) then
begin
Child := Parent.ChildNodes.First;
while Child <> nil do
begin
if AnsiSameText(Child.NodeName, ChildName) then
Exit(Child);
Child := Child.NextSibling;
end;
end;
end;
procedure PopulateKeyValuePairs(Parent: IXMLNode; PairList: TStrings; const PairNodeName: string;
const KeyNodeName: string;
const ValueNodeName: string);
var
ChildNode, Aux: IXMLNode;
Name: string;
begin
if PairList = nil then
Exit;
ChildNode := GetFirstMatchingChildNode(Parent, PairNodeName);
while ChildNode <> nil do
begin
try
if AnsiSameText(ChildNode.NodeName, PairNodeName) then
begin
Aux := ChildNode.ChildNodes.FindNode(KeyNodeName);
if (Aux <> nil) and Aux.IsTextElement then
begin
Name := Aux.Text;
Aux := ChildNode.ChildNodes.FindNode(ValueNodeName);
if (Aux <> nil) and Aux.IsTextElement then
begin
PairList.Values[Name] := Aux.Text;
end;
end;
end;
finally
ChildNode := ChildNode.NextSibling;
end;
end;
end;
function GetChildText(const NodeName: string; Parent: IXMLNode): string;
var
ChildNode: IXMLNode;
begin
if (Parent <> nil) and (NodeName <> EmptyStr) and Parent.HasChildNodes then
begin
ChildNode := Parent.ChildNodes.FindNode(NodeName);
if (ChildNode <> nil) and ChildNode.IsTextElement then
Result := ChildNode.Text;
end;
end;
{ TCloudAuthentication }
constructor TCloudAuthentication.Create(const ConnectionInfo: TCloudConnectionInfo);
begin
FConnectionInfo := ConnectionInfo;
FConnectionInfo.FAuthentication := Self;
if FConnectionInfo.AccountKey <> '' then
AssignKey(FConnectionInfo.AccountKey);
end;
destructor TCloudAuthentication.Destroy;
begin
if FConnectionInfo <> nil then
begin
FConnectionInfo.FAuthentication := nil;
FConnectionInfo := nil;
end;
inherited Destroy;
end;
procedure TCloudAuthentication.AssignKey(const AccountKey: string);
begin
FSHAKey := TEncoding.UTF8.GetBytes(AccountKey);
end;
function TCloudAuthentication.BuildAuthorizationString(const StringToSign: string): string;
begin
Result := Format('%s %s:%s', {do not localize}
[GetAuthorizationType,
FConnectionInfo.AccountName,
TNetEncoding.Base64.EncodeBytesToString(SignString(FSHAKey,StringToSign))]);
end;
{ TCloudSHA256Authentication }
constructor TCloudSHA256Authentication.Create(const ConnectionInfo: TCloudConnectionInfo;
AuthorizationType: string);
begin
inherited Create(ConnectionInfo);
FAuthorizationType := AuthorizationType;
end;
function TCloudSHA256Authentication.GetAuthorizationType: string;
begin
Result := FAuthorizationType;
end;
function TCloudSHA256Authentication.SignString(const Signkey: TBytes; const StringToSign: string): TBytes;
begin
Result := THashSHA2.GetHMACAsBytes(StringToSign, Signkey);
end;
class function TCloudSHA256Authentication.GetHashSHA256Hex( HashString: string): string;
var
LBytes: TArray<Byte>;
begin
//Hash bytes
LBytes := THashSHA2.GetHashBytes(HashString);
//hex string
Result := THash.DigestAsString(LBytes);
end;
class function TCloudSHA256Authentication.GetStreamToHashSHA256Hex(const Content: TStream): string;
var
LBytes : TBytes;
Hash: THashSHA2;
begin
SetLength(LBytes, Content.Size);
Content.Position := 0;
Content.Read(LBytes, Length(LBytes));
Content.Position := 0;
//Hash bytes
Hash := THashSHA2.Create;
Hash.Update(LBytes);
Result := Hash.HashAsString;
end;
{ TCloudSHA1Authentication }
constructor TCloudSHA1Authentication.Create(ConnectionInfo: TCloudConnectionInfo; AuthorizationType: string);
begin
inherited Create(ConnectionInfo);
FAuthorizationType := AuthorizationType;
end;
function TCloudSHA1Authentication.GetAuthorizationType: string;
begin
Result := FAuthorizationType;
end;
function TCloudSHA1Authentication.SignString(const Signkey: TBytes; const StringToSign: string): TArray<Byte>;
begin
Result := THashSHA1.GetHMACAsBytes(StringToSign, Signkey);
end;
function LexicographicalNameCompare(List: TStringList; Index1, Index2: Integer): Integer;
begin
Result := AnsiCompareText(List.Names[Index1], List.Names[Index2]);
//if the keys are the same, sort by value
if Result = 0 then
Result := AnsiCompareText(List.ValueFromIndex[Index1], List.ValueFromIndex[Index2]);
end;
{ TCloudService }
constructor TCloudService.Create(const ConnectionInfo: TCloudConnectionInfo; const Authenticator: TCloudAuthentication);
begin
FConnectionInfo := ConnectionInfo;
FAuthenticator := Authenticator;
FQueryStartChar := '?';
FQueryParamKeyValueSeparator := '=';
FQueryParamSeparator := '&';
FUseCanonicalizedHeaders := True;
FUseCanonicalizedResource := True;
FUseResourcePath := False;
end;
destructor TCloudService.Destroy;
begin
FreeAndNil(FAuthenticator);
inherited;
end;
procedure TCloudService.SortHeaders(const Headers: TStringList);
begin
if Headers <> nil then
Headers.CustomSort(LexicographicalNameCompare);
end;
procedure TCloudService.SortQueryParameters(const QueryParameters: TStringList; ForURL: Boolean);
begin
if QueryParameters <> nil then
QueryParameters.CustomSort(LexicographicalNameCompare);
end;
procedure TCloudService.URLEncodeQueryParams(const ForURL: Boolean; var ParamName, ParamValue: string);
begin
ParamName := URLEncodeValue(ParamName);
ParamValue := URLEncodeValue(ParamValue);
end;
function TCloudService.URLEncodeValue(const Value: string): string;
begin
Result := URLEncode(Value);
end;
function TCloudService.BuildQueryParameterString(const QueryPrefix: string; QueryParameters: TStringList;
DoSort, ForURL: Boolean): string;
var
Count: Integer;
I: Integer;
lastParam, nextParam: string;
QueryStartChar, QuerySepChar, QueryKeyValueSepChar: Char;
CurrValue: string;
CommaVal: string;
begin
//if there aren't any parameters, just return the prefix
if not Assigned(QueryParameters) or (QueryParameters.Count = 0) then
Exit(QueryPrefix);
if ForURL then
begin
//If the query parameter string is beign created for a URL, then
//we use the default characters for building the strings, as will be required in a URL
QueryStartChar := '?';
QuerySepChar := '&';
QueryKeyValueSepChar := '=';
end
else
begin
//otherwise, use the charaters as they need to appear in the signed string
QueryStartChar := FQueryStartChar;
QuerySepChar := FQueryParamSeparator;
QueryKeyValueSepChar := FQueryParamKeyValueSeparator;
end;
if DoSort and not QueryParameters.Sorted then
SortQueryParameters(QueryParameters, ForURL);
Count := QueryParameters.Count;
lastParam := QueryParameters.Names[0];
CurrValue := Trim(QueryParameters.ValueFromIndex[0]);
//URL Encode the firs set of params
URLEncodeQueryParams(ForURL, lastParam, CurrValue);
//there is at least one parameter, so add the query prefix, and then the first parameter
//provided it is a valid non-empty string name
Result := QueryPrefix;
if CurrValue <> EmptyStr then
Result := Result + Format('%s%s%s%s', [QueryStartChar, lastParam, QueryKeyValueSepChar, CurrValue])
else
Result := Result + Format('%s%s', [QueryStartChar, lastParam]);
//in the URL, the comma character must be escaped. In the StringToSign, it shouldn't be.
//this may need to be pulled out into a function which can be overridden by individual Cloud services.
if ForURL then
CommaVal := '%2c'
else
CommaVal := ',';
//add the remaining query parameters, if any
for I := 1 to Count - 1 do
begin
nextParam := Trim(QueryParameters.Names[I]);
CurrValue := QueryParameters.ValueFromIndex[I];
URLEncodeQueryParams(ForURL, nextParam, CurrValue);
//match on key name only if the key names are not empty string.
//if there is a key with no value, it should be formatted as in the else block
if (lastParam <> EmptyStr) and (AnsiCompareText(lastParam, nextParam) = 0) then
Result := Result + CommaVal + CurrValue
else begin
if (not ForURL) or (nextParam <> EmptyStr) then
begin
if CurrValue <> EmptyStr then
Result := Result + Format('%s%s%s%s', [QuerySepChar, nextParam, QueryKeyValueSepChar, CurrValue])
else
Result := Result + Format('%s%s', [QuerySepChar, nextParam]);
end;
lastParam := nextParam;
end;
end;
end;
function TCloudService.GetHTTPRequestURI(const URL: string): string;
begin
Result := TURI.Create(URL).Path + #10;
end;
function TCloudService.BuildStringToSignPrefix(const HTTPVerb: string): string;
begin
Result := HTTPVerb + #10;
end;
function TCloudService.BuildStringToSign(const HTTPVerb: string; Headers, QueryParameters: TStringList;
const QueryPrefix, URL: string): string;
begin
//Build the first part of the string to sign, including HTTPVerb
Result := BuildStringToSignPrefix(HTTPVerb);
//Build the resource path, which by default is from the end of the host/port
//to the beginning of the query parameters.
Result := Result + BuildStringToSignResourcePath(URL);
//Special headers with a specific prefix. Names (lowercase) and values
Result := Result + BuildStringToSignHeaders(Headers);
//Build the query parameter string, sorted and formatted for the StringToSign
Result := Result + BuildStringToSignResources(QueryPrefix, QueryParameters);
end;
function TCloudService.BuildStringToSignResourcePath(const URL: string): string;
begin
if FUseResourcePath then
Result := Result + GetHTTPRequestURI(URL);
end;
function TCloudService.BuildStringToSignResources(QueryPrefix: string; QueryParameters: TStringList): string;
begin
if FUseCanonicalizedResource then
Result := Result + BuildQueryParameterString(QueryPrefix, QueryParameters, true, false);
end;
function TCloudService.BuildStringToSignHeaders(Headers: TStringList): string;
var
RequiredHeadersInstanceOwner: Boolean;
RequiredHeaders: TStrings;
I, Count: Integer;
Aux: string;
lastParam, nextParam: string;
ConHeadPrefix: string;
begin
if (Headers <> nil) and (not Headers.Sorted) then
SortHeaders(Headers);
RequiredHeaders := GetRequiredHeaderNames(RequiredHeadersInstanceOwner);
//required headers. Values only, not header names
if (RequiredHeaders <> nil) then
begin
Count := RequiredHeaders.Count;
for I := 0 to Count - 1 do
begin
if (Headers <> nil) then
Aux := Headers.Values[RequiredHeaders[I]];
Result := Result + Format('%s'#10, [Aux]);
end;
end;
if RequiredHeadersInstanceOwner then
FreeAndNil(RequiredHeaders);
//Special headers with a specific prefix. Names (lowercase) and values
if FUseCanonicalizedHeaders and (Headers <> nil) then
begin
ConHeadPrefix := AnsiLowerCase(GetCanonicalizedHeaderPrefix);
Count := Headers.Count;
for I := 0 to Count - 1 do
begin
Aux := AnsiLowerCase(Headers.Names[I]);
if AnsiStartsStr(ConHeadPrefix, Aux) then
begin
nextParam := Aux;
if lastParam = EmptyStr then
begin
lastParam := nextParam;
Result := Result + Format('%s:%s', [nextParam, Headers.ValueFromIndex[I]]);
end
else if lastParam = nextParam then
Result := Result + Format(',%s', [Headers.ValueFromIndex[I]])
else
begin
lastParam := nextParam;
Result := Result + Format(#10'%s:%s', [nextParam, Headers.ValueFromIndex[I]]);
end;
end;
end;
end;
//add a newline at the end if at least one header name/value pair was added.
if lastParam <> EmptyStr then
Result := Result + #10'';
end;
procedure TCloudService.PopulateResponseInfo(ACloudHTTP: TCloudHTTP; ResponseInfo: TCloudResponseInfo);
var
HeadValuePair: TNameValuePair;
begin
if (ACloudHTTP <> nil) and (ACloudHTTP.Response <> nil) and (ResponseInfo <> nil) then
begin
ResponseInfo.StatusCode := ACloudHTTP.Response.StatusCode;
ResponseInfo.StatusMessage := ACloudHTTP.Response.StatusText;
//don't free these headers, they are owned by the response
ResponseInfo.Headers := TStringList.Create;
for HeadValuePair in ACloudHTTP.Response.Headers do
ResponseInfo.Headers.Values[Trim(HeadValuePair.Name)] := Trim(HeadValuePair.Value);
end;
end;
procedure TCloudService.SetDateFromString(Request: THTTPClient; const DateTimeAsString: string);
begin
//do nothing
end;
procedure TCloudService.AddHeaders(Request: THTTPClient; const headers: TStringList);
var
I: Integer;
begin
for I := 0 to Headers.Count - 1 do
Request.CustomHeaders[Headers.Names[I]] := Headers.ValueFromIndex[I];
end;
function TCloudService.PrepareRequest(const HTTPVerb: string; Headers, QueryParameters: TStringList;
const QueryPrefix: string; var URL: string): TCloudHTTP;
var
Content: TStream;
begin
Content := nil;
try
Result := PrepareRequest(HTTPVerb, Headers, QueryParameters, QueryPrefix, URL, Content);
finally
FreeAndNil(Content);
end;
end;
procedure TCloudService.PrepareRequestSignature(const HTTPVerb: string;
const Headers, QueryParameters: TStringList;
const StringToSign: string;
var URL: string; Request: TCloudHTTP; var Content: TStream);
var
AuthorizationString: string;
begin
if (Request <> nil) then
begin
AuthorizationString := FAuthenticator.BuildAuthorizationString(StringToSign);
Request.Client.CustomHeaders['Authorization'] := AuthorizationString;
end;
end;
function TCloudService.PrepareRequest(const HTTPVerb: string; Headers, QueryParameters: TStringList;
const QueryPrefix: string; var URL: string; var Content: TStream): TCloudHTTP;
var
StringToSign: string;
LProxySettings : TProxySettings;
begin
Result := TCloudHTTP.Create;
//Optionally set the request proxy information
if ConnectionInfo.RequestProxyHost <> EmptyStr then
begin
LProxySettings.Create(ConnectionInfo.RequestProxyHost, ConnectionInfo.RequestProxyPort);
Result.ProxyParams := LProxySettings;
end;
if FAuthenticator <> nil then
begin
StringToSign := BuildStringToSign(HTTPVerb, Headers, QueryParameters, QueryPrefix, URL);
PrepareRequestSignature(HTTPVerb, Headers, QueryParameters, StringToSign, URL, Result, Content);
end;
if Headers <> nil then
AddHeaders(Result.Client, Headers);
end;
function TCloudService.IssueDeleteRequest(URL: string; Headers, QueryParameters: TStringList;
const QueryPrefix: string; ResponseInfo: TCloudResponseInfo): TCloudHTTP;
var
ResponseStr: string;
begin
Result := IssueDeleteRequest(URL, Headers, QueryParameters, QueryPrefix, ResponseInfo, ResponseStr);
end;
function TCloudService.IssueDeleteRequest(URL: string; Headers, QueryParameters: TStringList;
const QueryPrefix: string; ResponseInfo: TCloudResponseInfo; out ResponseString: string): TCloudHTTP;
begin
Result := PrepareRequest('DELETE', Headers, QueryParameters, QueryPrefix, URL);
try
ResponseString := Result.Delete(URL);
PopulateResponseInfo(Result, ResponseInfo);
except
on E: Exception do
begin
Result.Free;
Raise;
end;
end;
end;
function TCloudService.IssueGetRequest(URL: string; Headers, QueryParameters: TStringList;
const QueryPrefix: string; ResponseInfo: TCloudResponseInfo): TCloudHTTP;
begin
Result := PrepareRequest('GET', Headers, QueryParameters, QueryPrefix, URL);
try
Result.Get(URL);
PopulateResponseInfo(Result, ResponseInfo);
except
on E: Exception do
begin
Result.Free;
Raise;
end;
end;
end;
function TCloudService.IssueHeadRequest(URL: string; Headers, QueryParameters: TStringList;
const QueryPrefix: string;
ResponseInfo: TCloudResponseInfo): TCloudHTTP;
begin
Result := PrepareRequest('HEAD', Headers, QueryParameters, QueryPrefix, URL);
try
Result.Head(URL);
PopulateResponseInfo(Result, ResponseInfo);
except
on E: Exception do
begin
Result.Free;
Raise;
end;
end;
end;
function TCloudService.IssueMergeRequest(URL: string; Headers, QueryParameters: TStringList;
const QueryPrefix: string; ResponseInfo: TCloudResponseInfo; Content: TStream): TCloudHTTP;
begin
// Android does not support MERGE as it is not standard
{$IFDEF ANDROID}
Headers.Values['x-method-override'] := 'PATCH';
Headers.Values['PATCHTYPE'] := 'MERGE';
Result := PrepareRequest('PUT', Headers, QueryParameters, QueryPrefix, URL);
{$ELSE}
Result := PrepareRequest('MERGE', Headers, QueryParameters, QueryPrefix, URL);
{$ENDIF}
try
Result.Merge(URL, Content);
PopulateResponseInfo(Result, ResponseInfo);
except
on E: Exception do
begin
Result.Free;
Raise;
end;
end;
end;
function TCloudService.IssueOptionsRequest(AURL: string; const AHeaders, AQueryParameters: TStringList;
const AQueryPrefix: string; const AResponseInfo: TCloudResponseInfo): TCloudHTTP;
var
LResponseStr: string;
begin
Result := IssueOptionsRequest(AURL, AHeaders, AQueryParameters, AQueryPrefix, AResponseInfo, LResponseStr);
end;
function TCloudService.IssueOptionsRequest(AURL: string; const AHeaders, AQueryParameters: TStringList;
const AQueryPrefix: string; const AResponseInfo: TCloudResponseInfo; out AResponseString: string): TCloudHTTP;
begin
Result := PrepareRequest('OPTIONS', AHeaders, AQueryParameters, AQueryPrefix, AURL);
try
AResponseString := Result.Options(AURL);
PopulateResponseInfo(Result, AResponseInfo);
except
on E: Exception do
begin
Result.Free;
Raise;
end;
end;
end;
function TCloudService.IssueGetRequest(URL: string; Headers, QueryParameters: TStringList;
const QueryPrefix: string; ResponseInfo: TCloudResponseInfo;
ResponseContent: TStream): TCloudHTTP;
begin
Result := PrepareRequest('GET', Headers, QueryParameters, QueryPrefix, URL);
try
Result.Get(URL, ResponseContent);
PopulateResponseInfo(Result, ResponseInfo);
except
on E: Exception do
begin
Result.Free;
Raise;
end;
end;
end;
function TCloudService.IssueGetRequest(URL: string; Headers, QueryParameters: TStringList;
const QueryPrefix: string; ResponseInfo: TCloudResponseInfo;
out ResponseString: string): TCloudHTTP;
var
MemoryStream: TMemoryStream;
Reader: TStreamReader;
begin
MemoryStream := nil;
Result := PrepareRequest('GET', Headers, QueryParameters, QueryPrefix, URL);
try
try
MemoryStream := TMemoryStream.Create;
Result.Get(URL, MemoryStream);
PopulateResponseInfo(Result, ResponseInfo);
MemoryStream.Position := 0;
Reader := TStreamReader.Create(MemoryStream, True (* Detect BOM *));
try
ResponseString := Reader.ReadToEnd;
finally
Reader.Free;
end;
except
on E: Exception do
begin
Result.Free;
Raise;
end;
end;
finally
MemoryStream.Free;
end;
end;
function TCloudService.IssuePostRequest(URL: string; Headers, QueryParameters: TStringList;
const QueryPrefix: string; ResponseInfo: TCloudResponseInfo;
Content: TStream; out ResponseString: string): TCloudHTTP;
var
OwnStream: Boolean;
begin
OwnStream := Content = nil;
Result := PrepareRequest('POST', Headers, QueryParameters, QueryPrefix, URL, Content);
try
try
ResponseString := Result.Post(URL, Content);
PopulateResponseInfo(Result, ResponseInfo);
except
on E: Exception do
begin
Result.Free;
Raise;
end;
end;
finally
if OwnStream then
FreeAndNil(Content);
end;
end;
function TCloudService.IssuePostRequest(URL: string; Headers, QueryParameters: TStringList;
const QueryPrefix: string; ResponseInfo: TCloudResponseInfo;
Content: TStream): TCloudHTTP;
var
OutStr: string;
begin
Result := IssuePostRequest(URL, Headers, QueryParameters, QueryPrefix, ResponseInfo, Content, OutStr);
end;
function TCloudService.IssuePutRequest(URL: string; Headers, QueryParameters: TStringList;
const QueryPrefix: string;
ResponseInfo: TCloudResponseInfo;
Content: TStream;
out ResponseString: string): TCloudHTTP;
begin
Result := PrepareRequest('PUT', Headers, QueryParameters, QueryPrefix, URL);
try
if Content <> nil then
ResponseString := Result.Put(URL, Content)
else
ResponseString := Result.Put(URL);
PopulateResponseInfo(Result, ResponseInfo);
except
on E: Exception do
begin
Result.Free;
Raise;
end;
end;
end;
function TCloudService.IssuePutRequest(URL: string; Headers, QueryParameters: TStringList;
const QueryPrefix: string; ResponseInfo: TCloudResponseInfo;
Content: TStream): TCloudHTTP;
var
RespStr: string;
begin
Result := IssuePutRequest(URL, Headers, QueryParameters, QueryPrefix, ResponseInfo, Content, RespStr);
end;
{TAzureHTTP}
constructor TCloudHTTP.Create;
begin
Create(nil);
end;
constructor TCloudHTTP.Create(AOwner: TComponent);
begin
inherited;
FClient := THTTPClient.Create;
FClient.OnValidateServerCertificate := DoValidateServerCertificate;
end;
destructor TCloudHTTP.Destroy;
begin
if Assigned(FClient) then
begin
FClient.Free;
FClient := nil;
end;
inherited;
end;
procedure TCloudHTTP.DoValidateServerCertificate(const Sender: TObject;
const ARequest: TURLRequest; const Certificate: TCertificate; var Accepted: Boolean);
begin
Accepted := True;
end;
function TCloudHTTP.Delete(AURL: string): string;
begin
FResponse := FClient.Delete(AURL);
Result := FResponse.ContentAsString;
end;
function TCloudHTTP.Delete(AURL: string; AResponseStream: TStream): string;
begin
FResponse := FClient.Delete(AURL,AResponseStream);
Result := FResponse.ContentAsString();
end;
function TCloudHTTP.Get(AURL: string): string;
begin
FResponse := FClient.Get(AURL);
Result := FResponse.ContentAsString();
end;
procedure TCloudHTTP.Get(AURL: string; AResponseContent: TStream);
begin
FResponse := FClient.Get(AURL, AResponseContent);
end;
function TCloudHTTP.GetProxyParams: TProxySettings;
begin
Result := FClient.ProxySettings;
end;
function TCloudHTTP.GetResponse: IHTTPResponse;
begin
Result := FResponse;
end;
function TCloudHTTP.GetResponseCode: Integer;
begin
Result := FResponse.StatusCode;
end;
function TCloudHTTP.GetResponseText: string;
begin
Result := FResponse.StatusText;
end;
procedure TCloudHTTP.Head(AURL: string);
begin
FResponse := FClient.Head(AURL);
end;
procedure TCloudHTTP.Merge(AURL: string; RequestStream: TStream);
begin
{$IFDEF ANDROID}
FResponse := FClient.MergeAlternative(AURL, RequestStream);
{$ELSE}
FResponse := FClient.Merge(AURL, RequestStream);
{$ENDIF}
end;
function TCloudHTTP.Options(const AURL: string): string;
begin
FResponse := FClient.Options(AURL);
Result := FResponse.ContentAsString();
end;
procedure TCloudHTTP.Options(const AURL: string; AResponseContent: TStream);
begin
FResponse := FClient.Options(AURL, AResponseContent);
end;
function TCloudHTTP.Post(AURL: string; Source: TStream): string;
var
LRespStream: TStringStream;
begin
//get the result stream so we handle charset ourselves
Result := EmptyStr;
LRespStream := TStringStream.Create(EmptyStr, TEncoding.UTF8);
try
FResponse := FClient.Post(AURL, Source, LRespStream);
Result := LRespStream.DataString;
finally
FreeAndNil(LRespStream);
end;
end;
function TCloudHTTP.Put(AURL: string; Source: TStream): string;
begin
FResponse := FClient.Put(AURL, Source);
Result := FResponse.ContentAsString();
end;
function TCloudHTTP.Put(AURL: string): string;
begin
Result := Put(AURL, nil);
end;
procedure TCloudHTTP.SetAuthentication(const AUser, APassword: string);
begin
FClient.CredentialsStorage.AddCredential(
TCredentialsStorage.TCredential.Create(TAuthTargetType.Server, '', '', AUser, APassword))
end;
procedure TCloudHTTP.SetProxyParams(const Value: TProxySettings);
begin
FClient.ProxySettings := Value;
if FClient.ProxySettings.UserName <> '' then
FClient.CredentialsStorage.AddCredential(
TCredentialsStorage.TCredential.Create(TAuthTargetType.Proxy, '', '', FClient.ProxySettings.UserName, FClient.ProxySettings.Password))
end;
{ TCloudResponseInfo }
procedure TCloudResponseInfo.Assign(const ASource: TObject);
begin
if ASource is TCloudResponseInfo then
begin
FStatusCode := TCloudResponseInfo(ASource).FStatusCode;
FStatusMessage := TCloudResponseInfo(ASource).FStatusMessage;
if FHeaders = nil then
FHeaders := TStringList.Create
else
FHeaders.Clear;
FHeaders.Assign(TCloudResponseInfo(ASource).FHeaders);
end
else
raise EConvertError.CreateFmt(SInvalidSourceException, [ClassName]);
end;
destructor TCloudResponseInfo.Destroy;
begin
try
FreeAndNil(FHeaders);
except
end;
inherited;
end;
procedure TCloudResponseInfo.SetHeaders(NewHeaders: TStrings);
begin
FreeAndNil(FHeaders);
FHeaders := NewHeaders;
end;
{ TCloudTableRow }
constructor TCloudTableRow.Create(SupportsDataType: Boolean);
begin
FColumns := TObjectList<TCloudTableColumn>.Create;
FSupportsDataType := SupportsDataType;
end;
destructor TCloudTableRow.Destroy;
begin
FColumns.Free;
inherited;
end;
function TCloudTableRow.GetColumn(const Name: string): TCloudTableColumn;
var
I, Count: Integer;
begin
Result := nil;
TMonitor.Enter(FColumns);
try
Count := FColumns.Count;
for I := 0 to Count - 1 do
begin
if AnsiCompareText(Name, FColumns[I].Name) = 0 then
Exit(FColumns[I]);
end;
finally
TMonitor.Exit(FColumns);
end;
end;
function TCloudTableRow.GetColumnValue(const Name: string; out Value: string): Boolean;
var
Col: TCloudTableColumn;
begin
Value := '';
Col := GetColumn(Name);
Result := False;
if Col <> nil then
begin
Result := True;
Value := Col.Value;
end;
end;
function TCloudTableRow.DeleteColumn(const Name: string): Boolean;
var
I, Count: Integer;
begin
Result := False;
TMonitor.Enter(FColumns);
try
Count := FColumns.Count;
for I := 0 to Count - 1 do
begin
if AnsiCompareText(Name, FColumns[I].Name) = 0 then
begin
FColumns.Delete(I);
Exit(True);
end;
end;
finally
TMonitor.Exit(FColumns);
end;
end;
procedure TCloudTableRow.SetColumn(const Name, Value, DataType: string; const Replace: Boolean);
var
Col: TCloudTableColumn;
begin
Col := GetColumn(Name);
TMonitor.Enter(FColumns);
try
//if the column doesn't exists, or if it does exist but Replace is set to false
//and the new value being set is different than the current value, then make a new column.
if (Col = nil) or ((not Replace) and (not AnsiSameStr(Col.Value, Value))) then
begin
Col := TCloudTableColumn.Create;
Col.Name := Name;
FColumns.Add(Col);
end;
Col.Value := Value;
Col.DataType := DataType;
finally
TMonitor.Exit(FColumns);
end;
end;
{ TCloudQueueMessage }
constructor TCloudQueueMessage.Create(const MessageId, MessageText: string; Properties: TStrings);
begin
FMessageId := MessageId;
FMessageText := MessageText;
if Properties <> nil then
FProperties := Properties
else
FProperties := TStringList.Create;
end;
class function TCloudQueueMessage.CreateFromRecord(ACloudQueueMessage: TCloudQueueMessageItem): TCloudQueueMessage;
var
LItem: TPair<string, string>;
begin
Result := TCloudQueueMessage.Create(ACloudQueueMessage.MessageId, ACloudQueueMessage.MessageText);
Result.PopReceipt := ACloudQueueMessage.PopReceipt;
for LItem in ACloudQueueMessage.Properties do
Result.Properties.AddPair(LItem.Key, LItem.Value);
end;
constructor TCloudQueueMessage.Create(const MessageId, MessageText: string);
begin
Create(MessageId, MessageText, nil);
end;
destructor TCloudQueueMessage.Destroy;
begin
FreeAndNil(FProperties);
inherited;
end;
{ TCloudConnectionInfo }
constructor TCloudConnectionInfo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Protocol := 'http';
end;
destructor TCloudConnectionInfo.Destroy;
begin
if FAuthentication <> nil then
begin
FAuthentication.FConnectionInfo := nil;
FAuthentication := nil;
end;
inherited Destroy;
end;
function TCloudConnectionInfo.GetAccountKey: string;
begin
Result := FAccountKey;
end;
procedure TCloudConnectionInfo.SetAccountKey(const AValue: string);
begin
if FAccountKey <> AValue then
begin
FAccountKey := AValue;
if FAuthentication <> nil then
FAuthentication.AssignKey(AccountKey);
end;
end;
function TCloudConnectionInfo.GetAccountName: string;
begin
Result := FAccountName;
end;
function TCloudConnectionInfo.IsProtocolStored: Boolean;
begin
Result := not SameText(FProtocol, 'http');
end;
{ TCloudQueue }
class function TCloudQueue.Create(Name, URL: string): TCloudQueue;
var
Inst: TCloudQueue;
begin
Inst.Name := Name;
Inst.URL := URL;
Result := Inst;
end;
class function TCloudQueue.Create(URL: string): TCloudQueue;
var
Index: Integer;
Inst: TCloudQueue;
begin
Inst.URL := URL;
Index := URL.LastDelimiter('/') + 1;
if (Index > 0) and (Index < URL.Length) then
Inst.Name := URL.Substring(Index)
else
Inst.Name := URL;
Result := Inst;
end;
end.
|
unit BillInterface;
interface
type
IBill = interface(IInterface)
function GetBillDate: TDate;
function GetBillNumber: Integer;
function GetBillNumberStr: String;
function GetBillWidth: Integer;
function GetDollarCource: Double;
function GetEuroCource: Double;
function GetShipmentDate: TDate;
property BillDate: TDate read GetBillDate;
property BillNumber: Integer read GetBillNumber;
property BillNumberStr: String read GetBillNumberStr;
property BillWidth: Integer read GetBillWidth;
property DollarCource: Double read GetDollarCource;
property EuroCource: Double read GetEuroCource;
property ShipmentDate: TDate read GetShipmentDate;
end;
implementation
end.
|
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is frmBaseSettingsFrame.pas, released April 2000.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
unit frmBaseSettingsFrame;
{ SetttingsFrame
AFS 29 Dec 1999
Subclass of TFrame with common interface for settings }
{$I JcfGlobal.inc}
interface
uses
{delphi }
Windows, Classes, Controls,
Forms, ShellAPI, SysUtils,
{ local }
frDrop;
type
TfrSettingsFrame = class(TFrameDrop)
private
// event handler
fcOnChange: TNotifyEvent;
protected
fiHelpContext: THelpContext;
procedure CallOnChange;
public
constructor Create(aOwner: TComponent); override;
procedure Read; virtual; abstract;
procedure Write; virtual; abstract;
procedure ShowContextHelp;
property OnChange: TNotifyEvent Read fcOnChange Write fcOnChange;
end;
TSettingsFrameClass = class of TfrSettingsFrame;
const
GUI_PAD = 3;
implementation
uses JcfHelp;
{$ifdef FPC}
{$R *.lfm}
{$else}
{$R *.dfm}
{$endif}
constructor TfrSettingsFrame.Create(aOwner: TComponent);
begin
inherited;
fcOnChange := nil;
fiHelpContext := 0;
end;
procedure TfrSettingsFrame.CallOnChange;
begin
if Assigned(fcOnChange) then
fcOnChange(self);
end;
procedure TfrSettingsFrame.ShowContextHelp;
var
liHelpContext: integer;
begin
liHelpContext := fiHelpContext;
if liHelpContext <= 0 then
liHelpContext := HELP_MAIN;
try
Application.HelpContext(liHelpContext);
except
if FileExists(Application.HelpFile) then
ShellExecute(Handle, 'open', PChar(Application.HelpFile), nil, nil, SW_SHOWNORMAL);
end;
end;
end.
|
unit RPreAchatLocDTOU;
interface
TYPE TRPreAchatLocDTO =class(TObject)
private
Fprixpreachatloc: Double;
Fqtepreachatloc: Double;
Fidbarcodeloc: string;
Fidrpreachatloc: Integer;
Fidpreachatloc: Integer;
procedure Setidbarcodeloc(const Value: string);
procedure Setidpreachatloc(const Value: Integer);
procedure Setidrpreachatloc(const Value: Integer);
procedure Setprixpreachatloc(const Value: Double);
procedure Setqtepreachatloc(const Value: Double);
public
constructor create();overload;
constructor create(id:Integer);overload;
property idpreachatloc:Integer read Fidpreachatloc write Setidpreachatloc;
property idrpreachatloc:Integer read Fidrpreachatloc write Setidrpreachatloc;
property idbarcodeloc:string read Fidbarcodeloc write Setidbarcodeloc;
property prixpreachatloc: Double read Fprixpreachatloc write Setprixpreachatloc;
property qtepreachatloc: Double read Fqtepreachatloc write Setqtepreachatloc;
end;
implementation
{ TRPreAchatLocDTO }
constructor TRPreAchatLocDTO.create(id: Integer);
begin
self.idrpreachatloc:=id;
end;
constructor TRPreAchatLocDTO.create;
begin
end;
procedure TRPreAchatLocDTO.Setidbarcodeloc(const Value: string);
begin
Fidbarcodeloc := Value;
end;
procedure TRPreAchatLocDTO.Setidpreachatloc(const Value: Integer);
begin
Fidpreachatloc := Value;
end;
procedure TRPreAchatLocDTO.Setidrpreachatloc(const Value: Integer);
begin
Fidrpreachatloc := Value;
end;
procedure TRPreAchatLocDTO.Setprixpreachatloc(const Value: Double);
begin
Fprixpreachatloc := Value;
end;
procedure TRPreAchatLocDTO.Setqtepreachatloc(const Value: Double);
begin
Fqtepreachatloc := Value;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Androidapi.Looper;
interface
(*$HPPEMIT '#include <android/looper.h>' *)
{$I Androidapi.inc}
const
{ Option for ALooper_prepare: this looper will accept calls to
ALooper_addFd() that do not have a callback (that is provide NULL
for the callback). In this case the caller of ALooper_pollOnce()
or ALooper_pollAll() MUST check the return from these functions to
discover when data is available on such fds and process it.
}
ALOOPER_PREPARE_ALLOW_NON_CALLBACKS = 1 shl 0;
{$EXTERNALSYM ALOOPER_PREPARE_ALLOW_NON_CALLBACKS}
const
{ Result from ALooper_pollOnce() and ALooper_pollAll():
The poll was awoken using wake() before the timeout expired
and no callbacks were executed and no other file descriptors were ready.
}
ALOOPER_POLL_WAKE = -1;
{$EXTERNALSYM ALOOPER_POLL_WAKE}
{ Result from ALooper_pollOnce() and ALooper_pollAll():
One or more callbacks were executed.
}
ALOOPER_POLL_CALLBACK = -2;
{$EXTERNALSYM ALOOPER_POLL_CALLBACK}
{ Result from ALooper_pollOnce() and ALooper_pollAll():
The timeout expired.
}
ALOOPER_POLL_TIMEOUT = -3;
{$EXTERNALSYM ALOOPER_POLL_TIMEOUT}
{ Result from ALooper_pollOnce() and ALooper_pollAll():
An error occurred.
}
ALOOPER_POLL_ERROR = -4;
{$EXTERNALSYM ALOOPER_POLL_ERROR}
{ Flags for file descriptor events that a looper can monitor.
These flag bits can be combined to monitor multiple events at once.
}
const
{ The file descriptor is available for read operations.
}
ALOOPER_EVENT_INPUT = 1 shl 0;
{$EXTERNALSYM ALOOPER_EVENT_INPUT}
{ The file descriptor is available for write operations.
}
ALOOPER_EVENT_OUTPUT = 1 shl 1;
{$EXTERNALSYM ALOOPER_EVENT_OUTPUT}
{ The file descriptor has encountered an error condition.
The looper always sends notifications about errors; it is not necessary
to specify this event flag in the requested event set.
}
ALOOPER_EVENT_ERROR = 1 shl 2;
{$EXTERNALSYM ALOOPER_EVENT_ERROR}
{ The file descriptor was hung up.
For example, indicates that the remote end of a pipe or socket was closed.
The looper always sends notifications about hangups; it is not necessary
to specify this event flag in the requested event set.
}
ALOOPER_EVENT_HANGUP = 1 shl 3;
{$EXTERNALSYM ALOOPER_EVENT_HANGUP}
{ The file descriptor is invalid.
For example, the file descriptor was closed prematurely.
The looper always sends notifications about invalid file descriptors; it is not necessary
to specify this event flag in the requested event set.
}
ALOOPER_EVENT_INVALID = 1 shl 4;
{$EXTERNALSYM ALOOPER_EVENT_INVALID}
type
ALooper = record end;
{$EXTERNALSYM ALooper}
PALooper = ^ALooper;
{ Returns the looper associated with the calling thread, or NULL if
there is not one.
}
function ALooper_forThread: PALooper; cdecl;
external AndroidLib name 'ALooper_forThread';
{$EXTERNALSYM ALooper_forThread}
{ Prepares a looper associated with the calling thread, and returns it.
If the thread already has a looper, it is returned. Otherwise, a new
one is created, associated with the thread, and returned.
The opts may be ALOOPER_PREPARE_ALLOW_NON_CALLBACKS or 0.
}
function ALooper_prepare(Options: Integer): PALooper; cdecl;
external AndroidLib name 'ALooper_prepare';
{$EXTERNALSYM ALooper_prepare}
{ Acquire a reference on the given ALooper object. This prevents the object
from being deleted until the reference is removed. This is only needed
to safely hand an ALooper from one thread to another.
}
procedure ALooper_acquire(Looper: PALooper); cdecl;
external AndroidLib name 'ALooper_acquire';
{$EXTERNALSYM ALooper_acquire}
{ Remove a reference that was previously acquired with ALooper_acquire().
}
procedure ALooper_release(Looper: PALooper); cdecl;
external AndroidLib name 'ALooper_release';
{$EXTERNALSYM ALooper_release}
{ For callback-based event loops, this is the prototype of the function
that is called. It is given the file descriptor it is associated with,
a bitmask of the poll events that were triggered (typically ALOOPER_EVENT_INPUT),
and the data pointer that was originally supplied.
Implementations should return 1 to continue receiving callbacks, or 0
to have this file descriptor and callback unregistered from the looper.
}
type
ALooper_callbackFunc = function(FileDescriptor, Events: Integer; Data: Pointer): Integer; cdecl;
{$EXTERNALSYM ALooper_callbackFunc}
{ Waits for events to be available, with optional timeout in milliseconds.
Invokes callbacks for all file descriptors on which an event occurred.
If the timeout is zero, returns immediately without blocking.
If the timeout is negative, waits indefinitely until an event appears.
Returns ALOOPER_POLL_WAKE if the poll was awoken using wake() before
the timeout expired and no callbacks were invoked and no other file
descriptors were ready.
Returns ALOOPER_POLL_CALLBACK if one or more callbacks were invoked.
Returns ALOOPER_POLL_TIMEOUT if there was no data before the given
timeout expired.
Returns ALOOPER_POLL_ERROR if an error occurred.
Returns a value >= 0 containing an identifier if its file descriptor has data
and it has no callback function (requiring the caller here to handle it).
In this (and only this) case outFd, outEvents and outData will contain the poll
events and data associated with the fd, otherwise they will be set to NULL.
This method does not return until it has finished invoking the appropriate callbacks
for all file descriptors that were signalled.
}
function ALooper_pollOnce(TimeOutMilliSeconds: Integer; OutFileDescriptor, OutEvents: PInteger; OutData: PPointer): Integer; cdecl;
external AndroidLib name 'ALooper_pollOnce';
{$EXTERNALSYM ALooper_pollOnce}
{ Like ALooper_pollOnce(), but performs all pending callbacks until all
data has been consumed or a file descriptor is available with no callback.
This function will never return ALOOPER_POLL_CALLBACK.
}
function ALooper_pollAll(TimeOutMilliSeconds: Integer; OutFileDescriptor, OutEvents: PInteger; OutData: PPointer): Integer; cdecl;
external AndroidLib name 'ALooper_pollAll';
{$EXTERNALSYM ALooper_pollAll}
{ Wakes the poll asynchronously.
This method can be called on any thread.
This method returns immediately.
}
procedure ALooper_wake(Looper: PALooper); cdecl;
external AndroidLib name 'ALooper_wake';
{$EXTERNALSYM ALooper_wake}
{ Adds a new file descriptor to be polled by the looper.
If the same file descriptor was previously added, it is replaced.
"fd" is the file descriptor to be added.
"ident" is an identifier for this event, which is returned from ALooper_pollOnce().
The identifier must be >= 0, or ALOOPER_POLL_CALLBACK if providing a non-NULL callback.
"events" are the poll events to wake up on. Typically this is ALOOPER_EVENT_INPUT.
"callback" is the function to call when there is an event on the file descriptor.
"data" is a private data pointer to supply to the callback.
There are two main uses of this function:
(1) If "callback" is non-NULL, then this function will be called when there is
data on the file descriptor. It should execute any events it has pending,
appropriately reading from the file descriptor. The 'ident' is ignored in this case.
(2) If "callback" is NULL, the 'ident' will be returned by ALooper_pollOnce
when its file descriptor has data available, requiring the caller to take
care of processing it.
Returns 1 if the file descriptor was added or -1 if an error occurred.
This method can be called on any thread.
This method may block briefly if it needs to wake the poll.
}
function ALooper_addFd(Looper: PALooper; FileHandler, Ident, Events: Integer; Callback: ALooper_callbackFunc; Data: Pointer): Integer; cdecl;
external AndroidLib name 'ALooper_addFd';
{$EXTERNALSYM ALooper_addFd}
{ Removes a previously added file descriptor from the looper.
When this method returns, it is safe to close the file descriptor since the looper
will no longer have a reference to it. However, it is possible for the callback to
already be running or for it to run one last time if the file descriptor was already
signalled. Calling code is responsible for ensuring that this case is safely handled.
For example, if the callback takes care of removing itself during its own execution either
by returning 0 or by calling this method, then it can be guaranteed to not be invoked
again at any later time unless registered anew.
Returns 1 if the file descriptor was removed, 0 if none was previously registered
or -1 if an error occurred.
This method can be called on any thread.
This method may block briefly if it needs to wake the poll.
}
function ALooper_removeFd(Looper: PALooper; FileHandler: Integer): Integer; cdecl;
external AndroidLib name 'ALooper_removeFd';
{$EXTERNALSYM ALooper_removeFd}
implementation
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 untEasyUtilInit;
interface
uses
SysUtils, Classes, Windows, DB, DBClient;
type
TLoadPkg = function (var AParamList: TStrings): Boolean; stdcall;
//加载指定包
function LoadPkg(APkgName, AFunctionName: string; var AParamList: TStrings): Integer;
//根据编号获取可执行查询的SQL语句
function GetSysSQL(ASQLEName: string): string;
implementation
var
tmpLoadPkg: TLoadPkg;
//加载指定包
function LoadPkg(APkgName, AFunctionName: string; var AParamList: TStrings): Integer;
begin
// Result := -1;
try
if not FileExists(APkgName) then
Result := -2
else
begin
try
Result := LoadPackage(APkgName);
except
Result := -3;
end;
if Result > 0 then
begin
tmpLoadPkg := GetProcAddress(Result, PChar(AFunctionName));
if @tmpLoadPkg <> nil then
tmpLoadPkg(AParamList);
end;
end;
except
Result := -4;
end;
end;
//根据编号获取可执行查询的SQL语句
function GetSysSQL(ASQLEName: string): string;
var
TmpClientDataSet: TClientDataSet;
begin
Result := '';
TmpClientDataSet := TClientDataSet.Create(nil);
try
// TmpClientDataSet.
with TmpClientDataSet do
begin
CommandText := 'SELECT sSQL FROM sysSQL WHERE iFlag = 1 AND sSQLEName = '
+ QuotedStr(ASQLEName);
Open;
if TmpClientDataSet.RecordCount > 0 then
Result := fieldbyname('sSQL').AsString;
end;
finally
TmpClientDataSet.Free;
end;
end;
end.
|
unit ClientData;
interface
uses
System.SysUtils, System.Classes, Data.DB, Data.Win.ADODB, Vcl.ImgList,
Vcl.Controls, Variants;
type
TdmClient = class(TDataModule)
dstPersonalInfo: TADODataSet;
dscPersonalInfo: TDataSource;
dstEntity: TADODataSet;
dstContactInfo: TADODataSet;
dscContactInfo: TDataSource;
dstAddressInfo: TADODataSet;
dscAddressInfo: TDataSource;
dstResStatus: TADODataSet;
dscResStatus: TDataSource;
dstEmpStatus: TADODataSet;
dscEmpStatus: TDataSource;
dstEmplInfo: TADODataSet;
dscEmplInfo: TDataSource;
dstIdentInfo: TADODataSet;
dscIdentInfo: TDataSource;
dstAddressInfo2: TADODataSet;
dscAddressInfo2: TDataSource;
dstAcctInfo: TADODataSet;
dscAcctInfo: TDataSource;
dstLoans: TADODataSet;
dscLoans: TDataSource;
dstComakers: TADODataSet;
dscComakers: TDataSource;
dstGroups: TADODataSet;
dstLedger: TADODataSet;
dstLedgerdue: TDateTimeField;
dstLedgerdocument_no: TStringField;
dstLedgerdebit_amt_p: TBCDField;
dstLedgercredit_amt_p: TBCDField;
dstLedgerbalance_p: TBCDField;
dstLedgerdebit_amt_i: TBCDField;
dstLedgercredit_amt_i: TBCDField;
dstLedgerbalance_i: TBCDField;
dstLedgersort_order: TSmallintField;
dscLedger: TDataSource;
dstPromissoryNotes: TADODataSet;
dscPromissoryNotes: TDataSource;
procedure dstPersonalInfoBeforeOpen(DataSet: TDataSet);
procedure dstEntityBeforeOpen(DataSet: TDataSet);
procedure dstContactInfoBeforeOpen(DataSet: TDataSet);
procedure dstEntityBeforePost(DataSet: TDataSet);
procedure dstPersonalInfoBeforePost(DataSet: TDataSet);
procedure dstContactInfoBeforePost(DataSet: TDataSet);
procedure dstAddressInfoAfterPost(DataSet: TDataSet);
procedure dstAddressInfoBeforeOpen(DataSet: TDataSet);
procedure dstAddressInfoBeforePost(DataSet: TDataSet);
procedure dstEmplInfoBeforeOpen(DataSet: TDataSet);
procedure dstEmplInfoBeforePost(DataSet: TDataSet);
procedure dstIdentInfoBeforeOpen(DataSet: TDataSet);
procedure dstIdentInfoBeforePost(DataSet: TDataSet);
procedure dstAddressInfo2AfterPost(DataSet: TDataSet);
procedure dstAddressInfo2BeforeOpen(DataSet: TDataSet);
procedure dstAddressInfo2BeforePost(DataSet: TDataSet);
procedure dstAcctInfoBeforeOpen(DataSet: TDataSet);
procedure dstAcctInfoBeforePost(DataSet: TDataSet);
procedure dstPersonalInfoAfterOpen(DataSet: TDataSet);
procedure dstPersonalInfoAfterPost(DataSet: TDataSet);
procedure dstEntityAfterOpen(DataSet: TDataSet);
procedure dstAddressInfoAfterOpen(DataSet: TDataSet);
procedure dstAddressInfo2AfterOpen(DataSet: TDataSet);
procedure dstEmplInfoAfterOpen(DataSet: TDataSet);
procedure dstEmplInfoAfterPost(DataSet: TDataSet);
procedure dstAcctInfoAfterOpen(DataSet: TDataSet);
procedure dstIdentInfoAfterOpen(DataSet: TDataSet);
procedure dstIdentInfoAfterPost(DataSet: TDataSet);
procedure dstLoansAfterScroll(DataSet: TDataSet);
procedure dstComakersBeforeOpen(DataSet: TDataSet);
procedure dstLoansBeforeOpen(DataSet: TDataSet);
procedure dstClientLoanClass2BeforeOpen(DataSet: TDataSet);
procedure dstGroupsBeforeOpen(DataSet: TDataSet);
procedure dstClientLoanClass2AfterScroll(DataSet: TDataSet);
procedure dstAcctInfoAfterPost(DataSet: TDataSet);
procedure dstAcctInfoBeforeDelete(DataSet: TDataSet);
procedure dstPromissoryNotesBeforeOpen(DataSet: TDataSet);
procedure dstPromissoryNotesAfterOpen(DataSet: TDataSet);
procedure dstPromissoryNotesBeforePost(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
end;
var
dmClient: TdmClient;
implementation
uses
AppData, DBUtil, Client, IFinanceGlobal, AppConstants, Referee, Landlord,
Employer, ImmediateHead, BankAccount, IdentityDoc, LoanClassification, Bank,
Group;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TdmClient.dstAcctInfoAfterOpen(DataSet: TDataSet);
var
acct: TBankAccount;
bk: TBank;
begin
(DataSet as TADODataSet).Properties['Unique table'].Value := 'AcctInfo';
with DataSet do
begin
cln.ClearBankAccounts;
while not Eof do
begin
bk := TBank.Create;
bk.Id := FieldByName('bank_id').AsString;
bk.BankName := FieldByName('bank_name').AsString;
bk.BankCode := FieldByName('bank_code').AsString;
bk.Branch := FieldByName('branch').AsString;
acct := TBankAccount.Create;
acct.Bank := bk;
acct.AccountNo := FieldByName('acct_no').AsString;
acct.CardNo := FieldByName('card_no').AsString;
acct.CardExpiry := FieldByName('card_expiry').AsDateTime;
cln.AddBankAccount(acct);
Next;
end;
end;
end;
procedure TdmClient.dstAcctInfoAfterPost(DataSet: TDataSet);
var
bankId: string;
begin
bankId := DataSet.FieldByName('bank_id').AsString;
RefreshDataSet(bankId,'bank_id',DataSet);
end;
procedure TdmClient.dstAcctInfoBeforeDelete(DataSet: TDataSet);
begin
cln.RemoveBankAccountByAccountNo(DataSet.FieldByName('acct_no').AsString);
end;
procedure TdmClient.dstAcctInfoBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := cln.Id;
end;
procedure TdmClient.dstAcctInfoBeforePost(DataSet: TDataSet);
begin
if DataSet.State = dsInsert then
DataSet.FieldByName('entity_id').AsString := cln.Id;
end;
procedure TdmClient.dstAddressInfo2AfterOpen(DataSet: TDataSet);
begin
if (cln.HasId) and (DataSet.FieldByName('landlord').AsString <> '') then
begin
cln.LandlordProv := TLandlord.Create;
cln.LandlordProv.Id := DataSet.FieldByName('landlord').AsString;
cln.LandlordProv.Name := DataSet.FieldByName('landlord_name').AsString;
cln.LandlordProv.Mobile := DataSet.FieldByName('landlord_mobile').AsString;
cln.LandlordProv.Telephone := DataSet.FieldByName('landlord_homephone').AsString;
end
end;
procedure TdmClient.dstAddressInfo2AfterPost(DataSet: TDataSet);
begin
DataSet.Edit;
end;
procedure TdmClient.dstAddressInfo2BeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := cln.Id;
end;
procedure TdmClient.dstAddressInfo2BeforePost(DataSet: TDataSet);
begin
if DataSet.State = dsInsert then
DataSet.FieldByName('entity_id').AsString := cln.Id;
DataSet.FieldByName('is_prov').AsInteger := 1;
if Assigned(cln.LandlordProv) then
DataSet.FieldByName('landlord').AsString := cln.LandlordProv.Id
else
DataSet.FieldByName('landlord').Value := null;
end;
procedure TdmClient.dstAddressInfoAfterOpen(DataSet: TDataSet);
begin
if (cln.HasId) and (DataSet.FieldByName('landlord').AsString <> '') then
begin
cln.LandlordPres := TLandlord.Create;
cln.LandlordPres.Id := DataSet.FieldByName('landlord').AsString;
cln.LandlordPres.Name := DataSet.FieldByName('landlord_name').AsString;
cln.LandlordPres.Mobile := DataSet.FieldByName('landlord_mobile').AsString;
cln.LandlordPres.Telephone := DataSet.FieldByName('landlord_homephone').AsString;
end
end;
procedure TdmClient.dstAddressInfoAfterPost(DataSet: TDataSet);
begin
DataSet.Edit;
end;
procedure TdmClient.dstAddressInfoBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := cln.Id;
end;
procedure TdmClient.dstAddressInfoBeforePost(DataSet: TDataSet);
begin
if DataSet.State = dsInsert then
DataSet.FieldByName('entity_id').AsString := cln.Id;
DataSet.FieldByName('is_prov').AsInteger := 0;
if Assigned(cln.LandlordPres) then
DataSet.FieldByName('landlord').AsString := cln.LandlordPres.Id
else
DataSet.FieldByName('landlord').Value := null;
end;
procedure TdmClient.dstClientLoanClass2AfterScroll(DataSet: TDataSet);
var
clId, term, comakersMin, comakersMax, age: integer;
clName: string;
interest, maxLoan: currency;
validFrom, validUntil: TDate;
begin
with DataSet do
begin
clId := FieldByName('class_id').AsInteger;
clName := FieldByName('class_name').AsString;
interest := FieldByName('int_rate').AsCurrency;
term := FieldByName('term').AsInteger;
maxLoan := FieldByName('max_loan').AsCurrency;
comakersMin := FieldByName('comakers_min').AsInteger;
comakersMax := FieldByName('comakers_max').AsInteger;
validFrom := FieldByName('valid_from').AsDateTime;
validUntil := FieldByName('valid_until').AsDateTime;
age := FieldByName('max_age').AsInteger;
end;
if not Assigned(lnc) then
lnc := TLoanClassification.Create(clId, clName, interest,
term, maxLoan, comakersMin, comakersMax, validFrom, validUntil,
age, nil, nil,'')
else
begin
lnc.ClassificationId := clId;
lnc.ClassificationName := clName;
lnc.Interest := interest;
lnc.Term := term;
lnc.MaxLoan := maxLoan;
lnc.ComakersMin := comakersMin;
lnc.ComakersMax := comakersMax;
lnc.ValidFrom := validFrom;
lnc.ValidUntil := validUntil;
lnc.MaxAge := age;
end;
end;
procedure TdmClient.dstClientLoanClass2BeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := cln.Id;
end;
procedure TdmClient.dstComakersBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := cln.Id;
end;
procedure TdmClient.dstContactInfoBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := cln.Id;
end;
procedure TdmClient.dstContactInfoBeforePost(DataSet: TDataSet);
begin
if DataSet.State = dsInsert then
DataSet.FieldByName('entity_id').AsString := cln.Id;
end;
procedure TdmClient.dstEmplInfoAfterOpen(DataSet: TDataSet);
var
gp: TGroup;
begin
if (cln.HasId) and (DataSet.RecordCount > 0) then
begin
if DataSet.FieldByName('emp_id').AsString <> '' then
begin
gp := TGroup.Create;
gp.GroupId := DataSet.FieldByName('grp_id').AsString;
gp.GroupName := DataSet.FieldByName('grp_name').AsString;
cln.Employer := TEmployer.Create;
cln.Employer.Id := DataSet.FieldByName('emp_id').AsString;
cln.Employer.Name := DataSet.FieldByName('emp_name').AsString;
cln.Employer.Address := DataSet.FieldByName('emp_add').AsString;
cln.Employer.Group := gp;
end;
if DataSet.FieldByName('imm_head').AsString <> '' then
begin
cln.ImmediateHead := TImmediateHead.Create;
cln.ImmediateHead.Id := DataSet.FieldByName('imm_head').AsString;
cln.ImmediateHead.Name := DataSet.FieldByName('imm_head_name').AsString;
end;
end
end;
procedure TdmClient.dstEmplInfoAfterPost(DataSet: TDataSet);
begin
DataSet.Edit;
end;
procedure TdmClient.dstEmplInfoBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := cln.Id;
end;
procedure TdmClient.dstEmplInfoBeforePost(DataSet: TDataSet);
begin
if DataSet.State = dsInsert then
DataSet.FieldByName('entity_id').AsString := cln.Id;
if Assigned(cln.ImmediateHead) then
DataSet.FieldByName('imm_head').AsString := cln.ImmediateHead.Id
else
DataSet.FieldByName('imm_head').Value := null;
if Assigned(cln.Employer) then
DataSet.FieldByName('emp_id').AsString := cln.Employer.Id
else
DataSet.FieldByName('emp_id').Value := null;
end;
procedure TdmClient.dstEntityAfterOpen(DataSet: TDataSet);
begin
if not DataSet.FieldByName('ref_entity_id').IsNull then
begin
cln.Referee := TReferee.Create;
cln.Referee.Id := DataSet.FieldByName('ref_entity_id').AsString;
cln.Referee.Name := DataSet.FieldByName('referee').AsString;
end;
cln.Photo := DataSet.FieldByName('photo').AsString;
end;
procedure TdmClient.dstEntityBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := cln.Id;
end;
procedure TdmClient.dstEntityBeforePost(DataSet: TDataSet);
var
id: string;
begin
if DataSet.State = dsInsert then
begin
id := GetEntityId;
DataSet.FieldByName('entity_id').AsString := id;
DataSet.FieldByName('loc_code').AsString := ifn.LocationCode;
SetCreatedFields(DataSet);
cln.Id := id;
end;
if Assigned(cln.Referee) then
DataSet.FieldByName('ref_entity_id').AsString := cln.Referee.Id
else
DataSet.FieldByName('ref_entity_id').Value := null;
// photo
DataSet.FieldByName('photo').AsString := cln.Photo;
end;
procedure TdmClient.dstIdentInfoAfterOpen(DataSet: TDataSet);
var
idType, idNo: string;
expiry: TDate;
hasExpiry: boolean;
begin
(DataSet as TADODataSet).Properties['Unique table'].Value := 'IdentityInfo';
with DataSet do
begin
DisableControls;
if RecordCount > 0 then
begin
while not Eof do
begin
idType := FieldByName('ident_type').AsString;
idNo := FieldByName('ident_no').AsString;
expiry := FieldByName('exp_date').AsDateTime;
hasExpiry := FieldByName('has_expiry').AsInteger = 1;
cln.AddIdentityDoc(TIdentityDoc.Create(idType,idNo,expiry,hasExpiry));
Next;
end;
First;
end;
EnableControls;
end;
end;
procedure TdmClient.dstIdentInfoAfterPost(DataSet: TDataSet);
var
idType, idNo: string;
expiry: TDate;
hasExpiry: boolean;
begin
with DataSet do
begin
idType := FieldByName('ident_type').AsString;
idNo := FieldByName('ident_no').AsString;
expiry := FieldByName('exp_date').AsDateTime;
hasExpiry := FieldByName('has_expiry').AsInteger = 1;
cln.AddIdentityDoc(TIdentityDoc.Create(idType,idNo,expiry,hasExpiry));
end;
RefreshDataSet(idType,'ident_type',DataSet);
end;
procedure TdmClient.dstIdentInfoBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := cln.Id;
end;
procedure TdmClient.dstIdentInfoBeforePost(DataSet: TDataSet);
begin
if DataSet.State = dsInsert then
DataSet.FieldByName('entity_id').AsString := cln.Id;
end;
procedure TdmClient.dstGroupsBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := cln.Id;
end;
procedure TdmClient.dstLoansAfterScroll(DataSet: TDataSet);
begin
// filter comakers
dstComakers.Filter := 'loan_id = ' + QuotedStr(DataSet.FieldByName('loan_id').AsString);
end;
procedure TdmClient.dstLoansBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := cln.Id;
end;
procedure TdmClient.dstPersonalInfoAfterOpen(DataSet: TDataSet);
begin
with DataSet do
begin
if cln.HasId then
begin
cln.Name := FieldByName('lastname').AsString + ', ' +
FieldByName('firstname').AsString;
end;
end;
end;
procedure TdmClient.dstPersonalInfoAfterPost(DataSet: TDataSet);
begin
with DataSet do
cln.Name := FieldByName('lastname').AsString + ', ' +
FieldByName('firstname').AsString;
end;
procedure TdmClient.dstPersonalInfoBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := cln.Id;
end;
procedure TdmClient.dstPersonalInfoBeforePost(DataSet: TDataSet);
begin
if DataSet.State = dsInsert then
DataSet.FieldByName('entity_id').AsString := cln.Id;
end;
procedure TdmClient.dstPromissoryNotesAfterOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Properties['Unique table'].Value := 'EntityPromissoryNote';
end;
procedure TdmClient.dstPromissoryNotesBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := cln.Id;
end;
procedure TdmClient.dstPromissoryNotesBeforePost(DataSet: TDataSet);
begin
if DataSet.State = dsInsert then
DataSet.FieldByName('entity_id').AsString := cln.Id;
end;
end.
|
unit CommandSet.SAT;
interface
uses
Windows, SysUtils,
OSFile.IoControl, CommandSet, BufferInterpreter, Device.SMART.List,
BufferInterpreter.ATA;
type
TSATCommandSet = class sealed(TCommandSet)
public
function IdentifyDevice: TIdentifyDeviceResult; override;
function SMARTReadData: TSMARTValueList; override;
function RAWIdentifyDevice: String; override;
function RAWSMARTReadData: String; override;
function DataSetManagement(StartLBA, LBACount: Int64): Cardinal; override;
function IsDataSetManagementSupported: Boolean; override;
function IsExternal: Boolean; override;
procedure Flush; override;
private
type
SCSI_COMMAND_DESCRIPTOR_BLOCK = record
SCSICommand: UCHAR;
MultiplecountProtocolExtend: UCHAR;
OfflineCkcondDirectionByteblockLength: UCHAR;
Features: UCHAR;
SectorCount: UCHAR;
LBALo: UCHAR;
LBAMid: UCHAR;
LBAHi: UCHAR;
DeviceHead: UCHAR;
ATACommand: UCHAR;
Reserved: UCHAR;
Control: UCHAR;
ReservedToFill16B: Array[0..3] of Byte;
end;
SCSI_COMMAND_DESCRIPTOR_BLOCK_16 = record
SCSICommand: UCHAR;
MultiplecountProtocolExtend: UCHAR;
OfflineCkcondDirectionByteblockLength: UCHAR;
FeaturesHi: UCHAR;
FeaturesLow: UCHAR;
SectorCountHi: UCHAR;
SectorCountLo: UCHAR;
LBALoHi: UCHAR;
LBALoLo: UCHAR;
LBAMidHi: UCHAR;
LBAMidLo: UCHAR;
LBAHiHi: UCHAR;
LBAHiLo: UCHAR;
DeviceHead: UCHAR;
ATACommand: UCHAR;
Control: UCHAR;
end;
SCSI_PASS_THROUGH = record
Length: USHORT;
ScsiStatus: UCHAR;
PathId: UCHAR;
TargetId: UCHAR;
Lun: UCHAR;
CdbLength: UCHAR;
SenseInfoLength: UCHAR;
DataIn: UCHAR;
DataTransferLength: ULONG;
TimeOutValue: ULONG;
DataBufferOffset: ULONG_PTR;
SenseInfoOffset: ULONG;
CommandDescriptorBlock: SCSI_COMMAND_DESCRIPTOR_BLOCK;
end;
SCSI_24B_SENSE_BUFFER = record
ResponseCodeAndValidBit: UCHAR;
Obsolete: UCHAR;
SenseKeyILIEOMFilemark: UCHAR;
Information: Array[0..3] of UCHAR;
AdditionalSenseLengthMinusSeven: UCHAR;
CommandSpecificInformation: Array[0..3] of UCHAR;
AdditionalSenseCode: UCHAR;
AdditionalSenseCodeQualifier: UCHAR;
FieldReplaceableUnitCode: UCHAR;
SenseKeySpecific: Array[0..2] of UCHAR;
AdditionalSenseBytes: Array[0..5] of UCHAR;
end;
SCSI_WITH_BUFFER = record
Parameter: SCSI_PASS_THROUGH;
SenseBuffer: SCSI_24B_SENSE_BUFFER;
Buffer: TSmallBuffer;
end;
const
SCSI_IOCTL_DATA_OUT = 0;
SCSI_IOCTL_DATA_IN = 1;
SCSI_IOCTL_DATA_UNSPECIFIED = 2;
private
IoInnerBuffer: SCSI_WITH_BUFFER;
IoOSBuffer: TIoControlIOBuffer;
function GetCommonBuffer: SCSI_WITH_BUFFER;
function GetCommonCommandDescriptorBlock: SCSI_COMMAND_DESCRIPTOR_BLOCK;
procedure SetOSBufferByInnerBuffer;
procedure SetInnerBufferAsFlagsAndCdb(Flags: ULONG;
CommandDescriptorBlock: SCSI_COMMAND_DESCRIPTOR_BLOCK);
procedure SetInnerBufferToSMARTReadData;
procedure SetInnerBufferToIdentifyDevice;
function InterpretIdentifyDeviceBuffer: TIdentifyDeviceResult;
procedure SetBufferAndIdentifyDevice;
function InterpretSMARTReadDataBuffer: TSMARTValueList;
procedure SetBufferAndSMARTReadData;
function InterpretSMARTThresholdBuffer(
const OriginalResult: TSMARTValueList): TSMARTValueList;
procedure SetBufferAndSMARTReadThreshold;
procedure SetInnerBufferToSMARTReadThreshold;
procedure SetDataSetManagementBuffer(StartLBA, LBACount: Int64);
procedure SetInnerBufferToDataSetManagement(StartLBA, LBACount: Int64);
procedure SetLBACountToDataSetManagementBuffer(LBACount: Int64);
procedure SetStartLBAToDataSetManagementBuffer(StartLBA: Int64);
function GetCommonCommandDescriptorBlock16:
SCSI_COMMAND_DESCRIPTOR_BLOCK_16;
procedure SetInnerBufferAsFlagsAndCdb16(Flags: ULONG;
CommandDescriptorBlock: SCSI_COMMAND_DESCRIPTOR_BLOCK_16);
end;
implementation
{ TSATCommandSet }
function TSATCommandSet.GetCommonBuffer: SCSI_WITH_BUFFER;
const
SATTargetId = 1;
begin
FillChar(result, SizeOf(result), #0);
result.Parameter.Length :=
SizeOf(result.Parameter);
result.Parameter.TargetId := SATTargetId;
result.Parameter.CdbLength := SizeOf(result.Parameter.CommandDescriptorBlock);
result.Parameter.SenseInfoLength :=
SizeOf(result.SenseBuffer);
result.Parameter.DataTransferLength :=
SizeOf(result.Buffer);
result.Parameter.TimeOutValue := 2;
result.Parameter.DataBufferOffset :=
PAnsiChar(@result.Buffer) - PAnsiChar(@result);
result.Parameter.SenseInfoOffset :=
PAnsiChar(@result.SenseBuffer) - PAnsiChar(@result);
end;
function TSATCommandSet.GetCommonCommandDescriptorBlock:
SCSI_COMMAND_DESCRIPTOR_BLOCK;
const
ATAPassThrough12Command = $A1;
SAT_PROTOCOL_DATA_IN = 1 shl 3;
SAT_PROTOCOL_DATA_OUT = 1 shl 4;
SAT_PROTOCOL_USE_DMA = 1 shl 5;
SAT_BYTEBLOCK_BYTE = 0;
SAT_BYTEBLOCK_BLOCK = 1 shl 2;
SAT_LENGTH_NO_DATA = 0;
SAT_LENGTH_AT_FEATURES = 1;
SAT_LENGTH_AT_SECTORCOUNT = 2;
SAT_LENGTH_AT_TPSIU = 3;
SAT_DIR_CLIENT_TO_DEVICE = 0;
SAT_DIR_DEVICE_TO_CLIENT = 1 shl 3;
begin
FillChar(result, SizeOf(result), #0);
result.SCSICommand := ATAPassThrough12Command;
result.MultiplecountProtocolExtend := SAT_PROTOCOL_DATA_IN;
result.OfflineCkcondDirectionByteblockLength :=
SAT_LENGTH_AT_SECTORCOUNT or SAT_BYTEBLOCK_BLOCK or
SAT_DIR_DEVICE_TO_CLIENT;
end;
function TSATCommandSet.GetCommonCommandDescriptorBlock16:
SCSI_COMMAND_DESCRIPTOR_BLOCK_16;
const
ATAPassThrough16Command = $85;
SCSI_IOCTL_DATA_48BIT = 1;
SAT_PROTOCOL_DATA_IN = 4 shl 1;
SAT_PROTOCOL_DATA_OUT = 5 shl 1;
SAT_PROTOCOL_USE_DMA = 6 shl 1;
SAT_BYTEBLOCK_BYTE = 0;
SAT_BYTEBLOCK_BLOCK = 1 shl 2;
SAT_LENGTH_NO_DATA = 0;
SAT_LENGTH_AT_FEATURES = 1;
SAT_LENGTH_AT_SECTORCOUNT = 2;
SAT_LENGTH_AT_TPSIU = 3;
SAT_DIR_CLIENT_TO_DEVICE = 0;
SAT_DIR_DEVICE_TO_CLIENT = 1 shl 3;
begin
FillChar(result, SizeOf(result), #0);
result.SCSICommand := ATAPassThrough16Command;
result.MultiplecountProtocolExtend :=
SCSI_IOCTL_DATA_48BIT or
SAT_PROTOCOL_USE_DMA;
result.OfflineCkcondDirectionByteblockLength :=
SAT_LENGTH_AT_SECTORCOUNT or SAT_BYTEBLOCK_BLOCK or
SAT_DIR_CLIENT_TO_DEVICE;
end;
procedure TSATCommandSet.SetInnerBufferAsFlagsAndCdb
(Flags: ULONG; CommandDescriptorBlock: SCSI_COMMAND_DESCRIPTOR_BLOCK);
begin
CommandDescriptorBlock.SectorCount := 1;
IoInnerBuffer := GetCommonBuffer;
IoInnerBuffer.Parameter.DataIn := Flags;
IoInnerBuffer.Parameter.CommandDescriptorBlock := CommandDescriptorBlock;
end;
procedure TSATCommandSet.SetInnerBufferAsFlagsAndCdb16
(Flags: ULONG; CommandDescriptorBlock: SCSI_COMMAND_DESCRIPTOR_BLOCK_16);
begin
Assert(SizeOf(CommandDescriptorBlock) =
SizeOf(SCSI_COMMAND_DESCRIPTOR_BLOCK));
IoInnerBuffer := GetCommonBuffer;
IoInnerBuffer.Parameter.DataIn := Flags;
Move(CommandDescriptorBlock,
IoInnerBuffer.Parameter.CommandDescriptorBlock,
SizeOf(SCSI_COMMAND_DESCRIPTOR_BLOCK));
end;
procedure TSATCommandSet.SetInnerBufferToIdentifyDevice;
const
IdentifyDeviceCommand = $EC;
var
CommandDescriptorBlock: SCSI_COMMAND_DESCRIPTOR_BLOCK;
begin
CommandDescriptorBlock := GetCommonCommandDescriptorBlock;
CommandDescriptorBlock.ATACommand := IdentifyDeviceCommand;
CommandDescriptorBlock.SectorCount := 1;
SetInnerBufferAsFlagsAndCdb(SCSI_IOCTL_DATA_IN, CommandDescriptorBlock);
end;
procedure TSATCommandSet.SetOSBufferByInnerBuffer;
begin
IoOSBuffer.InputBuffer.Size := SizeOf(IoInnerBuffer);
IoOSBuffer.InputBuffer.Buffer := @IOInnerBuffer;
IoOSBuffer.OutputBuffer.Size := SizeOf(IoInnerBuffer);
IoOSBuffer.OutputBuffer.Buffer := @IOInnerBuffer;
end;
procedure TSATCommandSet.SetBufferAndIdentifyDevice;
begin
SetInnerBufferToIdentifyDevice;
SetOSBufferByInnerBuffer;
IoControl(TIoControlCode.SCSIPassThrough, IoOSBuffer);
end;
function TSATCommandSet.InterpretIdentifyDeviceBuffer:
TIdentifyDeviceResult;
var
ATABufferInterpreter: TATABufferInterpreter;
begin
ATABufferInterpreter := TATABufferInterpreter.Create;
result :=
ATABufferInterpreter.BufferToIdentifyDeviceResult(IoInnerBuffer.Buffer);
FreeAndNil(ATABufferInterpreter);
end;
function TSATCommandSet.IdentifyDevice: TIdentifyDeviceResult;
begin
SetBufferAndIdentifyDevice;
result := InterpretIdentifyDeviceBuffer;
result.StorageInterface := TStorageInterface.SAT;
end;
procedure TSATCommandSet.SetInnerBufferToSMARTReadData;
const
SMARTFeatures = $D0;
SMARTCycleLo = $4F;
SMARTCycleHi = $C2;
SMARTReadDataCommand = $B0;
var
IoTaskFile: SCSI_COMMAND_DESCRIPTOR_BLOCK;
begin
IoTaskFile := GetCommonCommandDescriptorBlock;
IoTaskFile.Features := SMARTFeatures;
IoTaskFile.LBAMid := SMARTCycleLo;
IoTaskFile.LBAHi := SMARTCycleHi;
IoTaskFile.ATACommand := SMARTReadDataCommand;
SetInnerBufferAsFlagsAndCdb(SCSI_IOCTL_DATA_IN, IoTaskFile);
end;
procedure TSATCommandSet.SetBufferAndSMARTReadData;
begin
SetInnerBufferToSMARTReadData;
SetOSBufferByInnerBuffer;
IoControl(TIoControlCode.SCSIPassThrough, IoOSBuffer);
end;
function TSATCommandSet.InterpretSMARTReadDataBuffer:
TSMARTValueList;
var
ATABufferInterpreter: TATABufferInterpreter;
begin
ATABufferInterpreter := TATABufferInterpreter.Create;
result := ATABufferInterpreter.BufferToSMARTValueList(IoInnerBuffer.Buffer);
FreeAndNil(ATABufferInterpreter);
end;
procedure TSATCommandSet.SetInnerBufferToSMARTReadThreshold;
const
SMARTFeatures = $D1;
SMARTCycleLo = $4F;
SMARTCycleHi = $C2;
SMARTReadDataCommand = $B0;
var
IoTaskFile: SCSI_COMMAND_DESCRIPTOR_BLOCK;
begin
IoTaskFile := GetCommonCommandDescriptorBlock;
IoTaskFile.Features := SMARTFeatures;
IoTaskFile.LBAMid := SMARTCycleLo;
IoTaskFile.LBAHi := SMARTCycleHi;
IoTaskFile.ATACommand := SMARTReadDataCommand;
SetInnerBufferAsFlagsAndCdb(SCSI_IOCTL_DATA_IN, IoTaskFile);
end;
procedure TSATCommandSet.SetBufferAndSMARTReadThreshold;
begin
SetInnerBufferToSMARTReadThreshold;
SetOSBufferByInnerBuffer;
IoControl(TIoControlCode.SCSIPassThrough, IoOSBuffer);
end;
function TSATCommandSet.InterpretSMARTThresholdBuffer(
const OriginalResult: TSMARTValueList): TSMARTValueList;
var
ATABufferInterpreter: TATABufferInterpreter;
ThresholdList: TSMARTValueList;
SmallBuffer: TSmallBuffer;
begin
result := OriginalResult;
ATABufferInterpreter := TATABufferInterpreter.Create;
Move(IoInnerBuffer.Buffer, SmallBuffer, SizeOf(SmallBuffer));
ThresholdList := ATABufferInterpreter.BufferToSMARTThresholdValueList(
SmallBuffer);
try
OriginalResult.MergeThreshold(ThresholdList);
finally
FreeAndNil(ThresholdList);
end;
FreeAndNil(ATABufferInterpreter);
end;
function TSATCommandSet.SMARTReadData: TSMARTValueList;
begin
SetBufferAndSMARTReadData;
result := InterpretSMARTReadDataBuffer;
SetBufferAndSMARTReadThreshold;
result := InterpretSMARTThresholdBuffer(result);
end;
function TSATCommandSet.IsDataSetManagementSupported: Boolean;
begin
exit(true);
end;
function TSATCommandSet.IsExternal: Boolean;
begin
result := true;
end;
function TSATCommandSet.RAWIdentifyDevice: String;
begin
SetBufferAndIdentifyDevice;
result :=
IdentifyDevicePrefix +
TBufferInterpreter.BufferToString(IoInnerBuffer.Buffer) + ';';
end;
function TSATCommandSet.RAWSMARTReadData: String;
begin
SetBufferAndSMARTReadData;
result :=
SMARTPrefix +
TBufferInterpreter.BufferToString(IoInnerBuffer.Buffer) + ';';
SetBufferAndSMARTReadThreshold;
result := result +
'Threshold' +
TBufferInterpreter.BufferToString(IoInnerBuffer.Buffer) + ';';
end;
procedure TSATCommandSet.SetStartLBAToDataSetManagementBuffer(StartLBA: Int64);
const
StartLBALo = 0;
begin
IoInnerBuffer.Buffer[StartLBALo] := StartLBA and 255;
StartLBA := StartLBA shr 8;
IoInnerBuffer.Buffer[StartLBALo + 1] := StartLBA and 255;
StartLBA := StartLBA shr 8;
IoInnerBuffer.Buffer[StartLBALo + 2] := StartLBA and 255;
StartLBA := StartLBA shr 8;
IoInnerBuffer.Buffer[StartLBALo + 3] := StartLBA and 255;
StartLBA := StartLBA shr 8;
IoInnerBuffer.Buffer[StartLBALo + 4] := StartLBA and 255;
StartLBA := StartLBA shr 8;
IoInnerBuffer.Buffer[StartLBALo + 5] := StartLBA;
end;
procedure TSATCommandSet.SetLBACountToDataSetManagementBuffer(LBACount: Int64);
const
LBACountHi = 7;
LBACountLo = 6;
begin
IoInnerBuffer.Buffer[LBACountLo] := LBACount and 255;
IoInnerBuffer.Buffer[LBACountHi] := LBACount shr 8;
end;
procedure TSATCommandSet.SetDataSetManagementBuffer(
StartLBA, LBACount: Int64);
begin
SetStartLBAToDataSetManagementBuffer(StartLBA);
SetLBACountToDataSetManagementBuffer(LBACount);
end;
procedure TSATCommandSet.SetInnerBufferToDataSetManagement
(StartLBA, LBACount: Int64);
const
DataSetManagementFeatures = $1;
DataSetManagementSectorCount = $1;
DataSetManagementCommand = $6;
var
CommandDescriptorBlock: SCSI_COMMAND_DESCRIPTOR_BLOCK_16;
begin
CommandDescriptorBlock := GetCommonCommandDescriptorBlock16;
CommandDescriptorBlock.FeaturesLow := DataSetManagementFeatures;
CommandDescriptorBlock.SectorCountLo := DataSetManagementSectorCount;
CommandDescriptorBlock.ATACommand := DataSetManagementCommand;
SetInnerBufferAsFlagsAndCdb16(SCSI_IOCTL_DATA_OUT, CommandDescriptorBlock);
SetDataSetManagementBuffer(StartLBA, LBACount);
end;
function TSATCommandSet.DataSetManagement(StartLBA, LBACount: Int64):
Cardinal;
begin
SetInnerBufferToDataSetManagement(StartLBA, LBACount);
result := ExceptionFreeIoControl(TIoControlCode.SCSIPassThrough,
BuildOSBufferBy<SCSI_WITH_BUFFER, SCSI_WITH_BUFFER>(IoInnerBuffer,
IoInnerBuffer));
end;
procedure TSATCommandSet.Flush;
const
FlushCommand = $91;
var
CommandDescriptorBlock: SCSI_COMMAND_DESCRIPTOR_BLOCK;
begin
CommandDescriptorBlock := GetCommonCommandDescriptorBlock;
CommandDescriptorBlock.SCSICommand := FlushCommand;
SetInnerBufferAsFlagsAndCdb(SCSI_IOCTL_DATA_UNSPECIFIED,
CommandDescriptorBlock);
IoControl(TIoControlCode.SCSIPassThrough,
BuildOSBufferBy<SCSI_WITH_BUFFER, SCSI_WITH_BUFFER>(IoInnerBuffer,
IoInnerBuffer));
end;
end.
|
unit Step;
interface
uses
System.SysUtils, System.Classes, FMX.Types, FMX.Controls, FMX.Objects,
FMX.StdCtrls, System.UITypes, ColorClass, FMX.Graphics, FMX.Layouts;
type
TStep = class(TControl)
private
procedure ApplyColorChanges();
{ Private declarations }
protected
{ Protected declarations }
FPointerOnMouseEnter: TNotifyEvent;
FPointerOnMouseExit: TNotifyEvent;
FPointerOnClick: TNotifyEvent;
FPointerOnChange: TNotifyEvent;
FStepLayoutCircle: TLayout;
FStepCircle: TCircle;
FStepCircleSelect: TCircle;
FStepNumber: TLabel;
FStepText: TLabel;
FColorMain: TAlphaColor;
FIsChecked: Boolean;
procedure OnStepClick(Sender: TObject);
procedure OnStepMouseEnter(Sender: TObject);
procedure OnStepMouseExit(Sender: TObject);
function GetFButtonClass: TColorClass;
function GetFIsChecked: Boolean;
function GetFNumberStep: Integer;
function GetFTag: NativeInt;
function GetFText: String;
function GetFTextSettings: TTextSettings;
procedure SetFButtonClass(const Value: TColorClass);
procedure SetFIsChecked(const Value: Boolean);
procedure SetFNumberStep(const Value: Integer);
procedure SetFTag(const Value: NativeInt);
procedure SetFText(const Value: String);
procedure SetFTextSettings(const Value: TTextSettings);
function GetFNumberStepTextSettings: TTextSettings;
procedure SetFNumberStepTextSettings(const Value: TTextSettings);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ Published declarations }
property Cursor;
property Align;
property Anchors;
property Enabled;
property Height;
property Opacity;
property Visible;
property Width;
property Size;
property Scale;
property Margins;
property Position;
property RotationAngle;
property RotationCenter;
property HitTest;
{ Additional properties }
property ButtonClass: TColorClass read GetFButtonClass write SetFButtonClass;
property NumberStep: Integer read GetFNumberStep write SetFNumberStep;
property NumberStepTextSettings: TTextSettings read GetFNumberStepTextSettings write SetFNumberStepTextSettings;
property Text: String read GetFText write SetFText;
property TextSettings: TTextSettings read GetFTextSettings write SetFTextSettings;
property IsChecked: Boolean read GetFIsChecked write SetFIsChecked;
property Tag: NativeInt read GetFTag write SetFTag;
{ Events }
property OnPainting;
property OnPaint;
property OnResize;
{ Mouse events }
property OnChange: TNotifyEvent read FPointerOnChange write FPointerOnChange;
property OnClick: TNotifyEvent read FPointerOnClick write FPointerOnClick;
property OnDblClick;
property OnMouseDown;
property OnMouseUp;
property OnMouseWheel;
property OnMouseMove;
property OnMouseEnter: TNotifyEvent read FPointerOnMouseEnter write FPointerOnMouseEnter;
property OnMouseLeave: TNotifyEvent read FPointerOnMouseExit write FPointerOnMouseExit;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Componentes Customizados', [TStep]);
end;
{ TStep }
constructor TStep.Create(AOwner: TComponent);
begin
inherited;
Self.Width := 200;
Self.Height := 40;
FStepLayoutCircle := TLayout.Create(Self);
Self.AddObject(FStepLayoutCircle);
FStepLayoutCircle.Align := TAlignLayout.Left;
FStepLayoutCircle.HitTest := False;
FStepLayoutCircle.SetSubComponent(True);
FStepLayoutCircle.Stored := False;
FStepLayoutCircle.Width := 40;
FStepCircle := TCircle.Create(Self);
FStepLayoutCircle.AddObject(FStepCircle);
FStepCircle.Align := TAlignLayout.Client;
FStepCircle.HitTest := False;
FStepCircle.SetSubComponent(True);
FStepCircle.Stored := False;
FStepCircle.Stroke.Kind := TBrushKind.None;
FStepCircle.Width := 40;
FStepCircle.Height := 40;
FStepCircle.Fill.Color := SOLID_PRIMARY_COLOR;
FStepCircleSelect := TCircle.Create(Self);
FStepLayoutCircle.AddObject(FStepCircleSelect);
FStepCircleSelect.Align := TAlignLayout.Client;
FStepCircleSelect.HitTest := False;
FStepCircleSelect.SetSubComponent(True);
FStepCircleSelect.Stored := False;
FStepCircleSelect.Stroke.Kind := TBrushKind.None;
FStepCircleSelect.Margins.Top := -10;
FStepCircleSelect.Margins.Bottom := -10;
FStepCircleSelect.Margins.Left := -10;
FStepCircleSelect.Margins.Right := -10;
FStepCircleSelect.Fill.Color := SOLID_PRIMARY_COLOR;
FStepCircleSelect.Opacity := 0;
FStepCircleSelect.SendToBack;
FStepNumber := TLabel.Create(Self);
FStepCircle.AddObject(FStepNumber);
FStepNumber.Align := TAlignLayout.Client;
FStepNumber.HitTest := False;
FStepNumber.StyledSettings := [];
FStepNumber.TextSettings.Font.Size := 14;
FStepNumber.TextSettings.Font.Family := 'SF Pro Display';
FStepNumber.TextSettings.HorzAlign := TTextAlign.Center;
FStepNumber.SetSubComponent(True);
FStepNumber.Stored := False;
FStepNumber.TextSettings.FontColor := SOLID_WHITE;
FStepText := TLabel.Create(Self);
Self.AddObject(FStepText);
FStepText.Align := TAlignLayout.Client;
FStepText.HitTest := False;
FStepText.Margins.Left := 10;
FStepText.StyledSettings := [];
FStepText.TextSettings.Font.Size := 10;
FStepText.TextSettings.Font.Family := 'SF Pro Display';
FStepText.TextSettings.Font.Style := [TFontStyle.fsBold];
FStepText.SetSubComponent(True);
FStepText.Stored := False;
FStepText.TextSettings.FontColor := SOLID_PRIMARY_COLOR;
Self.NumberStep := 1;
Self.FColorMain := SOLID_PRIMARY_COLOR;
Self.IsChecked := True;
TControl(Self).OnClick := OnStepClick;
TControl(Self).OnMouseLeave := OnStepMouseExit;
TControl(Self).OnMouseEnter := OnStepMouseEnter;
end;
destructor TStep.Destroy;
begin
if Assigned(FStepText) then
FStepText.Free;
if Assigned(FStepNumber) then
FStepNumber.Free;
if Assigned(FStepCircle) then
FStepCircle.Free;
inherited;
end;
function TStep.GetFButtonClass: TColorClass;
begin
if FColorMain = SOLID_PRIMARY_COLOR then
Result := TColorClass.Primary
else if FColorMain = SOLID_SECONDARY_COLOR then
Result := TColorClass.Secondary
else if FColorMain = SOLID_ERROR_COLOR then
Result := TColorClass.Error
else if FColorMain = SOLID_WARNING_COLOR then
Result := TColorClass.Warning
else if FColorMain = SOLID_SUCCESS_COLOR then
Result := TColorClass.Success
else if FColorMain = SOLID_BLACK then
Result := TColorClass.Normal
else
Result := TColorClass.Custom;
end;
function TStep.GetFIsChecked: Boolean;
begin
Result := FIsChecked;
end;
function TStep.GetFNumberStep: Integer;
begin
Result := StrToInt(FStepNumber.Text);
end;
function TStep.GetFNumberStepTextSettings: TTextSettings;
begin
Result := FStepNumber.TextSettings;
end;
function TStep.GetFTag: NativeInt;
begin
Result := TControl(Self).Tag;
end;
function TStep.GetFText: String;
begin
Result := FStepText.Text;
end;
function TStep.GetFTextSettings: TTextSettings;
begin
Result := FStepText.TextSettings;
end;
procedure TStep.OnStepClick(Sender: TObject);
var
CircleEffect: TCircle;
begin
if Assigned(FPointerOnClick) then
begin
CircleEffect := TCircle.Create(Self);
CircleEffect.HitTest := False;
CircleEffect.Parent := FStepLayoutCircle;
CircleEffect.Align := TAlignLayout.Center;
CircleEffect.Stroke.Kind := TBrushKind.None;
CircleEffect.Fill.Color := FColorMain;
CircleEffect.SendToBack;
CircleEffect.Height := 0;
CircleEffect.Width := 0;
CircleEffect.Opacity := 0.6;
CircleEffect.AnimateFloat('Height', FStepCircleSelect.Height, 0.4, TAnimationType.Out, TInterpolationType.Circular);
CircleEffect.AnimateFloat('Width', FStepCircleSelect.Width, 0.4, TAnimationType.Out, TInterpolationType.Circular);
CircleEffect.AnimateFloat('Opacity', 0, 0.5);
FPointerOnClick(Sender);
end;
end;
procedure TStep.OnStepMouseEnter(Sender: TObject);
begin
if Assigned(FPointerOnClick) then
FStepCircleSelect.AnimateFloat('Opacity', 0.15, 0.2);
if Assigned(FPointerOnMouseEnter) then
FPointerOnMouseEnter(Sender);
end;
procedure TStep.OnStepMouseExit(Sender: TObject);
begin
if Assigned(FPointerOnClick) then
FStepCircleSelect.AnimateFloat('Opacity', 0, 0.2);
if Assigned(FPointerOnMouseExit) then
FPointerOnMouseExit(Sender);
end;
procedure TStep.SetFButtonClass(const Value: TColorClass);
begin
if Value = TColorClass.Primary then
FColorMain := SOLID_PRIMARY_COLOR
else if Value = TColorClass.Secondary then
FColorMain := SOLID_SECONDARY_COLOR
else if Value = TColorClass.Error then
FColorMain := SOLID_ERROR_COLOR
else if Value = TColorClass.Warning then
FColorMain := SOLID_WARNING_COLOR
else if Value = TColorClass.Normal then
FColorMain := SOLID_BLACK
else if Value = TColorClass.Success then
FColorMain := SOLID_SUCCESS_COLOR
else
FColorMain := TAlphaColor($FF323230);
ApplyColorChanges();
end;
procedure TStep.ApplyColorChanges;
begin
if Self.IsChecked then
begin
FStepCircle.Fill.Color := FColorMain;
FStepText.TextSettings.FontColor := FColorMain;
FStepNumber.TextSettings.FontColor := SOLID_WHITE;
end
else
begin
FStepCircle.Fill.Color := TAlphaColor($FFE5E5E5);
FStepText.TextSettings.FontColor := TAlphaColor($FF919191);
FStepNumber.TextSettings.FontColor := TAlphaColor($FF919191);
end;
end;
procedure TStep.SetFIsChecked(const Value: Boolean);
begin
FIsChecked := Value;
ApplyColorChanges();
if Assigned(FPointerOnChange) then
FPointerOnChange(Self);
end;
procedure TStep.SetFNumberStep(const Value: Integer);
begin
FStepNumber.Text := Value.ToString;
end;
procedure TStep.SetFNumberStepTextSettings(const Value: TTextSettings);
begin
FStepNumber.TextSettings := Value;
end;
procedure TStep.SetFTag(const Value: NativeInt);
begin
TControl(Self).Tag := Value;
end;
procedure TStep.SetFText(const Value: String);
begin
FStepText.Text := Value;
end;
procedure TStep.SetFTextSettings(const Value: TTextSettings);
begin
FStepText.TextSettings := Value;
end;
end.
|
unit public_unit;
interface
uses Graphics,SysUtils,forms,windows,messages,DB, ADODB,
stdctrls,comctrls,Classes, dialogs,
Grids,
rxToolEdit, rxCurrEdit, math, strUtils, Inifiles;
const HINT_TEXT :PAnsiChar='提示';
const TABLE_ERROR :PAnsiChar='数据库出错,无法读入数据!';
const DBERR_NOTSAVE :PAnsiChar='数据库错误,无法插入/更新数据!';
const DBERR_NOTREAD :PAnsiChar='数据库错误,无法正确读取数据!';
const DBERR_NOTDEL :PAnsiChar='数据库错误,无法删除数据!';
const DEL_CONFIRM :PAnsiChar='确定删除当前记录吗?';
const REPORT_SUCCESS :PAnsiChar='成功生成决算报表!';
const REPORT_FAIL :PAnsiChar='决算报表生成失败!';
const REPORT_OPEN_FAIL :PAnsiChar='决算报表打开失败!';
const EXCEL_NOTINSTALL :PAnsiChar='未安装Excel!';
const REPORT_PROCCESS :PAnsiChar='正在生成决算报表,请稍候...';
const FILE_SAVE_TITLE :PAnsiChar='决算报表保存';
const FILE_SAVE_TITLE_GZL :PAnsiChar='工作量统计表保存';
const FILE_SAVE_FILTER :PAnsiChar='Excel文件(*.csv;*.xls)|*.xls;*.csv|Excel文件(*.xls)|*.xls|Excel文件(*.csv)|*.csv';
const FILE_NOTEXIST :PAnsiChar='文件不存在!';
const FILE_EXIST :PAnsiChar='文件已经存在,是否覆盖该文件?';
const FILE_DELERR :PAnsiChar='无法删除(覆盖)文件!';
const EXCEL_ERROR :PAnsiChar='EXCEL运行中出错,无法生成报表!';
const REPORT_TITLE :String ='岩土工程勘察决算表';
const BACKUP_PROJECT_FILE_EXT:string='bak';
const REPORT_PRINT_SPLIT_CHAR: string='^'; //
//为了适应多语言报表的需要,在写INI文件时,
//土层名称是中文加分隔符加外文,例如:素填土^plain fill
type TTongJiFlags = set of (tfTuYang, tfJingTan, tfBiaoGuan, tfTeShuYang, tfTeShuYangBiaoZhuZhi, tfOther);
//在特征数表tezhengshuTmp中v_id字段对应的值
const TEZHENSHU_Flag_PingJunZhi : string='1';
const TEZHENSHU_Flag_BiaoZhunCha: string='2';
const TEZHENSHU_Flag_BianYiXiShu: string='3';
const TEZHENSHU_Flag_MaxValue : string='4';
const TEZHENSHU_Flag_MinValue : string='5';
const TEZHENSHU_Flag_SampleNum : string='6';
const TEZHENSHU_Flag_BiaoZhunZhi: string='7';
//在所有数据表中代表是否的字段对应的值,(是,值是0)(否,值是1)
const BOOLEAN_True : string = '0';
const BOOLEAN_False: string = '1';
type
TAnalyzeResult=record
PingJunZhi: double; //平均值
BiaoZhunCha: double;//标准差
BianYiXiShu: double;//变异系数
MaxValue: double;//最大值
MinValue: double;//最小值
SampleNum: integer;//样本数
BiaoZhunZhi:double;//标准值
FormatString: string; //格式化字符,如'0.00','0.0'
lstValues: TStringList; //保存所有的值,用来做计算用,因为有不合条件的值会被付空值,所以要用另一个StringList来保存同样的值。
lstValuesForPrint: TStringList;
FieldName: String; //
//字段名,在土分析分层总表的特征数计算时,因为有关联剔除,所以压根要用名字做标记,其他表的计算可以不设此值
//yys 2005/06/15 add, 当一层只有一个样时,标准差和变异系数不能为0,打印报表时要用空格,物理力学表也一样。
//strBiaoZhunCha: string;
//strBianYiXiShu: string;
//yys 2005/06/15
end;
//报表打印时的语言,暂时有中文和英文两种
type TReportLanguage =(trChineseReport, trEnglishReport); //
const GongMinJian ='0'; //工民建
const LuQiao ='1'; //路桥
const JiZuanQuTuKong = '1'; ////机钻取土孔
//打印到MiniCAD画图程序的报表的标识
const PrintChart_Section :PAnsiChar='1'; //工程地质剖面图
const PrintChart_ZhuZhuangTu :PAnsiChar='2'; //钻孔柱状图 工民建
const PrintChart_CPT_ShuangQiao :PAnsiChar='3'; //双桥钻孔静力触探成果表
const PrintChart_Buzhitu :PAnsiChar='4'; //工程勘察点平面布置图
const PrintChart_Legend :PAnsiChar='5'; //图例打印
const PrintChart_CrossBoard :PAnsiChar='6'; //十字板剪切试验曲线图
const PrintChart_CPT_DanQiao :PAnsiChar='7'; //单桥钻孔静力触探成果表
const PrintChart_FenCengYaSuo :PAnsiChar='8'; //分层压缩曲线
const PrintChart_ZhuZhuangTuZhiFangTu :PAnsiChar='9'; ////钻孔柱状图,带直方图格式 工民建
const PrintChart_ZhuZhuangTuShuangDa2 :PAnsiChar='10'; ////钻孔柱状图,带直方图格式 两个孔并排打印
const PrintChart_ZhuZhuangTuShuangDa1 :PAnsiChar='11'; ////钻孔柱状图,带直方图格式 单孔并排打印
type
TProjectInfo=class(TObject)
private
FPrj_no: string;
FPrj_no_ForSQL: string;
FPrj_name: string;
FPrj_name_en:string;
FPrj_type: string;
FPrj_ReportLanguage: TReportLanguage;
FPrj_ReportLanguageString: string;
public
constructor Create;
destructor Destroy; override;
procedure setProjectInfo(aPrj_no,aPrj_name,aPrj_name_en,aPrj_type: string);
procedure setReportLanguage(aReportLanguage: TReportLanguage);
property prj_no :string read FPrj_no; //工程编号
property prj_no_ForSQL:string read FPrj_no_ForSQL; //工程编号,为了插入数据库中,替换了真正工程编号中的单引号
property prj_name:string read FPrj_name; //工程名称
property prj_name_en:string read FPrj_name_en; //工程英文名称
property prj_type:string read FPrj_type; //工程类型
property prj_ReportLanguage: TReportLanguage read FPrj_ReportLanguage;
property prj_ReportLanguage_String: string read FPrj_ReportLanguageString;
end;
type TZKLXBianHao=record //钻孔类型编号
ShuangQiao: string; //双桥编号
DanQiao : string; //单桥编号
XiaoZuanKong:string; //小螺纹钻孔(也称作麻花钻)
end;
type TAppInfo=record
PathOfReports: string; //报表文件存放的路径
PathOfChartFile: string; //剖面图等的文本文件存放路径
CadExeName: string; //画CAD图的应用程序的路径+程序名(f:\minicad.exe)
CadExeNameEn:string; //画CAD图的应用程序的路径+英文程序名(f:\minicad_en.exe)
PathOfIniFile: string; //Server.ini 文件的存放路径(f:\server.ini)
end;
const g_cptIncreaseDepth=0.1; //静力触探每次进入的深度为0.1m
var
g_ProjectInfo : TProjectInfo; //保存当前打开的工程的工程信息
//g_Project_no:string; //保存当前打开的工程的工程编号
g_AppInfo : TAppInfo; //保存应用程序的一些信息。
g_ZKLXBianHao: TZKLXBianHao; //保存钻孔类型表中的钻孔编号
//将窗口上的所有Label的Transparent属性设为True
procedure setLabelsTransparent(aForm: TForm);
//根据在窗口上的按键不同来改变焦点位置。
procedure change_focus(key:word;frmCurrent: TCustomForm);
//删除一个StringGrid的一行。
procedure DeleteStringGridRow(aStringGrid:TStringGrid;aRow:integer);
//清除窗体的一些类型的控件内容,如Edit.Text='',ComboBox.ItemIndex=-1
procedure Clear_Data(frmCurrent: TCustomForm);
//控制窗体的一些控件可用不可用。
procedure Enable_Components(frmCurrent:TCustomForm;bEnable:boolean);
//AlignGridCell,改变StringGrid中某一CELL中的文字水平方向排列方式,同时在垂直方向居中.
procedure AlignGridCell(AStringGrid:TObject;ACol, ARow:Integer;
ARect: TRect; Alignment: TAlignment);
//处理数据库的删除、增加、修改操作。
function Delete_oneRecord(aADOQuery: TADOQuery;strSQL:string):boolean;
function Update_oneRecord(aADOQuery: TADOQuery;strSQL:string):boolean;
function Insert_oneRecord(aADOQuery: TADOQuery;strSQL:string):boolean;
//判断一笔记录在数据库中是否存在。
function isExistedRecord(aADOQuery: TADOQuery;strSQL:string): boolean;
//NumberKeyPress 控制edit控件的的输入,edit中的内容只能是整数或浮点数据.
//Sender一般为TEdit控件,Key为按下的键值,yunshufuhao是否允许输入负号
procedure NumberKeyPress(Sender: TObject;var Key: Char; yunshufuhao : boolean);
//把十六进制字符串转换为TBits
function HexToBits(aStr:string):TBits;
//把以分隔符分开的字符串分开放入StringList中。
procedure DivideString(str,separate:string;var str_list:TStringList);
//把以分隔符分开的字符串分开放入StringList中,其中为空的字符串不放入.
//如'1,2,,3'这个字符串,用这个过程分开的话会得到一个有三行的StringList
procedure DivideStringNoEmpty(str,separate:string;var str_list:TStringList);
function isFloat(ANumber: string): boolean;
function isInteger(ANumber: string): boolean;
procedure SetListBoxHorizonbar(aListBox: TCustomListBox);
//判断一个串在一个字符串列表中的位置,并返回位置值(-1--表示列表不没有此串)
function PosStrInList(aStrList:TStrings;aStr:string):integer;
//返回一个字符串在另一个字符串中最后出现的位置
function PosRightEx(const SubStr,S:AnsiString;const Offset:Cardinal=MaxInt):Integer;
function ComSrtring(aValue,aLen:integer):string;
function ReopenQryFAcount(aQuery:tadoquery;aSQLStr:string):boolean;
function SumMoney(aADOQry:tadoquery;aFieldName:string):double;
procedure EditFormat(aEdit:tedit);
procedure SetCBWidth(aCBox:tcombobox);
function getCadExcuteName: string;
//getCptAverageByDrill
//从静探表中计算一个孔的每一层的qc和fs的平均值,保存在两个字符串中,每个值用逗号隔开
procedure getCptAverageByDrill(aDrillNo:string;var aQcAverage,aFsAverage:
string);
function AddFuHao(aStr:string):string;
procedure FenXiFenCeng_TuYiangJiSuan;
procedure FenXiFenCeng_TeShuYiangJiSuan;
//在最近版本的 Delphi Pascal 编译器中,Round 函数是以 CPU 的 FPU (浮点部件) 处理器为基础的。
//这种处理器采用了所谓的 "银行家舍入法",即对中间值 (如 5.5、6.5) 实施 Round 函数时,
//处理器根据小数点前数字的奇、偶性来确定舍入与否,如 5.5 Round 结果为 6,而 6.5 Round 结果也为 6, 因为 6 是偶数。
function DoRound(Value: Extended):Int64;
function iif(ATest: Boolean; const ATrue: Integer; const AFalse: Integer): Integer; overload;
function iif(ATest: Boolean; const ATrue: string; const AFalse: string): string; overload;
function iif(ATest: Boolean; const ATrue: Boolean; const AFalse: Boolean): Boolean; overload;
implementation
uses MainDM,SdCadMath;
//Delphi 的 Round 函数使用的是银行家算法(Banker's Rounding)
//Round() 的结果并非通常意义上的四舍五入
//If X is exactly halfway between two whole numbers,
//the result is always the even number.
//对于 XXX.5 的情况,整数部分是奇数,那么会 Round Up,偶数会 Round Down,例如:
//x:= Round(17.5) 相当于 x = 18
//x:= Round(12.5) 相当于 x = 12
//做四舍五入处理时请使用 DRound 函数代替 Round
function DoRound(Value: Extended): Int64;
begin
if Value >= 0 then Result := Trunc(Value + 0.5)
else Result := Trunc(Value - 0.5);
end;
function iif(ATest: Boolean; const ATrue: Integer; const AFalse: Integer): Integer;
begin
if ATest then begin
Result := ATrue;
end else begin
Result := AFalse;
end;
end;
function iif(ATest: Boolean; const ATrue: string; const AFalse: string): string;
begin
if ATest then begin
Result := ATrue;
end else begin
Result := AFalse;
end;
end;
function iif(ATest: Boolean; const ATrue: Boolean; const AFalse: Boolean): Boolean;
begin
if ATest then begin
Result := ATrue;
end else begin
Result := AFalse;
end;
end;
function getCadExcuteName: string;
begin
if g_ProjectInfo.prj_ReportLanguage= trChineseReport then
result := g_AppInfo.CadExeName
else if g_ProjectInfo.prj_ReportLanguage= trEnglishReport then
result := g_AppInfo.CadExeNameEn;
end;
procedure setLabelsTransparent(aForm: TForm);
var
i: integer;
myComponent: TComponent;
begin
for i:=0 to aForm.ComponentCount-1 do
begin
myComponent:= aForm.Components[i];
if myComponent is TLabel then
TLabel(myComponent).Transparent := True;
end;
end;
//当按回车和向下箭头时移动光标到下一控件,向上箭头时移动光标到上一控件。
procedure change_focus(key:word;frmCurrent: TCustomForm);
begin
if (key=VK_DOWN) or (key=VK_RETURN) then
postMessage(frmCurrent.Handle, wm_NextDlgCtl,0,0);
if key=VK_UP then
postmessage(frmCurrent.handle,wm_nextdlgctl,1,0);
end;
procedure DeleteStringGridRow(aStringGrid:TStringGrid;aRow:integer);
const
MaxColCount=100; //一般说来,不会有StringGrid的列超过100列,
//这样做是因为有时候隐藏列超出了ColCount,删除数据时不完全;
var
iCol, iRow:integer;
begin
if (aRow<1) or (aRow>aStringGrid.RowCount-1) then exit;
if aStringGrid.RowCount =2 then
begin
for iCol:= 0 to MaxColCount do
aStringGrid.cells[iCol,1] :='';
exit;
end;
if aRow <> aStringGrid.RowCount -1 then
for iRow := aRow to aStringGrid.RowCount - 2 do
for iCol:= 0 to MaxColCount -1 do
aStringGrid.Cells[iCol,iRow] := aStringGrid.Cells[iCol,iRow+1];
aStringGrid.RowCount := aStringGrid.RowCount -1;
end;
procedure Clear_Data(frmCurrent: TCustomForm);
var
i: integer;
begin
with frmCurrent do
for i:=0 to frmCurrent.ComponentCount-1 do
begin
if components[i] is TEdit then
TEdit(components[i]).text:=''
else if components[i] is TComboBox then
TComboBox(components[i]).ItemIndex := -1
else if components[i] is TMemo then
TMemo(components[i]).Text := ''
else if components[i] is TCurrencyEdit then
TCurrencyEdit(components[i]).Text := ''
else if components[i] is TDateTimePicker then
TDateTimePicker(components[i]).Date :=Now;
end;
end;
procedure Enable_Components(frmCurrent:TCustomForm;bEnable:boolean);
var
i: integer;
begin
with frmCurrent do
for i:=0 to frmCurrent.ComponentCount-1 do
begin
if components[i] is TEdit then
TEdit(components[i]).Enabled := bEnable
else if components[i] is TCurrencyEdit then
TCurrencyEdit(components[i]).Enabled := bEnable
else if components[i] is TComboBox then
TComboBox(components[i]).Enabled := bEnable
else if components[i] is TMemo then
TMemo(components[i]).Enabled := bEnable
else if components[i] is TListBox then
TListBox(components[i]).Enabled := bEnable
else if components[i] is TDateTimePicker then
TDateTimePicker(components[i]).Enabled :=bEnable
else if components[i] is TRadioButton then
TRadioButton(components[i]).Enabled := bEnable
else if components[i] is TCheckBox then
TCheckBox(components[i]).Enabled := bEnable
else if components[i] is TLabel then
TLabel(components[i]).Enabled := bEnable;
end;
end;
function Delete_oneRecord(aADOQuery: TADOQuery;strSQL: string): boolean;
begin
with aADOQuery do
begin
close;
sql.Clear;
sql.Add(strSQL);
try
try
ExecSQL;
//MessageBox(application.Handle,'删除成功!','删除数据',MB_OK+MB_ICONINFORMATION);
result := true;
except
MessageBox(application.Handle,'数据库错误,不能删除所选数据。','数据库错误',MB_OK+MB_ICONERROR);
result := false;
end;
finally
close;
end;
end;
end;
function Update_oneRecord(aADOQuery: TADOQuery;strSQL:string):boolean;
begin
with aADOQuery do
begin
close;
sql.Clear;
sql.Add(strSQL);
try
try
ExecSQL;
//MessageBox(application.Handle,'更新数据成功!','更新数据',MB_OK+MB_ICONINFORMATION);
result := true;
except
//MessageBox(application.Handle,'数据库错误,更新数据失败。','数据库错误',MB_OK+MB_ICONERROR);
result:= false;
end;
finally
close;
end;
end;
end;
function Insert_oneRecord(aADOQuery: TADOQuery;strSQL:string):boolean;
var
ini_file:TInifile;
begin
with aADOQuery do
begin
close;
sql.Clear;
sql.Add(strSQL);
try
try
ExecSQL;
//MessageBox(application.Handle,'增加数据成功!','增加数据',MB_OK+MB_ICONINFORMATION);
result := true;
except
MessageBox(application.Handle,'数据库错误,增加数据失败。','数据库错误',MB_OK+MB_ICONERROR);
ini_file := TInifile.Create(g_AppInfo.PathOfIniFile);
ini_file.WriteString('SQL','error',strSQL);
ini_file.Free;
result:= false;
end;
finally
close;
end;
end;
end;
function isExistedRecord(aADOQuery: TADOQuery;strSQL:string): boolean;
begin
with aADOQuery do
begin
close;
sql.Clear;
sql.Add(strSQL);
try
try
Open;
if eof then
result:=false
else
result:=true;
except
result:=false;
end;
finally
close;
end;
end;
end;
procedure NumberKeyPress(Sender: TObject;var Key: Char; yunshufuhao : boolean);
var
strHead,strEnd,strAll,strFraction:string;
iDecimalSeparator:integer;
begin
//如果是整数,直接屏蔽掉小数点。
if (TEdit(Sender).Tag=0) and (key='.') then
begin
key:=#0;
exit;
end;
//屏蔽掉负号。
if (not yunshufuhao) and (key='-') then
begin
key:=#0;
exit;
end;
//屏蔽掉科学计数法。
if (lowercase(key)='e') or (key=' ') or(key='+') then
begin
key:=#0;
exit;
end;
if key =chr(vk_back) then exit;
try
strHead := copy(TEdit(Sender).Text,1,TEdit(Sender).SelStart);
strEnd := copy(TEdit(Sender).Text,TEdit(Sender).SelStart+TEdit(Sender).SelLength+1,length(TEdit(Sender).Text));
strAll := strHead+key+strEnd;
if (strAll)='-' then
begin
TEdit(Sender).Text :='-';
TEdit(Sender).SelStart :=2;
key:=#0;
exit;
end;
strtofloat(strAll);
iDecimalSeparator:= pos('.',strAll);
if iDecimalSeparator>0 then
begin
strFraction:= copy(strall,iDecimalSeparator+1,length(strall));
if (iDecimalSeparator>0) and (length(strFraction)>TEdit(Sender).Tag) then
key:=#0;
end;
except
key:=#0;
end;
end;
function HexToBits(aStr:string):TBits;
var
i,data,j,rst,inx,l:integer;
aBits:TBits;
c:char;
begin
aBits:=TBits.Create ;
aBits.Size :=1024;
inx:=0;
l:=length(aStr);
for i:=1 to l do
begin
c:=aStr[i];
case c of
'f','F':data:=15;
'e','E':data:=14;
'd','D':data:=13;
'c','C':data:=12;
'b','B':data:=11;
'a','A':data:=10
else
data:=byte(c)-48;
end;
rst:=data;
for j:=0 to 3 do
begin
if rst mod 2=1 then
aBits[inx+3-j]:=true
else
aBits[inx+3-j]:=false;
rst:=rst Div 2;
end;
inx:=inx+4;
end;
result:=aBits;
end;
//把以分隔符分开的字符串分开放入StringList中。
procedure DivideString(str,separate:string;var str_list:TStringList);
var
position:integer;
strTemp:string;
begin
str_list.Clear;
while length(str)>0 do
begin
position:=pos(separate,str);
if position=0 then position:=length(str)+1;
strTemp:=copy(str,1,position-1);
str_list.Add(trim(strTemp));
delete(str,1,position);
end;
end;
procedure DivideStringNoEmpty(str,separate:string;var str_list:TStringList);
var
position:integer;
strTemp:string;
begin
str_list.Clear;
while length(trim(str))>0 do
begin
position:=pos(separate,str);
if position=0 then position:=length(str)+1;
strTemp:=copy(str,1,position-1);
if length(trim(strTemp))>0 then
str_list.Add(trim(strTemp));
delete(str,1,position);
end;
end;
function isFloat(ANumber: string): boolean;
begin
result:= true;
try
StrToFloat(ANumber);
except
result:= false;
end;
end;
function isInteger(ANumber: string): boolean;
begin
result:= true;
try
StrToInt(ANumber);
except
result:= false;
end;
end;
procedure AlignGridCell(AStringGrid:TObject;ACol, ARow:Integer;
ARect: TRect; Alignment: TAlignment);
var
strText:String;
iLeft,iTop:integer;
begin
With AStringGrid as TStringGrid do
begin
strText:=Cells[ACol,ARow];
Canvas.FillRect(ARect);
iTop := ARect.Top +(ARect.bottom-ARect.top-Canvas.TextHeight(strText)) shr 1;
case Alignment of
taLeftJustify:
iLeft := ARect.Left + 2;
taRightJustify:
iLeft := ARect.Right - Canvas.TextWidth(strText) - 3;
else { taCenter }
iLeft := ARect.Left + (ARect.Right - ARect.Left) shr 1
- (Canvas.TextWidth(strText) shr 1);
end;
Canvas.TextOut(iLeft,iTop,strText);
end;
end;
procedure SetListBoxHorizonbar(aListBox: TCustomListBox);
var
i, MaxWidth: integer;
begin
MaxWidth:=0;
for i:=0 to aListBox.Count-1 do
MaxWidth:=Max(MaxWidth,aListBox.Canvas.TextWidth(aListBox.Items[i]));
SendMessage(aListBox.Handle, LB_SETHORIZONTALEXTENT, MaxWidth+4, 0);
end;
function PosRightEx(const SubStr,S:AnsiString;const Offset:Cardinal=MaxInt):Integer;
var
iPos: Integer;
i, j,Len,LenS,LenSub: Integer;
PCharS, PCharSub: PChar;
begin
Result := 0;
LenS:=Length(S);
lenSub := length(Substr);
if (LenS=0) Or (lenSub=0) then Exit;
if Offset<LenSub then Exit;
PCharS := PChar(s);
PCharSub := PChar(Substr);
Len:=Offset;
if Len>LenS then
Len:=LenS;
for I := Len-1 downto 0 do
begin
if I<LenSub-1 then Exit;
for j := lenSub - 1 downto 0 do
if PCharS[i -lenSub+j+1] <> PCharSub[j] then
break
else if J=0 then
begin
Result:=I-lenSub+2;
Exit;
end;
end;
end;
function PosStrInList(aStrList:TStrings;aStr:string):integer;
var
i,j:integer;
begin
j:=-1;
for i:=0 to aStrList.Count-1 do
if aStrList[i]=aStr then
begin
j:=i;
break;
end;
result:=j;
end;
//打开数据表 ,返回结果true--成功,false--失败
function ReopenQryFAcount(aQuery:tadoquery;aSQLStr:string):boolean;
begin
aQuery.Close ;
aQuery.SQL.Clear ;
aQuery.SQL.Add(aSQLStr);
try
aQuery.Open ;
except
result:=false;
exit;
end;
result:=true;
end;
function ComSrtring(aValue,aLen:integer):string;
var
aStr:string;
slen,i:integer;
begin
aStr:=inttostr(aValue);
slen:=length(aStr);
for i:=1 to aLen-slen do
aStr:='0'+aStr;
result:=aStr;
end;
//字段值求和
function SumMoney(aADOQry:tadoquery;aFieldName:string):double;
var
asum:double;
aBMark:tbookmark;
begin
aSum:=0;
aBMark:=aADOQry.GetBookmark;
aADOQry.First ;
while not aADOQry.Eof do
begin
aSum:=aSum+aADOQry.fieldbyname(aFieldName).AsFloat;
aADOQry.Next ;
end;
aADOQry.GotoBookmark(aBMark);
result:=asum;
end;
procedure SetCBWidth(aCBox:tcombobox);
var
i,maxLen:integer;
begin
maxLen:=0;
for i:=0 to acbox.Items.Count-1 do
if aCBox.Canvas.TextWidth(aCBox.Items[i])>maxLen then maxLen:=aCBox.Canvas.TextWidth(aCBox.Items[i]);
sendmessage(aCBox.Handle,CB_SETDROPPEDWIDTH,maxLen+55,0);
end;
procedure EditFormat(aEdit:tedit);
begin
if aEdit.Width>80 then
aEdit.Text :=stringofchar(' ',((aEdit.Width DIV 6)-length(trim(aEdit.Text)))*2-2)+trim(aEdit.Text)
else
aEdit.Text :=stringofchar(' ',((aEdit.Width DIV 6)-length(trim(aEdit.Text)))*2-1)+trim(aEdit.Text);
end;
{ TProjectInfo }
constructor TProjectInfo.Create;
begin
inherited Create;
FPrj_ReportLanguage := trChineseReport;
end;
destructor TProjectInfo.Destroy;
begin
inherited;
end;
procedure TProjectInfo.setProjectInfo(aPrj_no, aPrj_name,aPrj_name_en,
aPrj_type: string);
begin
FPrj_no := aPrj_no;
FPrj_name := aPrj_name;
FPrj_name_en := aPrj_name_en;
FPrj_type := aPrj_type;
FPrj_no_ForSQL := stringReplace(aPrj_no ,'''','''''',[rfReplaceAll]);
end;
procedure TProjectInfo.setReportLanguage(aReportLanguage: TReportLanguage);
begin
FPrj_ReportLanguage := aReportLanguage;
if aReportLanguage = trChineseReport then
FPrj_ReportLanguageString := 'cn'
else if aReportLanguage = trEnglishReport then
FPrj_ReportLanguageString := 'en';
end;
procedure getCptAverageByDrill(aDrillNo:string;var aQcAverage,aFsAverage: string);
var
iStratumCount,i,j, iCanJoinJiSuanCount:integer; //iCanJoinJiSuanCount 能参加计算的每层数据的个数,因为一层里面不一定有(距离/0.1)这么多数据,所以为空的数据要去掉
dBottom: double;
strSQL, strTmp: string;
lstStratumNo,lstSubNo,
lstStratumDepth,lstStratumBottDepth:TStringList;
strQcAll,strFsAll: String; //保存锥尖阻力和侧壁摩擦力的整个字符串。
qcList,fsList: TStringList; //保存锥尖阻力和侧壁摩擦力
dBeginDepth,dEndDepth:double; //保存开始深度和结束深度
dqcTotal, dfsTotal, dqcAverage,dfsAverage: double;
procedure GetStramDepth(const aDrillNo: string;
var AStratumNoList, ASubNoList, ABottList: TStringList);
begin
AStratumNoList.Clear;
ASubNoList.Clear;
ABottList.Clear;
strSQL:='select drl_no,stra_no,sub_no, stra_depth '
+' FROM stratum '
+' WHERE '
+' prj_no='+''''+g_ProjectInfo.prj_no_ForSQL+''''
+' AND drl_no ='+''''+aDrillNo+''''
+' ORDER BY stra_depth';
//+' ORDER BY d.drl_no,s.top_elev';
with MainDataModule.qryStratum do
begin
close;
sql.Clear;
sql.Add(strSQL);
open;
while not eof do
begin
AStratumNoList.Add(FieldByName('stra_no').AsString);
ASubNoList.Add(FieldByName('sub_no').AsString);
ABottList.Add(FieldByName('stra_depth').AsString);
next;
end;
close;
end;
end;
procedure FreeStringList;
begin
lstStratumNo.Free;
lstSubNo.Free;
lstStratumDepth.Free;
lstStratumBottDepth.Free;
qcList.Free;
fsList.Free;
end;
begin
lstStratumNo:= TStringList.Create;
lstSubNo:= TStringList.Create;
lstStratumDepth:= TStringList.Create;
lstStratumBottDepth:= TStringList.Create;
qcList:= TStringList.Create;
fsList:= TStringList.Create;
dBeginDepth:=0;
dEndDepth:=0;
try
GetStramDepth(aDrillNo,
lstStratumNo, lstSubNo, lstStratumBottDepth);
if lstStratumNo.Count =0 then exit;
//开始取得静力触探的数据。
qcList.Clear;
fsList.Clear;
strSQL:='SELECT prj_no,drl_no,begin_depth,end_depth,qc,fs '
+'FROM cpt '
+' WHERE prj_no=' +''''+g_ProjectInfo.prj_no_ForSQL +''''
+' AND drl_no=' +''''+aDrillNo+'''';
with MainDataModule.qryCPT do
begin
close;
sql.Clear;
sql.Add(strSQL);
open;
i:=0;
if not Eof then
begin
i:=i+1;
strQcAll := FieldByName('qc').AsString;
strFsAll := FieldByName('fs').AsString;
dBeginDepth := FieldByName('begin_depth').AsFloat;
dEndDepth := FieldByName('end_depth').AsFloat;
Next ;
end;
close;
end;
if i>0 then
begin
DivideString(strQcAll,',',qcList);
DivideString(strFsAll,',',fsList);
end
else
exit;
//开始分层,并计算毎层的qc和fs的平均值
for iStratumCount:=0 to lstStratumNo.Count -1 do
begin
dBottom:= strtofloat(lstStratumBottDepth.Strings[iStratumCount]);
if (dBottom-dBeginDepth)>=g_cptIncreaseDepth then
begin
if dEndDepth>dBottom then
j:= round((dBottom - dBeginDepth) / g_cptIncreaseDepth)
else
j:= round((dEndDepth - dBeginDepth) / g_cptIncreaseDepth);
dqcTotal:=0;
dfsTotal:=0;
iCanJoinJiSuanCount := 0;
for i:= 1 to j do
begin
strTmp:= trim(qcList.Strings[0]);
if isFloat(strTmp) then
begin
dqcTotal:= dqcTotal + strtofloat(strTmp);
iCanJoinJiSuanCount := iCanJoinJiSuanCount +1;
end;
if qcList.Count>0 then
qcList.Delete(0);
if fsList.Count>0 then
begin
strTmp:= trim(fsList.Strings[0]);
if isFloat(strTmp) then
dfsTotal:= dfsTotal + strtofloat(strTmp);
fsList.Delete(0);
end;
end;
if iCanJoinJiSuanCount > 0 then
begin
dqcAverage:= dqcToTal / iCanJoinJiSuanCount;
dfsAverage:= dfsToTal / iCanJoinJiSuanCount;
aQcAverage:= aQcAverage + FormatFloat('0.00',dqcAverage) + ',';
aFsAverage:= aFsAverage + FormatFloat('0.00',dfsAverage) + ',';
end;
dBeginDepth:= dBottom;
if dEndDepth <= dBottom then
Break;
end;
end;
finally
FreeStringList;
if copy(aQcAverage,length(aQcAverage),1)=',' then
aQcAverage:= copy(aQcAverage,1,length(aQcAverage)-1);
if copy(aFsAverage,length(aFsAverage),1)=',' then
aFsAverage:= copy(aFsAverage,1,length(aFsAverage)-1);
end;
end;
//给字符串减去一个1000,这样数值就负的比较多了,在打印时判断,如果小于-500,这样打印时可以把数值加上1000,再在前面加个*在前面
//目的就是把打印时把剔除的数据如23变成*23,减去10000的目的是因为正常数值本身就有负数,范围在 -100到正200
function AddFuHao(aStr:string):string;
begin
// if Pos('-',aStr)<1 then
// Result := '-' + aStr
// else
// Result := aStr;
Result := FloatToStr(StrToFloat(aStr)-1000) ;
end;
procedure FenXiFenCeng_TuYiangJiSuan;
type TGuanLianFlags = set of (tgHanShuiLiang, tgYeXian, tgYaSuoXiShu, tgNingJuLi_ZhiKuai, tgMoCaJiao_ZhiKuai,
tgNingJuLi_GuKuai, tgMoCaJiao_GuKuai);
//yys 20040610 modified
//const AnalyzeCount=17;
const AnalyzeCount=26;
//yys 20040610 modified
var
//层号 亚层号
lstStratumNo, lstSubNo: TStringList;
//钻孔号 土样编号 开始深度 结束深度
lstDrl_no, lstS_no, lstBeginDepth, lstEndDepth: TStringList;
//剪切类型 砂粒粗(%) 砂粒中(%) 砂粒细(%)
lstShear_type, lstSand_big, lstSand_middle,lstSand_small:Tstringlist;
//粉粒粗(%) 粉粒细(%) 粘粒(%) 不均匀系数 曲率系数 土类编号 土类名称
lstPowder_big, lstPowder_small, lstClay_grain, lstAsymmetry_coef,lstCurvature_coef, lstEa_name: TStringList;
//各级压力 各级压力下变形量 孔隙比 压缩系数 压缩模量
lstYssy_yali, lstYssy_bxl, lstYssy_kxb, lstYssy_ysxs, lstYssy_ysml: TStringList;
i,j,iRecordCount,iCol: integer;
strSQL, strFieldNames, strFieldValues , strTmp, strSubNo,strStratumNo,strPrjNo: string;
aAquiferous_rate: TAnalyzeResult;//含水量 0
aWet_density : TAnalyzeResult;//湿密度 1
aDry_density : TAnalyzeResult;//干密度 2
aSoil_proportion: TAnalyzeResult;//土粒比重 3
aGap_rate : TAnalyzeResult;//孔隙比 4
aGap_degree : TAnalyzeResult;//孔隙度 5
aSaturation : TAnalyzeResult;//饱合度 6
aLiquid_limit : TAnalyzeResult;//液限 7
aShape_limit : TAnalyzeResult;//塑限 8
aShape_index : TAnalyzeResult;//塑性指数 9
aLiquid_index : TAnalyzeResult;//液性指数 10
aZip_coef : TAnalyzeResult;//压缩系数 11
aZip_modulus : TAnalyzeResult;//压缩模量 12
aCohesion : TAnalyzeResult;//凝聚力直快 13
aFriction_angle : TAnalyzeResult;//摩擦角直快 14
//yys 20040610 modified
aCohesion_gk : TAnalyzeResult;//凝聚力固快 15
aFriction_gk : TAnalyzeResult;//摩擦角固快 16
//yys 20040610 modified
aWcx_yuanz : TAnalyzeResult;//无侧限抗压强度原状 17
aWcx_chsu : TAnalyzeResult;//无侧限抗压强度重塑 18
aWcx_lmd : TAnalyzeResult;//无侧限抗压强度灵敏度 19
aSand_big : TAnalyzeResult;//砂粒粗 20
aSand_middle : TAnalyzeResult;//砂粒中 21
aSand_small : TAnalyzeResult;//砂粒细 22
aPowder_big : TAnalyzeResult;//粉粒粗 23
aPowder_small : TAnalyzeResult;//粉粒细 24
aClay_grain : TAnalyzeResult;//粘粒 25
ArrayAnalyzeResult: Array[0..AnalyzeCount-1] of TAnalyzeResult; // 保存要参加统计的TAnalyzeResult
ArrayFieldNames: Array[0..AnalyzeCount-1] of String; // 保存要参加统计的字段名,与ArrayAnalyzeResult的内容一一对应
//初始化此过程中的变量
procedure InitVar;
var
iCount: integer;
begin
ArrayAnalyzeResult[0]:= aAquiferous_rate;
ArrayAnalyzeResult[1]:= aWet_density;
ArrayAnalyzeResult[2]:= aDry_density;
ArrayAnalyzeResult[3]:= aSoil_proportion;
ArrayAnalyzeResult[4]:= aGap_rate;
ArrayAnalyzeResult[5]:= aGap_degree;
ArrayAnalyzeResult[6]:= aSaturation;
ArrayAnalyzeResult[7]:= aLiquid_limit;
ArrayAnalyzeResult[8]:= aShape_limit;
ArrayAnalyzeResult[9]:= aShape_index;
ArrayAnalyzeResult[10]:= aLiquid_index;
ArrayAnalyzeResult[11]:= aZip_coef;
ArrayAnalyzeResult[12]:= aZip_modulus;
ArrayAnalyzeResult[13]:= aCohesion;
ArrayAnalyzeResult[14]:= aFriction_angle;
//yys 20040610 modified
//ArrayAnalyzeResult[14]:= aWcx_yuanz;
//ArrayAnalyzeResult[15]:= aWcx_chsu;
//ArrayAnalyzeResult[16]:= aWcx_lmd;
ArrayAnalyzeResult[15]:= aCohesion_gk;
ArrayAnalyzeResult[16]:= aFriction_gk;
ArrayAnalyzeResult[17]:= aWcx_yuanz;
ArrayAnalyzeResult[18]:= aWcx_chsu;
ArrayAnalyzeResult[19]:= aWcx_lmd;
ArrayAnalyzeResult[20]:= aSand_big;
ArrayAnalyzeResult[21]:= aSand_middle;
ArrayAnalyzeResult[22]:= aSand_small;
ArrayAnalyzeResult[23]:= aPowder_big;
ArrayAnalyzeResult[24]:= aPowder_small;
ArrayAnalyzeResult[25]:= aClay_grain;
//yys 20040610 modified
ArrayFieldNames[0]:= 'aquiferous_rate';
ArrayFieldNames[1]:= 'wet_density';
ArrayFieldNames[2]:= 'dry_density';
ArrayFieldNames[3]:= 'soil_proportion';
ArrayFieldNames[4]:= 'gap_rate';
ArrayFieldNames[5]:= 'gap_degree';
ArrayFieldNames[6]:= 'saturation';
ArrayFieldNames[7]:= 'liquid_limit';
ArrayFieldNames[8]:= 'shape_limit';
ArrayFieldNames[9]:= 'shape_index';
ArrayFieldNames[10]:= 'liquid_index';
ArrayFieldNames[11]:= 'zip_coef';
ArrayFieldNames[12]:= 'zip_modulus';
ArrayFieldNames[13]:= 'cohesion';
ArrayFieldNames[14]:= 'friction_angle';
//yys 20040610 modified
//ArrayFieldNames[14]:= 'wcx_yuanz';
//ArrayFieldNames[15]:= 'wcx_chsu';
//ArrayFieldNames[16]:= 'wcx_lmd';
ArrayFieldNames[15]:= 'cohesion_gk';
ArrayFieldNames[16]:= 'friction_gk';
ArrayFieldNames[17]:= 'wcx_yuanz';
ArrayFieldNames[18]:= 'wcx_chsu';
ArrayFieldNames[19]:= 'wcx_lmd';
ArrayFieldNames[20]:= 'sand_big';
ArrayFieldNames[21]:= 'sand_middle';
ArrayFieldNames[22]:= 'sand_small';
ArrayFieldNames[23]:= 'powder_big';
ArrayFieldNames[24]:= 'powder_small';
ArrayFieldNames[25]:= 'clay_grain';
//yys 20040610 modified
lstStratumNo:= TStringList.Create;
lstSubNo:= TStringList.Create;
lstBeginDepth:= TStringList.Create;
lstEndDepth:= TStringList.Create;
lstDrl_no:= TStringList.Create;
lstS_no:= TStringList.Create;
lstShear_type:= TStringList.Create;
lstsand_big:= TStringList.Create;
lstsand_middle:= TStringList.Create;
lstsand_small:= TStringList.Create;
lstPowder_big:= TStringList.Create;
lstPowder_small:= TStringList.Create;
lstClay_grain:= TStringList.Create;
lstAsymmetry_coef:= TStringList.Create;
lstCurvature_coef:= TStringList.Create;
lstEa_name:= TStringList.Create;
lstYssy_yali:= TStringList.Create;
lstYssy_bxl:= TStringList.Create;
lstYssy_kxb:= TStringList.Create;
lstYssy_ysxs:= TStringList.Create;
lstYssy_ysml:= TStringList.Create;
for iCount:=0 to AnalyzeCount-1 do
begin
ArrayAnalyzeResult[iCount].lstValues := TStringList.Create;
ArrayAnalyzeResult[iCount].lstValuesForPrint := TStringList.Create;
end;
aAquiferous_rate.FormatString := '0.0';
aWet_density.FormatString := '0.00';
aDry_density.FormatString := '0.00';
aSoil_proportion.FormatString := '0.00';
aGap_rate.FormatString := '0.000';
aGap_degree.FormatString := '0.0';
aSaturation.FormatString := '0';
aLiquid_limit.FormatString := '0.0';
aShape_limit.FormatString := '0.0';
aShape_index.FormatString := '0.0';
aLiquid_index.FormatString := '0.00';
aZip_coef.FormatString := '0.000';
aZip_modulus.FormatString := '0.00';
aCohesion.FormatString := '0.00';
aFriction_angle.FormatString := '0.00';
//yys 20040610 modified
aCohesion_gk.FormatString := '0.00';
aFriction_gk.FormatString := '0.00';
//yys 20040610 modified
aWcx_yuanz.FormatString := '0.0';
aWcx_chsu.FormatString := '0.0';
aWcx_lmd.FormatString := '0.0';
aSand_big.FormatString := '0.00';
aSand_middle.FormatString := '0.00';
aSand_small.FormatString := '0.00';
aPowder_big.FormatString := '0.00';
aPowder_small.FormatString := '0.00';
aClay_grain.FormatString := '0.00';
end;
//释放此过程中的变量
procedure FreeStringList;
var
iCount: integer;
begin
lstStratumNo.Free;
lstSubNo.Free;
lstBeginDepth.Free;
lstEndDepth.Free;
lstDrl_no.Free;
lstS_no.Free;
lstShear_type.Free;
lstsand_big.Free;
lstsand_middle.Free;
lstsand_small.Free;
lstPowder_big.Free;
lstPowder_small.Free;
lstClay_grain.Free;
lstAsymmetry_coef.Free;
lstCurvature_coef.Free;
lstEa_name.Free;
lstYssy_yali.Free;
lstYssy_bxl.Free;
lstYssy_kxb.Free;
lstYssy_ysxs.Free;
lstYssy_ysml.Free;
for iCount:=0 to AnalyzeCount-1 do
begin
ArrayAnalyzeResult[iCount].lstValues.Free;
ArrayAnalyzeResult[iCount].lstValuesForPrint.Free;
end;
end;
//计算临界值
function CalculateCriticalValue(aValue, aPingjunZhi, aBiaoZhunCha: double): double;
begin
if aBiaoZhunCha = 0 then
begin
result:= 0;
exit;
end;
result := (aValue - aPingjunZhi) / aBiaoZhunCha;
end;
//计算平均值、标准差、变异系数等特征值。关联剔除 就是一个剔除时,另一个也剔除
//1、压缩系数 在剔除时要同时把压缩模量剔除 ,压缩模量在计算时不再做剔除处理
//2、凝聚力和摩擦角 都需要剔除,关联剔除
//3、含水量,液限 若超差要剔除,同时把塑性指数和液性指数剔除 。
// 3的判别顺序是:先判断含水量,若剔除时也要把液限剔除。后判断液限,若剔除时并不要把含水量剔除。
//另外,2009/12/29工勘院修改要求,只有凝聚力和摩擦角、标贯、静探需要计算标准值,其他都不在计算标准值,同时报表上这些不要计算标准值的要空白显示。
procedure GetTeZhengShuGuanLian(var aAnalyzeResult : TAnalyzeResult;Flags: TGuanLianFlags);
var
i,iCount,iFirst,iMax:integer;
dTotal,dValue,dTotalFangCha,dCriticalValue:double;
strValue: string;
TiChuGuo: boolean; //数据在计算时是否有过剔除,如果有,那么涉及到关联剔除的另外的数据也要重新计算
begin
iMax:=0;
dTotal:= 0;
iFirst:= 0;
TiChuGuo := false;
dTotalFangCha:=0;
aAnalyzeResult.PingJunZhi := -1;
aAnalyzeResult.BiaoZhunCha := -1;
aAnalyzeResult.BianYiXiShu := -1;
aAnalyzeResult.MaxValue := -1;
aAnalyzeResult.MinValue := -1;
aAnalyzeResult.SampleNum := -1;
aAnalyzeResult.BiaoZhunZhi:= -1;
if aAnalyzeResult.lstValues.Count<1 then exit;
strValue := '';
for i:= 0 to aAnalyzeResult.lstValues.Count-1 do
strValue:=strValue + aAnalyzeResult.lstValues.Strings[i];
strValue := trim(strValue);
if strValue='' then exit;
//yys 2005/06/15
iCount:= aAnalyzeResult.lstValues.Count;
for i:= 0 to aAnalyzeResult.lstValues.Count-1 do
begin
strValue:=aAnalyzeResult.lstValues.Strings[i];
if strValue='' then
begin
iCount:=iCount-1;
end
else
begin
inc(iFirst);
dValue:= StrToFloat(strValue);
if iFirst=1 then
begin
aAnalyzeResult.MinValue:= dValue;
aAnalyzeResult.MaxValue:= dValue;
iMax := i;
end
else
begin
if aAnalyzeResult.MinValue>dValue then
begin
aAnalyzeResult.MinValue:= dValue;
end;
if aAnalyzeResult.MaxValue<dValue then
begin
aAnalyzeResult.MaxValue:= dValue;
iMax := i;
end;
end;
dTotal:= dTotal + dValue;
end;
end;
//dTotal:= dTotal - aAnalyzeResult.MinValue - aAnalyzeResult.MaxValue;
//iCount := iCount - 2;
if iCount>=1 then
aAnalyzeResult.PingJunZhi := dTotal/iCount
else
aAnalyzeResult.PingJunZhi := dTotal;
//aAnalyzeResult.lstValues.Strings[iMin]:= '';
//aAnalyzeResult.lstValues.Strings[iMax]:= '';
//iCount:= aAnalyzeResult.lstValues.Count;
for i:= 0 to aAnalyzeResult.lstValues.Count-1 do
begin
strValue:=aAnalyzeResult.lstValues.Strings[i];
if strValue<>'' then
begin
dValue := StrToFloat(strValue);
dTotalFangCha := dTotalFangCha + sqr(dValue-aAnalyzeResult.PingJunZhi);
end
//else iCount:= iCount -1;
end;
if iCount>1 then
dTotalFangCha:= dTotalFangCha/(iCount-1);
aAnalyzeResult.SampleNum := iCount;
if iCount >1 then
aAnalyzeResult.BiaoZhunCha := sqrt(dTotalFangCha)
else
aAnalyzeResult.BiaoZhunCha := sqrt(dTotalFangCha);
if not iszero(aAnalyzeResult.PingJunZhi) then
aAnalyzeResult.BianYiXiShu := strtofloat(formatfloat(aAnalyzeResult.FormatString,aAnalyzeResult.BiaoZhunCha / aAnalyzeResult.PingJunZhi))
else
aAnalyzeResult.BianYiXiShu:= 0;
if iCount>=6 then
begin //2009/12/29工勘院修改要求,只有凝聚力和摩擦角需要计算标准值,其他都不在计算标准值,同时报表上这些不要计算标准值的要空白显示。
if (tgNingJuLi_ZhiKuai in Flags) or (tgMoCaJiao_ZhiKuai in Flags) or (tgNingJuLi_GuKuai in Flags) or (tgMoCaJiao_GuKuai in Flags) then
aAnalyzeResult.BiaoZhunZhi := GetBiaoZhunZhi(aAnalyzeResult.SampleNum , aAnalyzeResult.BianYiXiShu, aAnalyzeResult.PingJunZhi);
end;
dValue:= CalculateCriticalValue(aAnalyzeResult.MaxValue, aAnalyzeResult.PingJunZhi,aAnalyzeResult.BiaoZhunCha);
dCriticalValue := GetCriticalValue(iCount);
//2005/07/25 yys edit 土样数据剔除时,到6个样就不再剔除,剔除时要先剔除最大的数据,同时关联的其他数据一并剔除
if (iCount> 6) AND (dValue > dCriticalValue) then
begin
aAnalyzeResult.lstValues.Strings[iMax]:= '';
//if pos('-',aAnalyzeResult.lstValuesForPrint.Strings[iMax])>0 then //如果本身是负数 则减去1000
//if (ArrayAnalyzeResult[7].lstValuesForPrint.Strings[iMax]<>'') then
if (aAnalyzeResult.lstValuesForPrint.Strings[iMax]<>'') then
aAnalyzeResult.lstValuesForPrint.Strings[iMax] := AddFuHao(aAnalyzeResult.lstValuesForPrint.Strings[iMax]) ;
//else
// aAnalyzeResult.lstValuesForPrint.Strings[iMax]:= '-'+aAnalyzeResult.lstValuesForPrint.Strings[iMax];
TiChuGuo := true;
if tgHanShuiLiang in Flags then
begin
ArrayAnalyzeResult[7].lstValues.Strings[iMax]:= ''; //液限
ArrayAnalyzeResult[8].lstValues.Strings[iMax]:= ''; //塑限 Shape_limit;
ArrayAnalyzeResult[9].lstValues.Strings[iMax]:= ''; //塑性指数 Shape_index;
ArrayAnalyzeResult[10].lstValues.Strings[iMax]:= ''; //液性指数 Liquid_index;
//打印时负数转换成*加正数 如-10 打印时会转换成*10 ,但是,本身就有负数的液限,塑限, 塑性指数,液性指数单独处理,-1000,打印时也单独处理<-500时加*再加上1000
if (ArrayAnalyzeResult[7].lstValuesForPrint.Strings[iMax]<>'') then
ArrayAnalyzeResult[7].lstValuesForPrint.Strings[iMax] := AddFuHao(ArrayAnalyzeResult[7].lstValuesForPrint.Strings[iMax]); //液限
if ArrayAnalyzeResult[8].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[8].lstValuesForPrint.Strings[iMax]:=AddFuHao(ArrayAnalyzeResult[8].lstValuesForPrint.Strings[iMax]); //塑限 Shape_limit;
if ArrayAnalyzeResult[9].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[9].lstValuesForPrint.Strings[iMax]:=AddFuHao(ArrayAnalyzeResult[9].lstValuesForPrint.Strings[iMax]); //塑性指数 Shape_index;
if ArrayAnalyzeResult[10].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[10].lstValuesForPrint.Strings[iMax]:=AddFuHao(ArrayAnalyzeResult[10].lstValuesForPrint.Strings[iMax]); //液性指数 Liquid_index;
end
else if tgYeXian in Flags then
begin
ArrayAnalyzeResult[8].lstValues.Strings[iMax]:= ''; //塑限 Shape_limit;
ArrayAnalyzeResult[9].lstValues.Strings[iMax]:= ''; //塑性指数 Shape_index;
ArrayAnalyzeResult[10].lstValues.Strings[iMax]:= ''; //液性指数 Liquid_index;
if ArrayAnalyzeResult[8].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[8].lstValuesForPrint.Strings[iMax]:= AddFuHao(ArrayAnalyzeResult[8].lstValuesForPrint.Strings[iMax]); //塑限 Shape_limit;
if ArrayAnalyzeResult[9].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[9].lstValuesForPrint.Strings[iMax]:= AddFuHao(ArrayAnalyzeResult[9].lstValuesForPrint.Strings[iMax]); //塑性指数 Shape_index;
if ArrayAnalyzeResult[10].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[10].lstValuesForPrint.Strings[iMax] := AddFuHao(ArrayAnalyzeResult[10].lstValuesForPrint.Strings[iMax]); //液性指数 Liquid_index;
end
else if tgYaSuoXiShu in Flags then
begin
ArrayAnalyzeResult[12].lstValues.Strings[iMax]:= ''; //压缩模量 Zip_modulus;
if ArrayAnalyzeResult[12].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[12].lstValuesForPrint.Strings[iMax] := AddFuHao(ArrayAnalyzeResult[12].lstValuesForPrint.Strings[iMax]);
end
else if tgNingJuLi_ZhiKuai in Flags then //凝聚力直快
begin
ArrayAnalyzeResult[14].lstValues.Strings[iMax]:= ''; //摩擦角直快 Friction_angle
if ArrayAnalyzeResult[14].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[14].lstValuesForPrint.Strings[iMax] := AddFuHao(ArrayAnalyzeResult[14].lstValuesForPrint.Strings[iMax]);
end
else if tgMoCaJiao_ZhiKuai in Flags then
begin
ArrayAnalyzeResult[13].lstValues.Strings[iMax]:= ''; //凝聚力直快 Cohesion
if ArrayAnalyzeResult[13].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[13].lstValuesForPrint.Strings[iMax] := AddFuHao(ArrayAnalyzeResult[13].lstValuesForPrint.Strings[iMax]);
end
else if tgNingJuLi_GuKuai in Flags then //凝聚力固快
begin
ArrayAnalyzeResult[16].lstValues.Strings[iMax]:= ''; //摩擦角固快 Friction_gk
if ArrayAnalyzeResult[16].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[16].lstValuesForPrint.Strings[iMax] := AddFuHao(ArrayAnalyzeResult[16].lstValuesForPrint.Strings[iMax]);
end
else if tgMoCaJiao_GuKuai in Flags then
begin
ArrayAnalyzeResult[15].lstValues.Strings[iMax]:= ''; //凝聚力固快 Cohesion_gk
if ArrayAnalyzeResult[15].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[15].lstValuesForPrint.Strings[iMax] := AddFuHao(ArrayAnalyzeResult[15].lstValuesForPrint.Strings[iMax]);
end;
GetTeZhengShuGuanLian(aAnalyzeResult, Flags);
end;
if TiChuGuo then
begin
if tgNingJuLi_ZhiKuai in Flags then //凝聚力直快
begin
GetTeZhengShuGuanLian(ArrayAnalyzeResult[14], [tgMoCaJiao_ZhiKuai]); //摩擦角直快 Friction_angle
end
else if tgMoCaJiao_ZhiKuai in Flags then
begin
GetTeZhengShuGuanLian(ArrayAnalyzeResult[13], [tgNingJuLi_ZhiKuai]);//凝聚力直快 Cohesion
end
else if tgNingJuLi_GuKuai in Flags then //凝聚力固快
begin
GetTeZhengShuGuanLian(ArrayAnalyzeResult[16], [tgMoCaJiao_GuKuai]);//摩擦角固快 Friction_gk
end
else if tgMoCaJiao_GuKuai in Flags then
begin
GetTeZhengShuGuanLian(ArrayAnalyzeResult[15], [tgNingJuLi_GuKuai]);//凝聚力固快 Cohesion_gk
end;
end;
//yys 2005/06/15 add, 当一层只有一个样时,标准差和变异系数不能为0,打印报表时要用空格,物理力学表也一样。所以用-1来表示空值,是因为在报表设计时可以通过判断来表示为空。
if iCount=1 then
begin
//aAnalyzeResult.strBianYiXiShu := 'null';
//aAnalyzeResult.strBiaoZhunCha := 'null';
aAnalyzeResult.BianYiXiShu := -1;
aAnalyzeResult.BiaoZhunCha := -1;
aAnalyzeResult.BiaoZhunZhi := -1;
end
else begin
//aAnalyzeResult.strBianYiXiShu := FloatToStr(aAnalyzeResult.BianYiXiShu);
// aAnalyzeResult.strBiaoZhunCha := FloatToStr(aAnalyzeResult.BiaoZhunCha);
end;
//yys 2005/06/15 add
end;
//取得一个工程中所有的层号和亚层号和土类名称,保存在三个TStringList变量中。
procedure GetAllStratumNo(var AStratumNoList, ASubNoList, AEaNameList: TStringList);
var
strSQL: string;
begin
AStratumNoList.Clear;
ASubNoList.Clear;
AEaNameList.Clear;
strSQL:='SELECT id,prj_no,stra_no,sub_no,ISNULL(ea_name,'''') as ea_name FROM stratum_description'
+' WHERE prj_no='+''''+g_ProjectInfo.prj_no_ForSQL+''''
+' ORDER BY id';
with MainDataModule.qryStratum do
begin
close;
sql.Clear;
sql.Add(strSQL);
open;
while not eof do
begin
AStratumNoList.Add(FieldByName('stra_no').AsString);
ASubNoList.Add(FieldByName('sub_no').AsString);
AEaNameList.Add(FieldByName('ea_name').AsString);
next;
end;
close;
end;
end;
begin
try
//开始给土样分层 ,此处注释掉不用是因为已经在其他地方分层了。
//SetTuYangCengHao;
//开始清空临时统计表的当前工程数据
//strSQL:= 'TRUNCATE TABLE stratumTmp; TRUNCATE TABLE TeZhengShuTmp; TRUNCATE TABLE earthsampleTmp; TRUNCATE TABLE earthsampleTmp ';
strSQL:= 'DELETE FROM stratumTmp WHERE prj_no = '+''''+g_ProjectInfo.prj_no_ForSQL+''''+';'
+'DELETE FROM TeZhengShuTmp WHERE prj_no = '+''''+g_ProjectInfo.prj_no_ForSQL+''''+';'
+'DELETE FROM earthsampleTmp WHERE prj_no = '+''''+g_ProjectInfo.prj_no_ForSQL+'''';
if not Delete_oneRecord(MainDataModule.qrySectionTotal, strSQL) then
begin
exit;
end;
InitVar;
GetAllStratumNo(lstStratumNo, lstSubNo, lstEa_name);
if lstStratumNo.Count = 0 then
begin
//FreeStringList;
exit;
end;
{//将层号和亚层号和土类名称插入临时主表
for i:=0 to lstStratumNo.Count-1 do
begin
strSQL:='INSERT INTO stratumTmp (prj_no,stra_no,sub_no,ea_name) VALUES('
+''''+g_ProjectInfo.prj_no_ForSQL+''''+','
+''''+lstStratumNo.Strings[i]+'''' +','
+''''+lstSubNo.Strings[i]+''''+','
+''''+lstEa_name.Strings[i]+''''+')';
Insert_oneRecord(MainDataModule.qrySectionTotal, strSQL);
end;}
strPrjNo := g_ProjectInfo.prj_no_ForSQL;
for i:=0 to lstStratumNo.Count-1 do
begin
strSubNo := stringReplace(lstSubNo.Strings[i],'''','''''',[rfReplaceAll]);
strStratumNo := lstStratumNo.Strings[i];
//2008/11/21 yys edit 加入选择条件,钻孔参与统计
strSQL:='SELECT es.*,et.ea_name_en FROM (SELECT * FROM earthsample '
+' WHERE prj_no='+''''+strPrjNo+''''
+' AND stra_no='+''''+strStratumNo+''''
+' AND sub_no='+''''+strSubNo+''''
+' AND if_statistic=1 and drl_no in (select drl_no from drills where can_tongji=0 '
+' AND prj_no='+''''+strPrjNo+''''
+')) as es '
+' Left Join earthtype et on es.ea_name=et.ea_name';
iRecordCount := 0;
lstBeginDepth.Clear;
lstEndDepth.Clear;
lstDrl_no.Clear;
lstS_no.Clear;
lstShear_type.Clear;
lstsand_big.Clear;
lstsand_middle.Clear;
lstsand_small.Clear;
lstPowder_big.Clear;
lstPowder_small.Clear;
lstClay_grain.Clear;
lstAsymmetry_coef.Clear;
lstCurvature_coef.Clear;
lstEa_name.Clear;
lstYssy_yali.Clear;
lstYssy_bxl.Clear;
lstYssy_kxb.Clear;
lstYssy_ysxs.Clear;
lstYssy_ysml.Clear;
for j:=0 to AnalyzeCount-1 do
begin
ArrayAnalyzeResult[j].lstValues.Clear;
ArrayAnalyzeResult[j].lstValuesForPrint.Clear;
end;
with MainDataModule.qryEarthSample do
begin
close;
sql.Clear;
sql.Add(strSQL);
open;
while not eof do
begin
inc(iRecordCount);
lstDrl_no.Add(FieldByName('drl_no').AsString);
lstS_no.Add(FieldByName('s_no').AsString);
lstBeginDepth.Add(FieldByName('s_depth_begin').AsString);
lstEndDepth.Add(FieldByName('s_depth_end').AsString);
lstShear_type.Add(FieldByName('shear_type').AsString);
lstsand_big.Add(FieldByName('sand_big').AsString);
lstsand_middle.Add(FieldByName('sand_middle').AsString);
lstsand_small.Add(FieldByName('sand_small').AsString);
lstPowder_big.Add(FieldByName('powder_big').AsString);
lstPowder_small.Add(FieldByName('powder_small').AsString);
lstClay_grain.Add(FieldByName('clay_grain').AsString);
lstAsymmetry_coef.Add(FieldByName('asymmetry_coef').AsString);
lstCurvature_coef.Add(FieldByName('curvature_coef').AsString);
if g_ProjectInfo.prj_ReportLanguage= trChineseReport then
lstEa_name.Add(FieldByName('ea_name').AsString)
else if g_ProjectInfo.prj_ReportLanguage= trEnglishReport then
lstEa_name.Add(FieldByName('ea_name_en').AsString);
lstYssy_yali.Add(FieldByName('Yssy_yali').AsString);
lstYssy_bxl.Add(FieldByName('Yssy_bxl').AsString);
lstYssy_kxb.Add(FieldByName('Yssy_kxb').AsString);
lstYssy_ysxs.Add(FieldByName('Yssy_ysxs').AsString);
lstYssy_ysml.Add(FieldByName('Yssy_ysml').AsString);
for j:=0 to AnalyzeCount-1 do
begin
ArrayAnalyzeResult[j].lstValues.Add(FieldByName(ArrayFieldNames[j]).AsString);
ArrayAnalyzeResult[j].lstValuesForPrint.Add(FieldByName(ArrayFieldNames[j]).AsString);
end;
next;
end;
close;
end;
if iRecordCount=0 then //如果没有土样信息,则插入空值到特征数表,
begin //这是为了以后在特征数表TeZhengShuTmp插入静力触探和标贯数据时,只用UPDATE语句就可以了
for j:= 1 to 7 do
begin
strSQL:='INSERT INTO TeZhengShuTmp '
+'VALUES ('+''''+strPrjNo+''''+','
+''''+strStratumNo+'''' +','
+''''+strSubNo+''''+','''+InttoStr(j)+'''' + DupeString(',-1', 33)+')'; //此处27是TezhengShuTmp表去掉前面4个列后列数
Insert_oneRecord(MainDataModule.qryPublic, strSQL);
end;
continue;
end;
//取得特征数
//2007/01/24 下面这两句注释起来是因为
// for j:=0 to AnalyzeCount-1 do
// getTeZhengShu(ArrayAnalyzeResult[j], [tfTuYang]);
GetTeZhengShuGuanLian(ArrayAnalyzeResult[0],[tgHanShuiLiang]); //含水量 0
GetTeZhengShuGuanLian(ArrayAnalyzeResult[7],[tgYeXian]); //液限 7
for j:=1 to 6 do
getTeZhengShu(ArrayAnalyzeResult[j], [tfTuYang]);
for j:=8 to 10 do //塑限 8 塑性指数 9 液性指数 10 不进行剔除
getTeZhengShu(ArrayAnalyzeResult[j], [tfOther]);
GetTeZhengShuGuanLian(ArrayAnalyzeResult[11],[tgYaSuoXiShu]); //压缩系数 11
getTeZhengShu(ArrayAnalyzeResult[12], [tfOther]); //压缩模量 12 不进行剔除
GetTeZhengShuGuanLian(ArrayAnalyzeResult[13],[tgNingJuLi_ZhiKuai]); //凝聚力直快 13
GetTeZhengShuGuanLian(ArrayAnalyzeResult[14],[tgMoCaJiao_ZhiKuai]); //摩擦角直快 14
GetTeZhengShuGuanLian(ArrayAnalyzeResult[15],[tgNingJuLi_GuKuai]); //凝聚力固快 15
GetTeZhengShuGuanLian(ArrayAnalyzeResult[16],[tgMoCaJiao_GuKuai]); //摩擦角固快 16
for j:=17 to 19 do
getTeZhengShu(ArrayAnalyzeResult[j], [tfTuYang]);
for j:=20 to AnalyzeCount-1 do
getTeZhengShu(ArrayAnalyzeResult[j], [tfOther]);
//2007/01/24
// for j:=0 to ArrayAnalyzeResult[15].lstValues.count-1 do
// caption:= caption + ArrayAnalyzeResult[15].lstValues[j];
{******把平均值、标准差、变异系数、最大值、**********}
{******最小值、样本值、标准值等插入特征数表TeZhengShuTmp ****}
//开始取得要插入的字段名称。
strFieldNames:= '';
for j:=0 to AnalyzeCount-1 do
strFieldNames:= strFieldNames + ArrayFieldNames[j] + ',';
strFieldNames:= strFieldNames + 'prj_no, stra_no, sub_no, v_id';
//开始插入平均值
strFieldValues:= '';
strSQL:= '';
for j:=0 to AnalyzeCount-1 do
strFieldValues:= strFieldValues +FloatToStr(ArrayAnalyzeResult[j].PingJunZhi)+',';
strFieldValues:= strFieldValues
+''''+strPrjNo+''''+','
+''''+strStratumNo+'''' +','
+''''+strSubNo+''''+','+TEZHENSHU_Flag_PingJunZhi;
strSQL:='INSERT INTO TeZhengShuTmp (' + strFieldNames + ')'
+'VALUES('+strFieldValues+')';
if not Insert_oneRecord(MainDataModule.qrySectionTotal, strSQL) then
continue;
//开始插入标准差
strFieldValues:= '';
strSQL:= '';
for j:=0 to AnalyzeCount-1 do
strFieldValues:= strFieldValues +FloatToStr(ArrayAnalyzeResult[j].BiaoZhunCha)+',';
//strFieldValues:= strFieldValues +ArrayAnalyzeResult[j].strBiaoZhunCha+',';
strFieldValues:= strFieldValues
+''''+strPrjNo+''''+','
+''''+strStratumNo+'''' +','
+''''+strSubNo+''''+','+TEZHENSHU_Flag_BiaoZhunCha;
strSQL:='INSERT INTO TeZhengShuTmp (' + strFieldNames + ')'
+'VALUES('+strFieldValues+')';
if not Insert_oneRecord(MainDataModule.qrySectionTotal, strSQL) then
continue;
//开始插入变异系数
strFieldValues:= '';
strSQL:= '';
for j:=0 to AnalyzeCount-1 do
strFieldValues:= strFieldValues +FloatToStr(ArrayAnalyzeResult[j].BianYiXiShu)+',';
//strFieldValues:= strFieldValues + ArrayAnalyzeResult[j].strBianYiXiShu+',';
strFieldValues:= strFieldValues
+''''+strPrjNo+''''+','
+''''+strStratumNo+'''' +','
+''''+strSubNo+''''+','+TEZHENSHU_Flag_BianYiXiShu;
strSQL:='INSERT INTO TeZhengShuTmp (' + strFieldNames + ')'
+'VALUES('+strFieldValues+')';
if not Insert_oneRecord(MainDataModule.qrySectionTotal, strSQL) then
continue;
//开始插入最大值
strFieldValues:= '';
strSQL:= '';
for j:=0 to AnalyzeCount-1 do
strFieldValues:= strFieldValues +FloatToStr(ArrayAnalyzeResult[j].MaxValue)+',';
strFieldValues:= strFieldValues
+''''+strPrjNo+''''+','
+''''+strStratumNo+'''' +','
+''''+strSubNo+''''+','+TEZHENSHU_Flag_MaxValue;
strSQL:='INSERT INTO TeZhengShuTmp (' + strFieldNames + ')'
+'VALUES('+strFieldValues+')';
if not Insert_oneRecord(MainDataModule.qrySectionTotal, strSQL) then
continue;
//开始插入最小值
strFieldValues:= '';
strSQL:= '';
for j:=0 to AnalyzeCount-1 do
strFieldValues:= strFieldValues +FloatToStr(ArrayAnalyzeResult[j].MinValue)+',';
strFieldValues:= strFieldValues
+''''+strPrjNo+''''+','
+''''+strStratumNo+'''' +','
+''''+strSubNo+''''+','+TEZHENSHU_Flag_MinValue;
strSQL:='INSERT INTO TeZhengShuTmp (' + strFieldNames + ')'
+'VALUES('+strFieldValues+')';
if not Insert_oneRecord(MainDataModule.qrySectionTotal, strSQL) then
continue;
//开始插入样本值
strFieldValues:= '';
strSQL:= '';
for j:=0 to AnalyzeCount-1 do
strFieldValues:= strFieldValues +FloatToStr(ArrayAnalyzeResult[j].SampleNum)+',';
strFieldValues:= strFieldValues
+''''+strPrjNo+''''+','
+''''+strStratumNo+'''' +','
+''''+strSubNo+''''+','+TEZHENSHU_Flag_SampleNum;
strSQL:='INSERT INTO TeZhengShuTmp (' + strFieldNames + ')'
+'VALUES('+strFieldValues+')';
if not Insert_oneRecord(MainDataModule.qrySectionTotal, strSQL) then
continue;
//开始插入标准值
strFieldValues:= '';
strSQL:= '';
for j:=0 to AnalyzeCount-1 do
strFieldValues:= strFieldValues +FloatToStr(ArrayAnalyzeResult[j].BiaoZhunZhi)+',';
strFieldValues:= strFieldValues
+''''+strPrjNo+''''+','
+''''+strStratumNo+'''' +','
+''''+strSubNo+''''+','+TEZHENSHU_Flag_BiaoZhunZhi;
strSQL:='INSERT INTO TeZhengShuTmp (' + strFieldNames + ')'
+'VALUES('+strFieldValues+')';
if not Insert_oneRecord(MainDataModule.qrySectionTotal, strSQL) then
continue;
{********把经过舍弃的数值插入临时土样表**********}
for j:=0 to iRecordCount-1 do
begin
strFieldNames:= '';
strFieldValues:= '';
strSQL:= '';
strFieldNames:='drl_no, s_no, s_depth_begin, s_depth_end,'
+'shear_type, sand_big, sand_middle, sand_small, powder_big,'
+'powder_small, clay_grain, asymmetry_coef, curvature_coef,ea_name,';
if lstDrl_no.Strings[j]='' then continue;
strFieldNames:= 'drl_no';
strFieldValues:= strFieldValues +'''' + stringReplace(lstDrl_no.Strings[j] ,'''','''''',[rfReplaceAll]) +'''';
if lstS_no.Strings[j]='' then continue;
strFieldNames:= strFieldNames + ',s_no';
strFieldValues:= strFieldValues +','+'''' + lstS_no.Strings[j] +'''';
if lstBeginDepth.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',s_depth_begin';
strFieldValues:= strFieldValues +','+'''' + lstBeginDepth.Strings[j] +'''' ;
end;
if lstEndDepth.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',s_depth_end';
strFieldValues:= strFieldValues +','+'''' + lstEndDepth.Strings[j] +'''' ;
end;
//yys 20040610 modified
//if lstShear_type.Strings[j]<>'' then
// strFieldValues:= strFieldValues +'''' + lstShear_type.Strings[j] +'''' +','
//else
// strFieldValues:= strFieldValues + 'NULL' +',';
//yys 20040610 modified
if lstsand_big.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',sand_big';
strFieldValues:= strFieldValues +','+'''' + lstsand_big.Strings[j] +'''';
end;
if lstsand_middle.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',sand_middle';
strFieldValues:= strFieldValues +','+'''' + lstsand_middle.Strings[j] +'''';
end;
if lstsand_small.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',sand_small';
strFieldValues:= strFieldValues +','+'''' + lstsand_small.Strings[j] +'''' ;
end;
if lstPowder_big.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',Powder_big';
strFieldValues:= strFieldValues +','+'''' + lstPowder_big.Strings[j] +'''' ;
end;
if lstPowder_small.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',Powder_small';
strFieldValues:= strFieldValues +','+'''' + lstPowder_small.Strings[j] +'''' ;
end;
if lstClay_grain.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',Clay_grain';
strFieldValues:= strFieldValues +','+'''' + lstClay_grain.Strings[j] +'''';
end;
if lstAsymmetry_coef.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',Asymmetry_coef';
strFieldValues:= strFieldValues +','+'''' + lstAsymmetry_coef.Strings[j] +'''';
end;
if lstCurvature_coef.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',Curvature_coef';
strFieldValues:= strFieldValues +','+'''' + lstCurvature_coef.Strings[j] +'''' ;
end;
if lstEa_name.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',Ea_name';
strFieldValues:= strFieldValues +','+'''' + lstEa_name.Strings[j] +'''';
end;
if lstYssy_yali.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',Yssy_yali';
strFieldValues:= strFieldValues +','+'''' + lstYssy_yali.Strings[j] +'''';
end;
if lstYssy_bxl.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',Yssy_bxl';
strFieldValues:= strFieldValues +','+'''' + lstYssy_bxl.Strings[j] +'''';
end;
if lstYssy_kxb.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',Yssy_kxb';
strFieldValues:= strFieldValues +','+'''' + lstYssy_kxb.Strings[j] +'''';
end;
if lstYssy_ysxs.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',Yssy_ysxs';
strFieldValues:= strFieldValues +','+'''' + lstYssy_ysxs.Strings[j] +'''';
end;
if lstYssy_ysml.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',Yssy_ysml';
strFieldValues:= strFieldValues +','+'''' + lstYssy_ysml.Strings[j] +'''';
end;
for iCol:=0 to 19 do // for iCol:=0 to AnalyzeCount-1 do 不要加上颗分数据,上面已经加了
begin
strTmp := ArrayAnalyzeResult[iCol].lstValuesForPrint.Strings[j];
if strTmp <> '' then
begin
strFieldNames:= strFieldNames + ','+ ArrayFieldNames[iCol] ;
strFieldValues:= strFieldValues +','+ strTmp ;
end;
end;
strFieldNames:= strFieldNames + ',prj_no, stra_no, sub_no';
strFieldValues:= strFieldValues +','+''''
+strPrjNo+''''+','
+''''+strStratumNo+'''' +','
+''''+strSubNo+'''';
strSQL:='INSERT INTO earthsampleTmp (' + strFieldNames + ')'
+'VALUES('+strFieldValues+')';
if Insert_oneRecord(MainDataModule.qrySectionTotal, strSQL) then
else;
end;
end; // end of for i:=0 to lstStratumNo.Count-1 do
finally
FreeStringList;
end;
end;
procedure FenXiFenCeng_TeShuYiangJiSuan;
type TGuanLianFlags = set of (tgHanShuiLiang, tgYeXian, tgYaSuoXiShu, tgNingJuLi_ZhiKuai, tgMoCaJiao_ZhiKuai,
tgNingJuLi_GuKuai, tgMoCaJiao_GuKuai);
//yys 20040610 modified
//const AnalyzeCount=17;
const AnalyzeCount=44;
//yys 20040610 modified
var
//层号 亚层号
lstStratumNo, lstSubNo: TStringList;
//钻孔号 土样编号 开始深度 结束深度
lstDrl_no, lstS_no, lstBeginDepth, lstEndDepth: TStringList;
//剪切类型 砂粒粗(%) 砂粒中(%) 砂粒细(%)
lstShear_type, lstsand_big, lstsand_middle,lstsand_small:Tstringlist;
//粉粒粗(%) 粉粒细(%) 粘粒(%) 不均匀系数 曲率系数 土类编号 土类名称
lstPowder_big, lstPowder_small, lstClay_grain, lstAsymmetry_coef,lstCurvature_coef, lstEa_name: TStringList;
//各级压力 各级压力下变形量 孔隙比 压缩系数 压缩模量
lstYssy_yali, lstYssy_bxl, lstYssy_kxb, lstYssy_ysxs, lstYssy_ysml: TStringList;
i,j,iRecordCount,iCol: integer;
strSQL, strFieldNames, strFieldValues , strTmp, strSubNo,strStratumNo,strPrjNo: string;
aGygj_pc : TAnalyzeResult;//先期固结压力 0
aGygj_cc : TAnalyzeResult;//压缩指数 1
aGygj_cs : TAnalyzeResult;//回弹指数 2
aHtml : TAnalyzeResult;//回弹模量 3
aGjxs50_1 : TAnalyzeResult;//固结系数50 4
aGjxs100_1 : TAnalyzeResult;//固结系数100 5
aGjxs200_1 : TAnalyzeResult;//固结系数200 6
aGjxs400_1 : TAnalyzeResult;//固结系数400 7
aGjxs50_2 : TAnalyzeResult;//固结系数50 8
aGjxs100_2 : TAnalyzeResult;//固结系数100 9
aGjxs200_2 : TAnalyzeResult;//固结系数200 10
aGjxs400_2 : TAnalyzeResult;//固结系数400 11
aJcxs_v_005_01 : TAnalyzeResult;//基床系数(垂直)0.05~0.1 12
aJcxs_v_01_02 : TAnalyzeResult;//基床系数(垂直)0.1~0.2 13
aJcxs_v_02_04 : TAnalyzeResult;//基床系数(垂直)0.05~0.1 14
aJcxs_h_005_01 : TAnalyzeResult;//基床系数(水平)0.05~0.1 15
aJcxs_h_01_02 : TAnalyzeResult;//基床系数(水平)0.1~0.2 16
aJcxs_h_02_04 : TAnalyzeResult;//基床系数(水平)0.2~0.4 17
aJzcylxs :TAnalyzeResult; //静止侧压力系数 18
aWcxkyqd_yz :TAnalyzeResult; //无侧限抗压强度 原状 19
aWcxkyqd_cs :TAnalyzeResult; //无侧限抗压强度 重塑 20
aWcxkyqd_lmd :TAnalyzeResult; //无侧限抗压强度 灵敏度 21
aSzsy_zyl_njl_UU :TAnalyzeResult; //总应力粘聚力UU 22
aSzsy_zyl_nmcj_UU :TAnalyzeResult; //总应力内摩擦角UU 23
aSzsy_zyl_njl_CU :TAnalyzeResult; //总应力 粘聚力CU 24
aSzsy_zyl_nmcj_CU :TAnalyzeResult; //总应力内摩擦角CU 25
aSzsy_yxyl_njl :TAnalyzeResult; //有效应力粘聚力 26
aSzsy_yxyl_nmcj :TAnalyzeResult; //有效应力内摩擦角 27
aStxs_kv : TAnalyzeResult;//渗透系数Kv 28
aStxs_kh : TAnalyzeResult;//渗透系数KH 29
aTrpj_g : TAnalyzeResult;//天然坡角 干 30
aTrpj_sx : TAnalyzeResult;//天然坡角 水下 31
aKlzc_li : TAnalyzeResult;//颗粒组成(砾)>2 32
aKlzc_sha_2_05 : TAnalyzeResult;//颗粒组成(砂)2~0.5 33
aKlzc_sha_05_025 : TAnalyzeResult;//颗粒组成(砂)0.5~0.25 34
aKlzc_sha_025_0075 : TAnalyzeResult;//颗粒组成(砂)0.25~0.075 35
aKlzc_fl :TAnalyzeResult; //颗粒组成(粉粒)0.075~0.005 36
aKlzc_nl :TAnalyzeResult; //颗粒组成(粘粒) <0.005 37
aLj_yxlj :TAnalyzeResult;//有效粒径 38
aLj_pjlj :TAnalyzeResult; //平均粒径 39
aLj_xzlj :TAnalyzeResult; //限制粒径 40
aLj_d70 :TAnalyzeResult; // 41
aBjyxs :TAnalyzeResult; //不均匀系数 42
aQlxs :TAnalyzeResult;//曲率系数 43
ArrayAnalyzeResult: Array[0..AnalyzeCount-1] of TAnalyzeResult; // 保存要参加统计的TAnalyzeResult
ArrayFieldNames: Array[0..AnalyzeCount-1] of String; // 保存要参加统计的字段名,与ArrayAnalyzeResult的内容一一对应
ArrayToFieldNames: Array[0..AnalyzeCount-1] of String; // 保存要插入到TeShuYangTzsTmp表的字段名,主要是为了剪切实验的UU和CU的总应力
//初始化此过程中的变量
procedure InitVar;
var
iCount: integer;
begin
ArrayAnalyzeResult[0]:= aGygj_pc; ArrayFieldNames[0]:= 'Gygj_pc';
ArrayAnalyzeResult[1]:= aGygj_cc; ArrayFieldNames[1]:= 'Gygj_cc';
ArrayAnalyzeResult[2]:= aGygj_cs; ArrayFieldNames[2]:= 'Gygj_cs';
ArrayAnalyzeResult[3]:= aHtml; ArrayFieldNames[3]:= 'Html';
ArrayAnalyzeResult[4]:= aGjxs50_1; ArrayFieldNames[4]:= 'Gjxs50_1';
ArrayAnalyzeResult[5]:= aGjxs100_1; ArrayFieldNames[5]:= 'Gjxs100_1';
ArrayAnalyzeResult[6]:= aGjxs200_1; ArrayFieldNames[6]:= 'Gjxs200_1';
ArrayAnalyzeResult[7]:= aGjxs400_1; ArrayFieldNames[7]:= 'Gjxs400_1';
ArrayAnalyzeResult[8]:= aGjxs50_2; ArrayFieldNames[8]:= 'Gjxs50_2';
ArrayAnalyzeResult[9]:= aGjxs100_2; ArrayFieldNames[9]:= 'Gjxs100_2';
ArrayAnalyzeResult[10]:= aGjxs200_2; ArrayFieldNames[10]:= 'Gjxs200_2';
ArrayAnalyzeResult[11]:= aGjxs400_2; ArrayFieldNames[11]:= 'Gjxs400_2';
ArrayAnalyzeResult[12]:= aJcxs_v_005_01; ArrayFieldNames[12]:= 'Jcxs_v_005_01';
ArrayAnalyzeResult[13]:= aJcxs_v_01_02; ArrayFieldNames[13]:= 'Jcxs_v_01_02';
ArrayAnalyzeResult[14]:= aJcxs_v_02_04; ArrayFieldNames[14]:= 'Jcxs_v_02_04';
ArrayAnalyzeResult[15]:= aJcxs_h_005_01; ArrayFieldNames[15]:= 'Jcxs_h_005_01';
ArrayAnalyzeResult[16]:= aJcxs_h_01_02; ArrayFieldNames[16]:= 'Jcxs_h_01_02';
ArrayAnalyzeResult[17]:= aJcxs_h_02_04; ArrayFieldNames[17]:= 'Jcxs_h_02_04';
ArrayAnalyzeResult[18]:= aJzcylxs; ArrayFieldNames[18]:= 'Jzcylxs';
ArrayAnalyzeResult[19]:= aWcxkyqd_yz; ArrayFieldNames[19]:= 'Wcxkyqd_yz';
ArrayAnalyzeResult[20]:= aWcxkyqd_cs; ArrayFieldNames[20]:= 'Wcxkyqd_cs';
ArrayAnalyzeResult[21]:= aWcxkyqd_lmd; ArrayFieldNames[21]:= 'Wcxkyqd_lmd';
ArrayAnalyzeResult[22]:= aSzsy_zyl_njl_UU; ArrayFieldNames[22]:= 'Szsy_zyl_njl_UU';
ArrayAnalyzeResult[23]:= aSzsy_zyl_nmcj_UU; ArrayFieldNames[23]:= 'Szsy_zyl_nmcj_UU';
ArrayAnalyzeResult[24]:= aSzsy_zyl_njl_CU; ArrayFieldNames[24]:= 'Szsy_zyl_njl_CU';
ArrayAnalyzeResult[25]:= aSzsy_zyl_nmcj_CU; ArrayFieldNames[25]:= 'Szsy_zyl_nmcj_CU';
ArrayAnalyzeResult[26]:= aSzsy_yxyl_njl; ArrayFieldNames[26]:= 'Szsy_yxyl_njl';
ArrayAnalyzeResult[27]:= aSzsy_yxyl_nmcj; ArrayFieldNames[27]:= 'Szsy_yxyl_nmcj';
ArrayAnalyzeResult[28]:= aStxs_kv; ArrayFieldNames[28]:= 'Stxs_kv';
ArrayAnalyzeResult[29]:= aStxs_kh; ArrayFieldNames[29]:= 'Stxs_kh';
ArrayAnalyzeResult[30]:= aTrpj_g; ArrayFieldNames[30]:= 'Trpj_g';
ArrayAnalyzeResult[31]:= aTrpj_sx; ArrayFieldNames[31]:= 'Trpj_sx';
ArrayAnalyzeResult[32]:= aKlzc_li; ArrayFieldNames[32]:= 'Klzc_li';
ArrayAnalyzeResult[33]:= aKlzc_sha_2_05; ArrayFieldNames[33]:= 'Klzc_sha_2_05';
ArrayAnalyzeResult[34]:= aKlzc_sha_05_025; ArrayFieldNames[34]:= 'Klzc_sha_05_025';
ArrayAnalyzeResult[35]:= aKlzc_sha_025_0075; ArrayFieldNames[35]:= 'Klzc_sha_025_0075';
ArrayAnalyzeResult[36]:= aKlzc_fl; ArrayFieldNames[36]:= 'Klzc_fl';
ArrayAnalyzeResult[37]:= aKlzc_nl; ArrayFieldNames[37]:= 'Klzc_nl';
ArrayAnalyzeResult[38]:= aLj_yxlj; ArrayFieldNames[38]:= 'Lj_yxlj';
ArrayAnalyzeResult[39]:= aLj_pjlj; ArrayFieldNames[39]:= 'Lj_pjlj';
ArrayAnalyzeResult[40]:= aLj_xzlj; ArrayFieldNames[40]:= 'Lj_xzlj';
ArrayAnalyzeResult[41]:= aLj_d70; ArrayFieldNames[41]:= 'Lj_d70';
ArrayAnalyzeResult[42]:= aBjyxs; ArrayFieldNames[42]:= 'bjyxs';
ArrayAnalyzeResult[43]:= aQlxs; ArrayFieldNames[43]:= 'qlxs';
lstStratumNo:= TStringList.Create;
lstSubNo:= TStringList.Create;
lstBeginDepth:= TStringList.Create;
lstEndDepth:= TStringList.Create;
lstDrl_no:= TStringList.Create;
lstS_no:= TStringList.Create;
lstShear_type:= TStringList.Create;
lstsand_big:= TStringList.Create;
lstsand_middle:= TStringList.Create;
lstsand_small:= TStringList.Create;
lstPowder_big:= TStringList.Create;
lstPowder_small:= TStringList.Create;
lstClay_grain:= TStringList.Create;
lstAsymmetry_coef:= TStringList.Create;
lstCurvature_coef:= TStringList.Create;
lstEa_name:= TStringList.Create;
lstYssy_yali:= TStringList.Create;
lstYssy_bxl:= TStringList.Create;
lstYssy_kxb:= TStringList.Create;
lstYssy_ysxs:= TStringList.Create;
lstYssy_ysml:= TStringList.Create;
for iCount:=0 to AnalyzeCount-1 do
begin
ArrayAnalyzeResult[iCount].lstValues := TStringList.Create;
ArrayAnalyzeResult[iCount].lstValuesForPrint := TStringList.Create;
end;
aGygj_pc.FormatString := '0.0';
aGygj_cc.FormatString := '0.0000';
aGygj_cs.FormatString := '0.0000';
aHtml.FormatString := '0.0';
aGjxs50_1.FormatString := '0.000';
aGjxs100_1.FormatString := '0.000';
aGjxs200_1.FormatString := '0.000';
aGjxs400_1.FormatString := '0.000';
aGjxs50_2.FormatString := '0.000'; aStxs_kv.FormatString := '0.0000';
aGjxs100_2.FormatString := '0.000'; aStxs_kh.FormatString := '0.0000';
aGjxs200_2.FormatString := '0.000'; aTrpj_g.FormatString := '0';
aGjxs400_2.FormatString := '0.000'; aTrpj_sx.FormatString := '0';
aJcxs_v_005_01.FormatString := '0.00';
aJcxs_v_01_02.FormatString := '0.00'; aKlzc_li.FormatString := '0.0';
aJcxs_v_02_04.FormatString := '0.00'; aKlzc_sha_2_05.FormatString := '0.0';
aJcxs_h_005_01.FormatString := '0.00'; aKlzc_sha_05_025.FormatString := '0.0';
aJcxs_h_01_02.FormatString := '0.00'; aKlzc_sha_025_0075.FormatString := '0.0';
aJcxs_h_02_04.FormatString := '0.00'; aKlzc_fl.FormatString := '0.0';
aJzcylxs.FormatString := '0.000'; aKlzc_nl.FormatString := '0.0';
aWcxkyqd_yz.FormatString := '0.0';
aWcxkyqd_cs.FormatString := '0.0'; aLj_yxlj.FormatString := '0.000';
aWcxkyqd_lmd.FormatString:= '0.00'; aLj_pjlj.FormatString := '0.000';
aSzsy_zyl_njl_UU.FormatString := '0.0'; aLj_xzlj.FormatString := '0.000';
aSzsy_zyl_nmcj_UU.FormatString := '0.0'; aLj_d70.FormatString := '0.000';
aSzsy_zyl_njl_CU.FormatString := '0.0';
aSzsy_zyl_nmcj_CU.FormatString := '0.0'; aBjyxs.FormatString := '0.00';
aSzsy_yxyl_njl.FormatString := '0.0'; aQlxs.FormatString := '0.00';
aSzsy_yxyl_nmcj.FormatString := '0.0';
end;
//释放此过程中的变量
procedure FreeStringList;
var
iCount: integer;
begin
lstStratumNo.Free; lstPowder_big.Free;
lstSubNo.Free; lstPowder_small.Free;
lstBeginDepth.Free; lstClay_grain.Free;
lstEndDepth.Free; lstAsymmetry_coef.Free;
lstDrl_no.Free; lstCurvature_coef.Free;
lstS_no.Free; lstEa_name.Free;
lstShear_type.Free; lstYssy_yali.Free;
lstsand_big.Free; lstYssy_bxl.Free;
lstsand_middle.Free; lstYssy_kxb.Free;
lstsand_small.Free; lstYssy_ysxs.Free;
lstYssy_ysml.Free;
for iCount:=0 to AnalyzeCount-1 do
begin
ArrayAnalyzeResult[iCount].lstValues.Free;
ArrayAnalyzeResult[iCount].lstValuesForPrint.Free;
end;
end;
//计算临界值
function CalculateCriticalValue(aValue, aPingjunZhi, aBiaoZhunCha: double): double;
begin
if aBiaoZhunCha = 0 then
begin
result:= 0;
exit;
end;
result := (aValue - aPingjunZhi) / aBiaoZhunCha;
end;
//计算平均值、标准差、变异系数等特征值。关联剔除 就是一个剔除时,另一个也剔除
//1、压缩系数 在剔除时要同时把压缩模量剔除 ,压缩模量在计算时不再做剔除处理
//2、凝聚力和摩擦角 都需要剔除,关联剔除
//3、含水量,液限 若超差要剔除,同时把塑性指数和液性指数剔除 。
// 3的判别顺序是:先判断含水量,若剔除时也要把液限剔除。后判断液限,若剔除时并不要把含水量剔除。
//另外,2009/12/29工勘院修改要求,只有凝聚力和摩擦角、标贯、静探需要计算标准值,其他都不在计算标准值,同时报表上这些不要计算标准值的要空白显示。
//2011/03/09 工勘院修改要求,所有字段都要计算标准值,因为特殊样分层统计表只是内部看,所以数据都要。
procedure GetTeZhengShuGuanLian(var aAnalyzeResult : TAnalyzeResult;Flags: TGuanLianFlags);
var
i,iCount,iFirst,iMax:integer;
dTotal,dValue,dTotalFangCha,dCriticalValue:double;
strValue: string;
TiChuGuo: boolean; //数据在计算时是否有过剔除,如果有,那么涉及到关联剔除的另外的数据也要重新计算
begin
iMax:=0;
dTotal:= 0;
iFirst:= 0;
TiChuGuo := false;
dTotalFangCha:=0;
aAnalyzeResult.PingJunZhi := -1;
aAnalyzeResult.BiaoZhunCha := -1;
aAnalyzeResult.BianYiXiShu := -1;
aAnalyzeResult.MaxValue := -1;
aAnalyzeResult.MinValue := -1;
aAnalyzeResult.SampleNum := -1;
aAnalyzeResult.BiaoZhunZhi:= -1;
if aAnalyzeResult.lstValues.Count<1 then exit;
strValue := '';
for i:= 0 to aAnalyzeResult.lstValues.Count-1 do
strValue:=strValue + aAnalyzeResult.lstValues.Strings[i];
strValue := trim(strValue);
if strValue='' then exit;
//yys 2005/06/15
iCount:= aAnalyzeResult.lstValues.Count;
for i:= 0 to aAnalyzeResult.lstValues.Count-1 do
begin
strValue:=aAnalyzeResult.lstValues.Strings[i];
if strValue='' then
begin
iCount:=iCount-1;
end
else
begin
inc(iFirst);
dValue:= StrToFloat(strValue);
if iFirst=1 then
begin
aAnalyzeResult.MinValue:= dValue;
aAnalyzeResult.MaxValue:= dValue;
iMax := i;
end
else
begin
if aAnalyzeResult.MinValue>dValue then
begin
aAnalyzeResult.MinValue:= dValue;
end;
if aAnalyzeResult.MaxValue<dValue then
begin
aAnalyzeResult.MaxValue:= dValue;
iMax := i;
end;
end;
dTotal:= dTotal + dValue;
end;
end;
//dTotal:= dTotal - aAnalyzeResult.MinValue - aAnalyzeResult.MaxValue;
//iCount := iCount - 2;
if iCount>=1 then
aAnalyzeResult.PingJunZhi := dTotal/iCount
else
aAnalyzeResult.PingJunZhi := dTotal;
//aAnalyzeResult.lstValues.Strings[iMin]:= '';
//aAnalyzeResult.lstValues.Strings[iMax]:= '';
//iCount:= aAnalyzeResult.lstValues.Count;
for i:= 0 to aAnalyzeResult.lstValues.Count-1 do
begin
strValue:=aAnalyzeResult.lstValues.Strings[i];
if strValue<>'' then
begin
dValue := StrToFloat(strValue);
dTotalFangCha := dTotalFangCha + sqr(dValue-aAnalyzeResult.PingJunZhi);
end
//else iCount:= iCount -1;
end;
if iCount>1 then
dTotalFangCha:= dTotalFangCha/(iCount-1);
aAnalyzeResult.SampleNum := iCount;
if iCount >1 then
aAnalyzeResult.BiaoZhunCha := sqrt(dTotalFangCha)
else
aAnalyzeResult.BiaoZhunCha := sqrt(dTotalFangCha);
if not iszero(aAnalyzeResult.PingJunZhi) then
aAnalyzeResult.BianYiXiShu := strtofloat(formatfloat(aAnalyzeResult.FormatString,aAnalyzeResult.BiaoZhunCha / aAnalyzeResult.PingJunZhi))
else
aAnalyzeResult.BianYiXiShu:= 0;
if iCount>=6 then
begin //2009/12/29工勘院修改要求,只有凝聚力和摩擦角需要计算标准值,其他都不在计算标准值,同时报表上这些不要计算标准值的要空白显示。
//2011/03/09 工勘院修改要求,所有的字段都要计算标准值
//if (tgNingJuLi_ZhiKuai in Flags) or (tgMoCaJiao_ZhiKuai in Flags) or (tgNingJuLi_GuKuai in Flags) or (tgMoCaJiao_GuKuai in Flags) then
aAnalyzeResult.BiaoZhunZhi := GetBiaoZhunZhi(aAnalyzeResult.SampleNum , aAnalyzeResult.BianYiXiShu, aAnalyzeResult.PingJunZhi);
end;
dValue:= CalculateCriticalValue(aAnalyzeResult.MaxValue, aAnalyzeResult.PingJunZhi,aAnalyzeResult.BiaoZhunCha);
dCriticalValue := GetCriticalValue(iCount);
//2005/07/25 yys edit 土样数据剔除时,到6个样就不再剔除,剔除时要先剔除最大的数据,同时关联的其他数据一并剔除
if (iCount> 6) AND (dValue > dCriticalValue) then
begin
aAnalyzeResult.lstValues.Strings[iMax]:= '';
aAnalyzeResult.lstValuesForPrint.Strings[iMax]:= '-'
+aAnalyzeResult.lstValuesForPrint.Strings[iMax];
TiChuGuo := true;
if tgHanShuiLiang in Flags then
begin
ArrayAnalyzeResult[7].lstValues.Strings[iMax]:= ''; //液限
ArrayAnalyzeResult[8].lstValues.Strings[iMax]:= ''; //塑限 Shape_limit;
ArrayAnalyzeResult[9].lstValues.Strings[iMax]:= ''; //塑性指数 Shape_index;
ArrayAnalyzeResult[10].lstValues.Strings[iMax]:= ''; //液性指数 Liquid_index;
//打印时负数转换成*加正数 如-10 打印时会转换成*10
if ArrayAnalyzeResult[7].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[7].lstValuesForPrint.Strings[iMax]:= '-'
+ArrayAnalyzeResult[7].lstValuesForPrint.Strings[iMax]; //液限
if ArrayAnalyzeResult[8].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[8].lstValuesForPrint.Strings[iMax]:= '-'
+ArrayAnalyzeResult[8].lstValuesForPrint.Strings[iMax]; //塑限 Shape_limit;
if ArrayAnalyzeResult[9].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[9].lstValuesForPrint.Strings[iMax]:= '-'
+ArrayAnalyzeResult[9].lstValuesForPrint.Strings[iMax]; //塑性指数 Shape_index;
if ArrayAnalyzeResult[10].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[10].lstValuesForPrint.Strings[iMax]:= '-'
+ArrayAnalyzeResult[10].lstValuesForPrint.Strings[iMax]; //液性指数 Liquid_index;
end
else if tgYeXian in Flags then
begin
ArrayAnalyzeResult[8].lstValues.Strings[iMax]:= ''; //塑限 Shape_limit;
ArrayAnalyzeResult[9].lstValues.Strings[iMax]:= ''; //塑性指数 Shape_index;
ArrayAnalyzeResult[10].lstValues.Strings[iMax]:= ''; //液性指数 Liquid_index;
if ArrayAnalyzeResult[8].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[8].lstValuesForPrint.Strings[iMax]:= '-'
+ArrayAnalyzeResult[8].lstValuesForPrint.Strings[iMax]; //塑限 Shape_limit;
if ArrayAnalyzeResult[9].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[9].lstValuesForPrint.Strings[iMax]:= '-'
+ArrayAnalyzeResult[9].lstValuesForPrint.Strings[iMax]; //塑性指数 Shape_index;
if ArrayAnalyzeResult[10].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[10].lstValuesForPrint.Strings[iMax]:= '-'
+ArrayAnalyzeResult[10].lstValuesForPrint.Strings[iMax]; //液性指数 Liquid_index;
end
else if tgYaSuoXiShu in Flags then
begin
ArrayAnalyzeResult[12].lstValues.Strings[iMax]:= ''; //压缩模量 Zip_modulus;
if ArrayAnalyzeResult[12].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[12].lstValuesForPrint.Strings[iMax]:= '-'
+ArrayAnalyzeResult[12].lstValuesForPrint.Strings[iMax];
end
else if tgNingJuLi_ZhiKuai in Flags then //凝聚力直快
begin
ArrayAnalyzeResult[14].lstValues.Strings[iMax]:= ''; //摩擦角直快 Friction_angle
if ArrayAnalyzeResult[14].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[14].lstValuesForPrint.Strings[iMax]:= '-'
+ArrayAnalyzeResult[14].lstValuesForPrint.Strings[iMax];
end
else if tgMoCaJiao_ZhiKuai in Flags then
begin
ArrayAnalyzeResult[13].lstValues.Strings[iMax]:= ''; //凝聚力直快 Cohesion
if ArrayAnalyzeResult[13].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[13].lstValuesForPrint.Strings[iMax]:= '-'
+ArrayAnalyzeResult[13].lstValuesForPrint.Strings[iMax];
end
else if tgNingJuLi_GuKuai in Flags then //凝聚力固快
begin
ArrayAnalyzeResult[16].lstValues.Strings[iMax]:= ''; //摩擦角固快 Friction_gk
if ArrayAnalyzeResult[16].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[16].lstValuesForPrint.Strings[iMax]:= '-'
+ArrayAnalyzeResult[16].lstValuesForPrint.Strings[iMax];
end
else if tgMoCaJiao_GuKuai in Flags then
begin
ArrayAnalyzeResult[15].lstValues.Strings[iMax]:= ''; //凝聚力固快 Cohesion_gk
if ArrayAnalyzeResult[15].lstValuesForPrint.Strings[iMax]<>'' then
ArrayAnalyzeResult[15].lstValuesForPrint.Strings[iMax]:= '-'
+ArrayAnalyzeResult[15].lstValuesForPrint.Strings[iMax];
end;
GetTeZhengShuGuanLian(aAnalyzeResult, Flags);
end;
if TiChuGuo then
begin
if tgNingJuLi_ZhiKuai in Flags then //凝聚力直快
begin
GetTeZhengShuGuanLian(ArrayAnalyzeResult[14], [tgMoCaJiao_ZhiKuai]); //摩擦角直快 Friction_angle
end
else if tgMoCaJiao_ZhiKuai in Flags then
begin
GetTeZhengShuGuanLian(ArrayAnalyzeResult[13], [tgNingJuLi_ZhiKuai]);//凝聚力直快 Cohesion
end
else if tgNingJuLi_GuKuai in Flags then //凝聚力固快
begin
GetTeZhengShuGuanLian(ArrayAnalyzeResult[16], [tgMoCaJiao_GuKuai]);//摩擦角固快 Friction_gk
end
else if tgMoCaJiao_GuKuai in Flags then
begin
GetTeZhengShuGuanLian(ArrayAnalyzeResult[15], [tgNingJuLi_GuKuai]);//凝聚力固快 Cohesion_gk
end;
end;
//yys 2005/06/15 add, 当一层只有一个样时,标准差和变异系数不能为0,打印报表时要用空格,物理力学表也一样。所以用-1来表示空值,是因为在报表设计时可以通过判断来表示为空。
if iCount=1 then
begin
//aAnalyzeResult.strBianYiXiShu := 'null';
//aAnalyzeResult.strBiaoZhunCha := 'null';
aAnalyzeResult.BianYiXiShu := -1;
aAnalyzeResult.BiaoZhunCha := -1;
aAnalyzeResult.BiaoZhunZhi := -1;
end
else begin
//aAnalyzeResult.strBianYiXiShu := FloatToStr(aAnalyzeResult.BianYiXiShu);
// aAnalyzeResult.strBiaoZhunCha := FloatToStr(aAnalyzeResult.BiaoZhunCha);
end;
//yys 2005/06/15 add
end;
//取得一个工程中所有的层号和亚层号和土类名称,保存在三个TStringList变量中。
procedure GetAllStratumNo(var AStratumNoList, ASubNoList, AEaNameList: TStringList);
var
strSQL: string;
begin
AStratumNoList.Clear;
ASubNoList.Clear;
AEaNameList.Clear;
strSQL:='SELECT id,prj_no,stra_no,sub_no,ISNULL(ea_name,'''') as ea_name FROM stratum_description'
+' WHERE prj_no='+''''+g_ProjectInfo.prj_no_ForSQL+''''
+' ORDER BY id';
with MainDataModule.qryStratum do
begin
close;
sql.Clear;
sql.Add(strSQL);
open;
while not eof do
begin
AStratumNoList.Add(FieldByName('stra_no').AsString);
ASubNoList.Add(FieldByName('sub_no').AsString);
AEaNameList.Add(FieldByName('ea_name').AsString);
next;
end;
close;
end;
end;
begin
try
//开始给土样分层 ,此处注释掉不用是因为已经在土样数据修改时分层了。
//SetTuYangCengHao;
//开始清空临时统计表的当前工程数据
//strSQL:= 'TRUNCATE TABLE stratumTmp; TRUNCATE TABLE TeZhengShuTmp; TRUNCATE TABLE earthsampleTmp; TRUNCATE TABLE earthsampleTmp ';
strSQL:= 'DELETE FROM stratumTmp WHERE prj_no = '+''''+g_ProjectInfo.prj_no_ForSQL+''''+';'
+'DELETE FROM TeShuYangTzsTmp WHERE prj_no = '+''''+g_ProjectInfo.prj_no_ForSQL+''''+';'
+'DELETE FROM TeShuYangTmp WHERE prj_no = '+''''+g_ProjectInfo.prj_no_ForSQL+'''';
if not Delete_oneRecord(MainDataModule.qrySectionTotal, strSQL) then
begin
exit;
end;
InitVar;
GetAllStratumNo(lstStratumNo, lstSubNo, lstEa_name);
if lstStratumNo.Count = 0 then
begin
//FreeStringList;
exit;
end;
{//将层号和亚层号和土类名称插入临时主表
for i:=0 to lstStratumNo.Count-1 do
begin
strSQL:='INSERT INTO stratumTmp (prj_no,stra_no,sub_no,ea_name) VALUES('
+''''+g_ProjectInfo.prj_no_ForSQL+''''+','
+''''+lstStratumNo.Strings[i]+'''' +','
+''''+lstSubNo.Strings[i]+''''+','
+''''+lstEa_name.Strings[i]+''''+')';
Insert_oneRecord(MainDataModule.qrySectionTotal, strSQL);
end;}
strPrjNo := g_ProjectInfo.prj_no_ForSQL;
for i:=0 to lstStratumNo.Count-1 do
begin
strSubNo := stringReplace(lstSubNo.Strings[i],'''','''''',[rfReplaceAll]);
strStratumNo := lstStratumNo.Strings[i];
//2008/11/21 yys edit 加入选择条件,钻孔参与统计
strSQL:='SELECT es.*,et.ea_name_en FROM (SELECT * FROM TeShuYang '
+' WHERE prj_no='+''''+strPrjNo+''''
+' AND stra_no='+''''+strStratumNo+''''
+' AND sub_no='+''''+strSubNo+''''
+' AND if_statistic=1 and drl_no in (select drl_no from drills where can_tongji=0 '
+' AND prj_no='+''''+strPrjNo+''''
+')) as es '
+' Left Join earthtype et on es.ea_name=et.ea_name';
iRecordCount := 0;
lstBeginDepth.Clear;
lstEndDepth.Clear;
lstDrl_no.Clear;
lstS_no.Clear;
lstShear_type.Clear;
lstsand_big.Clear;
lstsand_middle.Clear;
lstsand_small.Clear;
lstPowder_big.Clear;
lstPowder_small.Clear;
lstClay_grain.Clear;
lstAsymmetry_coef.Clear;
lstCurvature_coef.Clear;
lstEa_name.Clear;
lstYssy_yali.Clear;
lstYssy_bxl.Clear;
lstYssy_kxb.Clear;
lstYssy_ysxs.Clear;
lstYssy_ysml.Clear;
for j:=0 to AnalyzeCount-1 do
begin
ArrayAnalyzeResult[j].lstValues.Clear;
ArrayAnalyzeResult[j].lstValuesForPrint.Clear;
end;
with MainDataModule.qryEarthSample do
begin
close;
sql.Clear;
sql.Add(strSQL);
open;
while not eof do
begin
inc(iRecordCount);
lstDrl_no.Add(FieldByName('drl_no').AsString);
lstS_no.Add(FieldByName('s_no').AsString);
lstBeginDepth.Add(FieldByName('s_depth_begin').AsString);
lstEndDepth.Add(FieldByName('s_depth_end').AsString);
// lstShear_type.Add(FieldByName('shear_type').AsString);
// lstsand_big.Add(FieldByName('sand_big').AsString);
// lstsand_middle.Add(FieldByName('sand_middle').AsString);
// lstsand_small.Add(FieldByName('sand_small').AsString);
// lstPowder_big.Add(FieldByName('powder_big').AsString);
// lstPowder_small.Add(FieldByName('powder_small').AsString);
// lstClay_grain.Add(FieldByName('clay_grain').AsString);
// lstAsymmetry_coef.Add(FieldByName('asymmetry_coef').AsString);
// lstCurvature_coef.Add(FieldByName('curvature_coef').AsString);
if g_ProjectInfo.prj_ReportLanguage= trChineseReport then
lstEa_name.Add(FieldByName('ea_name').AsString)
else if g_ProjectInfo.prj_ReportLanguage= trEnglishReport then
lstEa_name.Add(FieldByName('ea_name_en').AsString);
// lstYssy_yali.Add(FieldByName('Yssy_yali').AsString);
// lstYssy_bxl.Add(FieldByName('Yssy_bxl').AsString);
// lstYssy_kxb.Add(FieldByName('Yssy_kxb').AsString);
// lstYssy_ysxs.Add(FieldByName('Yssy_ysxs').AsString);
// lstYssy_ysml.Add(FieldByName('Yssy_ysml').AsString);
for j:=0 to AnalyzeCount-1 do
begin
ArrayAnalyzeResult[j].lstValues.Add(FieldByName(ArrayFieldNames[j]).AsString);
ArrayAnalyzeResult[j].lstValuesForPrint.Add(FieldByName(ArrayFieldNames[j]).AsString);
end;
// if FieldByName('szsy_syff').AsString = 'UU' then //如果试验方法是UU,那么CU中的总应力和有效应力都应该是空,如果是CU,那么UU的总应力就要设为空的
// begin
//// ArrayAnalyzeResult[21]:= aSzsy_zyl_njl_CU;
//// ArrayAnalyzeResult[22]:= aSzsy_zyl_nmcj_CU;
//// ArrayAnalyzeResult[23]:= aSzsy_yxyl_njl;
//// ArrayAnalyzeResult[24]:= aSzsy_yxyl_nmcj;
// ArrayAnalyzeResult[21].lstValues[ArrayAnalyzeResult[21].lstValues.Count-1] := '';
// ArrayAnalyzeResult[22].lstValues[ArrayAnalyzeResult[22].lstValues.Count-1] := '';
// ArrayAnalyzeResult[23].lstValues[ArrayAnalyzeResult[23].lstValues.Count-1] := '';
// ArrayAnalyzeResult[24].lstValues[ArrayAnalyzeResult[24].lstValues.Count-1] := '';
// end
// else if FieldByName('szsy_syff').AsString = 'CU' then
// begin
// ArrayAnalyzeResult[19].lstValues[ArrayAnalyzeResult[21].lstValues.Count-1] := '';
// ArrayAnalyzeResult[20].lstValues[ArrayAnalyzeResult[22].lstValues.Count-1] := '';
// end;
next;
end;
close;
end;
if iRecordCount=0 then //如果没有土样信息,则插入空值到特征数表,
begin //这是为了以后在特征数表TeShuYangTzsTmp插入静力触探和标贯数据时,只用UPDATE语句就可以了
for j:= 1 to 7 do
begin
strSQL:='INSERT INTO TeShuYangTzsTmp '
+'VALUES ('+''''+strPrjNo+''''+','
+''''+strStratumNo+'''' +','
+''''+strSubNo+''''+','''+InttoStr(j)+'''' + DupeString(',-1', 46)+')';
Insert_oneRecord(MainDataModule.qryPublic, strSQL);
end;
continue;
end;
//取得特征数
//2007/01/24 下面这两句注释起来是因为
// for j:=0 to AnalyzeCount-1 do
// getTeZhengShu(ArrayAnalyzeResult[j], [tfTuYang]);
// GetTeZhengShuGuanLian(ArrayAnalyzeResult[0],[tgHanShuiLiang]); //含水量 0
// GetTeZhengShuGuanLian(ArrayAnalyzeResult[7],[tgYeXian]); //液限 7
// for j:=1 to 6 do
// getTeZhengShu(ArrayAnalyzeResult[j], [tfTuYang]);
// for j:=8 to 10 do //塑限 8 塑性指数 9 液性指数 10 不进行剔除
// getTeZhengShu(ArrayAnalyzeResult[j], [tfOther]);
// GetTeZhengShuGuanLian(ArrayAnalyzeResult[11],[tgYaSuoXiShu]); //压缩系数 11
// getTeZhengShu(ArrayAnalyzeResult[12], [tfOther]); //压缩模量 12 不进行剔除
//
// GetTeZhengShuGuanLian(ArrayAnalyzeResult[13],[tgNingJuLi_ZhiKuai]); //凝聚力直快 13
// GetTeZhengShuGuanLian(ArrayAnalyzeResult[14],[tgMoCaJiao_ZhiKuai]); //摩擦角直快 14
// GetTeZhengShuGuanLian(ArrayAnalyzeResult[15],[tgNingJuLi_GuKuai]); //凝聚力固快 15
// GetTeZhengShuGuanLian(ArrayAnalyzeResult[16],[tgMoCaJiao_GuKuai]); //摩擦角固快 16
// ArrayFieldNames[18]:= 'Jzcylxs'; ArrayToFieldNames[18]:= 'Jzcylxs';
// ArrayFieldNames[19]:= 'Szsy_zyl_njl_uu'; ArrayToFieldNames[19]:= 'Szsy_zyl_njl_uu';
// ArrayFieldNames[20]:= 'Szsy_zyl_nmcj_uu'; ArrayToFieldNames[20]:= 'Szsy_zyl_nmcj_uu';
// ArrayFieldNames[21]:= 'Szsy_zyl_njl_cu'; ArrayToFieldNames[21]:= 'Szsy_zyl_njl_cu';
// ArrayFieldNames[22]:= 'Szsy_zyl_nmcj_cu'; ArrayToFieldNames[22]:= 'Szsy_zyl_nmcj_cu';
// ArrayFieldNames[23]:= 'Szsy_yxyl_njl'; ArrayToFieldNames[23]:= 'Szsy_yxyl_njl';
// ArrayFieldNames[24]:= 'Szsy_yxyl_nmcj'; ArrayToFieldNames[24]:= 'Szsy_yxyl_nmcj';
// ArrayFieldNames[25]:= 'Stxs_kv'; ArrayToFieldNames[25]:= 'Stxs_kv';
// ArrayFieldNames[26]:= 'Stxs_kh'; ArrayToFieldNames[26]:= 'Stxs_kh';
for j:=0 to 21 do
getTeZhengShu(ArrayAnalyzeResult[j], [tfTeShuYang]); //1到21的栏目不需要剔除
for j:=22 to 27 do
getTeZhengShu(ArrayAnalyzeResult[j], [tfTeShuYangBiaoZhuZhi]); //只有UU和CU的总应力和有效应力需要剔除
for j:=28 to 43 do
getTeZhengShu(ArrayAnalyzeResult[j], [tfTeShuYang]); //渗透系数也不需要剔除
//2007/01/24
// for j:=0 to ArrayAnalyzeResult[15].lstValues.count-1 do
// caption:= caption + ArrayAnalyzeResult[15].lstValues[j];
{******把平均值、标准差、变异系数、最大值、**********}
{******最小值、样本值、标准值等插入特征数表TeZhengShuTmp ****}
//开始取得要插入的字段名称。
strFieldNames:= '';
for j:=0 to AnalyzeCount-1 do
strFieldNames:= strFieldNames + ArrayFieldNames[j] + ',';
strFieldNames:= strFieldNames + 'prj_no, stra_no, sub_no, v_id';
//开始插入平均值
strFieldValues:= '';
strSQL:= '';
for j:=0 to AnalyzeCount-1 do
strFieldValues:= strFieldValues +FloatToStr(ArrayAnalyzeResult[j].PingJunZhi)+',';
strFieldValues:= strFieldValues
+''''+strPrjNo+''''+','
+''''+strStratumNo+'''' +','
+''''+strSubNo+''''+','+TEZHENSHU_Flag_PingJunZhi;
strSQL:='INSERT INTO TeShuYangTzsTmp (' + strFieldNames + ')'
+'VALUES('+strFieldValues+')';
if not Insert_oneRecord(MainDataModule.qrySectionTotal, strSQL) then
continue;
//开始插入标准差
strFieldValues:= '';
strSQL:= '';
for j:=0 to AnalyzeCount-1 do
strFieldValues:= strFieldValues +FloatToStr(ArrayAnalyzeResult[j].BiaoZhunCha)+',';
//strFieldValues:= strFieldValues +ArrayAnalyzeResult[j].strBiaoZhunCha+',';
strFieldValues:= strFieldValues
+''''+strPrjNo+''''+','
+''''+strStratumNo+'''' +','
+''''+strSubNo+''''+','+TEZHENSHU_Flag_BiaoZhunCha;
strSQL:='INSERT INTO TeShuYangTzsTmp (' + strFieldNames + ')'
+'VALUES('+strFieldValues+')';
if not Insert_oneRecord(MainDataModule.qrySectionTotal, strSQL) then
continue;
//开始插入变异系数
strFieldValues:= '';
strSQL:= '';
for j:=0 to AnalyzeCount-1 do
strFieldValues:= strFieldValues +FloatToStr(ArrayAnalyzeResult[j].BianYiXiShu)+',';
//strFieldValues:= strFieldValues + ArrayAnalyzeResult[j].strBianYiXiShu+',';
strFieldValues:= strFieldValues
+''''+strPrjNo+''''+','
+''''+strStratumNo+'''' +','
+''''+strSubNo+''''+','+TEZHENSHU_Flag_BianYiXiShu;
strSQL:='INSERT INTO TeShuYangTzsTmp (' + strFieldNames + ')'
+'VALUES('+strFieldValues+')';
if not Insert_oneRecord(MainDataModule.qrySectionTotal, strSQL) then
continue;
//开始插入最大值
strFieldValues:= '';
strSQL:= '';
for j:=0 to AnalyzeCount-1 do
strFieldValues:= strFieldValues +FloatToStr(ArrayAnalyzeResult[j].MaxValue)+',';
strFieldValues:= strFieldValues
+''''+strPrjNo+''''+','
+''''+strStratumNo+'''' +','
+''''+strSubNo+''''+','+TEZHENSHU_Flag_MaxValue;
strSQL:='INSERT INTO TeShuYangTzsTmp (' + strFieldNames + ')'
+'VALUES('+strFieldValues+')';
if not Insert_oneRecord(MainDataModule.qrySectionTotal, strSQL) then
continue;
//开始插入最小值
strFieldValues:= '';
strSQL:= '';
for j:=0 to AnalyzeCount-1 do
strFieldValues:= strFieldValues +FloatToStr(ArrayAnalyzeResult[j].MinValue)+',';
strFieldValues:= strFieldValues
+''''+strPrjNo+''''+','
+''''+strStratumNo+'''' +','
+''''+strSubNo+''''+','+TEZHENSHU_Flag_MinValue;
strSQL:='INSERT INTO TeShuYangTzsTmp (' + strFieldNames + ')'
+'VALUES('+strFieldValues+')';
if not Insert_oneRecord(MainDataModule.qrySectionTotal, strSQL) then
continue;
//开始插入样本值
strFieldValues:= '';
strSQL:= '';
for j:=0 to AnalyzeCount-1 do
strFieldValues:= strFieldValues +FloatToStr(ArrayAnalyzeResult[j].SampleNum)+',';
strFieldValues:= strFieldValues
+''''+strPrjNo+''''+','
+''''+strStratumNo+'''' +','
+''''+strSubNo+''''+','+TEZHENSHU_Flag_SampleNum;
strSQL:='INSERT INTO TeShuYangTzsTmp (' + strFieldNames + ')'
+'VALUES('+strFieldValues+')';
if not Insert_oneRecord(MainDataModule.qrySectionTotal, strSQL) then
continue;
//开始插入标准值
strFieldValues:= '';
strSQL:= '';
for j:=0 to AnalyzeCount-1 do
strFieldValues:= strFieldValues +FloatToStr(ArrayAnalyzeResult[j].BiaoZhunZhi)+',';
strFieldValues:= strFieldValues
+''''+strPrjNo+''''+','
+''''+strStratumNo+'''' +','
+''''+strSubNo+''''+','+TEZHENSHU_Flag_BiaoZhunZhi;
strSQL:='INSERT INTO TeShuYangTzsTmp (' + strFieldNames + ')'
+'VALUES('+strFieldValues+')';
if not Insert_oneRecord(MainDataModule.qrySectionTotal, strSQL) then
continue;
{********把经过舍弃的数值插入临时土样表**********}
for j:=0 to iRecordCount-1 do
begin
strFieldNames:= '';
strFieldValues:= '';
strSQL:= '';
strFieldNames:='drl_no, s_no, s_depth_begin, s_depth_end,ea_name,';
if lstDrl_no.Strings[j]='' then continue;
strFieldNames:= 'drl_no';
strFieldValues:= strFieldValues +'''' + stringReplace(lstDrl_no.Strings[j] ,'''','''''',[rfReplaceAll]) +'''';
if lstS_no.Strings[j]='' then continue;
strFieldNames:= strFieldNames + ',s_no';
strFieldValues:= strFieldValues +','+'''' + lstS_no.Strings[j] +'''';
if lstBeginDepth.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',s_depth_begin';
strFieldValues:= strFieldValues +','+'''' + lstBeginDepth.Strings[j] +'''' ;
end;
if lstEndDepth.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',s_depth_end';
strFieldValues:= strFieldValues +','+'''' + lstEndDepth.Strings[j] +'''' ;
end;
if lstEa_name.Strings[j]<>'' then
begin
strFieldNames:= strFieldNames + ',Ea_name';
strFieldValues:= strFieldValues +','+'''' + lstEa_name.Strings[j] +'''';
end;
for iCol:=0 to AnalyzeCount-1 do
begin
strTmp := ArrayAnalyzeResult[iCol].lstValuesForPrint.Strings[j];
if strTmp <> '' then
begin
strFieldNames:= strFieldNames + ','+ ArrayFieldNames[iCol] ;
strFieldValues:= strFieldValues +','+ strTmp ;
end;
end;
strFieldNames:= strFieldNames + ',prj_no, stra_no, sub_no';
strFieldValues:= strFieldValues +','+''''
+strPrjNo+''''+','
+''''+strStratumNo+'''' +','
+''''+strSubNo+'''';
strSQL:='INSERT INTO TeShuYangTmp (' + strFieldNames + ')'
+'VALUES('+strFieldValues+')';
if Insert_oneRecord(MainDataModule.qrySectionTotal, strSQL) then
else;
end;
end; // end of for i:=0 to lstStratumNo.Count-1 do
finally
FreeStringList;
end;
end;
end.
|
unit UnitFormData;
interface
uses
server_data_types,
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Grids,
Vcl.ComCtrls, UnitFormDataTable, Vcl.Menus;
type
TFormData = class(TForm)
Panel1: TPanel;
Panel3: TPanel;
ComboBox1: TComboBox;
Splitter1: TSplitter;
StringGrid1: TStringGrid;
procedure FormCreate(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
procedure StringGrid1SelectCell(Sender: TObject; ACol, ARow: integer;
var CanSelect: Boolean);
procedure StringGrid1DrawCell(Sender: TObject; ACol, ARow: integer;
Rect: TRect; State: TGridDrawState);
procedure Panel1Resize(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FYearMonth: TArray<TYearMonth>;
FProducts: TArray<TProductInfo>;
public
{ Public declarations }
procedure FetchYearsMonths;
end;
var
FormData: TFormData;
implementation
{$R *.dfm}
uses app, UnitFormProductData, HttpClient, services, dateutils, stringgridutils, stringutils,
UnitFormPopup;
function NewMeregedRow(ARow: integer; Atext: string): TMeregedRow;
begin
Result.Text := Atext;
Result.Row := ARow;
end;
procedure TFormData.FormCreate(Sender: TObject);
begin
//
end;
procedure TFormData.FormShow(Sender: TObject);
begin
//
end;
procedure TFormData.Panel1Resize(Sender: TObject);
var ACol:integer;
begin
with StringGrid1 do
begin
// Panel1.Constraints.MinWidth := ColWidths[0] + ColWidths[1] +
// ColWidths[2] + 10;
ColWidths[ColCount-1] := Panel1.Width - 10;
for ACol := ColCount-2 downto 0 do
ColWidths[ColCount-1] := ColWidths[ColCount-1] - ColWidths[ACol];
Repaint;
end;
end;
procedure TFormData.StringGrid1DrawCell(Sender: TObject; ACol, ARow: integer;
Rect: TRect; State: TGridDrawState);
var
grd: TStringGrid;
cnv: TCanvas;
ta: TAlignment;
begin
grd := Sender as TStringGrid;
cnv := grd.Canvas;
cnv.Font.Assign(grd.Font);
cnv.Brush.Color := clWhite;
if gdSelected in State then
cnv.Brush.Color := clGradientInactiveCaption
else if gdFixed in State then
cnv.Brush.Color := cl3DLight;
ta := taLeftJustify;
case ACol of
0:
begin
ta := taCenter;
cnv.Font.Color := clGreen;
end;
1:
begin
ta := taLeftJustify;
cnv.Font.Color := clBlack;
end;
end;
DrawCellText(grd, ACol, ARow, Rect, ta, grd.Cells[ACol, ARow]);
end;
procedure TFormData.StringGrid1SelectCell(Sender: TObject; ACol, ARow: integer;
var CanSelect: Boolean);
var
Products: TArray<TProduct>;
tbs: TTabSheet;
I: integer;
begin
if ARow - 1 >= length(FProducts) then
exit;
FormProductData.Parent := self;
FormProductData.FetchProductData(FProducts[ARow - 1].productID);
FormProductData.Show;
Caption := 'ÄÀÔ-Ì ' + IntToStr(FProducts[ARow - 1].productID);
end;
procedure TFormData.ComboBox1Change(Sender: TObject);
var
I: integer;
CanSelect: Boolean;
begin
with StringGrid1 do
begin
ColCount := 5;
OnSelectCell := nil;
with FYearMonth[ComboBox1.ItemIndex] do
FProducts := TProductsSvc.ProductsOfYearMonth(year, month);
RowCount := length(FProducts) + 1;
if RowCount = 1 then
exit;
FixedRows := 1;
Cells[0, 0] := 'Äåíü';
Cells[1, 0] := 'Âåðìÿ';
Cells[2, 0] := 'ÄÀÔ-Ì';
Cells[3, 0] := 'Ñåð.¹';
Cells[4, 0] := 'Ïàðòèÿ';
for I := 0 to length(FProducts) - 1 do
with FProducts[I] do
begin
Cells[0, I + 1] := IntToStr2(day);
Cells[1, I + 1] :=
Format('%s:%s', [IntToStr2(hour), IntToStr2(minute)]);
Cells[2, I + 1] := IntToStr(productID);
Cells[3, I + 1] := IntToStr(Serial);
Cells[4, I + 1] := IntToStr(partyID);
end;
Row := RowCount - 1;
OnSelectCell := StringGrid1SelectCell;
CanSelect := true;
StringGrid1SelectCell(StringGrid1, 1, Row, CanSelect);
end;
StringGrid_SetupColumnsWidth(StringGrid1);
end;
procedure TFormData.FetchYearsMonths;
var
I: integer;
ym: TYearMonth;
begin
ComboBox1.Clear;
FYearMonth := TProductsSvc.YearsMonths;
if length(FYearMonth) = 0 then
with ym do
begin
year := YearOf(now);
month := MonthOf(now);
FYearMonth := [ym];
end;
for I := 0 to length(FYearMonth) - 1 do
with FYearMonth[I] do
ComboBox1.Items.Add(Format('%d %s',
[year, FormatDateTime('MMMM', IncMonth(0, month))]));
ComboBox1.ItemIndex := 0;
ComboBox1Change(nil);
end;
end.
|
{
Data exchange through named pipes
Sergey Bodrov, 2012-2016
Data exchange through named pipes. Pipe name is platform-specific. On Windows,
'\\.\pipe\' prefix added automaticaly.
Pipe must be already exists, created by Linux 'mkfifo' command or some other program.
Methods:
* Open() - open pipe channel with specified name
}
unit DataPortPipes;
interface
uses SysUtils, Classes, DataPort, Pipes;
type
{ TPipesClient - pipes port reader/writer }
TPipesClient = class(TThread)
private
FInputPipeStream: TInputPipeStream;
FOutputPipeStream: TOutputPipeStream;
s: AnsiString;
sLastError: string;
FSafeMode: boolean;
FInputHandle: THandle;
FOutputHandle: THandle;
FOnIncomingMsgEvent: TMsgEvent;
FOnErrorEvent: TMsgEvent;
FOnConnectEvent: TNotifyEvent;
procedure SyncProc();
procedure SyncProcOnConnect();
protected
procedure Execute(); override;
public
InitStr: string;
CalledFromThread: boolean;
sToSend: AnsiString;
property SafeMode: boolean read FSafeMode write FSafeMode;
property InputHandle: THandle read FInputHandle write FInputHandle;
property OutputHandle: THandle read FOutputHandle write FOutputHandle;
property OnIncomingMsgEvent: TMsgEvent read FOnIncomingMsgEvent
write FOnIncomingMsgEvent;
property OnErrorEvent: TMsgEvent read FOnErrorEvent write FOnErrorEvent;
property OnConnectEvent: TNotifyEvent read FOnConnectEvent write FOnConnectEvent;
function SendString(const s: AnsiString): boolean;
procedure SendStream(st: TStream);
end;
{ TDataPortPipes - serial DataPort }
TDataPortPipes = class(TDataPort)
private
//slReadData: TStringList; // for storing every incoming data packet separately
sReadData: AnsiString;
lock: TMultiReadExclusiveWriteSynchronizer;
FInitStr: string;
FMinDataBytes: Integer;
FInputHandle: THandle;
FOutputHandle: THandle;
procedure OnIncomingMsgHandler(Sender: TObject; const AMsg: string);
procedure OnErrorHandler(Sender: TObject; const AMsg: string);
procedure OnConnectHandler(Sender: TObject);
public
PipesClient: TPipesClient;
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
{ Open pipe, InitStr = pipe name }
procedure Open(const AInitStr: string = ''); override;
procedure Close(); override;
function Push(const AData: AnsiString): boolean; override;
function Pull(size: Integer = MaxInt): AnsiString; override;
function Peek(size: Integer = MaxInt): AnsiString; override;
function PeekSize(): Cardinal; override;
published
property InputHandle: THandle read FInputHandle write FInputHandle;
property OutputHandle: THandle read FOutputHandle write FOutputHandle;
{ Minimum bytes in incoming buffer to trigger OnDataAppear }
property MinDataBytes: Integer read FMinDataBytes write FMinDataBytes;
property Active;
property OnDataAppear;
property OnError;
property OnOpen;
property OnClose;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('DataPort', [TDataPortPipes]);
end;
// === TPipesClient ===
procedure TPipesClient.SyncProc();
begin
if CalledFromThread then
Exit;
//if s:='' then Exit;
CalledFromThread := True;
if s <> '' then
begin
if Assigned(self.FOnIncomingMsgEvent) then
FOnIncomingMsgEvent(self, s);
s := '';
end;
if sLastError <> '' then
begin
if Assigned(self.FOnErrorEvent) then
FOnErrorEvent(self, sLastError);
self.Terminate();
end;
CalledFromThread := False;
end;
procedure TPipesClient.SyncProcOnConnect();
begin
if CalledFromThread then
Exit;
CalledFromThread := True;
if Assigned(self.FOnConnectEvent) then
self.FOnConnectEvent(self);
CalledFromThread := False;
end;
procedure TPipesClient.Execute();
var
buf: array[0..1023] of byte;
n: Integer;
ss: AnsiString;
begin
sLastError := '';
buf[0] := 0;
try
FInputPipeStream := TInputPipeStream.Create(FInputHandle);
FOutputPipeStream := TOutputPipeStream.Create(FOutputHandle);
Synchronize(SyncProcOnConnect);
while not Terminated do
begin
n := FInputPipeStream.Read(buf, Length(buf));
while n > 0 do
begin
SetString(ss, PAnsiChar(@buf), n);
s := s + ss;
n := FInputPipeStream.Read(buf, Length(buf));
end;
sLastError := '';
if (Length(s) > 0) or (Length(sLastError) > 0) then
Synchronize(SyncProc);
Sleep(1);
if sToSend <> '' then
begin
try
Self.FOutputPipeStream.WriteAnsiString(sToSend);
except
on E: Exception do
begin
sLastError := E.Message;
Synchronize(SyncProc);
end;
end;
sToSend := '';
end;
end;
finally
FreeAndNil(FOutputPipeStream);
FreeAndNil(FInputPipeStream);
end;
end;
function TPipesClient.SendString(const s: AnsiString): boolean;
begin
Result := False;
if not Assigned(Self.FOutputPipeStream) then
Exit;
if SafeMode then
self.sToSend := s
else
begin
try
Self.FOutputPipeStream.WriteAnsiString(s);
except
on E: Exception do
begin
sLastError := E.Message;
Synchronize(SyncProc);
Exit;
end;
end;
end;
Result := True;
end;
procedure TPipesClient.SendStream(st: TStream);
begin
if not Assigned(Self.FOutputPipeStream) then
Exit;
try
Self.FOutputPipeStream.CopyFrom(st, st.Size);
except
on E: Exception do
begin
sLastError := E.Message;
Synchronize(SyncProc);
end;
end;
end;
{ TDataPortPipes }
constructor TDataPortPipes.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
self.lock := TMultiReadExclusiveWriteSynchronizer.Create();
FMinDataBytes := 1;
FActive := False;
Self.sReadData := '';
Self.PipesClient := nil;
end;
function GetFirstWord(var s: string; delimiter: string = ' '): string;
var
i: Integer;
begin
Result := '';
i := Pos(delimiter, s);
if i > 0 then
begin
Result := Copy(s, 1, i - 1);
s := Copy(s, i + 1, maxint);
end
else
begin
Result := s;
s := '';
end;
end;
procedure TDataPortPipes.Open(const AInitStr: string = '');
var
s, ss: string;
begin
ss := AInitStr;
if ss = '' then
ss := FInitStr
else
FInitStr := ss;
if Assigned(self.PipesClient) then
begin
FreeAndNil(self.PipesClient);
end;
Self.PipesClient := TPipesClient.Create(True);
Self.PipesClient.OnIncomingMsgEvent := self.OnIncomingMsgHandler;
Self.PipesClient.OnErrorEvent := self.OnErrorHandler;
Self.PipesClient.OnConnectEvent := self.OnConnectHandler;
Self.PipesClient.SafeMode := True;
if ss <> '' then
begin
s := AInitStr;
{$IFDEF MSWINDOWS}
if Pos('\\.\pipe\', FInitStr) = 0 then
s := '\\.\pipe\' + FInitStr;
{$ENDIF}
PipesClient.InputHandle := FileOpen(s, fmOpenReadWrite or fmShareDenyNone);
PipesClient.OutputHandle := PipesClient.InputHandle;
end
else
begin
PipesClient.InputHandle := InputHandle;
PipesClient.OutputHandle := OutputHandle;
end;
Self.PipesClient.Suspended := False;
// don't inherits Open() - OnOpen event will be after successfull connection
end;
procedure TDataPortPipes.Close();
begin
if Assigned(self.PipesClient) then
begin
if self.PipesClient.CalledFromThread then
self.PipesClient.Terminate()
else
FreeAndNil(self.PipesClient);
end;
inherited Close();
end;
destructor TDataPortPipes.Destroy();
begin
if Assigned(self.PipesClient) then
begin
self.PipesClient.OnIncomingMsgEvent := nil;
self.PipesClient.OnErrorEvent := nil;
self.PipesClient.OnConnectEvent := nil;
FreeAndNil(self.PipesClient);
end;
FreeAndNil(self.lock);
inherited Destroy();
end;
procedure TDataPortPipes.OnIncomingMsgHandler(Sender: TObject; const AMsg: string);
begin
if AMsg <> '' then
begin
if lock.BeginWrite then
begin
sReadData := sReadData + AMsg;
lock.EndWrite;
if Assigned(FOnDataAppear) then
FOnDataAppear(self);
end;
end;
end;
procedure TDataPortPipes.OnErrorHandler(Sender: TObject; const AMsg: string);
begin
if Assigned(Self.FOnError) then
Self.FOnError(Self, AMsg);
self.FActive := False;
end;
function TDataPortPipes.Peek(size: Integer = MaxInt): AnsiString;
begin
lock.BeginRead();
Result := Copy(sReadData, 1, size);
lock.EndRead();
end;
function TDataPortPipes.PeekSize(): Cardinal;
begin
lock.BeginRead();
Result := Cardinal(Length(sReadData));
lock.EndRead();
end;
function TDataPortPipes.Pull(size: Integer = MaxInt): AnsiString;
begin
Result := '';
if lock.BeginWrite() then
begin
try
Result := Copy(sReadData, 1, size);
Delete(sReadData, 1, size);
finally
lock.EndWrite();
end;
end;
end;
function TDataPortPipes.Push(const AData: AnsiString): boolean;
begin
Result := False;
if Assigned(self.PipesClient) and lock.BeginWrite() then
begin
try
Result := self.PipesClient.SendString(AData);
finally
lock.EndWrite();
end;
end;
end;
procedure TDataPortPipes.OnConnectHandler(Sender: TObject);
begin
self.FActive := True;
if Assigned(OnOpen) then
OnOpen(Self);
end;
end.
|
unit OriUtils;
interface
uses
FGL;
type
TIntegerList = specialize TFPGList<Integer>;
{%region Paths and FileNames}
function EnsurePath(const APath: String): String;
function ExtractFileExtNoDot(const FileName: String): String;
{%endregion}
{%region Log}
procedure WriteLogString(const LogString: String; Params: array of const); overload;
procedure WriteLogString(const FileName: String; const LogString: String; Params: array of const); overload;
procedure WriteLogString(const FileName: String; const LogString: String); overload;
{%endregion}
implementation
uses
SysUtils, FileUtil;
{%region Log}
procedure WriteLogString(const LogString: String; Params: array of const);
{$ifndef ORI_DISABLE_LOG}
var
FileName: String;
{$endif}
begin
{$ifndef ORI_DISABLE_LOG}
FileName := ChangeFileExt(ParamStrUTF8(0), '.log');
WriteLogString(FileName, Format(LogString, Params));
{$endif}
end;
procedure WriteLogString(const FileName: String; const LogString: String; Params: array of const);
begin
{$ifndef ORI_DISABLE_LOG}
WriteLogString(FileName, Format(LogString, Params));
{$endif}
end;
procedure WriteLogString(const FileName: String; const LogString: String);
{$ifndef ORI_DISABLE_LOG}
var
FileOut: TextFile;
{$endif}
begin
{$ifndef ORI_DISABLE_LOG}
if not FileExistsUTF8(FileName) then
FileClose(FileCreateUTF8(FileName));
AssignFile(FileOut, UTF8ToSys(FileName));
Append(FileOut);
WriteLn(FileOut, Format('%s : %s', [
FormatDateTime('yyyy/mm/dd hh:nn:ss.zzz', Now), LogString]));
Flush(FileOut);
CloseFile(FileOut);
{$endif}
end;
{%endregion}
{%region Paths and FileNames}
// Procedure checks if a path exists and substitutes an existed if not.
function EnsurePath(const APath: String): String;
begin
if (APath = '') or not (DirectoryExistsUTF8(APath))
then Result := ExtractFilePath(ParamStrUTF8(0))
else Result := APath;
end;
function ExtractFileExtNoDot(const FileName: String): String;
begin
Result := Copy(ExtractFileExt(FileName), 2, MaxInt);
end;
{%endregion}
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ Copyright(c) 2016 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit FMX.StrokeBuilder;
interface
{$SCOPEDENUMS ON}
uses
System.Types, System.UITypes, System.Math, System.Math.Vectors, FMX.Graphics, FMX.Canvas.GPU.Helpers;
{.$DEFINE SafeInitArrays}
{.$DEFINE BuildSanityChecks}
type
TStrokeBuilder = class
private
FMatrix: TMatrix;
FBrush: TStrokeBrush;
FVertices: TCanvasHelper.TVertexArray;
FColors: TCanvasHelper.TAlphaColorArray;
FIndices: TCanvasHelper.TIndexArray;
FCurrentVertex: Integer;
FCurrentIndex: Integer;
FSegmentCount: Integer;
FLastSegmentFraction: Single;
FExtraPieces: Integer;
FLastDashExtend: Boolean;
FThickness: Single;
FHalfThickness: Single;
FStrokeColor: TAlphaColor;
FEllipseCenter: TPointF;
FEllipseRadius: TPointF;
FEllipseCircumf: Single;
FEllipseTransfCenter: TPointF;
FUndeterminedMode: Boolean;
function GetMatrixScale: TPointF;
procedure ArrayFillCheck;
procedure InitArrays(const VertexCount, IndexCount: Integer); inline;
procedure FinalizeArrays;
procedure InitArrayPointers;
procedure InsertVertex(const VertexPos: TPointF; const Color: TAlphaColor);
procedure InsertIndex(const Value: Integer);
function GetCapDivisions: Integer; inline;
procedure GetDashEstimate(out VertexCount, IndexCount: Integer);
procedure InsertDash(SrcPos, DestPos: TPointF; const DashDirVec, ThickPerp: TPointF);
procedure GetDotEstimate(out VertexCount, IndexCount: Integer);
procedure InsertDot(const MidPos, DotDirVec, ThickPerp: TPointF);
function GetPatternStepCount: Integer;
procedure ComputeBuildEstimates(const TentSegmentCount: Single; out VertexCount, IndexCount: Integer);
procedure InsertSegment(const SegmentPos, SegDirVec, ThickPerp, DestPos: TPointF; IsLast: Boolean);
function GetEllipseTransfAt(const Delta: Single): TPointF;
procedure InsertEllipseSegment(const SegInitDist: Single; IsLast: Boolean);
public
procedure BuildLine(const SrcPos, DestPos: TPointF; const Opacity: Single);
procedure BuildIntermEllipse(const Center, Radius: TPointF; const Opacity: Single);
procedure BuildSolidEllipse(const Center, Radius: TPointF; const Opacity: Single);
procedure BuildIntermPolygon(const Points: TPolygon; const Opacity: Single; BreakAtEnd: Boolean = False);
procedure BuildSolidPolygon(const Points: TPolygon; const Opacity: Single; BreakAtEnd: Boolean = False);
procedure BuildIntermPath(const Path: TPathData; const Opacity: Single);
procedure BuildSolidPath(const Path: TPathData; const Opacity: Single);
procedure ResetArrays;
property Matrix: TMatrix read FMatrix write FMatrix;
property Brush: TStrokeBrush read FBrush write FBrush;
property Vertices: TCanvasHelper.TVertexArray read FVertices;
property Colors: TCanvasHelper.TAlphaColorArray read FColors;
property Indices: TCanvasHelper.TIndexArray read FIndices;
end;
implementation
uses
System.UIConsts, System.Generics.Collections;
function PointFDot(const P1, P2: TPointF): Single;
begin
Result := (P1.X * P2.X) + (P1.Y * P2.Y);
end;
{$REGION 'Stroke Builder implementation'}
function TStrokeBuilder.GetMatrixScale: TPointF;
const
BaseVector: TPointF = (X: 0; Y: 0);
begin
Result.X := (PointF(1, 0) * FMatrix).Distance(BaseVector * FMatrix);
Result.Y := (PointF(0, 1) * FMatrix).Distance(BaseVector * FMatrix);
end;
procedure TStrokeBuilder.InitArrayPointers();
begin
FCurrentVertex := 0;
FCurrentIndex := 0;
end;
procedure TStrokeBuilder.InitArrays(const VertexCount, IndexCount: Integer);
{$IFDEF SafeInitArrays}
var
Index: Integer;
{$ENDIF}
begin
SetLength(FVertices, VertexCount);
SetLength(FColors, VertexCount);
SetLength(FIndices, IndexCount);
{$IFDEF SafeInitArrays}
for Index := 0 to IndexCount - 1 do
FIndices[Index] := -1;
FillChar(FVertices[0], SizeOf(TPointF) * VertexCount, 0);
FillChar(FColors[0], SizeOf(TAlphaColor) * VertexCount, 0);
{$ENDIF}
InitArrayPointers();
end;
procedure TStrokeBuilder.ResetArrays;
begin
SetLength(FVertices, 0);
SetLength(FColors, 0);
SetLength(FIndices, 0);
end;
procedure TStrokeBuilder.ArrayFillCheck;
begin
{$IFDEF BuildSanityChecks}
Assert(FCurrentVertex = Length(FVertices), 'Vertices have not been filled correctly.');
Assert(FCurrentIndex = Length(FIndices), 'Indices have not been filled correctly.');
{$ENDIF}
end;
procedure TStrokeBuilder.FinalizeArrays;
begin
if FUndeterminedMode then
begin
SetLength(FVertices, FCurrentVertex);
SetLength(FColors, FCurrentVertex);
SetLength(FIndices, FCurrentIndex);
end;
end;
procedure TStrokeBuilder.InsertVertex(const VertexPos: TPointF; const Color: TAlphaColor);
var
NewValue: Integer;
begin
if FUndeterminedMode and (Length(FVertices) <= FCurrentVertex) then
begin
NewValue := 8 + Ceil(Length(FVertices) * 1.5);
SetLength(FVertices, NewValue);
SetLength(FColors, NewValue);
end;
{$IFDEF BuildSanityChecks}
Assert(FCurrentVertex < Length(FVertices), 'Too many vertices.');
{$ENDIF}
FVertices[FCurrentVertex] := VertexPos;
FColors[FCurrentVertex] := Color;
Inc(FCurrentVertex);
end;
procedure TStrokeBuilder.InsertIndex(const Value: Integer);
var
NewValue: Integer;
begin
if FUndeterminedMode and (Length(FIndices) <= FCurrentIndex) then
begin
NewValue := 12 + Ceil(Length(FIndices) * 1.5);
SetLength(FIndices, NewValue);
end;
{$IFDEF BuildSanityChecks}
Assert(FCurrentIndex < Length(FIndices), 'Too many indices.');
{$ENDIF}
FIndices[FCurrentIndex] := Value;
Inc(FCurrentIndex);
end;
function TStrokeBuilder.GetCapDivisions: Integer;
begin
if FBrush.Cap = TStrokeCap.Round then
Result := Max(Ceil(FThickness * Pi / 4.0), 2)
else
Result := 0;
end;
procedure TStrokeBuilder.GetDashEstimate(out VertexCount, IndexCount: Integer);
var
Divisions: Integer;
begin
case FBrush.Cap of
TStrokeCap.Round:
begin
Divisions := GetCapDivisions;
VertexCount := 6 + Divisions * 2;
IndexCount := 6 + (Divisions + 1) * 6;
end;
else
begin
VertexCount := 4;
IndexCount := 6;
end;
end;
end;
procedure TStrokeBuilder.InsertDash(SrcPos, DestPos: TPointF; const DashDirVec, ThickPerp: TPointF);
var
InitIndex, DivIndex, Divisions: Integer;
SinValue, CosValue: Single;
RoundShift: TPointF;
begin
if FBrush.Cap = TStrokeCap.Round then
begin
RoundShift := DashDirVec * FHalfThickness;
SrcPos := SrcPos + RoundShift;
DestPos := DestPos - RoundShift;
end;
InitIndex := FCurrentVertex;
InsertVertex(SrcPos + ThickPerp, FStrokeColor);
InsertVertex(DestPos + ThickPerp, FStrokeColor);
InsertVertex(DestPos - ThickPerp, FStrokeColor);
InsertVertex(SrcPos - ThickPerp, FStrokeColor);
InsertIndex(InitIndex + 0);
InsertIndex(InitIndex + 1);
InsertIndex(InitIndex + 2);
InsertIndex(InitIndex + 2);
InsertIndex(InitIndex + 3);
InsertIndex(InitIndex + 0);
if FBrush.Cap = TStrokeCap.Round then
begin
InsertVertex(SrcPos, FStrokeColor);
InsertVertex(DestPos, FStrokeColor);
Divisions := GetCapDivisions;
for DivIndex := 0 to Divisions - 1 do
begin
SinCos((DivIndex + 1) * Pi / (Divisions + 1), SinValue, CosValue);
InsertVertex(PointF(SrcPos.X + ThickPerp.X * CosValue - ThickPerp.Y * SinValue, SrcPos.Y + ThickPerp.X * SinValue + ThickPerp.Y *
CosValue), FStrokeColor);
end;
for DivIndex := 0 to Divisions - 1 do
begin
SinCos((DivIndex + 1) * Pi / (Divisions + 1), SinValue, CosValue);
InsertVertex(PointF(DestPos.X + ThickPerp.Y * SinValue - ThickPerp.X * CosValue,
DestPos.Y - (ThickPerp.X * SinValue + ThickPerp.Y * CosValue)), FStrokeColor);
end;
InsertIndex(InitIndex + 4);
InsertIndex(InitIndex + 0);
InsertIndex(InitIndex + 6);
InsertIndex(InitIndex + 4);
InsertIndex(InitIndex + 5 + Divisions);
InsertIndex(InitIndex + 3);
for DivIndex := 0 to Divisions - 2 do
begin
InsertIndex(InitIndex + 4);
InsertIndex(InitIndex + 6 + DivIndex);
InsertIndex(InitIndex + 7 + DivIndex);
end;
InsertIndex(InitIndex + 2);
InsertIndex(InitIndex + 6 + Divisions);
InsertIndex(InitIndex + 5);
InsertIndex(InitIndex + 5);
InsertIndex(InitIndex + 5 + Divisions * 2);
InsertIndex(InitIndex + 1);
for DivIndex := 0 to Divisions - 2 do
begin
InsertIndex(InitIndex + 5);
InsertIndex(InitIndex + 6 + Divisions + DivIndex);
InsertIndex(InitIndex + 7 + Divisions + DivIndex);
end;
end;
end;
procedure TStrokeBuilder.GetDotEstimate(out VertexCount, IndexCount: Integer);
var
Divisions: Integer;
begin
case FBrush.Cap of
TStrokeCap.Round:
begin
Divisions := GetCapDivisions;
VertexCount := 3 + Divisions * 2;
IndexCount := (Divisions + 1) * 6;
end;
else
begin
VertexCount := 4;
IndexCount := 6;
end;
end;
end;
procedure TStrokeBuilder.InsertDot(const MidPos, DotDirVec, ThickPerp: TPointF);
var
InitIndex, DivIndex, Divisions: Integer;
SinValue, CosValue: Single;
DotParShift: TPointF;
begin
InitIndex := FCurrentVertex;
if FBrush.Cap = TStrokeCap.Flat then
begin
DotParShift := DotDirVec * FHalfThickness;
InsertVertex(MidPos + ThickPerp - DotParShift, FStrokeColor);
InsertVertex(MidPos + DotParShift + ThickPerp, FStrokeColor);
InsertVertex(MidPos + DotParShift - ThickPerp, FStrokeColor);
InsertVertex(MidPos - (ThickPerp + DotParShift), FStrokeColor);
InsertIndex(InitIndex + 0);
InsertIndex(InitIndex + 1);
InsertIndex(InitIndex + 2);
InsertIndex(InitIndex + 2);
InsertIndex(InitIndex + 3);
InsertIndex(InitIndex + 0);
end
else
begin
InsertVertex(MidPos, FStrokeColor);
Divisions := 2 + GetCapDivisions * 2;
for DivIndex := 0 to Divisions - 1 do
begin
SinCos(DivIndex * (Pi * 2.0) / Divisions, SinValue, CosValue);
InsertVertex(PointF(MidPos.X + ThickPerp.X * CosValue - ThickPerp.Y * SinValue, MidPos.Y + ThickPerp.X * SinValue + ThickPerp.Y *
CosValue), FStrokeColor);
end;
for DivIndex := 0 to Divisions - 1 do
begin
InsertIndex(InitIndex);
InsertIndex(InitIndex + 1 + DivIndex);
InsertIndex(InitIndex + 1 + ((DivIndex + 1) mod Divisions));
end;
end;
end;
function TStrokeBuilder.GetPatternStepCount: Integer;
begin
case FBrush.Dash of
TStrokeDash.Solid, TStrokeDash.Custom:
Result := 1;
TStrokeDash.Dash:
Result := 4;
TStrokeDash.Dot:
Result := 2;
TStrokeDash.DashDot:
Result := 6;
TStrokeDash.DashDotDot:
Result := 8;
else
Result := 0;
end;
end;
procedure TStrokeBuilder.ComputeBuildEstimates(const TentSegmentCount: Single; out VertexCount, IndexCount: Integer);
var
PieceVertices, PieceIndices, FloorSegmentCount, CeilSegmentCount: Integer;
begin
FExtraPieces := 0;
FLastDashExtend := False;
FLastSegmentFraction := Frac(TentSegmentCount);
FloorSegmentCount := Floor(TentSegmentCount);
CeilSegmentCount := Ceil(TentSegmentCount);
case FBrush.Dash of
TStrokeDash.Solid, TStrokeDash.Custom:
begin
FSegmentCount := 1;
GetDashEstimate(VertexCount, IndexCount);
end;
TStrokeDash.Dash:
begin
FSegmentCount := FloorSegmentCount;
if FLastSegmentFraction >= 0.25 then
begin
FSegmentCount := CeilSegmentCount;
FLastDashExtend := (CeilSegmentCount <> FloorSegmentCount) and (FLastSegmentFraction < 0.75);
end;
GetDashEstimate(PieceVertices, PieceIndices);
VertexCount := PieceVertices * FSegmentCount;
IndexCount := PieceIndices * FSegmentCount;
end;
TStrokeDash.Dot:
begin
FSegmentCount := Round(TentSegmentCount);
GetDotEstimate(PieceVertices, PieceIndices);
VertexCount := PieceVertices * FSegmentCount;
IndexCount := PieceIndices * FSegmentCount;
end;
TStrokeDash.DashDot:
begin
FSegmentCount := FloorSegmentCount;
if FLastSegmentFraction >= 1 / 6 then
begin
FSegmentCount := CeilSegmentCount;
FLastDashExtend := (CeilSegmentCount <> FloorSegmentCount) and (FLastSegmentFraction < 0.5);
end
else
FLastSegmentFraction := 1;
GetDashEstimate(PieceVertices, PieceIndices);
VertexCount := PieceVertices * FSegmentCount;
IndexCount := PieceIndices * FSegmentCount;
GetDotEstimate(PieceVertices, PieceIndices);
if FSegmentCount > 1 then
begin
Inc(VertexCount, PieceVertices * (FSegmentCount - 1));
Inc(IndexCount, PieceIndices * (FSegmentCount - 1));
end;
if FLastSegmentFraction >= 5 / 6 then
begin
Inc(VertexCount, PieceVertices);
Inc(IndexCount, PieceIndices);
Inc(FExtraPieces);
end;
end;
TStrokeDash.DashDotDot:
begin
FSegmentCount := FloorSegmentCount;
if FLastSegmentFraction >= 1 / 8 then
begin
FSegmentCount := CeilSegmentCount;
FLastDashExtend := (CeilSegmentCount <> FloorSegmentCount) and (FLastSegmentFraction < 3.0 / 8.0);
end
else
FLastSegmentFraction := 1;
GetDashEstimate(PieceVertices, PieceIndices);
VertexCount := PieceVertices * FSegmentCount;
IndexCount := PieceIndices * FSegmentCount;
GetDotEstimate(PieceVertices, PieceIndices);
if FSegmentCount > 1 then
begin
Inc(VertexCount, PieceVertices * (FSegmentCount - 1) * 2);
Inc(IndexCount, PieceIndices * (FSegmentCount - 1) * 2);
end;
if FLastSegmentFraction >= 7 / 8 then
begin
Inc(VertexCount, PieceVertices * 2);
Inc(IndexCount, PieceIndices * 2);
Inc(FExtraPieces, 2);
end
else if FLastSegmentFraction >= 5 / 8 then
begin
Inc(VertexCount, PieceVertices);
Inc(IndexCount, PieceIndices);
Inc(FExtraPieces);
end;
end;
end;
end;
procedure TStrokeBuilder.InsertSegment(const SegmentPos, SegDirVec, ThickPerp, DestPos: TPointF; IsLast: Boolean);
var
PieceTail: TPointF;
begin
case FBrush.Dash of
TStrokeDash.Solid, TStrokeDash.Custom:
InsertDash(SegmentPos, DestPos, SegDirVec, ThickPerp);
TStrokeDash.Dash:
begin
if IsLast and FLastDashExtend then
PieceTail := DestPos
else
PieceTail := SegmentPos + (SegDirVec * FThickness * 3);
InsertDash(SegmentPos, PieceTail, SegDirVec, ThickPerp);
end;
TStrokeDash.Dot:
InsertDot(SegmentPos + (SegDirVec * FHalfThickness), SegDirVec, ThickPerp);
TStrokeDash.DashDot:
begin
if IsLast and FLastDashExtend then
PieceTail := DestPos
else
PieceTail := SegmentPos + (SegDirVec * FThickness * 3);
InsertDash(SegmentPos, PieceTail, SegDirVec, ThickPerp);
if (not IsLast) or (FExtraPieces > 0) then
InsertDot(SegmentPos + (SegDirVec * FThickness * 4.5), SegDirVec, ThickPerp);
end;
TStrokeDash.DashDotDot:
begin
if IsLast and FLastDashExtend then
PieceTail := DestPos
else
PieceTail := SegmentPos + (SegDirVec * FThickness * 3);
InsertDash(SegmentPos, PieceTail, SegDirVec, ThickPerp);
if (not IsLast) or (FExtraPieces > 0) then
InsertDot(SegmentPos + (SegDirVec * FThickness * 4.5), SegDirVec, ThickPerp);
if (not IsLast) or (FExtraPieces > 1) then
InsertDot(SegmentPos + (SegDirVec * FThickness * 6.5), SegDirVec, ThickPerp);
end;
end;
end;
procedure TStrokeBuilder.BuildLine(const SrcPos, DestPos: TPointF; const Opacity: Single);
var
FinalSrcPos, FinalDestPos, PiecePos, StepDelta, ThickPerp: TPointF;
PieceDirVec, CurScale: TPointF;
StepSize, PiecesCount: Single;
StepIndex, LastStepIndex, PatternStepCount: Integer;
LineLength: Single;
TotalVertices, TotalIndices: Integer;
begin
CurScale := GetMatrixScale;
FThickness := FBrush.Thickness * (CurScale.X + CurScale.Y) * 0.5;
FHalfThickness := FThickness * 0.5;
FStrokeColor := PremultiplyAlpha(MakeColor(FBrush.Color, Opacity));
FUndeterminedMode := False;
FinalSrcPos := SrcPos * Matrix;
FinalDestPos := DestPos * Matrix;
LineLength := FinalSrcPos.Distance(FinalDestPos);
PieceDirVec := (FinalDestPos - FinalSrcPos).Normalize;
PatternStepCount := GetPatternStepCount;
if PatternStepCount > 0 then
StepSize := FThickness * PatternStepCount
else
StepSize := LineLength;
StepDelta := PieceDirVec * StepSize;
PiecePos := FinalSrcPos;
ThickPerp := PointF(-PieceDirVec.Y, PieceDirVec.X) * (FThickness * 0.5);
if StepSize <= 0 then
begin
InitArrays(0, 0);
Exit;
end;
PiecesCount := LineLength / StepSize;
ComputeBuildEstimates(PiecesCount, TotalVertices, TotalIndices);
if FSegmentCount < 1 then
begin
InitArrays(0, 0);
Exit;
end;
LastStepIndex := FSegmentCount - 1;
InitArrays(TotalVertices, TotalIndices);
for StepIndex := 0 to LastStepIndex do
begin
InsertSegment(PiecePos, PieceDirVec, ThickPerp, FinalDestPos, StepIndex >= LastStepIndex);
PiecePos := PiecePos + StepDelta;
end;
ArrayFillCheck();
end;
function TStrokeBuilder.GetEllipseTransfAt(const Delta: Single): TPointF;
var
Angle, CosAngle, SinAngle: Single;
SampleAt: TPointF;
begin
Angle := Delta * 2.0 * Pi / FEllipseCircumf;
SinCos(Angle, SinAngle, CosAngle);
SampleAt.X := FEllipseCenter.X + CosAngle * FEllipseRadius.X;
SampleAt.Y := FEllipseCenter.Y - SinAngle * FEllipseRadius.Y;
Result := SampleAt * FMatrix;
end;
procedure TStrokeBuilder.InsertEllipseSegment(const SegInitDist: Single; IsLast: Boolean);
var
TempDelta: Single;
SegSrcPos, SegDestPos, SegDirVec, ThickPerp: TPointF;
begin
case FBrush.Dash of
TStrokeDash.Dash:
begin
SegSrcPos := GetEllipseTransfAt(SegInitDist);
if IsLast and FLastDashExtend then
TempDelta := FEllipseCircumf
else
TempDelta := SegInitDist + FThickness * 3.0;
SegDestPos := GetEllipseTransfAt(TempDelta);
SegDirVec := (SegDestPos - SegSrcPos).Normalize;
ThickPerp := PointF(-SegDirVec.Y, SegDirVec.X) * FHalfThickness;
InsertDash(SegSrcPos, SegDestPos, SegDirVec, ThickPerp);
end;
TStrokeDash.Dot:
begin
TempDelta := SegInitDist + FHalfThickness;
SegSrcPos := GetEllipseTransfAt(TempDelta);
SegDirVec := (GetEllipseTransfAt(TempDelta + FHalfThickness) - GetEllipseTransfAt(TempDelta -
FHalfThickness)).Normalize;
ThickPerp := PointF(-SegDirVec.Y, SegDirVec.X) * FHalfThickness;
InsertDot(SegSrcPos, SegDirVec, ThickPerp);
end;
TStrokeDash.DashDot:
begin
SegSrcPos := GetEllipseTransfAt(SegInitDist);
if IsLast and FLastDashExtend then
TempDelta := FEllipseCircumf
else
TempDelta := SegInitDist + FThickness * 3.0;
SegDestPos := GetEllipseTransfAt(TempDelta);
SegDirVec := (SegDestPos - SegSrcPos).Normalize;
ThickPerp := PointF(-SegDirVec.Y, SegDirVec.X) * FHalfThickness;
InsertDash(SegSrcPos, SegDestPos, SegDirVec, ThickPerp);
if (not IsLast) or (FExtraPieces > 0) then
begin
TempDelta := SegInitDist + FThickness * 4.5;
SegSrcPos := GetEllipseTransfAt(TempDelta);
SegDirVec := (GetEllipseTransfAt(TempDelta + FHalfThickness) - GetEllipseTransfAt(TempDelta -
FHalfThickness)).Normalize;
ThickPerp := PointF(-SegDirVec.Y, SegDirVec.X) * FHalfThickness;
InsertDot(SegSrcPos, SegDirVec, ThickPerp);
end;
end;
TStrokeDash.DashDotDot:
begin
SegSrcPos := GetEllipseTransfAt(SegInitDist);
if IsLast and FLastDashExtend then
TempDelta := FEllipseCircumf
else
TempDelta := SegInitDist + FThickness * 3;
SegDestPos := GetEllipseTransfAt(TempDelta);
SegDirVec := (SegDestPos - SegSrcPos).Normalize;
ThickPerp := PointF(-SegDirVec.Y, SegDirVec.X) * FHalfThickness;
InsertDash(SegSrcPos, SegDestPos, SegDirVec, ThickPerp);
if (not IsLast) or (FExtraPieces > 0) then
begin
TempDelta := SegInitDist + FThickness * 4.5;
SegSrcPos := GetEllipseTransfAt(TempDelta);
SegDirVec := (GetEllipseTransfAt(TempDelta + FHalfThickness) - GetEllipseTransfAt(TempDelta -
FHalfThickness)).Normalize;
ThickPerp := PointF(-SegDirVec.Y, SegDirVec.X) * FHalfThickness;
InsertDot(SegSrcPos, SegDirVec, ThickPerp);
end;
if (not IsLast) or (FExtraPieces > 1) then
begin
TempDelta := SegInitDist + FThickness * 6.5;
SegSrcPos := GetEllipseTransfAt(TempDelta);
SegDirVec := (GetEllipseTransfAt(TempDelta + FHalfThickness) - GetEllipseTransfAt(TempDelta -
FHalfThickness)).Normalize;
ThickPerp := PointF(-SegDirVec.Y, SegDirVec.X) * FHalfThickness;
InsertDot(SegSrcPos, SegDirVec, ThickPerp);
end;
end;
end;
end;
procedure TStrokeBuilder.BuildIntermEllipse(const Center, Radius: TPointF; const Opacity: Single);
var
MajorAxis, MinorAxis, AxisSum, AxisSub, SubDivSumSq3: Single;
StepSize, TentSegmentCount, SegInitDist: Single;
CurScale: TPointF;
PatternStepCount, TotalVertices, TotalIndices, StepIndex: Integer;
begin
CurScale := GetMatrixScale;
FThickness := FBrush.Thickness * (CurScale.X + CurScale.Y) * 0.5;
FHalfThickness := FThickness * 0.5;
FStrokeColor := PremultiplyAlpha(MakeColor(FBrush.Color, Opacity));
FUndeterminedMode := False;
FEllipseCenter := Center;
FEllipseRadius := Radius;
FEllipseTransfCenter := Center * FMatrix;
if Radius.X > Radius.Y then
begin
MajorAxis := Radius.X * CurScale.X;
MinorAxis := Radius.Y * CurScale.Y;
end
else
begin
MajorAxis := Radius.Y * CurScale.Y;
MinorAxis := Radius.X * CurScale.X;
end;
AxisSum := MajorAxis + MinorAxis;
AxisSub := MajorAxis - MinorAxis;
if AxisSum <= 0 then
begin
InitArrays(0, 0);
Exit;
end;
SubDivSumSq3 := 3 * Sqr(AxisSub / AxisSum);
FEllipseCircumf := Pi * AxisSum * (1 + (SubDivSumSq3 / (10 + Sqrt(4 - SubDivSumSq3))));
PatternStepCount := GetPatternStepCount;
if PatternStepCount < 1 then
begin
InitArrays(0, 0);
Exit;
end;
StepSize := FThickness * PatternStepCount;
TentSegmentCount := FEllipseCircumf / StepSize;
ComputeBuildEstimates(TentSegmentCount, TotalVertices, TotalIndices);
if (FSegmentCount < 1) or (FEllipseCircumf < FThickness) then
begin
InitArrays(0, 0);
Exit;
end;
InitArrays(TotalVertices, TotalIndices);
SegInitDist := 0.0;
for StepIndex := 0 to FSegmentCount - 1 do
begin
InsertEllipseSegment(SegInitDist, StepIndex = FSegmentCount - 1);
SegInitDist := SegInitDist + StepSize;
end;
ArrayFillCheck;
end;
procedure TStrokeBuilder.BuildSolidEllipse(const Center, Radius: TPointF; const Opacity: Single);
var
MajorAxis, MinorAxis, AxisSum, AxisSub, SubDivSumSq3: Single;
StepSize, HalfStepSize, SegInitDist: Single;
CurScale, SampleAt, SampleDirVec, ThickPerp: TPointF;
TotalVertices, TotalIndices, StepIndex: Integer;
begin
CurScale := GetMatrixScale;
FThickness := FBrush.Thickness * (CurScale.X + CurScale.Y) * 0.5;
FHalfThickness := FThickness * 0.5;
FStrokeColor := PremultiplyAlpha(MakeColor(FBrush.Color, Opacity));
FUndeterminedMode := False;
FEllipseCenter := Center;
FEllipseRadius := Radius;
FEllipseTransfCenter := Center * FMatrix;
if Radius.X > Radius.Y then
begin
MajorAxis := Radius.X * CurScale.X;
MinorAxis := Radius.Y * CurScale.Y;
end
else
begin
MajorAxis := Radius.Y * CurScale.Y;
MinorAxis := Radius.X * CurScale.X;
end;
AxisSum := MajorAxis + MinorAxis;
AxisSub := MajorAxis - MinorAxis;
if AxisSum <= 0 then
begin
InitArrays(0, 0);
Exit;
end;
SubDivSumSq3 := 3 * Sqr(AxisSub / AxisSum);
FEllipseCircumf := Pi * AxisSum * (1 + (SubDivSumSq3 / (10 + Sqrt(4 - SubDivSumSq3))));
if MajorAxis > 100 then
StepSize := FEllipseCircumf / (2.0 * Sqrt(FEllipseCircumf))
else
if MajorAxis > 50 then
StepSize := MajorAxis * 0.1
else
StepSize := MajorAxis * 0.05;
HalfStepSize := StepSize * 0.5;
FSegmentCount := Round(FEllipseCircumf / StepSize);
if (FSegmentCount < 1) or (FEllipseCircumf < FThickness) then
begin
InitArrays(0, 0);
Exit;
end;
TotalVertices := FSegmentCount * 2;
TotalIndices := FSegmentCount * 6;
InitArrays(TotalVertices, TotalIndices);
SegInitDist := 0;
for StepIndex := 0 to FSegmentCount - 1 do
begin
SampleAt := GetEllipseTransfAt(SegInitDist);
SampleDirVec := (GetEllipseTransfAt(SegInitDist + HalfStepSize) - GetEllipseTransfAt(SegInitDist -
HalfStepSize)).Normalize;
ThickPerp := PointF(-SampleDirVec.Y, SampleDirVec.X) * FHalfThickness;
InsertVertex(SampleAt - ThickPerp, FStrokeColor);
InsertVertex(SampleAt + ThickPerp, FStrokeColor);
InsertIndex((StepIndex * 2 + 3) mod TotalVertices);
InsertIndex((StepIndex * 2 + 1) mod TotalVertices);
InsertIndex(StepIndex * 2);
InsertIndex(StepIndex * 2);
InsertIndex((StepIndex * 2 + 2) mod TotalVertices);
InsertIndex((StepIndex * 2 + 3) mod TotalVertices);
SegInitDist := SegInitDist + StepSize;
end;
ArrayFillCheck;
end;
procedure TStrokeBuilder.BuildIntermPolygon(const Points: TPolygon; const Opacity: Single; BreakAtEnd: Boolean);
var
StepSize, Distance: Single;
CurScale, SrcPos, DestPos, PieceDirVec, ThickPerp: TPointF;
SrcPosValid, DestPosValid: Boolean;
PatternStepCount, CurIndex, TempVertexCount, TempIndexCount: Integer;
begin
if Length(Points) < 2 then
begin
InitArrays(0, 0);
Exit;
end;
CurScale := GetMatrixScale;
FThickness := FBrush.Thickness * (CurScale.X + CurScale.Y) * 0.5;
FHalfThickness := FThickness * 0.5;
FStrokeColor := PremultiplyAlpha(MakeColor(FBrush.Color, Opacity));
FUndeterminedMode := True;
InitArrayPointers;
PatternStepCount := GetPatternStepCount;
if PatternStepCount < 1 then
begin
InitArrays(0, 0);
Exit;
end;
StepSize := FThickness * PatternStepCount;
CurIndex := 0;
SrcPosValid := False;
DestPosValid := False;
while CurIndex < Length(Points) do
begin
if (CurIndex >= Length(Points) - 1) and BreakAtEnd then
Break;
if not SrcPosValid then
begin
SrcPos := Points[CurIndex];
if (SrcPos.X >= $FFFF) or (SrcPos.Y >= $FFFF) then
begin
DestPosValid := False;
Inc(CurIndex);
Continue;
end;
SrcPos := SrcPos * FMatrix;
end
else
SrcPosValid := False;
if not DestPosValid then
begin
DestPos := Points[(CurIndex + 1) mod Length(Points)];
if (DestPos.X >= $FFFF) or (DestPos.Y >= $FFFF) then
begin
DestPos := Points[CurIndex];
if (DestPos.X >= $FFFF) or (DestPos.Y >= $FFFF) then
begin
Inc(CurIndex);
Continue;
end;
DestPos := DestPos * FMatrix;
end
else
DestPos := DestPos * FMatrix;
end
else
DestPosValid := False;
Distance := DestPos.Distance(SrcPos);
if Distance >= StepSize then
begin
PieceDirVec := (DestPos - SrcPos).Normalize;
ThickPerp := TPointF.Create(-PieceDirVec.Y, PieceDirVec.X) * FHalfThickness;
InsertSegment(SrcPos, PieceDirVec, ThickPerp, DestPos, False);
SrcPos := SrcPos + (PieceDirVec * StepSize);
SrcPosValid := True;
DestPosValid := True;
Continue;
end;
if (CurIndex = Length(Points) - 1) or (Points[CurIndex + 1].X >= $FFFF) or (Points[CurIndex + 1].Y >= $FFFF) or
((CurIndex < Length(Points) - 2) and (Points[CurIndex + 1].X < $FFFF) and (Points[CurIndex + 1].Y < $FFFF) and
(Points[CurIndex + 2].X < $FFFF) and (Points[CurIndex + 2].Y < $FFFF) and
(Points[CurIndex + 1].Distance(Points[CurIndex + 2]) > StepSize)) then
begin
ComputeBuildEstimates(1 + Distance / StepSize, TempVertexCount, TempIndexCount);
if FSegmentCount > 1 then
begin
PieceDirVec := (DestPos - SrcPos).Normalize();
ThickPerp := TPointF.Create(-PieceDirVec.Y, PieceDirVec.X) * FHalfThickness;
InsertSegment(SrcPos, PieceDirVec, ThickPerp, DestPos, True);
end;
if CurIndex < Length(Points) - 1 then
begin
Inc(CurIndex);
Continue;
end
else
Break;
end;
SrcPosValid := True;
Inc(CurIndex);
end;
FinalizeArrays;
end;
procedure TStrokeBuilder.BuildIntermPath(const Path: TPathData; const Opacity: Single);
var
Points: TPolygon;
begin
Path.FlattenToPolygon(Points, 1);
BuildIntermPolygon(Points, Opacity, (Path.Count > 0) and (Path[Path.Count - 1].Kind <> TPathPointKind.Close));
end;
procedure TStrokeBuilder.BuildSolidPolygon(const Points: TPolygon; const Opacity: Single; BreakAtEnd: Boolean);
var
StepSize, Distance: Single;
CurScale, SrcPos, DestPos, PieceDirVec, ThickPerp: TPointF;
SrcPosValid, DestPosValid, PrevVerticesPlaced: Boolean;
CurIndex, LPoints: Integer;
begin
LPoints := Length(Points); // by YangYxd
if LPoints < 2 then
begin
InitArrays(0, 0);
Exit;
end;
CurScale := GetMatrixScale;
FThickness := FBrush.Thickness * (CurScale.X + CurScale.Y) * 0.5;
FHalfThickness := FThickness * 0.5;
FStrokeColor := PremultiplyAlpha(MakeColor(FBrush.Color, Opacity));
FUndeterminedMode := True;
InitArrayPointers;
// StepSize := FThickness;
// if StepSize < 2 then
// StepSize := 2;
StepSize := 1;
CurIndex := 0;
SrcPosValid := False;
DestPosValid := False;
PrevVerticesPlaced := False;
while CurIndex < LPoints do
begin
if (CurIndex >= LPoints - 1) and BreakAtEnd and (Points[0] <> Points[LPoints - 1]) then
Break;
if not SrcPosValid then
begin
SrcPos := Points[CurIndex];
if (SrcPos.X >= $FFFF) or (SrcPos.Y >= $FFFF) then
begin
DestPosValid := False;
PrevVerticesPlaced := False;
Inc(CurIndex);
Continue;
end;
SrcPos := SrcPos * FMatrix;
end
else
SrcPosValid := False;
if not DestPosValid then
begin
DestPos := Points[(CurIndex + 1) mod LPoints];
if (DestPos.X >= $FFFF) or (DestPos.Y >= $FFFF) then
begin
DestPos := Points[CurIndex];
if (DestPos.X >= $FFFF) or (DestPos.Y >= $FFFF) then
begin
PrevVerticesPlaced := False;
Inc(CurIndex);
Continue;
end;
DestPos := DestPos * FMatrix;
end
else
DestPos := DestPos * FMatrix;
end
else
DestPosValid := False;
Distance := DestPos.Distance(SrcPos);
if Distance >= StepSize then
begin
PieceDirVec := (DestPos - SrcPos).Normalize;
ThickPerp := TPointF.Create(-PieceDirVec.Y, PieceDirVec.X) * FHalfThickness;
InsertVertex(SrcPos - ThickPerp, FStrokeColor);
InsertVertex(SrcPos + ThickPerp, FStrokeColor);
if PrevVerticesPlaced then
begin
InsertIndex(FCurrentVertex - 3);
InsertIndex(FCurrentVertex - 1);
InsertIndex(FCurrentVertex - 2);
InsertIndex(FCurrentVertex - 2);
InsertIndex(FCurrentVertex - 4);
InsertIndex(FCurrentVertex - 3);
end;
PrevVerticesPlaced := True;
SrcPos := SrcPos + (PieceDirVec * StepSize);
SrcPosValid := True;
DestPosValid := True;
Continue;
end;
if ((CurIndex < Length(Points) - 2) and (Points[CurIndex + 1].X < $FFFF) and (Points[CurIndex + 1].Y < $FFFF) and
(Points[CurIndex + 2].X < $FFFF) and (Points[CurIndex + 2].Y < $FFFF) and
(Points[CurIndex + 1].Distance(Points[CurIndex + 2]) > StepSize)) then
begin
PieceDirVec := (DestPos - SrcPos).Normalize;
ThickPerp := TPointF.Create(-PieceDirVec.Y, PieceDirVec.X) * FHalfThickness;
InsertVertex(DestPos - ThickPerp, FStrokeColor);
InsertVertex(DestPos + ThickPerp, FStrokeColor);
if PrevVerticesPlaced then
begin
InsertIndex(FCurrentVertex - 3);
InsertIndex(FCurrentVertex - 1);
InsertIndex(FCurrentVertex - 2);
InsertIndex(FCurrentVertex - 2);
InsertIndex(FCurrentVertex - 4);
InsertIndex(FCurrentVertex - 3);
end;
if CurIndex < Length(Points) - 1 then
begin
Inc(CurIndex);
Continue;
end
else
Break;
end;
if (CurIndex = LPoints - 1) or (Points[CurIndex + 1].X >= $FFFF) or (Points[CurIndex + 1].Y >= $FFFF) then
begin
PieceDirVec := (DestPos - SrcPos).Normalize;
ThickPerp := TPointF.Create(-PieceDirVec.Y, PieceDirVec.X) * FHalfThickness;
InsertVertex(DestPos - ThickPerp, FStrokeColor);
InsertVertex(DestPos + ThickPerp, FStrokeColor);
if PrevVerticesPlaced then
begin
InsertIndex(FCurrentVertex - 3);
InsertIndex(FCurrentVertex - 1);
InsertIndex(FCurrentVertex - 2);
InsertIndex(FCurrentVertex - 2);
InsertIndex(FCurrentVertex - 4);
InsertIndex(FCurrentVertex - 3);
end;
PrevVerticesPlaced := False;
if CurIndex < LPoints - 1 then
begin
Inc(CurIndex);
Continue;
end
else
Break;
end;
SrcPosValid := True;
Inc(CurIndex);
end;
FinalizeArrays;
end;
procedure TStrokeBuilder.BuildSolidPath(const Path: TPathData; const Opacity: Single);
var
Points: TPolygon;
begin
Path.FlattenToPolygon(Points, 1);
BuildSolidPolygon(Points, Opacity, (Path.Count > 0) and (Path[Path.Count - 1].Kind <> TPathPointKind.Close));
end;
{$ENDREGION}
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit BindVisualizers;
interface
uses System.Bindings.EvalProtocol, System.Classes,System.SysUtils, Vcl.StdCtrls, Vcl.Controls;
type
TBindExpressionVisualizerView = class;
TBindExpressionVisualizer = class
protected
function GetName: string; virtual; abstract;
public
property Name: string read GetName;
function SupportsValue(AValue: IValue): Boolean; virtual; abstract;
function CreateView: TBindExpressionVisualizerView; virtual; abstract;
end;
TBindExpressionVisualizerClass = class of TBindExpressionVisualizer;
TBindExpressionVisualizerView = class
private
FVisualizer: TBindExpressionVisualizer;
public
constructor Create(AVisualizer: TBindExpressionVisualizer);
procedure Show(AOwner: TComponent; AParent: TWinControl); virtual; abstract;
procedure Update(AValue: IValue); virtual; abstract;
procedure Clear; virtual; abstract;
property Visualizer: TBindExpressionVisualizer read FVisualizer;
end;
procedure RegisterVisualizerClasses(AClasses: array of TBindExpressionVisualizerClass);
procedure UnregisterVisualizerClasses(AClasses: array of TBindExpressionVisualizerClass);
function GetVisualizerClasses: TArray<TBindExpressionVisualizerClass>;
implementation
uses
System.Generics.Collections, Vcl.Graphics, Vcl.ExtCtrls, Vcl.Forms,
System.UITypes, BindCompDsnResStrs;
type
TVisualizerClasses = class
strict private
class var FInstance: TVisualizerClasses;
var
FList: TList<TBindExpressionVisualizerClass>;
public
class constructor Create;
class destructor Destroy;
constructor Create;
destructor Destroy; override;
procedure Add(AClass: TBindExpressionVisualizerClass);
procedure Remove(AClass: TBindExpressionVisualizerClass);
function GetClasses: TArray<TBindExpressionVisualizerClass>;
class property Instance: TVisualizerClasses read FInstance;
end;
procedure RegisterVisualizerClasses(AClasses: array of TBindExpressionVisualizerClass);
var
LClass: TBindExpressionVisualizerClass;
begin
for LClass in AClasses do
TVisualizerClasses.Instance.Add(LClass);
end;
procedure UnregisterVisualizerClasses(AClasses: array of TBindExpressionVisualizerClass);
var
LClass: TBindExpressionVisualizerClass;
begin
for LClass in AClasses do
TVisualizerClasses.Instance.Remove(LClass);
end;
function GetVisualizerClasses: TArray<TBindExpressionVisualizerClass>;
begin
Result := TVisualizerClasses.Instance.GetClasses;
end;
type
TBindExpressStringVisualizer = class(TBindExpressionVisualizer)
private
function TryAsString(AValue: IValue; out AString: string): Boolean;
protected
function GetName: string; override;
public
function SupportsValue(AValue: IValue): Boolean; override;
function CreateView: TBindExpressionVisualizerView; override;
end;
TBindExpressionStringVisualizerView = class(TBindExpressionVisualizerView)
private
FMemo: TMemo;
FVisualizer: TBindExpressStringVisualizer;
public
constructor Create(AVisualizer: TBindExpressionVisualizer);
destructor Destroy; override;
procedure Show(AOwner: TComponent; AParent: TWinControl); override;
procedure Update(AValue: IValue); override;
procedure Clear; override;
end;
TBindExpressTypeVisualizer = class(TBindExpressionVisualizer)
protected
function GetName: string; override;
public
function SupportsValue(AValue: IValue): Boolean; override;
function CreateView: TBindExpressionVisualizerView; override;
end;
TBindExpressionTypeVisualizerView = class(TBindExpressionVisualizerView)
private
FMemo: TMemo;
public
destructor Destroy; override;
procedure Show(AOwner: TComponent; AParent: TWinControl); override;
procedure Update(AValue: IValue); override;
procedure Clear; override;
end;
TBindExpressPictureVisualizer = class(TBindExpressionVisualizer)
private
function TryAsPicture(AValue: IValue; out APicture: TPicture): Boolean;
protected
function GetName: string; override;
public
function SupportsValue(AValue: IValue): Boolean; override;
function CreateView: TBindExpressionVisualizerView; override;
end;
TBindExpressionPictureVisualizerView = class(TBindExpressionVisualizerView)
private
FImage: TImage;
FPanel: TPanel;
FVisualizer: TBindExpressPictureVisualizer;
public
constructor Create(AVisualizer: TBindExpressionVisualizer);
destructor Destroy; override;
procedure Show(AOwner: TComponent; AParent: TWinControl); override;
procedure Update(AValue: IValue); override;
procedure Clear; override;
end;
{ TBindExpressStringVisualizer }
function TBindExpressStringVisualizer.CreateView: TBindExpressionVisualizerView;
begin
Result := TBindExpressionStringVisualizerView.Create(Self);
end;
function TBindExpressStringVisualizer.GetName: string;
begin
Result := sStringVisualizer;
end;
function TBindExpressStringVisualizer.TryAsString(AValue: IValue; out AString: string): Boolean;
var
LString: string;
LInteger: Integer;
LDouble: Double;
begin
Result := True;
AString := '';
if AValue = nil then
AString := '(nil)'
else if AValue.GetValue.IsEmpty then
AString := '(empty)'
else
if AValue.GetValue.TryAsType<string>(LString) then
AString := '''' + LString + ''''
else if AValue.GetValue.TryAsType<Integer>(LInteger) then
AString := IntToStr(LInteger)
else if AValue.GetValue.TryAsType<Double>(LDouble) then
AString := FloatToStr(LDouble)
else
Result := False;
end;
function TBindExpressStringVisualizer.SupportsValue(AValue: IValue): Boolean;
var
LString: string;
begin
Result := (AValue <> nil) and TryAsString(AValue, LString);
end;
{ TBindExpressionStringVisualizerView }
procedure TBindExpressionStringVisualizerView.Clear;
begin
if FMemo <> nil then
FMemo.Clear;
end;
constructor TBindExpressionStringVisualizerView.Create(
AVisualizer: TBindExpressionVisualizer);
begin
inherited;
FVisualizer := TBindExpressStringVisualizer(AVisualizer);
end;
destructor TBindExpressionStringVisualizerView.Destroy;
begin
FMemo.Free;
inherited;
end;
procedure TBindExpressionStringVisualizerView.Show(AOwner: TComponent; AParent: TWinControl);
begin
if FMemo = nil then
begin
FMemo := TMemo.Create(AOwner);
FMemo.ScrollBars := System.UITypes.TScrollStyle.ssVertical;
FMemo.WordWrap := True;
FMemo.Align := alClient;
FMemo.ReadOnly := True;
end;
FMemo.Parent := AParent;
end;
procedure TBindExpressionStringVisualizerView.Update(AValue: IValue);
var
LString: string;
begin
if FMemo <> nil then
begin
if FVisualizer.TryAsString(AValue, LString) then
FMemo.Text := LString
else if AValue.GetValue.TypeInfo <> nil then
FMemo.Text := 'Visualizer does not support type: ' + String(AValue.GetValue.TypeInfo.Name)
else
FMemo.Text := '(undefined)';
end;
end;
{ TBindExpressTypeVisualizer }
function TBindExpressTypeVisualizer.CreateView: TBindExpressionVisualizerView;
begin
Result := TBindExpressionTypeVisualizerView.Create(Self);
end;
function TBindExpressTypeVisualizer.GetName: string;
begin
Result := sTypeVisualizer;
end;
function TBindExpressTypeVisualizer.SupportsValue(AValue: IValue): Boolean;
begin
Result := True;
end;
{ TBindExpressionTypeVisualizerView }
procedure TBindExpressionTypeVisualizerView.Clear;
begin
if FMemo <> nil then
FMemo.Clear;
end;
destructor TBindExpressionTypeVisualizerView.Destroy;
begin
FMemo.Free;
inherited;
end;
procedure TBindExpressionTypeVisualizerView.Show(AOwner: TComponent; AParent: TWinControl);
begin
if FMemo = nil then
begin
FMemo := TMemo.Create(AOwner);
FMemo.ScrollBars := System.UITypes.TScrollStyle.ssVertical;
FMemo.WordWrap := True;
FMemo.Align := alClient;
FMemo.ReadOnly := True;
end;
FMemo.Parent := AParent;
end;
procedure TBindExpressionTypeVisualizerView.Update(AValue: IValue);
begin
if FMemo <> nil then
begin
if AValue = nil then
FMemo.Text := '(nil)'
else if AValue.GetValue.IsEmpty then
FMemo.Text := '(empty)'
else
try
if AValue.GetValue.TypeInfo <> nil then
FMemo.Text := 'Type: ' + String(AValue.GetValue.TypeInfo.Name)
else
FMemo.Text := '(undefined)';
except
on E: Exception do
FMemo.Text := E.Message;
end;
end;
end;
{ TBindExpressPictureVisualizer }
function TBindExpressPictureVisualizer.CreateView: TBindExpressionVisualizerView;
begin
Result := TBindExpressionPictureVisualizerView.Create(Self);
end;
function TBindExpressPictureVisualizer.GetName: string;
begin
Result := sPictureVisualizer;
end;
function TBindExpressPictureVisualizer.TryAsPicture(AValue: IValue; out APicture: TPicture): Boolean;
begin
Result := False;
if AValue <> nil then
if not AValue.GetValue.IsEmpty then
if AValue.GetValue.TryAsType<TPicture>(APicture) then
Result := True;
end;
function TBindExpressPictureVisualizer.SupportsValue(AValue: IValue): Boolean;
var
LPicture: TPicture;
begin
Result := TryAsPicture(AValue, LPicture);
end;
{ TBindExpressionPictureVisualizerView }
procedure TBindExpressionPictureVisualizerView.Clear;
begin
if FImage <> nil then
FImage.Picture.Graphic := nil;
end;
constructor TBindExpressionPictureVisualizerView.Create(
AVisualizer: TBindExpressionVisualizer);
begin
inherited;
FVisualizer := TBindExpressPictureVisualizer(AVisualizer);
end;
destructor TBindExpressionPictureVisualizerView.Destroy;
begin
FPanel.Free;
inherited;
end;
procedure TBindExpressionPictureVisualizerView.Show(AOwner: TComponent; AParent: TWinControl);
begin
if FImage = nil then
begin
FPanel := TPanel.Create(AOwner);
FPanel.Align := alClient;
FPanel.BorderStyle := Vcl.Forms.TFormBorderStyle.bsSingle;
FPanel.BorderWidth := 1;
FPanel.BevelOuter := bvNone;
FImage := TImage.Create(FPanel);
FImage.Align := alClient;
FImage.Parent := FPanel;
end;
FPanel.Parent := AParent;
end;
procedure TBindExpressionPictureVisualizerView.Update(AValue: IValue);
var
LPicture: TPicture;
begin
if FImage <> nil then
begin
if FVisualizer.TryAsPicture(AValue, LPicture) then
FImage.Picture.Assign(LPicture)
else
FImage.Picture.Graphic := nil;
end;
end;
{ TVisualizerClasses }
procedure TVisualizerClasses.Add(AClass: TBindExpressionVisualizerClass);
begin
FList.Add(AClass);
end;
constructor TVisualizerClasses.Create;
begin
FList := TList<TBindExpressionVisualizerClass>.Create;
end;
class constructor TVisualizerClasses.Create;
begin
FInstance := TVisualizerClasses.Create;
end;
destructor TVisualizerClasses.Destroy;
begin
FList.Free;
inherited;
end;
class destructor TVisualizerClasses.Destroy;
begin
FreeAndNil(FInstance);
end;
function TVisualizerClasses.GetClasses: TArray<TBindExpressionVisualizerClass>;
begin
Result := FList.ToArray;
end;
procedure TVisualizerClasses.Remove(AClass: TBindExpressionVisualizerClass);
begin
FList.Remove(AClass);
end;
{ TBindExpressionVisualizerView }
constructor TBindExpressionVisualizerView.Create(
AVisualizer: TBindExpressionVisualizer);
begin
FVisualizer := AVisualizer;
end;
initialization
RegisterVisualizerClasses([TBindExpressStringVisualizer, TBindExpressTypeVisualizer, TBindExpressPictureVisualizer]);
finalization
UnregisterVisualizerClasses([TBindExpressStringVisualizer, TBindExpressTypeVisualizer, TBindExpressPictureVisualizer]);
end.
|
unit IdRexecServer;
{based on
http://www.winsock.com/hypermail/winsock2/2235.html
http://www.private.org.il/mini-tcpip.faq.html}
{ 2001, Feb 17 - J. Peter Mugaas
moved much of the code into IdRemoteCMDServer so it can be
reused in IdRSHServer
2001, Feb 15 - J. Peter Mugaas
made methods for error and sucess command results
2001, Feb 14 - J. Peter Mugaas
started this unit
This is based on the IdRexec.pas unit and
programming comments at http://www.abandoned.org/nemon/rexeclib.py}
interface
uses
Classes,
IdAssignedNumbers, IdRemoteCMDServer, IdTCPClient, IdTCPServer;
type
TIdRexecCommandEvent = procedure (AThread: TIdPeerThread;
AStdError : TIdTCPClient; AUserName, APassword, ACommand : String) of object;
TIdRexecServer = class(TIdRemoteCMDServer)
protected
FOnCommand : TIdRexecCommandEvent;
procedure DoCMD(AThread: TIdPeerThread;
AStdError : TIdTCPClient; AParam1, AParam2, ACommand : String); override;
public
constructor Create(AOwner : TComponent); override;
published
property OnCommand : TIdRexecCommandEvent read FOnCommand write FOnCommand;
property DefaultPort default Id_PORT_exec;
end;
implementation
{ TIdRexecServer }
constructor TIdRexecServer.Create(AOwner: TComponent);
begin
inherited;
DefaultPort := Id_PORT_exec;
{This variable is defined in the TIdRemoteCMDServer component. We do not
use it here because Rexec does not require it. However, we have to set this to
to false to disable forcing ports to be in a specific range. The variable in is the
anscestor because only accepting clients in a specific range would require a change
to the base component.}
FForcePortsInRange := False;
FStdErrorPortsInRange := False;
end;
procedure TIdRexecServer.DoCMD(AThread: TIdPeerThread;
AStdError: TIdTCPClient; AParam1, AParam2, ACommand: String);
begin
if Assigned(FOnCommand) then begin
FOnCommand(AThread,AStdError,AParam1,AParam2,ACommand);
end;
end;
end.
|
unit Prcllist;
interface
uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons,
StdCtrls, ExtCtrls, Grids, Dialogs, Types, DBTables, DB, SysUtils,
RPFiler, RPDefine, RPBase, RPCanvas, RPrinter, ComCtrls;
type
TParcelListDialog = class(TForm)
LoadButton: TBitBtn;
ParcelStringGrid: TStringGrid;
Label1: TLabel;
SaveButton: TBitBtn;
SortButton: TBitBtn;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
DescriptionMemo: TMemo;
NewButton: TBitBtn;
AddButton: TBitBtn;
DeleteButton: TBitBtn;
NameLabel: TLabel;
AddressLabel: TLabel;
ParcelTable: TTable;
SwisCodeTable: TTable;
NumParcelsLabel: TLabel;
PrintButton: TBitBtn;
ImportButton: TBitBtn;
ExportButton: TBitBtn;
PrintDialog: TPrintDialog;
ReportPrinter: TReportPrinter;
ReportFiler: TReportFiler;
SortingPanel: TPanel;
Label2: TLabel;
SortProgressBar: TProgressBar;
SortByPanel: TPanel;
SortByRadioGroup: TRadioGroup;
SortByOKButton: TBitBtn;
SortByCancelButton: TBitBtn;
procedure FormCreate(Sender: TObject);
procedure SortButtonClick(Sender: TObject);
procedure LoadButtonClick(Sender: TObject);
procedure SaveButtonClick(Sender: TObject);
procedure NewButtonClick(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure ParcelStringGridClick(Sender: TObject);
procedure ParcelStringGridDblClick(Sender: TObject);
procedure ReportPrintHeader(Sender: TObject);
procedure ReportPrint(Sender: TObject);
procedure PrintButtonClick(Sender: TObject);
procedure ImportButtonClick(Sender: TObject);
procedure ExportButtonClick(Sender: TObject);
procedure SortByCancelButtonClick(Sender: TObject);
procedure SortByOKButtonClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure ParcelStringGridMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure ParcelStringGridMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
private
{ Private declarations }
public
{ Public declarations }
FileName : String;
Dragging, Modified : Boolean;
LastRow : Integer;
DragStartRow : LongInt;
PrintCheckedStatus : Boolean;
Function AddOneParcel(SwisSBLKey : String) : Boolean;
Procedure ClearParcelGrid(AskForSave : Boolean);
Function GetParcelSwisSBLKey(Index : Integer) : String;
Function GetParcelID(Index : Integer) : String;
Function NumItems : Integer;
Function GetParcel(ParcelTable : TTable;
Index : Integer) : Boolean;
Function GetParcelWithAssessmentYear(ParcelTable : TTable;
Index : Integer;
AssessmentYear : String) : Boolean;
Procedure SetCaption;
Procedure CheckAndSaveModifiedList;
Procedure SetNumParcelsLabel(NumParcels : Integer);
Procedure CloseFiles;
Function ParcelExistsInList(SwisSBLKey : String) : Boolean;
Procedure SortList(SortType : Integer);
Function GetCheckedStatus(Index : Integer) : Boolean;
Procedure SwitchRows(Row1,
Row2 : LongInt);
end;
const
stByParcelID = 0;
stByName = 1;
stByLegalAddressStreet_Number = 2;
stByLegalAddressNumber_Street = 3;
var
ParcelListDialog: TParcelListDialog;
implementation
uses GlblVars, Utilitys, PASUtils, PASTypes, WINUtils, Glblcnst,
Prclocat, ParclTab, Prog, Preview, DataModule, DataAccessUnit;
{$R *.DFM}
type
SortRecord = record
SwisSBLKey : String;
ParcelID : String;
Name : String;
LegalAddressStreet : String;
LegalAddressNumber : String;
Checked : Boolean;
end;
SortPointer = ^SortRecord;
{============================================================}
Procedure TParcelListDialog.SetCaption;
{FXX10302001-1: Remove the path from the file name.}
begin
Caption := 'Parcel List - (' + StripPath(Trim(FileName)) + ')';
end;
{============================================================}
Procedure TParcelListDialog.FormCreate(Sender: TObject);
begin
ParcelStringGrid.Cells[1, 0] := 'Parcel ID';
OpenDialog.InitialDir := GlblListDir;
SaveDialog.InitialDir := GlblListDir;
Top := 0;
Left := 0;
FileName := 'unnamed';
SetCaption;
Modified := False;
Dragging := False;
end; {FormCreate}
{============================================================}
Function FindLastItem(ParcelStringGrid : TStringGrid) : Integer;
var
I : Integer;
begin
Result := 0;
with ParcelStringGrid do
For I := 1 to (RowCount - 1) do
If (Deblank(Cells[1, I]) <> '')
then Result := Result + 1;
end; {FindLastItem}
{============================================================}
Procedure TParcelListDialog.CheckAndSaveModifiedList;
var
TempStr : String;
begin
If ((Modified or
(FileName = 'unnamed')) and
(FindLastItem(ParcelStringGrid) > 0)) {Make sure there is info in the grid.}
then
begin
If (FileName = 'unnamed')
then TempStr := 'The current list has not been saved.'
else TempStr := 'The current list has been changed.';
If (MessageDlg(TempStr + #13 +
'Do you wish to save the list?', mtConfirmation,
[mbYes, mbNo], 0) = idYes)
then SaveButtonClick(SaveButton);
end; {If (Modified or ...}
end; {CheckAndSaveModifiedList}
{============================================================}
Procedure TParcelListDialog.SetNumParcelsLabel(NumParcels : Integer);
begin
NumParcelsLabel.Caption := 'Num Parcels = ' + IntToStr(NumParcels);
end; {SetNumParcelsLabel}
{============================================================}
Function TParcelListDialog.AddOneParcel(SwisSBLKey : String) : Boolean;
var
LastItem : Integer;
begin
Result := False;
If not ParcelExistsInList(SwisSBLKey)
then
begin
LastItem := FindLastItem(ParcelStringGrid);
with ParcelStringGrid do
begin
If (LastItem = (RowCount - 1))
then RowCount := RowCount + 1;
Cells[0, (LastItem + 1)] := '';
Cells[1, (LastItem + 1)] := ConvertSwisSBLToDashDot(SwisSBLKey);
Cells[2, (LastItem + 1)] := SwisSBLKey;
end; {with ParcelStringGrid do}
ParcelStringGrid.Row := LastItem + 1;
SetNumParcelsLabel(LastItem + 1);
Modified := True;
Result := True;
end; {If not ParcelExistsInList(SwisSBLKey)}
end; {AddOneParcel}
{============================================================}
Function GetTempKey(TempSortList : TList;
J : Integer;
SortType : Integer) : String;
begin
with SortPointer(TempSortList[J])^ do
case SortType of
stByParcelID : Result := SwisSBLKey;
stByName : Result := Take(25, Name);
stByLegalAddressStreet_Number : Result := Take(25, LegalAddressStreet) +
ShiftRightAddZeroes(Take(10, LegalAddressNumber));
stByLegalAddressNumber_Street : Result := ShiftRightAddZeroes(Take(10, LegalAddressNumber)) +
Take(25, LegalAddressStreet);
end; {case SortType of}
end; {GetTempKey}
{============================================================}
Procedure SortTempList(TempSortList : TList;
SortType : Integer);
var
I, J : LongInt;
OldKey, NewKey : String;
TempSortPtr : SortPointer;
begin
For I := 0 to (TempSortList.Count - 1) do
begin
OldKey := GetTempKey(TempSortList, I, SortType);
For J := (I + 1) to (TempSortList.Count - 1) do
begin
NewKey := GetTempKey(TempSortList, J, SortType);
If (NewKey < OldKey)
then
begin
TempSortPtr := TempSortList[I];
TempSortList[I] := TempSortList[J];
TempSortList[J] := TempSortPtr;
OldKey := NewKey;
end; {If (NewKey < OldKey)}
end; {For J := (I + 1) to (TempSortList.Count - 1) do}
end; {For I := 0 to (TempSortList.Count - 1) do}
end; {SortTempList}
{============================================================}
Procedure TParcelListDialog.SortList(SortType : Integer);
var
TempSortList : TList;
SortPtr : SortPointer;
I, TotalItems : LongInt;
begin
TempSortList := TList.Create;
TotalItems := NumItems;
SortingPanel.Visible := True;
Refresh;
SortProgressBar.Position := 0;
SortProgressBar.Max := TotalItems;
Application.ProcessMessages;
{First create a TList with all the items.}
For I := 1 to TotalItems do
If GetParcel(ParcelTable, I)
then
begin
New(SortPtr);
with SortPtr^, ParcelTable do
begin
SwisSBLKey := GetParcelSwisSBLKey(I);
ParcelID := GetParcelID(I);
SortPtr^.Name := FieldByName('Name1').Text;
LegalAddressStreet := FieldByName('LegalAddr').Text;
LegalAddressNumber := ShiftRightAddZeroes(Take(10, FieldByName('LegalAddrNo').Text));
Checked := GetCheckedStatus(I);
end; {with SortPtr^ do}
SortProgressBar.Position := SortProgressBar.Position + 1;
TempSortList.Add(SortPtr);
end; {If GetParcel(ParcelTable, I)}
SortTempList(TempSortList, SortType);
{Now clear the grid and refill it in the new order.}
ClearParcelGrid(False);
For I := 1 to TotalItems do
with SortPointer(TempSortList[I - 1])^ do
begin
If Checked
then ParcelStringGrid.Cells[0, I] := 'X'
else ParcelStringGrid.Cells[0, I] := ' ';
ParcelStringGrid.Cells[1, I] := ParcelID;
ParcelStringGrid.Cells[2, I] := SwisSBLKey;
end; {with SortPointer(TempSortList[I])^ do}
SortingPanel.Visible := False;
end; {SortList}
{==============================================================}
Procedure TParcelListDialog.SortByCancelButtonClick(Sender: TObject);
begin
SortByPanel.Hide;
end;
{==============================================================}
Procedure TParcelListDialog.SortByOKButtonClick(Sender: TObject);
begin
SortByPanel.Hide;
SortList(SortByRadioGroup.ItemIndex);
end;
{==============================================================}
Procedure TParcelListDialog.SortButtonClick(Sender: TObject);
{CHG11052001-1: Allow for sort of parcel list.}
begin
SortByPanel.Show;
end;
{============================================================}
Procedure TParcelListDialog.ClearParcelGrid(AskForSave : Boolean);
var
I, J : Integer;
Quit : Boolean;
begin
If AskForSave
then CheckAndSaveModifiedList;
{FXX07211999-5: Delete leaves 'X' in grid.}
with ParcelStringGrid do
For I := 0 to (ColCount - 1) do
For J := 1 to (RowCount - 1) do
Cells[I, J] := '';
with DescriptionMemo do
For I := 0 to 4 do
Lines[I] := '';
FileName := 'unnamed';
SetCaption;
Modified := False;
LastRow := 1;
SetNumParcelsLabel(0);
{Let's always reopen the parcel table when we clear the grid to
make sure it is set to the right processing type.}
OpenTableForProcessingType(ParcelTable, ParcelTableName,
GlblProcessingType, Quit);
OpenTableForProcessingType(SwisCodeTable, SwisCodeTableName,
GlblProcessingType, Quit);
end; {ClearParcelGrid}
{==============================================================}
Procedure TParcelListDialog.LoadButtonClick(Sender: TObject);
var
Done : Boolean;
ListFile : TextFile;
TempStr, ParcelID : String;
I : Integer;
begin
Done := False;
OpenDialog.FilterIndex := 1;
If OpenDialog.Execute
then
begin
ClearParcelGrid(True);
AssignFile(ListFile, OpenDialog.FileName);
Reset(ListFile);
For I := 0 to 4 do
begin
Readln(ListFile, TempStr);
DescriptionMemo.Lines[I] := TempStr;
end;
repeat
Readln(ListFile, ParcelID);
ParcelID := Take(28, ParcelID);
If EOF(ListFile)
then Done := True;
AddOneParcel(Take(26, ParcelID));
{Now display if this was selected before.}
ParcelStringGrid.Cells[0, (ParcelStringGrid.Row - 1)] := Copy(ParcelID, 28, 1);
until Done;
CloseFile(ListFile);
FileName := OpenDialog.FileName;
SetCaption;
Modified := False;
end; {If OpenDialog.Execute}
end; {LoadButtonClick}
{=================================================================}
Procedure TParcelListDialog.SaveButtonClick(Sender: TObject);
var
I : Integer;
ListFile : TextFile;
begin
SaveDialog.FilterIndex := 1;
If SaveDialog.Execute
then
begin
AssignFile(ListFile, SaveDialog.FileName);
Rewrite(ListFile);
{Write the description.}
with DescriptionMemo do
For I := 0 to 4 do
Writeln(ListFile, Lines[I]);
{CHG05131999-2: Let people look up parcels from the parcel list.}
{Also write if selected or not.}
For I := 1 to (ParcelStringGrid.RowCount - 1) do
If (Deblank(ParcelStringGrid.Cells[2, I]) <> '')
then Writeln(ListFile, ParcelStringGrid.Cells[2, I], ' ',
Take(1, ParcelStringGrid.Cells[0, I]));
CloseFile(ListFile);
FileName := SaveDialog.FileName;
SetCaption;
Modified := False;
{FXX11021999-14: Preventative measure to make sure that the file saved.}
If not FileExists(SaveDialog.FileName)
then MessageDlg('The parcel list did not save correctly.' + #13 +
'Please try again.', mtError, [mbOK], 0);
end; {If SaveDialog.Execute}
end; {SaveButtonClick}
{=================================================================}
Function TParcelListDialog.GetParcelSwisSBLKey(Index : Integer) : String;
begin
Result := ParcelStringGrid.Cells[2, Index];
end;
{=================================================================}
Function TParcelListDialog.GetCheckedStatus(Index : Integer) : Boolean;
begin
Result := (ParcelStringGrid.Cells[0, Index] = 'X');
end;
{=================================================================}
Function TParcelListDialog.NumItems : Integer;
begin
Result := FindLastItem(ParcelStringGrid);
end;
{=================================================================}
Function TParcelListDialog.GetParcel(ParcelTable : TTable;
Index : Integer) : Boolean;
var
SBLRec : SBLRecord;
begin
Result := False;
SBLRec := ExtractSwisSBLFromSwisSBLKey(GetParcelSwisSBLKey(Index));
If (Deblank(SBLRec.SwisCode) <> '')
then
with SBLRec do
Result := FindKeyOld(ParcelTable,
['TaxRollYr', 'SwisCode',
'Section', 'Subsection',
'Block', 'Lot', 'Sublot', 'Suffix'],
[ParcelTable.FieldByName('TaxRollYr').Text,
SwisCode, Section, Subsection, Block,
Lot, Sublot, Suffix]);
end; {GetParcel}
{=================================================================}
Function TParcelListDialog.GetParcelWithAssessmentYear(ParcelTable : TTable;
Index : Integer;
AssessmentYear : String) : Boolean;
var
SBLRec : SBLRecord;
begin
Result := False;
SBLRec := ExtractSwisSBLFromSwisSBLKey(GetParcelSwisSBLKey(Index));
If (Deblank(SBLRec.SwisCode) <> '')
then
with SBLRec do
Result := FindKeyOld(ParcelTable,
['TaxRollYr', 'SwisCode',
'Section', 'Subsection',
'Block', 'Lot', 'Sublot', 'Suffix'],
[AssessmentYear,
SwisCode, Section, Subsection, Block,
Lot, Sublot, Suffix]);
end; {GetParcelWithAssessmentYear}
{=================================================================}
Function TParcelListDialog.GetParcelID(Index : Integer) : String;
begin
Result := ParcelStringGrid.Cells[1, Index];
end;
{===========================================================}
Procedure TParcelListDialog.NewButtonClick(Sender: TObject);
begin
ClearParcelGrid(True);
end;
{===================================================================}
Procedure TParcelListDialog.AddButtonClick(Sender: TObject);
var
SwisSBLKey : String;
begin
If ExecuteParcelLocateDialog(SwisSBLKey, True, False, 'Add to Parcel List', False, nil)
then
begin
AddOneParcel(SwisSBLKey);
ParcelStringGridClick(Sender);
end;
end; {AddButtonClick}
{====================================================================}
Procedure TParcelListDialog.DeleteButtonClick(Sender: TObject);
var
TempRow, I : Integer;
begin
TempRow := ParcelStringGrid.Row;
{FXX07211999-5: Delete leaves 'X' in grid.}
with ParcelStringGrid do
begin
For I := (TempRow + 1) to (RowCount - 1) do
begin
Cells[0, (I - 1)] := Cells[0, I];
Cells[1, (I - 1)] := Cells[1, I];
Cells[2, (I - 1)] := Cells[2, I];
end;
{Blank out the last row.}
Cells[0, (RowCount - 1)] := '';
Cells[1, (RowCount - 1)] := '';
Cells[2, (RowCount - 1)] := '';
end; {with ParcelStringGrid do}
SetNumParcelsLabel(FindLastItem(ParcelStringGrid));
Modified := True;
end; {DeleteButtonClick}
{========================================================================}
Procedure TParcelListDialog.ParcelStringGridClick(Sender: TObject);
var
Found : Boolean;
begin
Found := GetParcel(ParcelTable, ParcelStringGrid.Row);
If Found
then
begin
NameLabel.Caption := Take(15, ParcelTable.FieldByName('Name1').Text);
AddressLabel.Caption := Take(15, GetLegalAddressFromTable(ParcelTable));
end
else
begin
NameLabel.Caption := '';
AddressLabel.Caption := '';
end;
end; {ParcelStringGridClick}
{===========================================================}
Procedure TParcelListDialog.ParcelStringGridDblClick(Sender: TObject);
{CHG05131999-2: Let people look up parcels from the parcel list.}
var
Found : Boolean;
SwisSBLKey : String;
begin
Found := GetParcel(ParcelTable, ParcelStringGrid.Row);
SwisSBLKey := GetParcelSwisSBLKey(ParcelStringGrid.Row);
If Found
then
begin
{Display this parcel in the list.}
ParcelStringGridClick(Sender);
{Now see if parcel view or mod is active.}
If (GlblParcelMaintenance <> nil)
then
begin
ParcelStringGrid.Cells[0, ParcelStringGrid.Row] := 'X';
GlblLocateParcelFromList := True;
GlblParcelListSBLKey := SwisSBLKey;
ParcelListDialog.SendToBack;
TParcelTabForm(GlblParcelMaintenance).Show;
TParcelTabForm(GlblParcelMaintenance).BringToFront;
TParcelTabForm(GlblParcelMaintenance).LocateParcel1Click(TParcelTabForm(GlblParcelMaintenance).LocateParcel1);
end; {If ParcelViewOrModifyActive}
end; {If Found}
end; {ParcelStringGridDblClick}
{===========================================================}
Function TParcelListDialog.ParcelExistsInList(SwisSBLKey : String) : Boolean;
var
I : Integer;
begin
Result := False;
with ParcelStringGrid do
For I := 0 to (RowCount - 1) do
If ((Deblank(Cells[2, I]) <> '') and
(Take(26, Cells[2, I]) = Take(26, SwisSBLKey)))
then Result := True;
end; {ParcelExistsInList}
{===========================================================}
Procedure TParcelListDialog.ReportPrintHeader(Sender: TObject);
begin
with Sender as TBaseReport do
begin
{Print the date and page number.}
SectionTop := 0.25;
SectionLeft := 0.5;
SectionRight := PageWidth - 0.5;
SetFont('Times New Roman',8);
PrintHeader('Page: ' + IntToStr(CurrentPage), pjRight);
PrintHeader('Date: ' + DateToStr(Date) +
' Time: ' + FormatDateTime(TimeFormat, Now), pjLeft);
SectionTop := 0.5;
SetFont('Arial',14);
Underline := True;
Home;
CRLF;
PrintCenter('Parcel List ' + FileName, (PageWidth / 2));
SetFont('Times New Roman', 12);
CRLF;
CRLF;
Underline := False;
ClearTabs;
SetTab(0.5, pjLeft, 1.5, 0, BOXLINENONE, 0); {Parcel 1}
SetTab(2.1, pjLeft, 0.1, 0, BOXLINENONE, 0); {Checked off 1}
SetTab(2.5, pjLeft, 1.5, 0, BOXLINENONE, 0); {Parcel 2}
SetTab(4.1, pjLeft, 0.1, 0, BOXLINENONE, 0); {Checked off 2}
SetTab(4.5, pjLeft, 1.5, 0, BOXLINENONE, 0); {Parcel 3}
SetTab(6.1, pjLeft, 0.1, 0, BOXLINENONE, 0); {Checked off 3}
end; {with Sender as TBaseReport do}
end; {ReportPrintHeader}
{===========================================================}
Procedure TParcelListDialog.ReportPrint(Sender: TObject);
var
I : Integer;
begin
with Sender as TBaseReport do
begin
For I := 1 to NumItems do
begin
Print(#9 + GetParcelID(I));
If PrintCheckedStatus
then Print(#9 + ParcelStringGrid.Cells[0, I])
else Print(#9);
If ((I MOD 3) = 0)
then Println('');
If (LinesLeft < 5)
then NewPage;
ProgressDialog.Update(Self, IntToStr(I));
end; {For I := 1 to NumItems do}
end; {with Sender as TBaseReport do}
end; {ReportPrint}
{===========================================================}
Procedure TParcelListDialog.PrintButtonClick(Sender: TObject);
{CHG03232001-3: Add the ability to print, export, and import from the
parcel list.}
var
NewFileName : String;
Quit : Boolean;
begin
If PrintDialog.Execute
then
begin
PrintCheckedStatus := (MessageDlg('Do you want to print the checked status of each parcel?',
mtConfirmation, [mbYes, mbNo], 0) = idYes);
AssignPrinterSettings(PrintDialog, ReportPrinter, ReportFiler, [ptLaser], False, Quit);
If not Quit
then
begin
ProgressDialog.Start(NumItems, True, True);
{If they want to preview the print (i.e. have it
go to the screen), then we need to come up with
a unique file name to tell the ReportFiler
component where to put the output.
Once we have done that, we will execute the
report filer which will print the report to
that file. Then we will create and show the
preview print form and give it the name of the
file. When we are done, we will delete the file
and make sure that we go back to the original
directory.}
If PrintDialog.PrintToFile
then
begin
NewFileName := GetPrintFileName(Self.Caption, True);
ReportFiler.FileName := NewFileName;
try
PreviewForm := TPreviewForm.Create(self);
PreviewForm.FilePrinter.FileName := NewFileName;
PreviewForm.FilePreview.FileName := NewFileName;
PreviewForm.FilePreview.ZoomFactor := 130;
ReportFiler.Execute;
PreviewForm.ShowModal;
finally
PreviewForm.Free;
end; {If PrintRangeDlg.PreviewPrint}
end {They did not select preview, so we will go
right to the printer.}
else ReportPrinter.Execute;
ProgressDialog.Finish;
end; {If not Quit}
ResetPrinter(ReportPrinter);
end; {If PrintDialog.Execute}
end; {PrintButtonClick}
{===========================================================}
Procedure TParcelListDialog.ImportButtonClick(Sender: TObject);
var
Done, ValidEntry : Boolean;
ListFile, flRejects : TextFile;
ParcelID, SwisSBLKey, SBLKey : String;
LineNumber : Integer;
SBLRec : SBLRecord;
begin
Done := False;
LineNumber := 1;
OpenDialog.FilterIndex := 2;
If OpenDialog.Execute
then
begin
ClearParcelGrid(True);
AssignFile(ListFile, OpenDialog.FileName);
Reset(ListFile);
AssignFile(flRejects, glblProgramDir + 'ListRejects.txt');
Rewrite(flRejects);
repeat
ValidEntry := False;
Readln(ListFile, ParcelID);
ParcelID := Trim(ParcelID);
If EOF(ListFile)
then Done := True;
{If it is in dash dot format, convert it to full format.}
{FXX03312010-1(2.22.2.8)[I7182]: For some municipalities with odd SBLs, they don't have a length of 26.}
If (_Compare(Length(ParcelID), 26, coEqual) or
(_Compare(Pos('-', ParcelID), 0, coEqual) and
_Compare(Pos('.', ParcelID), 0, coEqual)))
then
begin
SwisSBLKey := ParcelID;
If _Locate(ParcelTable, [GetTaxRlYr, SwisSBLKey], '', [loParseSwisSBLKey])
then ValidEntry := True
else SwisSBLKey := '';
end
else
If _Compare(ParcelID[3], '/', coEqual)
then SwisSBLKey := ConvertSwisDashDotToSwisSBL(ParcelID,
PASDataModule.TYSwisCodeTable,
ValidEntry)
else
begin
ParcelTable.IndexName := 'BYTAXROLLYR_SBLKEY';
SBLRec := ConvertDashDotSBLToSegmentSBL(ParcelID, ValidEntry);
with SBLRec do
SBLKey := Take(3, Section) + Take(3, SubSection) +
Take(4, Block) + Take(3, Lot) + Take(3, Sublot) + Take(4, Suffix);
If _Locate(ParcelTable, [GetTaxRlYr, SBLKey], '', [loParseSBLOnly])
then
begin
SwisSBLKey := ParcelTable.FieldByName('SwisCode').AsString + SBLKey;
ValidEntry := True;
end
else SwisSBLKey := '';
ParcelTable.IndexName := 'BYTAXROLLYR_SWISSBLKEY';
end; {If _Compare(ParcelID, '/', coContains)}
If not ValidEntry
then
begin
ParcelTable.IndexName := 'BYACCOUNTNO';
If _Locate(ParcelTable, [ParcelID], '', [])
then
begin
ValidEntry := True;
SwisSBLKey := ExtractSSKey(ParcelTable);
end;
end; {If not ValidEntry}
If not ValidEntry
then
begin
ParcelTable.IndexName := 'BYPrintKey';
If _Locate(ParcelTable, [ParcelID], '', [])
then
begin
ValidEntry := True;
SwisSBLKey := ExtractSSKey(ParcelTable);
end;
end; {If not ValidEntry}
ParcelTable.IndexName := 'BYTAXROLLYR_SWISSBLKEY';
If ValidEntry
then
begin
If not AddOneParcel(SwisSBLKey)
then Writeln(flRejects, SwisSBLKey, ',', 'Already in list.');
end;
{Make sure that we can locate this parcel.}
If not GetParcel(ParcelTable, NumItems)
then
begin
MessageDlg('The parcel ' + ParcelID + ' on line ' +
IntToStr(LineNumber) + ' could not be found.' + #13 +
'It has not been added to the list.',
mtError, [mbOk], 0);
DeleteButtonClick(Sender);
Writeln(flRejects, SwisSBLKey, ',', 'Not found.');
end; {If not GetParcel(ParcelTable, NumItems)}
LineNumber := LineNumber + 1;
until Done;
CloseFile(ListFile);
FileName := OpenDialog.FileName;
SetCaption;
Modified := False;
CloseFile(flRejects);
end; {If OpenDialog.Execute}
end; {ImportButtonClick}
{===========================================================}
Procedure TParcelListDialog.ExportButtonClick(Sender: TObject);
var
I, ColumnNumber : Integer;
ListFile : TextFile;
SaveInDashDotFormat : Boolean;
begin
SaveDialog.FilterIndex := 2;
If SaveDialog.Execute
then
begin
SaveInDashDotFormat := (MessageDlg('Do you want to export the parcel IDs in dash dot format?' + #13 +
'If you answer no, the parcel IDs will be exported in full 26 character format.',
mtConfirmation, [mbYes, mbNo], 0) = idYes);
If SaveInDashDotFormat
then ColumnNumber := 1
else ColumnNumber := 2;
AssignFile(ListFile, SaveDialog.FileName);
Rewrite(ListFile);
For I := 1 to (ParcelStringGrid.RowCount - 1) do
If (Deblank(ParcelStringGrid.Cells[2, I]) <> '')
then Writeln(ListFile, ParcelStringGrid.Cells[ColumnNumber, I]);
CloseFile(ListFile);
MessageDlg('The parcel list has been exported to ' + SaveDialog.FileName + '.',
mtInformation, [mbOK], 0);
end; {If SaveDialog.Execute}
end; {ExportButtonClick}
{============================================================}
Procedure TParcelListDialog.SwitchRows(Row1,
Row2 : LongInt);
var
TempStr : String;
I : Integer;
begin
with ParcelStringGrid do
If ((Row1 >= 0) and
(Row1 <= (RowCount - 1)) and
(Row2 >= 0) and
(Row2 <= (RowCount - 1)))
then
For I := 0 to (ColCount - 1) do
begin
TempStr := Cells[I, Row1];
Cells[I, Row1] := Cells[I, Row2];
Cells[I, Row2] := TempStr;
end;
end; {SwitchRows}
{===========================================================}
Procedure TParcelListDialog.ParcelStringGridMouseDown(Sender: TObject;
Button: TMouseButton;
Shift: TShiftState;
X, Y: Integer);
{CHG11052001-2: Allow drag drop.}
var
DragStartCol : LongInt;
begin
Dragging := True;
ParcelStringGrid.Cursor := crDrag;
ParcelStringGrid.MouseToCell(X, Y, DragStartCol, DragStartRow);
end; {ParcelStringGridMouseDown}
{===========================================================}
Procedure TParcelListDialog.ParcelStringGridMouseUp(Sender: TObject;
Button: TMouseButton;
Shift: TShiftState;
X, Y: Integer);
{CHG11052001-2: Allow drag drop.}
var
DragEndCol, DragEndRow : LongInt;
begin
ParcelStringGrid.MouseToCell(X, Y, DragEndCol, DragEndRow);
If (DragStartRow <> DragEndRow)
then SwitchRows(DragStartRow, DragEndRow);
ParcelStringGrid.Cursor := crDefault;
Dragging := False;
end; {ParcelStringGridMouseUp}
{===========================================================}
Procedure TParcelListDialog.CloseFiles;
begin
SwisCodeTable.Close;
ParcelTable.Close;
end; {CloseFiles}
{===========================================================}
Procedure TParcelListDialog.FormCloseQuery( Sender: TObject;
var CanClose: Boolean);
begin
CheckAndSaveModifiedList;
end;
end. |
{***************************************************************
*
* Project : HTTPClient
* Unit Name: Main
* Purpose : Demonstrates use of HTTPClient component
* NOtes : Demo for Windows only
* Date : 21/01/2001 - 14:26:51
* Author: Hadi Hariri
* History :
*
****************************************************************}
unit Main;
interface
uses
{$IFDEF Linux}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QButtons,
QComCtrls,
{$ELSE}
Windows, Messages, Graphics, Controls, Forms, Dialogs, StdCtrls,
ExtCtrls, Buttons, ComCtrls,
{$ENDIF}
SysUtils, Classes, IdComponent, IdTCPConnection,
IdTCPClient, IdHTTP, IdBaseComponent, IdSSLOpenSSL, IdIntercept,
IdSSLIntercept, IdAntiFreezeBase, IdAntiFreeze, IdLogBase, IdLogDebug;
type
TForm1 = class(TForm)
IdAntiFreeze1: TIdAntiFreeze;
Panel1: TPanel;
memoHTML: TMemo;
HTTP: TIdHTTP;
StatusBar1: TStatusBar;
ProgressBar1: TProgressBar;
btnGo: TBitBtn;
btnStop: TBitBtn;
cbURL: TComboBox;
cbProtocol: TComboBox;
Label1: TLabel;
Label2: TLabel;
cbSSL: TCheckBox;
Label3: TLabel;
cbMethod: TComboBox;
GroupBox1: TGroupBox;
Label4: TLabel;
Label5: TLabel;
edUsername: TEdit;
edPassword: TEdit;
GroupBox2: TGroupBox;
Label6: TLabel;
Label7: TLabel;
edProxyServer: TEdit;
edProxyPort: TEdit;
GroupBox3: TGroupBox;
mePostData: TMemo;
GroupBox4: TGroupBox;
edPostFile: TEdit;
Label8: TLabel;
SpeedButton1: TSpeedButton;
OpenDialog1: TOpenDialog;
SSL: TIdConnectionInterceptOpenSSL;
Label9: TLabel;
edContentType: TEdit;
LogDebug: TIdLogDebug;
Memo1: TMemo;
Splitter1: TSplitter;
procedure btnGoClick(Sender: TObject);
procedure btnStopClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure cbURLChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure HTTPStatus(axSender: TObject; const axStatus: TIdStatus;
const asStatusText: string);
procedure HTTPWorkBegin(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCountMax: Integer);
procedure HTTPWorkEnd(Sender: TObject; AWorkMode: TWorkMode);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure HTTPWork(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCount: Integer);
procedure cbProtocolChange(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure edPostFileExit(Sender: TObject);
procedure mePostDataExit(Sender: TObject);
procedure cbSSLClick(Sender: TObject);
procedure LogDebugLogItem(ASender: TComponent; var AText: string);
private
bPostFile: Boolean;
public
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.btnGoClick(Sender: TObject);
var
Source: TMemoryStream;
Response: TStringStream;
begin
// Add the URL to the combo-box.
if cbURL.Items.IndexOf(cbURL.Text) = -1 then
cbURL.Items.Add(cbURL.Text);
Screen.Cursor := crHourGlass;
btnStop.Enabled := True;
btnGo.Enabled := False;
try
memoHTML.Clear;
// Set the properties for HTTP
HTTP.Request.Username := edUsername.Text;
HTTP.Request.Password := edPassword.Text;
HTTP.Request.ProxyServer := edProxyServer.Text;
HTTP.Request.ProxyPort := StrToIntDef(edProxyPort.Text, 80);
HTTP.Request.ContentType := edContentType.Text;
if cbSSL.Checked then
begin
HTTP.Intercept := SSL;
end
else
begin
HTTP.Intercept := LogDebug;
HTTP.InterceptEnabled := true;
end;
case cbMethod.ItemIndex of
0: // Head
begin
HTTP.Head(cbURL.Text);
memoHTML.Lines.Add('This is an example of some of the headers returned: ');
memoHTML.Lines.Add('---------------------------------------------------');
memoHTML.Lines.Add('Content-Type: ' + HTTP.Response.ContentType);
memoHTML.Lines.Add('Date: ' + DatetoStr(HTTP.Response.Date));
memoHTML.Lines.Add('');
memoHTML.Lines.Add('You can view all the headers by examining HTTP.Response');
end;
1: // Get
begin
memoHTML.Lines.Text := HTTP.Get(cbURL.Text);
end;
2: // Post
begin
Response := TStringStream.Create('');
try
if not bPostFile then
HTTP.Post(cbURL.Text, mePostData.Lines, Response)
else
begin
Source := TMemoryStream.Create;
try
Source.LoadFromFile(edPostFile.Text);
HTTP.Post(cbURL.Text, Source, Response);
finally
Source.Free;
end;
end;
memoHTML.Lines.Text := Response.DataString;
finally
Response.Free;
end;
end;
end;
finally
Screen.Cursor := crDefault;
btnStop.Enabled := False;
btnGo.Enabled := True;
end;
end;
procedure TForm1.btnStopClick(Sender: TObject);
begin
http.DisconnectSocket;
// Clicking this does not get rid of the hourclass cursor
btnStop.Enabled := False;
Screen.Cursor := crDefault;
end;
procedure TForm1.FormActivate(Sender: TObject);
begin
btnStop.Enabled := False;
cbMethod.ItemIndex := 1; // Set to GET
cbProtocol.ItemIndex := 0; // Set to 1.0
cbProtocol.OnChange(nil);
bPostFile := False;
// Load history
if FileExists(ExtractFilePath(ParamStr(0)) + 'history.dat') then
begin
cbURL.Items.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'history.dat');
end;
end;
procedure TForm1.cbURLChange(Sender: TObject);
begin
btnGo.Enabled := Length(cbURL.Text) > 0;
cbSSL.Checked := Pos('HTTPS', UpperCase(cbURL.Text)) > 0;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
// Set the progress bar
ProgressBar1.Parent := StatusBar1;
ProgressBar1.Top := 2;
ProgressBar1.Left := 1;
end;
procedure TForm1.HTTPStatus(axSender: TObject; const axStatus: TIdStatus;
const asStatusText: string);
begin
StatusBar1.Panels[1].Text := asStatusText;
end;
procedure TForm1.HTTPWorkBegin(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCountMax: Integer);
begin
ProgressBar1.Position := 0;
ProgressBar1.Max := AWorkcountMax;
if AWorkCountMax > 0 then
StatusBar1.Panels[1].Text := 'Transfering: ' + IntToStr(AWorkCountMax);
end;
procedure TForm1.HTTPWorkEnd(Sender: TObject; AWorkMode: TWorkMode);
begin
StatusBar1.Panels[1].Text := 'Done';
ProgressBar1.Position := 0;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
btnStop.OnClick(nil);
try
cbURL.Items.SaveToFile(ExtractFilePath(ParamStr(0)) + 'history.dat');
except
end;
end;
procedure TForm1.HTTPWork(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCount: Integer);
begin
if ProgressBar1.Max > 0 then
begin
StatusBar1.Panels[1].Text := IntToStr(AWorkCount) + ' bytes of ' +
IntToStr(ProgressBar1.Max) + ' bytes.';
ProgressBar1.Position := AWorkCount;
end
else
StatusBar1.Panels[1].Text := IntToStr(AworkCount) + ' bytes.';
end;
procedure TForm1.cbProtocolChange(Sender: TObject);
begin
case cbProtocol.ItemIndex of
0: HTTP.ProtocolVersion := pv1_0;
1: HTTP.ProtocolVersion := pv1_1;
end;
end;
procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
edPostFile.Text := OpenDialog1.FileName;
edPostFile.OnExit(nil);
end;
end;
procedure TForm1.edPostFileExit(Sender: TObject);
begin
if Length(edPostFile.Text) > 0 then
begin
mePostData.Clear;
bPostFile := True;
end;
end;
procedure TForm1.mePostDataExit(Sender: TObject);
begin
if mePostData.Lines.Count > 0 then
begin
edPostFile.Text := '';
bPostFile := False;
end;
end;
procedure TForm1.cbSSLClick(Sender: TObject);
var
p: Integer;
begin
// check if the url has proper protocol set
if cbSSL.Checked then
begin
if Pos('HTTPS', UpperCase(cbURL.Text)) <= 0 then
begin
p := Pos('://', UpperCase(cbURL.Text));
if p > 0 then
begin
cbURL.Text := 'https://' + Copy(cbURL.Text, p + 3, Length(cbURL.Text) -
(p + 2));
end
else
begin
cbURL.Text := 'https://' + cbURL.Text;
end;
end;
end
else
begin
if Pos('HTTPS', UpperCase(cbURL.Text)) > 0 then
begin
p := Pos('://', UpperCase(cbURL.Text));
cbURL.Text := 'http://' + Copy(cbURL.Text, p + 3, Length(cbURL.Text) - (p
+ 2));
end;
end;
end;
procedure TForm1.LogDebugLogItem(ASender: TComponent;
var AText: string);
begin
Memo1.Lines.Add(AText);
end;
end.
|
unit BCEditor.Highlighter.JSONImporter;
interface
uses
System.Classes, BCEditor.Highlighter, BCEditor.Highlighter.Colors;
procedure ImportFromFile(Highlighter: TBCEditorHighlighter; AFileName: string);
procedure ImportFromStream(Highlighter: TBCEditorHighlighter; AStream: TStream);
procedure ImportColorsFromFile(Highlighter: TBCEditorHighlighter; AFileName: string);
procedure ImportColorsFromStream(Highlighter: TBCEditorHighlighter; AStream: TStream);
implementation
uses
JsonDataObjects, System.SysUtils, Vcl.Graphics, Vcl.Forms, BCEditor.Consts, BCEditor.Editor.Base, BCEditor.Utils,
BCEditor.Highlighter.Attributes, BCEditor.Highlighter.Rules, BCEditor.Types, Vcl.Dialogs,
BCEditor.Highlighter.Token, BCEditor.Editor.CodeFolding.FoldRegions, BCEditor.Language,
BCEditor.Editor.SkipRegions, BCEditor.Highlighter.Info, BCEditor.Editor.CodeFolding.Types;
var
GMultiHighlighter: Boolean;
function StringToColorDef(const AString: string; const DefaultColor: TColor): Integer;
begin
if Trim(AString) = '' then
Result := DefaultColor
else
Result := StringToColor(AString);
end;
function StrToSet(const AString: string): TBCEditorCharSet;
var
i: Integer;
begin
Result := [];
for i := 1 to Length(AString) do
Result := Result + [AString[i]];
end;
function StrToBoolean(const AString: string): Boolean;
begin
if AString = '' then
Result := False
else
Result := StrToBool(AString);
end;
function StrToStrDef(const AString: string; const AStringDef: string): string;
begin
if Trim(AString) = '' then
Result := AStringDef
else
Result := AString
end;
function StrToFontStyle(const AString: string): TFontStyles;
begin
Result := [];
if Pos('Bold', AString) > 0 then
Include(Result, fsBold);
if Pos('Italic', AString) > 0 then
Include(Result, fsItalic);
if Pos('Underline', AString) > 0 then
Include(Result, fsUnderline);
if Pos('StrikeOut', AString) > 0 then
Include(Result, fsStrikeOut);
end;
function StrToBreakType(const AString: string): TBCEditorBreakType;
begin
if (AString = 'Any') or (AString = '') then
Result := btAny
else
if AString = 'Term' then
Result := btTerm
else
Result := btUnspecified;
end;
function StrToRegionType(const AString: string): TBCEditorSkipRegionItemType;
begin
if AString = 'SingleLine' then
Result := ritSingleLineComment
else
if AString = 'MultiLine' then
Result := ritMultiLineComment
else
Result := ritString;
end;
function StrToRangeType(const AString: string): TBCEditorRangeType;
begin
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_ADDRESS then
Result := ttAddress
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_CHARACTER then
Result := ttChar
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_COMMENT then
Result := ttComment
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_DIRECTIVE then
Result := ttDirective
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_FLOAT then
Result := ttFloat
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_HEX then
Result := ttHex
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_MAIL_TO_LINK then
Result := ttMailtoLink
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_NUMBER then
Result := ttNumber
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_OCTAL then
Result := ttOctal
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_RESERVED_WORD then
Result := ttReservedWord
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_STRING then
Result := ttString
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_SYMBOL then
Result := ttSymbol
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_WEB_LINK then
Result := ttWebLink
else
Result := ttUnspecified;
end;
function StrToTokenKind(const AString: string): Integer;
begin
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_ADDRESS then
Result := Integer(ttAddress)
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_CHARACTER then
Result := Integer(ttChar)
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_COMMENT then
Result := Integer(ttComment)
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_DIRECTIVE then
Result := Integer(ttDirective)
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_FLOAT then
Result := Integer(ttFloat)
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_HEX then
Result := Integer(ttHex)
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_MAIL_TO_LINK then
Result := Integer(ttMailtoLink)
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_NUMBER then
Result := Integer(ttNumber)
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_OCTAL then
Result := Integer(ttOctal)
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_RESERVED_WORD then
Result := Integer(ttReservedWord)
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_STRING then
Result := Integer(ttString)
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_SYMBOL then
Result := Integer(ttSymbol)
else
if AString = BCEDITOR_ATTRIBUTE_ELEMENT_WEB_LINK then
Result := Integer(ttWebLink)
else
Result := Integer(ttUnspecified);
end;
procedure ImportInfo(AInfo: TBCEditorHighlighterInfo; InfoObject: TJsonObject);
begin
if Assigned(InfoObject) then
begin
{ General }
GMultiHighlighter := StrToBoolean(InfoObject['General']['MultiHighlighter'].Value);
AInfo.General.Version := InfoObject['General']['Version'].Value;
AInfo.General.Date := InfoObject['General']['Date'].Value;
AInfo.General.Sample := InfoObject['General']['Sample'].Value;
{ Author }
AInfo.Author.Name := InfoObject['Author']['Name'].Value;
AInfo.Author.Email := InfoObject['Author']['Email'].Value;
AInfo.Author.Comments := InfoObject['Author']['Comments'].Value;
end;
end;
procedure ImportColorsInfo(AInfo: TBCEditorHighlighterInfo; InfoObject: TJsonObject);
begin
if Assigned(InfoObject) then
begin
{ General }
AInfo.General.Version := InfoObject['General']['Version'].Value;
AInfo.General.Date := InfoObject['General']['Date'].Value;
{ Author }
AInfo.Author.Name := InfoObject['Author']['Name'].Value;
AInfo.Author.Email := InfoObject['Author']['Email'].Value;
AInfo.Author.Comments := InfoObject['Author']['Comments'].Value;
end;
end;
procedure ImportEditorProperties(AEditor: TBCBaseEditor; EditorObject: TJsonObject);
begin
if Assigned(EditorObject) then
AEditor.URIOpener := StrToBoolDef(EditorObject['URIOpener'].Value, False);
end;
procedure ImportColorsEditorProperties(AEditor: TBCBaseEditor; EditorObject: TJsonObject);
var
ColorsObject, FontsObject, FontSizesObject: TJsonObject;
begin
if Assigned(EditorObject) then
begin
ColorsObject := EditorObject['Colors'].ObjectValue;
if Assigned(ColorsObject) then
begin
AEditor.BackgroundColor := StringToColorDef(ColorsObject['Background'].Value, AEditor.BackgroundColor);
AEditor.ActiveLine.Color := StringToColorDef(ColorsObject['ActiveLine'].Value, AEditor.ActiveLine.Color);
AEditor.CodeFolding.Colors.Background := StringToColorDef(ColorsObject['CodeFoldingBackground'].Value, AEditor.CodeFolding.Colors.Background);
AEditor.CodeFolding.Colors.CollapsedLine := StringToColorDef(ColorsObject['CodeFoldingCollapsedLine'].Value, AEditor.CodeFolding.Colors.CollapsedLine);
AEditor.CodeFolding.Colors.FoldingLine := StringToColorDef(ColorsObject['CodeFoldingFoldingLine'].Value, AEditor.CodeFolding.Colors.FoldingLine);
AEditor.CodeFolding.Colors.IndentHighlight := StringToColorDef(ColorsObject['CodeFoldingIndentHighlight'].Value, AEditor.CodeFolding.Colors.IndentHighlight);
AEditor.CodeFolding.Hint.Colors.Background := StringToColorDef(ColorsObject['CodeFoldingHintBackground'].Value, AEditor.CodeFolding.Hint.Colors.Background);
AEditor.CodeFolding.Hint.Colors.Border := StringToColorDef(ColorsObject['CodeFoldingHintBorder'].Value, AEditor.CodeFolding.Hint.Colors.Border);
AEditor.CodeFolding.Hint.Font.Color := StringToColorDef(ColorsObject['CodeFoldingHintText'].Value, AEditor.CodeFolding.Hint.Font.Color);
AEditor.CompletionProposal.Colors.Background := StringToColorDef(ColorsObject['CompletionProposalBackground'].Value, AEditor.CompletionProposal.Colors.Background);
AEditor.CompletionProposal.Font.Color := StringToColorDef(ColorsObject['CompletionProposalForeground'].Value, AEditor.CompletionProposal.Font.Color);
AEditor.CompletionProposal.Colors.Border := StringToColorDef(ColorsObject['CompletionProposalBorder'].Value, AEditor.CompletionProposal.Colors.Border);
AEditor.CompletionProposal.Colors.SelectedBackground := StringToColorDef(ColorsObject['CompletionProposalSelectedBackground'].Value, AEditor.CompletionProposal.Colors.SelectedBackground);
AEditor.CompletionProposal.Colors.SelectedText := StringToColorDef(ColorsObject['CompletionProposalSelectedText'].Value, AEditor.CompletionProposal.Colors.SelectedText);
AEditor.LeftMargin.Color := StringToColorDef(ColorsObject['LeftMarginBackground'].Value, AEditor.LeftMargin.Color);
AEditor.LeftMargin.Font.Color := StringToColorDef(ColorsObject['LeftMarginLineNumbers'].Value, AEditor.LeftMargin.Font.Color);
AEditor.LeftMargin.Bookmarks.Panel.Color := StringToColorDef(ColorsObject['LeftMarginBookmarkPanel'].Value, AEditor.LeftMargin.Bookmarks.Panel.Color);
AEditor.LeftMargin.LineState.Colors.Modified := StringToColorDef(ColorsObject['LeftMarginLineStateModified'].Value, AEditor.LeftMargin.LineState.Colors.Modified);
AEditor.LeftMargin.LineState.Colors.Normal := StringToColorDef(ColorsObject['LeftMarginLineStateNormal'].Value, AEditor.LeftMargin.LineState.Colors.Normal);
AEditor.MatchingPair.Colors.Matched := StringToColorDef(ColorsObject['MatchingPairMatched'].Value, AEditor.MatchingPair.Colors.Matched);
AEditor.MatchingPair.Colors.Unmatched := StringToColorDef(ColorsObject['MatchingPairUnmatched'].Value, AEditor.MatchingPair.Colors.Unmatched);
AEditor.RightMargin.Colors.Edge := StringToColorDef(ColorsObject['RightEdge'].Value, AEditor.RightMargin.Colors.Edge);
AEditor.RightMargin.Colors.MovingEdge := StringToColorDef(ColorsObject['RightMovingEdge'].Value, AEditor.RightMargin.Colors.MovingEdge);
AEditor.Search.Highlighter.Colors.Background := StringToColorDef(ColorsObject['SearchHighlighterBackground'].Value, AEditor.Search.Highlighter.Colors.Background);
AEditor.Search.Highlighter.Colors.Foreground := StringToColorDef(ColorsObject['SearchHighlighterForeground'].Value, AEditor.Search.Highlighter.Colors.Foreground);
AEditor.Search.Map.Colors.ActiveLine := StringToColorDef(ColorsObject['SearchMapActiveLine'].Value, AEditor.Search.Map.Colors.ActiveLine);
AEditor.Search.Map.Colors.Background := StringToColorDef(ColorsObject['SearchMapBackground'].Value, AEditor.Search.Map.Colors.Background);
AEditor.Search.Map.Colors.Foreground := StringToColorDef(ColorsObject['SearchMapForeground'].Value, AEditor.Search.Map.Colors.Foreground);
AEditor.Selection.Colors.Background := StringToColorDef(ColorsObject['SelectionBackground'].Value, AEditor.Selection.Colors.Background);
AEditor.Selection.Colors.Foreground := StringToColorDef(ColorsObject['SelectionForeground'].Value, AEditor.Selection.Colors.Foreground);
end;
FontsObject := EditorObject['Fonts'].ObjectValue;
if Assigned(FontsObject) then
begin
AEditor.LeftMargin.Font.Name := StrToStrDef(FontsObject['LineNumbers'].Value, AEditor.LeftMargin.Font.Name);
AEditor.Font.Name := StrToStrDef(FontsObject['Text'].Value, AEditor.Font.Name);
AEditor.Minimap.Font.Name := StrToStrDef(FontsObject['Minimap'].Value, AEditor.Minimap.Font.Name);
AEditor.CodeFolding.Hint.Font.Name := StrToStrDef(FontsObject['CodeFoldingHint'].Value, AEditor.CodeFolding.Hint.Font.Name);
AEditor.CompletionProposal.Font.Name := StrToStrDef(FontsObject['CompletionProposal'].Value, AEditor.CompletionProposal.Font.Name);
end;
FontSizesObject := EditorObject['FontSizes'].ObjectValue;
if Assigned(FontSizesObject) then
begin
AEditor.LeftMargin.Font.Size := StrToIntDef(FontSizesObject['LineNumbers'].Value, AEditor.LeftMargin.Font.Size);
AEditor.Font.Size := StrToIntDef(FontSizesObject['Text'].Value, AEditor.Font.Size);
AEditor.Minimap.Font.Size := StrToIntDef(FontSizesObject['Minimap'].Value, AEditor.Minimap.Font.Size);
AEditor.CodeFolding.Hint.Font.Size := StrToIntDef(FontSizesObject['CodeFoldingHint'].Value, AEditor.CodeFolding.Hint.Font.Size);
AEditor.CompletionProposal.Font.Size := StrToIntDef(FontSizesObject['CompletionProposal'].Value, AEditor.CompletionProposal.Font.Size);
end;
end;
end;
procedure ImportAttributes(AHighlighterAttribute: TBCEditorHighlighterAttribute; AttributesObject: TJsonObject);
begin
if Assigned(AttributesObject) then
begin
AHighlighterAttribute.Element := AttributesObject['Element'].Value;
AHighlighterAttribute.ParentForeground := StrToBoolean(AttributesObject['ParentForeground'].Value);
AHighlighterAttribute.ParentBackground := StrToBoolean(AttributesObject['ParentBackground'].Value);
AHighlighterAttribute.UseParentElementForTokens := StrToBoolean(AttributesObject['UseParentElementForTokens'].Value);
end;
end;
procedure ImportKeyList(AKeyList: TBCEditorKeyList; KeyListObject: TJsonObject);
begin
if Assigned(KeyListObject) then
begin
AKeyList.TokenType := StrToRangeType(KeyListObject['Type'].Value);
AKeyList.KeyList.Text := KeyListObject['Words'].Value;
ImportAttributes(AKeyList.Attribute, KeyListObject['Attributes'].ObjectValue);
end;
end;
procedure ImportSet(ASet: TBCEditorSet; SetObject: TJsonObject);
begin
if Assigned(SetObject) then
begin
ASet.CharSet := StrToSet(SetObject['Symbols'].Value);
ImportAttributes(ASet.Attribute, SetObject['Attributes'].ObjectValue);
end;
end;
procedure ImportRange(ARange: TBCEditorRange; RangeObject: TJsonObject; AParentRange: TBCEditorRange = nil; ASkipBeforeSubRules: Boolean = False); { Recursive method }
var
i, j: Integer;
LFileName: string;
NewRange: TBCEditorRange;
NewKeyList: TBCEditorKeyList;
NewSet: TBCEditorSet;
SubRulesObject, PropertiesObject, TokenRangeObject: TJsonObject;
JSONObject: TJsonObject;
begin
if Assigned(RangeObject) then
begin
LFileName := RangeObject['File'].Value;
if GMultiHighlighter and (LFileName <> '') then
begin
JSONObject := TJsonObject.ParseFromFile(Format('%sHighlighters\%s', [ExtractFilePath(Application.ExeName), LFileName])) as TJsonObject;
if Assigned(JSONObject) then
try
TokenRangeObject := JSONObject['Highlighter']['MainRules'].ObjectValue;
{ You can include MainRules... }
if TokenRangeObject['Name'].Value = RangeObject['IncludeRange'].Value then
ImportRange(AParentRange, TokenRangeObject, nil, True)
else
{ or SubRules... }
begin
SubRulesObject := TokenRangeObject['SubRules'].ObjectValue;
if Assigned(SubRulesObject) then
for i := 0 to SubRulesObject.Count - 1 do
begin
if SubRulesObject.Names[i] = 'Range' then
for j := 0 to SubRulesObject.Items[i].ArrayValue.Count - 1 do
if SubRulesObject.Items[i].ArrayValue.O[j].S['Name'] = RangeObject['IncludeRange'].Value then
begin
ImportRange(ARange, SubRulesObject.Items[i].ArrayValue.O[j]);
Break;
end;
end;
end;
finally
JSONObject.Free;
end;
end
else
begin
if not ASkipBeforeSubRules then
begin
ARange.Clear;
ARange.CaseSensitive := StrToBoolean(RangeObject['CaseSensitive'].Value);
ImportAttributes(ARange.Attribute, RangeObject['Attributes'].ObjectValue);
if RangeObject['Delimiters'].Value <> '' then
ARange.Delimiters := StrToSet(RangeObject['Delimiters'].Value);
ARange.TokenType := StrToRangeType(RangeObject['Type'].Value);
PropertiesObject := RangeObject['Properties'].ObjectValue;
if Assigned(PropertiesObject) then
begin
ARange.CloseOnEol := StrToBoolean(PropertiesObject['CloseOnEol'].Value);
ARange.CloseOnTerm := StrToBoolean(PropertiesObject['CloseOnTerm'].Value);
ARange.AlternativeClose := PropertiesObject['AlternativeClose'].Value;
end;
ARange.OpenToken.Clear;
ARange.OpenToken.BreakType := btAny;
ARange.CloseToken.Clear;
ARange.CloseToken.BreakType := btAny;
TokenRangeObject := RangeObject['TokenRange'].ObjectValue;
if Assigned(TokenRangeObject) then
ARange.AddTokenRange(TokenRangeObject['Open'].Value, TokenRangeObject['Close'].Value);
end;
{ Sub rules }
SubRulesObject := RangeObject['SubRules'].ObjectValue;
if Assigned(SubRulesObject) then
begin
for i := 0 to SubRulesObject.Count - 1 do
begin
if SubRulesObject.Names[i] = 'Range' then
for j := 0 to SubRulesObject.Items[i].ArrayValue.Count - 1 do
begin
NewRange := TBCEditorRange.Create;
ImportRange(NewRange, SubRulesObject.Items[i].ArrayValue.O[j], ARange); { ARange is for the MainRules include }
ARange.AddRange(NewRange);
end
else
if SubRulesObject.Names[i] = 'KeyList' then
for j := 0 to SubRulesObject.Items[i].ArrayValue.Count - 1 do
begin
NewKeyList := TBCEditorKeyList.Create;
ImportKeyList(NewKeyList, SubRulesObject.Items[i].ArrayValue.O[j]);
ARange.AddKeyList(NewKeyList);
end
else
if SubRulesObject.Names[i] = 'Set' then
for j := 0 to SubRulesObject.Items[i].ArrayValue.Count - 1 do
begin
NewSet := TBCEditorSet.Create;
ImportSet(NewSet, SubRulesObject.Items[i].ArrayValue.O[j]);
ARange.AddSet(NewSet);
end
end;
end;
end;
end;
end;
procedure ImportCompletionProposal(ASkipRegions: TBCEditorSkipRegions; CodeFoldingObject: TJsonObject);
var
i: Integer;
SkipRegionItem: TBCEditorSkipRegionItem;
begin
if not Assigned(CodeFoldingObject) then
Exit;
{ Skip regions }
for i := 0 to CodeFoldingObject['SkipRegion'].ArrayValue.Count - 1 do
begin
SkipRegionItem := ASkipRegions.Add(CodeFoldingObject['SkipRegion'].ArrayValue.Items[i].ObjectValue['OpenToken'].Value,
CodeFoldingObject['SkipRegion'].ArrayValue.Items[i].ObjectValue['CloseToken'].Value);
SkipRegionItem.RegionType := StrToRegionType(CodeFoldingObject['SkipRegion'].ArrayValue.Items[i].ObjectValue['RegionType'].Value);
SkipRegionItem.SkipEmptyChars := StrToBoolean(CodeFoldingObject['SkipRegion'].ArrayValue.Items[i].ObjectValue['SkipEmptyChars'].Value);
end;
end;
procedure ImportCodeFolding(AEditor: TBCBaseEditor; AFoldRegions: TBCEditorCodeFoldingRegions; CodeFoldingObject: TJsonObject);
var
i: Integer;
SkipRegionType: TBCEditorSkipRegionItemType;
MemberObject: TJsonObject;
FoldRegionItem: TBCEditorFoldRegionItem;
SkipRegionItem: TBCEditorSkipRegionItem;
begin
if not Assigned(CodeFoldingObject) then
Exit;
if CodeFoldingObject.Contains('Options') then
AFoldRegions.StringEscapeChar := CodeFoldingObject['Options'].ObjectValue['StringEscapeChar'].Value[1]
else
AFoldRegions.StringEscapeChar := #0;
{ Skip regions }
if CodeFoldingObject.Contains('SkipRegion') then
for i := 0 to CodeFoldingObject['SkipRegion'].ArrayValue.Count - 1 do
begin
SkipRegionType := StrToRegionType(CodeFoldingObject['SkipRegion'].ArrayValue.Items[i].ObjectValue['RegionType'].Value);
if (SkipRegionType = ritMultiLineComment) and (cfoFoldMultilineComments in AEditor.CodeFolding.Options) then
begin
FoldRegionItem := AFoldRegions.Add(CodeFoldingObject['SkipRegion'].ArrayValue.Items[i].ObjectValue['OpenToken'].Value,
CodeFoldingObject['SkipRegion'].ArrayValue.Items[i].ObjectValue['CloseToken'].Value);
FoldRegionItem.NoSubs := True;
end
else
begin
SkipRegionItem := AFoldRegions.SkipRegions.Add(CodeFoldingObject['SkipRegion'].ArrayValue.Items[i].ObjectValue['OpenToken'].Value,
CodeFoldingObject['SkipRegion'].ArrayValue.Items[i].ObjectValue['CloseToken'].Value);
SkipRegionItem.RegionType := SkipRegionType;
SkipRegionItem.SkipEmptyChars := StrToBoolean(CodeFoldingObject['SkipRegion'].ArrayValue.Items[i].ObjectValue['SkipEmptyChars'].Value);
end;
end;
{ Fold regions }
if CodeFoldingObject.Contains('FoldRegion') then
for i := 0 to CodeFoldingObject['FoldRegion'].ArrayValue.Count - 1 do
begin
FoldRegionItem := AFoldRegions.Add(CodeFoldingObject['FoldRegion'].ArrayValue.Items[i].ObjectValue['OpenToken'].Value,
CodeFoldingObject['FoldRegion'].ArrayValue.Items[i].ObjectValue['CloseToken'].Value);
MemberObject := CodeFoldingObject['FoldRegion'].ArrayValue.Items[i].ObjectValue['Properties'].ObjectValue;
if Assigned(MemberObject) then
begin
{ Options }
FoldRegionItem.BeginningOfLine := StrToBoolean(MemberObject['BeginningOfLine'].Value);
FoldRegionItem.SharedClose := StrToBoolean(MemberObject['SharedClose'].Value);
FoldRegionItem.OpenIsClose := StrToBoolean(MemberObject['OpenIsClose'].Value);
FoldRegionItem.NoSubs := StrToBoolean(MemberObject['NoSubs'].Value);
FoldRegionItem.SkipIfFoundAfterOpenToken := MemberObject['SkipIfFoundAfterOpenToken'].Value;
FoldRegionItem.BreakIfNotFoundBeforeNextRegion := MemberObject['BreakIfNotFoundBeforeNextRegion'].Value;
end;
end;
end;
procedure ImportMatchingPair(AMatchingPairs: TList; MatchingPairObject: TJsonObject);
var
i: Integer;
TokenMatch: PBCEditorMatchingPairToken;
begin
if not Assigned(MatchingPairObject) then
Exit;
{ Matching token pairs }
for i := 0 to MatchingPairObject['Pairs'].ArrayValue.Count - 1 do
begin
{ Add element }
New(TokenMatch);
TokenMatch.OpenToken := MatchingPairObject['Pairs'].ArrayValue.Items[i].ObjectValue['OpenToken'].Value;
TokenMatch.CloseToken := MatchingPairObject['Pairs'].ArrayValue.Items[i].ObjectValue['CloseToken'].Value;
AMatchingPairs.Add(TokenMatch)
end;
end;
procedure ImportElements(AStyles: TList; ColorsObject: TJsonObject);
var
i: Integer;
Element: PBCEditorHighlighterElement;
begin
if not Assigned(ColorsObject) then
Exit;
for i := 0 to ColorsObject['Elements'].ArrayValue.Count - 1 do
begin
New(Element);
Element.Background := StringToColorDef(ColorsObject['Elements'].ArrayValue.Items[i].ObjectValue['Background'].Value, clWindow);
Element.Foreground := StringToColorDef(ColorsObject['Elements'].ArrayValue.Items[i].ObjectValue['Foreground'].Value, clWindowText);
Element.Name := ColorsObject['Elements'].ArrayValue.Items[i].ObjectValue['Name'].Value;
Element.Style := StrToFontStyle(ColorsObject['Elements'].ArrayValue.Items[i].ObjectValue['Style'].Value);
AStyles.Add(Element)
end;
end;
procedure ImportHighlighter(Highlighter: TBCEditorHighlighter; JSONObject: TJsonObject);
var
Editor: TBCBaseEditor;
begin
Editor := Highlighter.Editor as TBCBaseEditor;
Highlighter.Clear;
ImportInfo(Highlighter.Info, JSONObject['Highlighter']['Info'].ObjectValue);
ImportEditorProperties(Editor, JSONObject['Highlighter']['Editor'].ObjectValue);
ImportRange(Highlighter.MainRules, JSONObject['Highlighter']['MainRules'].ObjectValue);
ImportCodeFolding(Editor, Highlighter.CodeFoldingRegions, JSONObject['CodeFolding'].ObjectValue);
ImportMatchingPair(Highlighter.MatchingPairs, JSONObject['MatchingPair'].ObjectValue);
ImportCompletionProposal(Highlighter.CompletionProposalSkipRegions, JSONObject['CompletionProposal'].ObjectValue);
end;
procedure ImportColors(Highlighter: TBCEditorHighlighter; JSONObject: TJsonObject);
begin
Highlighter.Colors.Clear;
ImportColorsInfo(Highlighter.Colors.Info, JSONObject['Colors']['Info'].ObjectValue);
ImportColorsEditorProperties(Highlighter.Editor as TBCBaseEditor, JSONObject['Colors']['Editor'].ObjectValue);
ImportElements(Highlighter.Colors.Styles, JSONObject['Colors'].ObjectValue);
end;
procedure ImportFromStream(Highlighter: TBCEditorHighlighter; AStream: TStream);
var
JSONObject: TJsonObject;
begin
JSONObject := TJsonObject.ParseFromStream(AStream) as TJsonObject;
if Assigned(JSONObject) then
try
ImportHighlighter(Highlighter, JSONObject);
finally
JSONObject.Free;
end;
end;
procedure ImportFromFile(Highlighter: TBCEditorHighlighter; AFileName: string);
var
JSONObject: TJsonObject;
begin
if FileExists(AFileName) then
begin
JSONObject := TJsonObject.ParseFromFile(AFileName) as TJsonObject;
try
if Assigned(JSONObject) then
ImportHighlighter(Highlighter, JSONObject);
finally
JSONObject.Free
end;
end
else
MessageDialog(Format(SBCEditorImporterFileNotFound, [AFileName]), mtError, [mbOK]);
end;
procedure ImportColorsFromStream(Highlighter: TBCEditorHighlighter; AStream: TStream);
var
JSONObject: TJsonObject;
begin
JSONObject := TJsonObject.ParseFromStream(AStream) as TJsonObject;
if Assigned(JSONObject) then
try
ImportColors(Highlighter, JSONObject);
finally
JSONObject.Free;
end;
end;
procedure ImportColorsFromFile(Highlighter: TBCEditorHighlighter; AFileName: string);
var
JSONObject: TJsonObject;
begin
if FileExists(AFileName) then
begin
JSONObject := TJsonObject.ParseFromFile(AFileName) as TJsonObject;
if Assigned(JSONObject) then
try
ImportColors(Highlighter, JSONObject);
finally
JSONObject.Free;
end;
end
else
MessageDialog(Format(SBCEditorImporterFileNotFound, [AFileName]), mtError, [mbOK]);
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls,
//GLS
GLScene, GLObjects, GLVectorGeometry, GLTexture, GLCadencer,
GLWin32Viewer, GLColor, GLCrossPlatform, GLCoordinates, GLMaterial,
GLSimpleNavigation, GLBaseClasses;
type
TForm1 = class(TForm)
GLSceneViewer1: TGLSceneViewer;
GLScene1: TGLScene;
GLCamera1: TGLCamera;
DummyCube1: TGLDummyCube;
GLLightSource1: TGLLightSource;
GLCadencer1: TGLCadencer;
GLSimpleNavigation1: TGLSimpleNavigation;
procedure FormCreate(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
const
cSize = 5;
procedure TForm1.FormCreate(Sender: TObject);
var
x, y, z : Integer;
cube : TGLCube;
factor, cubeSize : Single;
Color : TColor;
begin
// bench only creation and 1st render (with lists builds, etc...)
factor:=70/(cSize*2+1);
cubeSize:=0.4*factor;
for x := -cSize to cSize do
for y := -cSize to cSize do
for z := -cSize to cSize do
begin
cube := TGLCube(DummyCube1.AddNewChild(TGLCube));
cube.Position.AsVector := PointMake(factor * x, factor * y, factor * z);
cube.CubeWidth := cubeSize;
cube.CubeHeight := cubeSize;
cube.CubeDepth := cubeSize;
cube.Material.BlendingMode := bmTransparency;
with cube.Material.FrontProperties do
begin
Color := Random(1);
Diffuse.Color := VectorLerp(clrBlue, clrWhite, (x * x + y * y + z * z)
/ (cSize * cSize * 3));
Diffuse.Alpha := 0.5;
end;
end;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
begin
DummyCube1.TurnAngle:=90*newTime; // 90° per second
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX_ASE_Lexer;
{$IFDEF FPC}
{$mode delphi}
{$ENDIF}
interface
uses
SysUtils, Classes, {$IFNDEF FPC}System.Generics.Defaults, {$ENDIF}
TypInfo;
type
TASEToken = (atUnknown, atEOF, atKeyWord, atIdent, atString, atInteger,
atFloat, atColon, atOpenBracket, atCloseBracket, atComma);
TKeyWord = (kw_UNKNOWN, // special position, for all unknown key words
kw_3DSMAX_ASCIIEXPORT,
kw_COMMENT,
kw_SCENE,
kw_SCENE_FILENAME,
kw_SCENE_FIRSTFRAME,
kw_SCENE_LASTFRAME,
kw_SCENE_FRAMESPEED,
kw_SCENE_TICKSPERFRAME,
kw_SCENE_BACKGROUND_STATIC,
kw_SCENE_AMBIENT_STATIC,
kw_MATERIAL_LIST,
kw_MATERIAL_COUNT,
kw_MATERIAL,
kw_MATERIAL_NAME,
kw_MATERIAL_CLASS,
kw_MATERIAL_AMBIENT,
kw_MATERIAL_DIFFUSE,
kw_MATERIAL_SPECULAR,
kw_MATERIAL_SHINE,
kw_MATERIAL_SHINESTRENGTH,
kw_MATERIAL_TRANSPARENCY,
kw_MATERIAL_WIRESIZE,
kw_MATERIAL_SHADING,
kw_MATERIAL_XP_FALLOFF,
kw_MATERIAL_SELFILLUM,
kw_MATERIAL_FALLOFF,
kw_MATERIAL_XP_TYPE,
kw_NUMSUBMTLS,
kw_SUBMATERIAL,
kw_MAP_DIFFUSE,
kw_MAP_NAME,
kw_MAP_CLASS,
kw_MAP_SUBNO,
kw_MAP_AMOUNT,
kw_BITMAP,
kw_MAP_TYPE,
kw_UVW_U_OFFSET,
kw_UVW_V_OFFSET,
kw_UVW_U_TILING,
kw_UVW_V_TILING,
kw_UVW_ANGLE,
kw_UVW_BLUR,
kw_UVW_BLUR_OFFSET,
kw_UVW_NOUSE_AMT,
kw_UVW_NOISE_SIZE,
kw_UVW_NOISE_LEVEL,
kw_UVW_NOISE_PHASE,
kw_BITMAP_FILTER,
kw_GEOMOBJECT,
kw_NODE_NAME,
kw_NODE_TM,
// kw_NODE_NAME,
kw_INHERIT_POS,
kw_INHERIT_ROT,
kw_INHERIT_SCL,
kw_TM_ROW0,
kw_TM_ROW1,
kw_TM_ROW2,
kw_TM_ROW3,
kw_TM_POS,
kw_TM_ROTAXIS,
kw_TM_ROTANGLE,
kw_TM_SCALE,
kw_TM_SCALEAXIS,
kw_TM_SCALEAXISANG,
kw_MESH,
kw_TIMEVALUE,
kw_MESH_NUMVERTEX,
kw_MESH_NUMFACES,
kw_MESH_VERTEX_LIST,
kw_MESH_VERTEX,
kw_MESH_FACE_LIST,
kw_MESH_FACE,
kw_MESH_SMOOTHING,
kw_MESH_MTLID,
kw_MESH_NUMTVERTEX,
kw_MESH_TVERTLIST,
kw_MESH_TVERT,
kw_MESH_NUMTVFACES,
kw_MESH_TFACELIST,
kw_MESH_TFACE,
kw_MESH_NORMALS,
kw_MESH_FACENORMAL,
kw_MESH_VERTEXNORMAL,
kw_PROP_MOTIONBLUR,
kw_PROP_CASTSHADOW,
kw_PROP_RECVSHADOW,
kw_MATERIAL_REF
);
TKeyWordRec = record
Str: WideString;
Hash: Integer;
end;
const
{$J+}
// hash table for fast text processing
// completed in implementation section
KEY_WORDS: array[TKeyWord] of TKeyWordRec = (
(Str: '' ),
(Str: '*3DSMAX_ASCIIEXPORT' ),
(Str: '*COMMENT' ),
(Str: '*SCENE' ),
(Str: '*SCENE_FILENAME' ),
(Str: '*SCENE_FIRSTFRAME' ),
(Str: '*SCENE_LASTFRAME' ),
(Str: '*SCENE_FRAMESPEED' ),
(Str: '*SCENE_TICKSPERFRAME' ),
(Str: '*SCENE_BACKGROUND_STATIC' ),
(Str: '*SCENE_AMBIENT_STATIC' ),
(Str: '*MATERIAL_LIST' ),
(Str: '*MATERIAL_COUNT' ),
(Str: '*MATERIAL' ),
(Str: '*MATERIAL_NAME' ),
(Str: '*MATERIAL_CLASS' ),
(Str: '*MATERIAL_AMBIENT' ),
(Str: '*MATERIAL_DIFFUSE' ),
(Str: '*MATERIAL_SPECULAR' ),
(Str: '*MATERIAL_SHINE' ),
(Str: '*MATERIAL_SHINESTRENGTH' ),
(Str: '*MATERIAL_TRANSPARENCY' ),
(Str: '*MATERIAL_WIRESIZE' ),
(Str: '*MATERIAL_SHADING' ),
(Str: '*MATERIAL_XP_FALLOFF' ),
(Str: '*MATERIAL_SELFILLUM' ),
(Str: '*MATERIAL_FALLOFF' ),
(Str: '*MATERIAL_XP_TYPE' ),
(Str: '*NUMSUBMTLS' ),
(Str: '*SUBMATERIAL' ),
(Str: '*MAP_DIFFUSE' ),
(Str: '*MAP_NAME' ),
(Str: '*MAP_CLASS' ),
(Str: '*MAP_SUBNO' ),
(Str: '*MAP_AMOUNT' ),
(Str: '*BITMAP' ),
(Str: '*MAP_TYPE' ),
(Str: '*UVW_U_OFFSET' ),
(Str: '*UVW_V_OFFSET' ),
(Str: '*UVW_U_TILING' ),
(Str: '*UVW_V_TILING' ),
(Str: '*UVW_ANGLE' ),
(Str: '*UVW_BLUR' ),
(Str: '*UVW_BLUR_OFFSET' ),
(Str: '*UVW_NOUSE_AMT' ),
(Str: '*UVW_NOISE_SIZE' ),
(Str: '*UVW_NOISE_LEVEL' ),
(Str: '*UVW_NOISE_PHASE' ),
(Str: '*BITMAP_FILTER' ),
(Str: '*GEOMOBJECT' ),
(Str: '*NODE_NAME' ),
(Str: '*NODE_TM' ),
(Str: '*INHERIT_POS' ),
(Str: '*INHERIT_ROT' ),
(Str: '*INHERIT_SCL' ),
(Str: '*TM_ROW0' ),
(Str: '*TM_ROW1' ),
(Str: '*TM_ROW2' ),
(Str: '*TM_ROW3' ),
(Str: '*TM_POS' ),
(Str: '*TM_ROTAXIS' ),
(Str: '*TM_ROTANGLE' ),
(Str: '*TM_SCALE' ),
(Str: '*TM_SCALEAXIS' ),
(Str: '*TM_SCALEAXISANG' ),
(Str: '*MESH' ),
(Str: '*TIMEVALUE' ),
(Str: '*MESH_NUMVERTEX' ),
(Str: '*MESH_NUMFACES' ),
(Str: '*MESH_VERTEX_LIST' ),
(Str: '*MESH_VERTEX' ),
(Str: '*MESH_FACE_LIST' ),
(Str: '*MESH_FACE' ),
(Str: '*MESH_SMOOTHING' ),
(Str: '*MESH_MTLID' ),
(Str: '*MESH_NUMTVERTEX' ),
(Str: '*MESH_TVERTLIST' ),
(Str: '*MESH_TVERT' ),
(Str: '*MESH_NUMTVFACES' ),
(Str: '*MESH_TFACELIST' ),
(Str: '*MESH_TFACE' ),
(Str: '*MESH_NORMALS' ),
(Str: '*MESH_FACENORMAL' ),
(Str: '*MESH_VERTEXNORMAL' ),
(Str: '*PROP_MOTIONBLUR' ),
(Str: '*PROP_CASTSHADOW' ),
(Str: '*PROP_RECVSHADOW' ),
(Str: '*MATERIAL_REF' )
);
{$J-}
type
TAseLexer = class
strict private
procedure StringToKeyWord;
procedure SkipBlanks; inline;
private
FAhead: Boolean;
FASE: TextFile;
FToken: TASEToken;
FUseCommaToken: boolean;
FC: PCHAR;
FLine: WideString;
FLineId: Integer;
FString: WideString;
FKeyWord: TKeyWord;
FFormatSettings: TFormatSettings;
function GetTokenFloat: Single;
function GetTokenInteger: Integer;
public
constructor Create(const AFileName: WideString);
destructor Destroy; override;
function NextToken: TASEToken;
procedure NextTokenExpected(AToken: TASEToken); inline;
procedure TokenExpected(AToken: TASEToken);
property Token: TASEToken read FToken;
procedure SkipKeyWordBlock;
property TokenKeyWord: TKeyWord read FKeyWord;
property TokenString: WideString read FString;
property TokenIdent: WideString read FString;
property TokenFloat: Single read GetTokenFloat;
property TokenInteger: Integer read GetTokenInteger;
property Ahead: boolean read FAhead write FAhead;
property UseCommaToken: boolean read FUseCommaToken write FUseCommaToken;
end;
EAseLexerError = class(Exception);
implementation
uses
FMX_Consts;
{ TAseParser }
constructor TAseLexer.Create(const AFileName: WideString);
begin
AssignFile(FASE, AFileName);
Reset(FASE);
{$IFDEF FPC}
FFormatSettings := DefaultFormatSettings;
{$ELSE}
FFormatSettings := TFormatSettings.Create;
{$ENDIF}
end;
destructor TAseLexer.Destroy;
begin
CloseFile(FAse);
inherited;
end;
function TAseLexer.GetTokenFloat: Single;
begin
Result := StrToFloat(FString, FFormatSettings);
end;
function TAseLexer.GetTokenInteger: Integer;
begin
Result := StrToInt(FString);
end;
function TAseLexer.NextToken: TASEToken;
var
LLine: AnsiString;
begin
if FAhead then
begin
FAhead := False;
Exit(FToken);
end;
if FToken = atEOF then
Exit(atEOF);
while True do
begin
if (FC = nil) or (FC^ = #0) then
begin
if EOF(FASE) then
begin
FToken := atEOF;
Exit(atEOF);
end;
ReadLn(FASE, LLine);
FLine := String(LLine);
Inc(FLineId);
if FLine = '' then
Continue;
FC := @FLine[1];
end;
//
SkipBlanks;
if FC^ <> #0 then
Break;
end;
FToken := atUnknown;
case FC^ of
'*':
begin
FString := '*';
Inc(FC);
while AnsiChar(FC^) in ['A'..'Z', '_', '0'..'9'] do
begin
FString := FString + FC^;
Inc(FC);
end;
FToken := atKeyWord;
StringToKeyWord;
end;
'"':
begin
FString := '';
Inc(FC);
while not (AnsiChar(FC^) in [#13, #10, #0, '"']) do
begin
FString := FString + FC^;
Inc(FC);
end;
if FC^ <> '"' then
raise EAseLexerError.CreateResFmt(@SAseLexerCharError, [FLineId, '"', FC^])
else
Inc(FC);
FToken := atString;
end;
'{':
begin
FToken := atOpenBracket;
Inc(FC);
end;
'}':
begin
FToken := atCloseBracket;
Inc(FC);
end;
':':
begin
FToken := atColon;
Inc(FC);
end;
'a'..'z', 'A'..'Z', '_':
begin
FString := FC^;
Inc(FC);
while AnsiChar(FC^) in ['A'..'Z', '_', '0'..'9', 'a'..'z'] do
begin
FString := FString + FC^;
Inc(FC);
end;
FToken := atIdent;
end;
'-', '0'..'9':
begin
FString := FC^;
Inc(FC);
while AnsiChar(FC^) in ['0'..'9'] do
begin
FString := FString + FC^;
Inc(FC);
end;
if (not FUseCommaToken and (AnsiChar(FC^) in ['.', ',']))
or (AnsiChar(FC^) = '.') then
begin
FFormatSettings.DecimalSeparator := FC^;
FString := FString + FC^;
Inc(FC);
while AnsiChar(FC^) in ['0'..'9'] do
begin
FString := FString + FC^;
Inc(FC);
end;
FToken := atFloat;
end
else
FToken := atInteger;
end;
',':
if FUseCommaToken then
begin
FToken := atComma;
Inc(FC);
end;
end;
Result := FToken;
end;
procedure TAseLexer.NextTokenExpected(AToken: TASEToken);
begin
NextToken;
TokenExpected(AToken);
end;
procedure TAseLexer.SkipBlanks;
begin
while AnsiChar(FC^) in [#1..#32] do
Inc(FC);
end;
procedure TAseLexer.SkipKeyWordBlock;
var
LBracketCount: Integer;
begin
Assert(Token = atKeyWord);
if NextToken = atOpenBracket then
begin
LBracketCount := 1;
repeat
case NextToken of
atOpenBracket: Inc(LBracketCount);
atCloseBracket: Dec(LBracketCount);
atEOF: Exit;
end;
until (Token = atEOF) or (LBracketCount = 0);
// NextToken;
end
else
begin
while not (NextToken in [atKeyWord, atEOF, atCloseBracket]) do
{none};
FAhead := True;
end;
end;
{$IFDEF FPC}
{ BobJenkinsHash }
function Rot(x, k: Cardinal): Cardinal; inline;
begin
Result := (x shl k) or (x shr (32 - k));
end;
procedure Mix(var a, b, c: Cardinal); inline;
begin
Dec(a, c); a := a xor Rot(c, 4); Inc(c, b);
Dec(b, a); b := b xor Rot(a, 6); Inc(a, c);
Dec(c, b); c := c xor Rot(b, 8); Inc(b, a);
Dec(a, c); a := a xor Rot(c,16); Inc(c, b);
Dec(b, a); b := b xor Rot(a,19); Inc(a, c);
Dec(c, b); c := c xor Rot(b, 4); Inc(b, a);
end;
procedure Final(var a, b, c: Cardinal); inline;
begin
c := c xor b; Dec(c, Rot(b,14));
a := a xor c; Dec(a, Rot(c,11));
b := b xor a; Dec(b, Rot(a,25));
c := c xor b; Dec(c, Rot(b,16));
a := a xor c; Dec(a, Rot(c, 4));
b := b xor a; Dec(b, Rot(a,14));
c := c xor b; Dec(c, Rot(b,24));
end;
type
TCardinalArray = array[0..$FF] of Cardinal;
TByteArray = array[0..$FF] of Byte;
function HashLittle(const Data; Len, InitVal: Integer): Integer;
var
pb: ^TByteArray;
pd: ^TCardinalArray absolute pb;
a, b, c: Cardinal;
label
case_1, case_2, case_3, case_4, case_5, case_6,
case_7, case_8, case_9, case_10, case_11, case_12;
begin
a := Cardinal($DEADBEEF) + Cardinal(Len shl 2) + Cardinal(InitVal);
b := a;
c := a;
pb := @Data;
// 4-byte aligned data
if (Cardinal(pb) and 3) = 0 then
begin
while Len > 12 do
begin
Inc(a, pd[0]);
Inc(b, pd[1]);
Inc(c, pd[2]);
Mix(a, b, c);
Dec(Len, 12);
Inc(pd, 3);
end;
case Len of
0: Exit(Integer(c));
1: Inc(a, pd[0] and $FF);
2: Inc(a, pd[0] and $FFFF);
3: Inc(a, pd[0] and $FFFFFF);
4: Inc(a, pd[0]);
5:
begin
Inc(a, pd[0]);
Inc(b, pd[1] and $FF);
end;
6:
begin
Inc(a, pd[0]);
Inc(b, pd[1] and $FFFF);
end;
7:
begin
Inc(a, pd[0]);
Inc(b, pd[1] and $FFFFFF);
end;
8:
begin
Inc(a, pd[0]);
Inc(b, pd[1]);
end;
9:
begin
Inc(a, pd[0]);
Inc(b, pd[1]);
Inc(c, pd[2] and $FF);
end;
10:
begin
Inc(a, pd[0]);
Inc(b, pd[1]);
Inc(c, pd[2] and $FFFF);
end;
11:
begin
Inc(a, pd[0]);
Inc(b, pd[1]);
Inc(c, pd[2] and $FFFFFF);
end;
12:
begin
Inc(a, pd[0]);
Inc(b, pd[1]);
Inc(c, pd[2]);
end;
end;
end
else
begin
// Ignoring rare case of 2-byte aligned data. This handles all other cases.
while Len > 12 do
begin
Inc(a, pb[0] + pb[1] shl 8 + pb[2] shl 16 + pb[3] shl 24);
Inc(b, pb[4] + pb[5] shl 8 + pb[6] shl 16 + pb[7] shl 24);
Inc(c, pb[8] + pb[9] shl 8 + pb[10] shl 16 + pb[11] shl 24);
Mix(a, b, c);
Dec(Len, 12);
Inc(pb, 12);
end;
case Len of
0: Exit(c);
1: goto case_1;
2: goto case_2;
3: goto case_3;
4: goto case_4;
5: goto case_5;
6: goto case_6;
7: goto case_7;
8: goto case_8;
9: goto case_9;
10: goto case_10;
11: goto case_11;
12: goto case_12;
end;
case_12:
Inc(c, pb[11] shl 24);
case_11:
Inc(c, pb[10] shl 16);
case_10:
Inc(c, pb[9] shl 8);
case_9:
Inc(c, pb[8]);
case_8:
Inc(b, pb[7] shl 24);
case_7:
Inc(b, pb[6] shl 16);
case_6:
Inc(b, pb[5] shl 8);
case_5:
Inc(b, pb[4]);
case_4:
Inc(a, pb[3] shl 24);
case_3:
Inc(a, pb[2] shl 16);
case_2:
Inc(a, pb[1] shl 8);
case_1:
Inc(a, pb[0]);
end;
Final(a, b, c);
Result := Integer(c);
end;
function BobJenkinsHash(const Data; Len, InitData: Integer): Integer;
begin
Result := HashLittle(Data, Len, InitData);
end;
{$ENDIF}
procedure TAseLexer.StringToKeyWord;
var
kw: TKeyWord;
LHash: Integer;
begin
LHash := BobJenkinsHash(FString[1], Length(FString) * SizeOf(FString[1]), 2004);
FKeyWord := kw_UNKNOWN;
for kw := Succ(Low(TKeyWord)) to High(TKeyWord) do
if KEY_WORDS[kw].Hash = LHash then
if AnsiSameStr(FString, KEY_WORDS[kw].Str) then
begin
FKeyWord := kw;
Exit;
end;
end;
procedure TAseLexer.TokenExpected(AToken: TASEToken);
begin
if FToken <> AToken then
raise EAseLexerError.CreateResFmt(@SAseLexerTokenError, [FLineId,
GetEnumName(TypeInfo(TASEToken), Integer(AToken)),
GetEnumName(TypeInfo(TASEToken), Integer(FToken))]);
end;
procedure InitializeKeyWordsHash;
var
kw: TKeyWord;
begin
for kw := Succ(Low(TKeyWord)) to High(TKeyWord) do
KEY_WORDS[kw].Hash := BobJenkinsHash(KEY_WORDS[kw].Str[1],
Length(KEY_WORDS[kw].Str) * SizeOf(KEY_WORDS[kw].Str[1]), 2004);
end;
begin
InitializeKeyWordsHash;
end.
|
{
Allows you to communicate via HTTP. Specify URL and request parameters,
then call Push() to connect and transfer data to a remote server.
After successful execution of the request, data can be read from the input buffer.
Large amounts of data received by parts, and OnDataAppear event can be triggered multiple times.
If POST method selected, then request parameter mime-type='application/x-www-form-urlencoded' set,
it allow transfer parameters as web form values.
Sergey Bodrov, 2012-2016
Properties:
Url - address and params string, URL
Params - HTTP request params in name=value format
Method - HTTP request method
httpGet - GET
httpPost - POST
Methods:
Open() - sets URL string for HTTP request, but not send request itself. Request will be sent on Push(). URL string format:
URL = 'http://RemoteHost:RemotePort/Path'
RemoteHost - IP-address or name of remote host
RemotePort - remote UPD or TCP port number
Path - path to requested resource
}
unit DataPortHTTP;
interface
uses SysUtils, Classes, DataPort, httpsend, synautil, synacode;
type
THttpMethods = (httpGet, httpPost);
THttpClient = class(TThread)
private
HttpSend: THTTPSend;
s: string;
sLastError: string;
FOnIncomingMsgEvent: TMsgEvent;
FOnErrorEvent: TMsgEvent;
procedure SyncProc();
protected
procedure Execute(); override;
public
url: string;
method: THttpMethods;
Data: string;
property OnIncomingMsgEvent: TMsgEvent read FOnIncomingMsgEvent write FOnIncomingMsgEvent;
property OnErrorEvent: TMsgEvent read FOnErrorEvent write FOnErrorEvent;
function SendString(s: string): Boolean;
procedure SendStream(st: TStream; Dest: string);
end;
{ TDataPortHTTP }
TDataPortHTTP = class(TDataPort)
private
//slReadData: TStringList; // for storing every incoming data packet separately
sReadData: AnsiString;
lock: TMultiReadExclusiveWriteSynchronizer;
HttpClient: THttpClient;
HttpSend: THTTPSend;
FUrl: string;
FParams: TStrings;
FMethod: THttpMethods;
FSafeMode: Boolean;
procedure OnIncomingMsgHandler(Sender: TObject; const AMsg: string);
procedure OnErrorHandler(Sender: TObject; const AMsg: string);
protected
procedure FSetParams(Val: TStrings);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
{ Open() - sets URL string for HTTP request, but not send request itself. Request will be sent on Push(). URL string format:
URL = 'http://RemoteHost:RemotePort/Path'
RemoteHost - IP-address or name of remote host
RemotePort - remote UPD or TCP port number
Path - path to requested resource }
procedure Open(const AInitStr: string = ''); override;
procedure Close(); override;
function Push(const AData: AnsiString): Boolean; override;
function Pull(size: Integer = MaxInt): AnsiString; override;
function Peek(size: Integer = MaxInt): AnsiString; override;
function PeekSize(): Cardinal; override;
published
{ address and params string, URL }
property Url: string read FUrl write FUrl;
{ HTTP request params in name=value format }
property Params: TStrings read FParams write FSetParams;
{ Method - HTTP request method
httpGet - GET
httpPost - POST }
property Method: THttpMethods read FMethod write FMethod;
{ Use this property if you encounter troubles:
True - Non-threaded synchronous behavior
False - Asynchronous behavior }
property SafeMode: Boolean read FSafeMode write FSafeMode;
property Active;
property OnDataAppear;
property OnError;
property OnOpen;
property OnClose;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('DataPort', [TDataPortHTTP]);
end;
// === THttpClient ===
procedure THttpClient.SyncProc();
begin
//if s:='' then Exit;
if s <> '' then
begin
if Assigned(self.FOnIncomingMsgEvent) then
FOnIncomingMsgEvent(self, s);
s := '';
end;
if sLastError <> '' then
begin
if Assigned(self.FOnErrorEvent) then
FOnErrorEvent(self, sLastError);
//self.Terminate();
end;
end;
procedure THttpClient.Execute();
var
bResult: Boolean;
sMethod: string;
begin
Self.HttpSend := THTTPSend.Create();
sLastError := '';
sMethod := 'GET';
synautil.WriteStrToStream(Self.HttpSend.Document, self.Data);
if self.method = httpPost then
begin
sMethod := 'POST';
Self.HttpSend.MimeType := 'application/x-www-form-urlencoded';
end;
try
bResult := self.HttpSend.HTTPMethod(sMethod, Self.url);
except
bResult := False;
end;
if not bResult then
begin
sLastError := 'Cannot connect';
Synchronize(SyncProc);
end;
if Self.HttpSend.Document.Size = 0 then
begin
sLastError := 'Zero content size';
Synchronize(SyncProc);
end;
if self.HttpSend.DownloadSize <> Self.HttpSend.Document.Size then
begin
sLastError := 'Download size=' + IntToStr(self.HttpSend.DownloadSize) +
' doc size=' + IntToStr(Self.HttpSend.Document.Size);
Synchronize(SyncProc);
end;
s := synautil.ReadStrFromStream(Self.HttpSend.Document, Self.HttpSend.Document.Size);
Synchronize(SyncProc);
Self.HttpSend.Clear();
FreeAndNil(Self.HttpSend);
Terminate();
end;
function THttpClient.SendString(s: string): Boolean;
begin
Result := False;
if Assigned(Self.HttpSend) then
Exit;
self.Data := s;
self.Suspended := False;
Result := True;
end;
procedure THttpClient.SendStream(st: TStream; Dest: string);
begin
if Assigned(Self.HttpSend) then
Exit;
self.Data := synautil.ReadStrFromStream(st, st.Size);
self.Suspended := False;
end;
{ TDataPortHTTP }
constructor TDataPortHTTP.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
self.lock := TMultiReadExclusiveWriteSynchronizer.Create();
FParams := TStringList.Create();
FMethod := httpGet;
FActive := False;
FSafeMode := True;
//Self.slReadData:=TStringList.Create();
Self.sReadData := '';
Self.HttpClient := nil;
end;
procedure TDataPortHTTP.Open(const AInitStr: string);
begin
if Assigned(self.HttpClient) then
FreeAndNil(self.HttpClient);
if Length(AInitStr) > 0 then
Url := AInitStr;
if Length(Url) = 0 then
begin
if Assigned(Self.FOnError) then
Self.FOnError(Self, 'Empty URL');
Exit;
end;
if not self.SafeMode then
begin
// threaded request
Self.HttpClient := THttpClient.Create(True);
Self.HttpClient.OnIncomingMsgEvent := self.OnIncomingMsgHandler;
Self.HttpClient.OnErrorEvent := Self.OnErrorHandler;
Self.HttpClient.url := Url;
Self.HttpClient.FreeOnTerminate := True;
Self.HttpClient.Suspended := False;
end;
inherited Open(AInitStr);
end;
procedure TDataPortHTTP.Close();
begin
if not self.SafeMode then
begin
if Assigned(self.HttpClient) then
begin
//Self.HttpClient.OnIncomingMsgEvent:=nil;
//Self.HttpClient.OnErrorEvent:=nil;
self.HttpClient.Terminate();
//FreeAndNil(self.HttpClient);
self.HttpClient := nil;
end;
end;
inherited Close();
end;
destructor TDataPortHTTP.Destroy();
begin
if Assigned(self.HttpClient) then
FreeAndNil(self.HttpClient);
//FreeAndNil(self.slReadData);
FreeAndNil(FParams);
FreeAndNil(self.lock);
inherited Destroy();
end;
procedure TDataPortHTTP.OnIncomingMsgHandler(Sender: TObject; const AMsg: string);
begin
if AMsg <> '' then
begin
if lock.BeginWrite then
begin
//slReadData.Add(AMsg);
sReadData := sReadData + AMsg;
lock.EndWrite;
if Assigned(FOnDataAppear) then
FOnDataAppear(self);
end
else if Assigned(FOnError) then
FOnError(self, 'Lock failed');
end;
end;
procedure TDataPortHTTP.OnErrorHandler(Sender: TObject; const AMsg: string);
begin
if Assigned(Self.FOnError) then
Self.FOnError(Self, AMsg);
self.FActive := False;
end;
{
function TDataPortIP.Peek(size: Integer = MaxInt): AnsiString;
var
i, num, remain: Integer;
begin
Result:='';
remain:=size;
lock.BeginRead();
for i:=0 to slReadData.Count do
begin
num:=Length(slReadData[i]);
if num>remain then num:=remain;
Result:=Result+Copy(slReadData[i], 1, num);
remain:=remain-num;
if remain<=0 then Break;
end;
lock.EndRead();
end;
}
function TDataPortHTTP.Peek(size: Integer = MaxInt): AnsiString;
begin
lock.BeginRead();
Result := Copy(sReadData, 1, size);
lock.EndRead();
end;
function TDataPortHTTP.PeekSize(): Cardinal;
//var i: Integer;
begin
//Result:=0;
lock.BeginRead();
//// Length of all strings
//for i:=0 to slReadData.Count-1 do Result:=Result+Cardinal(Length(slReadData[i]));
Result := Cardinal(Length(sReadData));
lock.EndRead();
end;
{
function TDataPortIP.Pull(size: Integer = MaxInt): AnsiString;
var
num, len, remain: Integer;
begin
Result:='';
remain:=size;
if not lock.BeginWrite() then Exit;
while slReadData.Count>0 do
begin
// we read every string to exclude line delimiters
len:=Length(slReadData[0]);
num:=len;
if num>remain then num:=remain;
Result:=Result+Copy(slReadData[0], 1, num);
remain:=remain-num;
if num>=len then slReadData.Delete(0)
else
begin
Delete(slReadData[0], 1, num);
Break;
end;
if remain<=0 then Break;
end;
lock.EndWrite();
end;
}
function TDataPortHTTP.Pull(size: Integer = MaxInt): AnsiString;
begin
Result := '';
if not lock.BeginWrite() then
Exit;
Result := Copy(sReadData, 1, size);
Delete(sReadData, 1, size);
//sReadData:='';
lock.EndWrite();
end;
function TDataPortHTTP.Push(const AData: AnsiString): Boolean;
var
i: Integer;
sUrl, sParams, sData: string;
sMethod: string;
bResult: Boolean;
begin
Result := False;
sUrl := url;
sData := AData;
sParams := '';
// encode params into string
for i := 0 to FParams.Count - 1 do
begin
if sParams <> '' then
sParams := sParams + '&';
sParams := sParams + synacode.EncodeURL(FParams[i]);
end;
if method = httpGet then
begin
if FParams.Count > 0 then
begin
sUrl := sUrl + '?' + sParams;
end;
end
else if method = httpPost then
begin
sData := sParams + AData;
end;
if self.SafeMode then
begin
// non-threaded
Self.HttpSend := THTTPSend.Create();
sMethod := 'GET';
synautil.WriteStrToStream(Self.HttpSend.Document, sData);
if self.method = httpPost then
begin
sMethod := 'POST';
Self.HttpSend.MimeType := 'application/x-www-form-urlencoded';
end;
try
bResult := self.HttpSend.HTTPMethod(sMethod, sUrl);
except
bResult := False;
end;
if not bResult then
begin
if Assigned(OnError) then
OnError(self, 'Cannot connect');
end
else if Self.HttpSend.Document.Size = 0 then
begin
if Assigned(OnError) then
OnError(self, 'Zero content size');
end
else
begin
if lock.BeginWrite() then
begin
try
sReadData := sReadData + synautil.ReadStrFromStream(Self.HttpSend.Document,
Self.HttpSend.Document.Size);
finally
lock.EndWrite();
end;
end;
if Assigned(OnDataAppear) then
OnDataAppear(self);
end;
FreeAndNil(Self.HttpSend);
end
else
begin
// threaded
if not Assigned(self.HttpClient) then
Exit;
if not Active then
Exit;
if lock.BeginWrite() then
begin
try
HttpClient.url := FUrl;
HttpClient.method := FMethod;
sParams := '';
for i := 0 to FParams.Count - 1 do
begin
if sParams <> '' then
sParams := sParams + '&';
sParams := sParams + synacode.EncodeURL(FParams[i]);
end;
if method = httpGet then
begin
if FParams.Count > 0 then
begin
HttpClient.url := HttpClient.url + '?' + sParams;
self.HttpClient.SendString(AData);
end;
end
else if method = httpPost then
begin
HttpClient.SendString(sParams + AData);
end;
Result := True;
finally
lock.EndWrite();
end;
end;
end;
end;
procedure TDataPortHTTP.FSetParams(Val: TStrings);
begin
FParams.Assign(Val);
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit ExpertsReg;
interface
uses ToolsAPI, SysUtils, StrEdit;
procedure Register;
implementation
uses ExpertsResStrs, ExpertsProject, ExpertsModules, Classes, ExpertsTemplates, DesignEditors, DesignIntf,
Dialogs, Forms;
type
{ TTemplateFilePropertyEditor }
TTemplateFilePropertyEditor = class(TStringProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
TCustomExpertsTemplateFileComponentEditor = class(TComponentEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
procedure Edit; override;
end;
TCustomExpertsTemplatePersonalityFilesEditor = class(TComponentEditor)
private
FFiles: TStrings;
function GetFiles: TStrings;
public
destructor Destroy; override;
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
procedure Edit; override;
end;
TCustomExpertsModuleComponentEditor = class(TComponentEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
procedure Edit; override;
end;
procedure Register;
begin
// RegisterPropertyEditor(TypeInfo(TFileName), TCustomExpertsTemplateFile, 'TemplateFile',
// TTemplateFilePropertyEditor);
// RegisterPropertyEditor(TypeInfo(TFileName), TCustomExpertsModule, 'TemplateFile',
// TTemplateFilePropertyEditor);
// RegisterPropertyEditor(TypeInfo(TFileName), TCustomExpertsUnit, 'TemplateFile',
// TTemplateFilePropertyEditor);
// RegisterPropertyEditor(TypeInfo(TFileName), TCustomExpertsClassUnit, 'TemplateFile',
// TTemplateFilePropertyEditor);
// RegisterPropertyEditor(TypeInfo(TFileName), TCustomExpertsTextFile, 'TemplateFile',
// TTemplateFilePropertyEditor);
RegisterPropertyEditor(TypeInfo(TFileName), TExpertsModulesComponent, 'TemplateFile',
TTemplateFilePropertyEditor);
RegisterPropertyEditor(TypeInfo(TFileName), TExpertsTemplatePersonalityFiles, 'DelphiTemplateFile',
TTemplateFilePropertyEditor);
RegisterPropertyEditor(TypeInfo(TFileName), TExpertsTemplatePersonalityFiles, 'CBuilderTemplateFile',
TTemplateFilePropertyEditor);
RegisterPropertyEditor(TypeInfo(TFileName), TExpertsTemplatePersonalityFiles, 'GenericTemplateFile',
TTemplateFilePropertyEditor);
RegisterPropertyEditor(TypeInfo(TStrings), TCustomExpertsTemplateProperties, 'Properties', TValueListProperty);
// RegisterPropertyEditor(TypeInfo(TStrings), TCustomExpertsModule, 'TemplatePropertiesDoc', TValueListProperty);
// RegisterPropertyEditor(TypeInfo(TStrings), TCustomExpertsUnit, 'TemplatePropertiesDoc', TValueListProperty);
// RegisterPropertyEditor(TypeInfo(TStrings), TCustomExpertsClassUnit, 'TemplatePropertiesDoc', TValueListProperty);
// RegisterPropertyEditor(TypeInfo(TStrings), TCustomExpertsTextFile, 'TemplatePropertiesDoc', TValueListProperty);
// RegisterPropertyEditor(TypeInfo(TStrings), TCustomExpertsProject, 'TemplatePropertiesDoc', TValueListProperty);
RegisterPropertyEditor(TypeInfo(TStrings), TExpertsModulesComponent, 'TemplatePropertiesDoc', TValueListProperty);
RegisterPropertyEditor(TypeInfo(TStrings), TExpertsTemplateFile, 'TemplatePropertiesDoc', TValueListProperty);
RegisterComponents(rsExpertsComponents, [TExpertsProject, TExpertsTemplateFile, TExpertsTemplateProperties,
TExpertsModule, TExpertsUnit, TExpertsTextFile, TExpertsClassUnit, TExpertsPchModule, TExpertsTemplatePersonalityFiles]);
RegisterComponentEditor(TCustomExpertsTemplateFile, TCustomExpertsTemplateFileComponentEditor);
RegisterComponentEditor(TExpertsPersonalityModuleComponent, TCustomExpertsModuleComponentEditor);
RegisterComponentEditor(TExpertsGenericModuleComponent, TCustomExpertsModuleComponentEditor);
RegisterComponentEditor(TCustomExpertsTemplatePersonalityFiles, TCustomExpertsTemplatePersonalityFilesEditor);
end;
{ TTemplateFilePropertyEditor }
resourcestring
SOpenFileTitle = 'Open';
sCreateSampleModuleCommand = 'Create sample module';
sCreateDelphiSampleModuleCommand = 'Create Delphi sample module';
sCreateCBuilderSampleModuleCommand = 'Create CBuilder sample module';
sTemplateFileFilter = 'Source File(*.pas; *.cpp; *.txt)|*.pas;*.cpp;*.txt|Any file (*.*)|*.*';
sOpenTemplateFileCommand = 'Open %s';
sFileNotFound = 'File not found: %s';
procedure TCustomExpertsTemplateFileComponentEditor.Edit;
begin
//do nothing
end;
procedure TCustomExpertsTemplateFileComponentEditor.ExecuteVerb(Index: Integer);
var
I: Integer;
LComponent: TCustomExpertsTemplateFile;
LFile: string;
begin
LComponent := TCustomExpertsTemplateFile(Component);
I := inherited GetVerbCount;
if Index < I then
inherited
else
begin
i := Index - I;
case I of
0:
try
if not FindTemplateFile(LComponent.TemplateFile, LFile) then
MessageDlg(Format(sFileNotFound, [LFile]), mtError, [mbOK], 0)
else
(BorlandIDEServices as IOTAActionServices).OpenFile(LFile);
// DocModul.CallDefaultOpenProc(
// LFile);
except
on E: EAbort do
Exit;
on E: Exception do
MessageDlg(E.Message, mtError, [mbOK], 0);
end;
end;
end;
end;
//class function TDSDesigntimeProxyGenerator.GetDefaultClientClassesUnitName: string;
//var
// LUnitIdent, LClassName, LFileName: string;
//begin
// Result := '';
// if rsClientClassesUnitName <> '' then
// begin
// (BorlandIDEServices as IOTAModuleServices).GetNewModuleAndClassName(rsClientClassesUnitName,
// LUnitIdent, LClassName, LFileName);
// Result := LUnitIdent;
// end;
//end;
function TCustomExpertsTemplateFileComponentEditor.GetVerb(Index: Integer): string;
var
I: Integer;
LComponent: TCustomExpertsTemplateFile;
begin
LComponent := TCustomExpertsTemplateFile(Component);
I := inherited GetVerbCount;
if Index < I then
Result := inherited GetVerb(Index)
else
begin
i := Index - I;
case I of
0: Result := Format(sOpenTemplateFileCommand, [LComponent.TemplateFile]);
end;
end;
end;
function TCustomExpertsTemplateFileComponentEditor.GetVerbCount: Integer;
var
LComponent: TCustomExpertsTemplateFile;
begin
LComponent := TCustomExpertsTemplateFile(Component);
Result := inherited;
if LComponent.TemplateFile <> '' then
Result := Result + 1;
end;
destructor TCustomExpertsTemplatePersonalityFilesEditor.Destroy;
begin
FFiles.Free;
inherited;
end;
procedure TCustomExpertsTemplatePersonalityFilesEditor.Edit;
begin
//do nothing
end;
function TCustomExpertsTemplatePersonalityFilesEditor.GetFiles: TStrings;
var
LComponent: TCustomExpertsTemplatePersonalityFiles;
begin
if FFiles = nil then
begin
LComponent := TCustomExpertsTemplatePersonalityFiles(Component);
FFiles := TStringList.Create;
if LComponent.DelphiTemplateFile <> '' then
FFiles.Add(LComponent.DelphiTemplateFile);
if LComponent.CBuilderTemplateFile <> '' then
FFiles.Add(LComponent.CBuilderTemplateFile);
if LComponent.GenericTemplateFile <> '' then
FFiles.Add(LComponent.GenericTemplateFile);
end;
Result := FFiles;
end;
procedure TCustomExpertsTemplatePersonalityFilesEditor.ExecuteVerb(Index: Integer);
var
I: Integer;
LFile: string;
begin
I := inherited GetVerbCount;
if Index < I then
inherited
else
begin
i := Index - I;
try
if not FindTemplateFile(GetFiles[I], LFile) then
MessageDlg(Format(sFileNotFound, [LFile]), mtError, [mbOK], 0)
else
(BorlandIDEServices as IOTAActionServices).OpenFile(LFile);
// DocModul.CallDefaultOpenProc(
// LFile);
except
on E: EAbort do
Exit;
on E: Exception do
MessageDlg(E.Message, mtError, [mbOK], 0);
end;
end;
end;
//class function TDSDesigntimeProxyGenerator.GetDefaultClientClassesUnitName: string;
//var
// LUnitIdent, LClassName, LFileName: string;
//begin
// Result := '';
// if rsClientClassesUnitName <> '' then
// begin
// (BorlandIDEServices as IOTAModuleServices).GetNewModuleAndClassName(rsClientClassesUnitName,
// LUnitIdent, LClassName, LFileName);
// Result := LUnitIdent;
// end;
//end;
function TCustomExpertsTemplatePersonalityFilesEditor.GetVerb(Index: Integer): string;
var
I: Integer;
begin
I := inherited GetVerbCount;
if Index < I then
Result := inherited GetVerb(Index)
else
begin
i := Index - I;
Result := Format(sOpenTemplateFileCommand, [GetFiles[I]])
end;
end;
function TCustomExpertsTemplatePersonalityFilesEditor.GetVerbCount: Integer;
var
LComponent: TCustomExpertsTemplateFile;
begin
LComponent := TCustomExpertsTemplateFile(Component);
Result := inherited;
if LComponent.TemplateFile <> '' then
Result := Result + GetFiles.Count;
end;
{ TCustomExpertsModuleComponentEditor }
procedure TCustomExpertsModuleComponentEditor.Edit;
begin
//do nothing
end;
resourcestring
sUnexpectedClass = 'Unexpected class: %';
function PersonalityExists(const APersonality: string): Boolean;
begin
Result := PersonalityServices.PersonalityExists(APersonality);
end;
procedure ExecuteInPersonality(const APersonality: string; ACallback: TProc);
var
LCurrentPersonality: string;
begin
LCurrentPersonality := PersonalityServices.CurrentPersonality;
try
PersonalityServices.CurrentPersonality := APersonality;
ACallback();
finally
PersonalityServices.CurrentPersonality := LCurrentPersonality;
end;
end;
procedure TCustomExpertsModuleComponentEditor.ExecuteVerb(Index: Integer);
var
I: Integer;
LComponent: TExpertsModulesComponent;
begin
LComponent := TExpertsModulesComponent(Component);
I := inherited GetVerbCount;
if Index < I then
inherited
else
begin
i := Index - I;
case I of
0:
// Prompt for personality
if LComponent is TExpertsPersonalityModuleComponent then
ExecuteInPersonality(sDelphiPersonality,
procedure begin
TExpertsPersonalityModuleComponent(LComponent).CreateModule(sDelphiPersonality)
end)
else if LComponent is TExpertsGenericModuleComponent then
TExpertsGenericModuleComponent(LComponent).CreateModule
else
raise Exception.CreateFmt(sUnexpectedClass, [LComponent.ClassName]);
1:
// Prompt for personality
if LComponent is TExpertsPersonalityModuleComponent then
ExecuteInPersonality(sCBuilderPersonality,
procedure begin
TExpertsPersonalityModuleComponent(LComponent).CreateModule(sCBuilderPersonality)
end)
else
raise Exception.CreateFmt(sUnexpectedClass, [LComponent.ClassName]);
end;
end;
end;
function TCustomExpertsModuleComponentEditor.GetVerb(Index: Integer): string;
var
I: Integer;
LComponent: TExpertsModulesComponent;
begin
LComponent := TExpertsModulesComponent(Component);
I := inherited GetVerbCount;
if Index < I then
Result := inherited GetVerb(Index)
else
begin
i := Index - I;
case I of
0:
if LComponent is TExpertsPersonalityModuleComponent then
Result := sCreateDelphiSampleModuleCommand
else
Result := sCreateSampleModuleCommand;
1: Result := sCreateCBuilderSampleModuleCommand;
end;
end;
end;
function TCustomExpertsModuleComponentEditor.GetVerbCount: Integer;
var
LComponent: TExpertsModulesComponent;
begin
LComponent := TExpertsModulesComponent(Component);
Result := inherited;
//if LComponent.TemplateFile <> '' then
Result := Result + 1;
if LComponent is TExpertsPersonalityModuleComponent then
Result := Result + 1
end;
procedure TTemplateFilePropertyEditor.Edit;
var
Dialog: Dialogs.TOpenDialog;
TemplateDir: string;
begin
TemplateDir := (BorlandIDEServices as IOTAServices).GetTemplateDirectory;
Dialog := Dialogs.TOpenDialog.Create(Application);
with Dialog do
try
Title := sOpenFileTitle;
Filename := GetValue;
if IsRelativePath(FileName) then
FileName := ExpandFileName(TemplateDir + FileName);
Filter := sTemplateFileFilter;
if FileName = '' then
InitialDir := (BorlandIDEServices as IOTAServices).GetTemplateDirectory;
HelpContext := 0;
Options := Options + [ofShowHelp, ofPathMustExist, ofHideReadonly, ofFileMustExist];
if Dialog.Execute then
SetValue(ExtractRelativePath(TemplateDir, Filename));
finally
Free;
end;
end;
function TTemplateFilePropertyEditor.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paRevertable, paVCL];
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 2010-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Macapi.Consts;
interface
resourcestring
SObjectiveCRTTINotAvailable = 'RTTI for type %s was not found. Perhaps missing {$M+}?';
SObjectiveCClassNotFound = 'ObjectiveC class %s could not be found';
SInvalidObjectiveCType = '%s is not a valid ObjectiveC type';
SInternalBindingError = 'Internal error creating binding for ''%s''';
SMethodMustBeCDecl = 'Method ''%s'' of type ''%s'' must have cdecl calling convention';
SBadObjectiveCClass = '''%s'' must be an interface derived from IObjectiveCClass';
SBadObjectiveCInstance = '''%s'' must be an interface derived from IObjectiveCInstance';
SBadObjectiveCProtocol = '''%s'' must be an interface derived from IObjectiveCProtocol';
SErrorCreatingOCObject = 'Unable to create ObjectiveC persona for instance of ''%s''';
SOCInvokeError = 'Fatal error invoking interface';
SInvalidObjCType = 'The type ''%s'' is not supported with ObjectiveC interoperability';
implementation
end.
|
(*
Name: keymanoption
Copyright: Copyright (C) SIL International.
Documentation:
Description:
Create Date: 1 Aug 2006
Modified Date: 28 Aug 2014
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 01 Aug 2006 - mcdurdin - Add Serialize
04 Dec 2006 - mcdurdin - Remove description from options (localizable)
12 Mar 2010 - mcdurdin - I2230 - Resolve crashes due to incorrect reference counting
28 Aug 2014 - mcdurdin - I4390 - V9.0 - Free vs Pro
*)
unit keymankeyboardoption;
interface
uses
System.Classes,
Winapi.ActiveX,
keymanapi_TLB,
keymanautoobject,
KeymanContext;
type
TKeymanKeyboardOption = class(TKeymanAutoObject, IKeymanKeyboardOption)
private
FKeyboardID, FName, FValue: string;
protected
function Serialize(Flags: TOleEnum; const ImagePath: WideString;
References: TStrings): WideString; override;
{ IKeymanKeyboardOption }
function Get_Name: WideString; safecall;
function Get_Value: WideString; safecall;
procedure Set_Value(const Value: WideString); safecall;
public
constructor Create(AContext: TKeymanContext; const AKeyboardID, AName, AValue: string);
end;
implementation
uses
// ComServ,
System.Win.Registry,
RegistryKeys,
utilxml;
procedure TKeymanKeyboardOption.Set_Value(const Value: WideString);
begin
FValue := Value;
with TRegistry.Create do // I2890
try
if OpenKey(BuildKeyboardOptionKey(FKeyboardID), True) then
begin
WriteString(FName, Value);
if OpenKey(SRegKey_SharedOptionsSubKey, False) then
WriteString(FName, Value);
end;
finally
Free;
end;
end;
constructor TKeymanKeyboardOption.Create(AContext: TKeymanContext; const AKeyboardID, AName, AValue: string);
begin
inherited Create(AContext, IKeymanKeyboardOption);
FKeyboardID := AKeyboardID;
FName := AName;
FValue := AValue;
end;
function TKeymanKeyboardOption.Get_Name: WideString;
begin
Result := FName;
end;
function TKeymanKeyboardOption.Get_Value: WideString;
begin
Result := FValue;
end;
function TKeymanKeyboardOption.Serialize(Flags: TOleEnum; const ImagePath: WideString;
References: TStrings): WideString;
begin
Result := XMLFormat([
'name', Get_Name,
'value', Get_Value]);
end;
end.
|
////////////////////////////////////////////
// Служебные функции для приборов ДРК-4ОП
////////////////////////////////////////////
unit Devices.DRK;
interface
uses Devices.ReqCreatorBase, GMConst, GMGlobals;
type
TDRK4OPReqCreator = class(TDevReqCreator)
private
procedure AddRequests_OneChannel(nChannel: int);
public
procedure AddRequests(); override;
end;
implementation
uses ProgramLogFile, SysUtils, GmSqlQuery, Math;
{ TDRK4OPReqCreator }
procedure TDRK4OPReqCreator.AddRequests_OneChannel(nChannel: int);
var q: TGMSqlQuery;
buf: ArrayOfByte;
begin
FReqDetails.ClearReqLink();
FReqDetails.AddReqLink(0);
FReqDetails.AddReqLink(0);
q := TGMSqlQuery.Create();
q.SQL.Text := 'select * from DeviceSystem where ID_Device = ' + IntToStr(FReqDetails.ID_Device) + ' and N_Src = ' + IntToStr(nChannel);
try
q.Open();
while not q.Eof do
begin
case q.FieldByName('ID_Src').AsInteger of
SRC_AI: FReqDetails.ReqLinks[0].id := q.FieldByName('ID_Prm').AsInteger;
SRC_CNT_MTR: FReqDetails.ReqLinks[1].id := q.FieldByName('ID_Prm').AsInteger;
end;
q.Next();
end;
buf := TextNumbersStringToArray('D0 D0 D0 D0 D1 ' + IntToHex(FReqDetails.DevNumber, 2) + ' D2 C' + IntToStr(nChannel));
AddBufRequestToSendBuf(buf, Length(buf), rqtDRK);
except
on e: Exception do
ProgramLog().AddException('AddI7041DToSendBuf - ' + e.Message);
end;
q.Free();
end;
procedure TDRK4OPReqCreator.AddRequests;
begin
AddRequests_OneChannel(1);
AddRequests_OneChannel(2);
end;
end.
|
{ }
{ Hashing functions v3.06 }
{ }
{ This unit is copyright © 2002-2004 by David J Butler }
{ }
{ This unit is part of Delphi Fundamentals. }
{ Its original file name is cHash.pas }
{ The latest version is available from the Fundamentals home page }
{ http://fundementals.sourceforge.net/ }
{ }
{ I invite you to use this unit, free of charge. }
{ I invite you to distibute this unit, but it must be for free. }
{ I also invite you to contribute to its development, }
{ but do not distribute a modified copy of this file. }
{ }
{ A forum is available on SourceForge for general discussion }
{ http://sourceforge.net/forum/forum.php?forum_id=2117 }
{ }
{ }
{ Description: }
{ }
{ Hashes are algorithms for computing (fixed size) 'condensed }
{ representations' of 'messages'. The 'message' refers to the (usually }
{ large variable size) data being hashed. The 'condensed representation' }
{ is refered to as the 'message digest'. }
{ }
{ Hashing functions are useful when a (unique) 'fingerprint' is }
{ needed to represent a (large) piece of data. }
{ }
{ Hashes are refered to as 'secure' if it is computationally infeasible to }
{ find a message that produce a given digest. }
{ }
{ 'Keyed' hashes use a key (password) in the hashing process. }
{ }
{ Supported hashes: }
{ }
{ Algorithm Digest size (bits) Type }
{ ------------ ------------------ ------------------------------ }
{ Checksum 32 Checksum }
{ XOR8 8 Checksum }
{ XOR16 16 Checksum }
{ XOR32 32 Checksum }
{ CRC16 16 Checksum / Error detection }
{ CRC32 32 Checksum / Error detection }
{ ELF 32 Checksum }
{ MD5 128 Secure hash }
{ SHA1 160 Secure hash }
{ HMAC/MD5 128 Secure keyed hash }
{ HMAC/SHA1 160 Secure keyed hash }
{ }
{ Other: }
{ }
{ Algorithm Type }
{ ------------ -------------------------------------------------- }
{ ISBN Check-digit for International Standard Book Number }
{ LUHN Check-digit for credit card numbers }
{ }
{ }
{ Revision history: }
{ 02/04/2002 0.01 Initial version from cUtils unit. }
{ Hash: Checksum, XOR, CRC, MD5, SHA1, SNS }
{ Keyed hash: HMAC-MD5, HMAC-SHA1 }
{ 03/04/2002 0.02 Securely clear passwords from memory after use. }
{ 05/04/2002 0.03 Added SNS hashing. }
{ 19/04/2002 0.04 Added ISBN checksum. }
{ 26/07/2003 0.05 Added ELF hashing. }
{ 09/08/2003 3.06 Revise for Fundamentals 3. }
{ }
{$INCLUDE ..\cDefines.inc}
unit cHash;
interface
uses
{ Delphi }
SysUtils;
{ }
{ Hash digests }
{ }
type
PByte = ^Byte;
PWord = ^Word;
PLongWord = ^LongWord;
T128BitDigest = record
case integer of
0 : (Int64s : Array [0..1] of Int64);
1 : (Longs : Array [0..3] of LongWord);
2 : (Words : Array [0..7] of Word);
3 : (Bytes : Array [0..15] of Byte);
end;
P128BitDigest = ^T128BitDigest;
T160BitDigest = record
case integer of
0 : (Longs : Array [0..4] of LongWord);
1 : (Words : Array [0..9] of Word);
2 : (Bytes : Array [0..19] of Byte);
end;
P160BitDigest = ^T160BitDigest;
const
MaxHashDigestSize = Sizeof (T160BitDigest);
Procedure DigestToHexBuf (const Digest; const Size : Integer; const Buf);
Function DigestToHex (const Digest; const Size : Integer) : String;
Function Digest128Equal (const Digest1, Digest2 : T128BitDigest) : Boolean;
Function Digest160Equal (const Digest1, Digest2 : T160BitDigest) : Boolean;
{ }
{ Hash errors }
{ }
const
hashNoError = 0;
hashInternalError = 1;
hashInvalidHashType = 2;
hashInvalidBuffer = 3;
hashInvalidBufferSize = 4;
hashInvalidDigest = 5;
hashInvalidKey = 6;
hashInvalidFileName = 7;
hashFileOpenError = 8;
hashFileSeekError = 9;
hashFileReadError = 10;
hashNotKeyedHashType = 11;
hashTooManyOpenHandles = 12;
hashInvalidHandle = 13;
hashMAX_ERROR = 13;
Function GetHashErrorMessage (const ErrorCode : LongWord) : PChar;
type
EHashError = class (Exception)
protected
FErrorCode : LongWord;
public
Constructor Create (const ErrorCode : LongWord; const Msg : String = '');
Property ErrorCode : LongWord read FErrorCode;
end;
{ }
{ Secure memory clear }
{ Used to clear keys (passwords) from memory }
{ }
Procedure SecureClear (var Buf; const BufSize : Integer);
Procedure SecureClearStr (var S : String);
{ }
{ Checksum hashing }
{ }
Function CalcChecksum32 (const Buf; const BufSize : Integer) : LongWord; overload;
Function CalcChecksum32 (const Buf : String) : LongWord; overload;
{ }
{ XOR hashing }
{ }
Function CalcXOR8 (const Buf; const BufSize : Integer) : Byte; overload;
Function CalcXOR8 (const Buf : String) : Byte; overload;
Function CalcXOR16 (const Buf; const BufSize : Integer) : Word; overload;
Function CalcXOR16 (const Buf : String) : Word; overload;
Function CalcXOR32 (const Buf; const BufSize : Integer) : LongWord; overload;
Function CalcXOR32 (const Buf : String) : LongWord; overload;
{ }
{ CRC 16 hashing }
{ }
{ The theory behind CCITT V.41 CRCs: }
{ }
{ 1. Select the magnitude of the CRC to be used (typically 16 or 32 }
{ bits) and choose the polynomial to use. In the case of 16 bit }
{ CRCs, the CCITT polynomial is recommended and is }
{ }
{ 16 12 5 }
{ G(x) = x + x + x + 1 }
{ }
{ This polynomial traps 100% of 1 bit, 2 bit, odd numbers of bit }
{ errors, 100% of <= 16 bit burst errors and over 99% of all }
{ other errors. }
{ }
{ 2. The CRC is calculated as }
{ r }
{ D(x) = (M(x) * 2 ) mod G(x) }
{ }
{ This may be better described as : Add r bits (0 content) to }
{ the end of M(x). Divide this by G(x) and the remainder is the }
{ CRC. }
{ }
{ 3. Tag the CRC onto the end of M(x). }
{ }
{ 4. To check it, calculate the CRC of the new message D(x), using }
{ the same process as in 2. above. The newly calculated CRC }
{ should be zero. }
{ }
{ This effectively means that using CRCs, it is possible to calculate a }
{ series of bits to tag onto the data which makes the data an exact }
{ multiple of the polynomial. }
{ }
Procedure CRC16Init (var CRC16 : Word);
Function CRC16Byte (const CRC16 : Word; const Octet : Byte) : Word;
Function CRC16Buf (const CRC16 : Word; const Buf; const BufSize : Integer) : Word;
Function CalcCRC16 (const Buf; const BufSize : Integer) : Word; overload;
Function CalcCRC16 (const Buf : String) : Word; overload;
{ }
{ CRC 32 hashing }
{ }
Procedure SetCRC32Poly (const Poly : LongWord);
Procedure CRC32Init (var CRC32 : LongWord);
Function CRC32Byte (const CRC32 : LongWord; const Octet : Byte) : LongWord;
Function CRC32Buf (const CRC32 : LongWord; const Buf; const BufSize : Integer) : LongWord;
Function CRC32BufNoCase (const CRC32 : LongWord; const Buf; const BufSize : Integer) : LongWord;
Function CalcCRC32 (const Buf; const BufSize : Integer) : LongWord; overload;
Function CalcCRC32 (const Buf : String) : LongWord; overload;
{ }
{ ELF hashing }
{ }
Procedure ELFInit (var Digest : LongWord);
Function ELFBuf (const Digest : LongWord; const Buf; const BufSize : Integer) : LongWord;
Function CalcELF (const Buf; const BufSize : Integer) : LongWord; overload;
Function CalcELF (const Buf : String) : LongWord; overload;
{ }
{ ISBN checksum }
{ }
Function IsValidISBN (const S : String) : Boolean;
{ }
{ LUHN checksum }
{ }
{ The LUHN forumula (also known as mod-10) is used in major credit card }
{ account numbers for validity checking. }
{ }
Function IsValidLUHN (const S : String) : Boolean;
{ }
{ MD5 hashing }
{ }
{ MD5 is an Internet standard secure hashing function, that was }
{ developed by Professor Ronald L. Rivest in 1991. Subsequently it has }
{ been placed in the public domain. }
{ MD5 was developed to be more secure after MD4 was 'broken'. }
{ Den Boer and Bosselaers estimate that if a custom machine were to be }
{ built specifically to find collisions for MD5 (costing $10m in 1994) it }
{ would on average take 24 days to find a collision. }
{ }
Procedure MD5InitDigest (var Digest : T128BitDigest);
Procedure MD5Buf (var Digest : T128BitDigest; const Buf; const BufSize : Integer);
Procedure MD5FinalBuf (var Digest : T128BitDigest; const Buf; const BufSize : Integer;
const TotalSize : Int64);
Function CalcMD5 (const Buf; const BufSize : Integer) : T128BitDigest; overload;
Function CalcMD5 (const Buf : String) : T128BitDigest; overload;
Function MD5DigestAsString (const Digest : T128BitDigest) : String;
Function MD5DigestToHex (const Digest : T128BitDigest) : String;
{ }
{ HMAC-MD5 keyed hashing }
{ }
{ HMAC allows secure keyed hashing (hashing with a password). }
{ HMAC was designed to meet the requirements of the IPSEC working group in }
{ the IETF, and is now a standard. }
{ HMAC, are proven to be secure as long as the underlying hash function }
{ has some reasonable cryptographic strengths. }
{ See RFC 2104 for details on HMAC. }
{ }
Procedure HMAC_MD5Init (const Key : Pointer; const KeySize : Integer;
var Digest : T128BitDigest; var K : String);
Procedure HMAC_MD5Buf (var Digest : T128BitDigest; const Buf; const BufSize : Integer);
Procedure HMAC_MD5FinalBuf (const K : String; var Digest : T128BitDigest;
const Buf; const BufSize : Integer; const TotalSize : Int64);
Function CalcHMAC_MD5 (const Key : Pointer; const KeySize : Integer;
const Buf; const BufSize : Integer) : T128BitDigest; overload;
Function CalcHMAC_MD5 (const Key : String; const Buf; const BufSize : Integer) : T128BitDigest; overload;
Function CalcHMAC_MD5 (const Key, Buf : String) : T128BitDigest; overload;
{ }
{ SHA1 Hashing }
{ }
{ Specification at http://www.itl.nist.gov/fipspubs/fip180-1.htm }
{ Also see RFC 3174. }
{ SHA1 was developed by NIST and is specified in the Secure Hash Standard }
{ (SHS, FIPS 180) and corrects an unpublished flaw the original SHA }
{ algorithm. }
{ SHA1 produces a 160-bit digest and is considered more secure than MD5. }
{ SHA1 has a similar design to the MD4-family of hash functions. }
{ }
Procedure SHA1InitDigest (var Digest : T160BitDigest);
Procedure SHA1Buf (var Digest : T160BitDigest; const Buf; const BufSize : Integer);
Procedure SHA1FinalBuf (var Digest : T160BitDigest; const Buf; const BufSize : Integer;
const TotalSize : Int64);
Function CalcSHA1 (const Buf; const BufSize : Integer) : T160BitDigest; overload;
Function CalcSHA1 (const Buf : String) : T160BitDigest; overload;
Function SHA1DigestAsString (const Digest : T160BitDigest) : String;
Function SHA1DigestToHex (const Digest : T160BitDigest) : String;
{ }
{ HMAC-SHA1 keyed hashing }
{ }
Procedure HMAC_SHA1Init (const Key : Pointer; const KeySize : Integer;
var Digest : T160BitDigest; var K : String);
Procedure HMAC_SHA1Buf (var Digest : T160BitDigest; const Buf; const BufSize : Integer);
Procedure HMAC_SHA1FinalBuf (const K : String; var Digest : T160BitDigest;
const Buf; const BufSize : Integer; const TotalSize : Int64);
Function CalcHMAC_SHA1 (const Key : Pointer; const KeySize : Integer;
const Buf; const BufSize : Integer) : T160BitDigest; overload;
Function CalcHMAC_SHA1 (const Key : String; const Buf; const BufSize : Integer) : T160BitDigest; overload;
Function CalcHMAC_SHA1 (const Key, Buf : String) : T160BitDigest; overload;
{ }
{ Hash class wrappers }
{ }
type
{ AHash }
{ Base class for hash classes. }
AHash = class
protected
FDigest : Pointer;
FTotalSize : Int64;
Procedure InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer); virtual; abstract;
Procedure ProcessBuf (const Buf; const BufSize : Integer); virtual; abstract;
Procedure ProcessFinalBuf (const Buf; const BufSize : Integer; const TotalSize : Int64); virtual;
public
class Function DigestSize : Integer; virtual; abstract;
Procedure Init (const Digest : Pointer; const Key : Pointer = nil;
const KeySize : Integer = 0); overload;
Procedure Init (const Digest : Pointer; const Key : String = ''); overload;
Procedure HashBuf (const Buf; const BufSize : Integer; const FinalBuf : Boolean);
Procedure HashFile (const FileName : String; const Offset : Int64 = 0;
const MaxCount : Int64 = -1);
end;
THashClass = class of AHash;
{ TChecksum32Hash }
TChecksum32Hash = class (AHash)
protected
Procedure InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer); override;
Procedure ProcessBuf (const Buf; const BufSize : Integer); override;
public
class Function DigestSize : Integer; override;
end;
{ TXOR8Hash }
TXOR8Hash = class (AHash)
protected
Procedure InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer); override;
Procedure ProcessBuf (const Buf; const BufSize : Integer); override;
public
class Function DigestSize : Integer; override;
end;
{ TXOR16Hash }
TXOR16Hash = class (AHash)
protected
Procedure InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer); override;
Procedure ProcessBuf (const Buf; const BufSize : Integer); override;
public
class Function DigestSize : Integer; override;
end;
{ TXOR32Hash }
TXOR32Hash = class (AHash)
protected
Procedure InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer); override;
Procedure ProcessBuf (const Buf; const BufSize : Integer); override;
public
class Function DigestSize : Integer; override;
end;
{ TCRC16Hash }
TCRC16Hash = class (AHash)
protected
Procedure InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer); override;
Procedure ProcessBuf (const Buf; const BufSize : Integer); override;
public
class Function DigestSize : Integer; override;
end;
{ TCRC32Hash }
TCRC32Hash = class (AHash)
protected
Procedure InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer); override;
Procedure ProcessBuf (const Buf; const BufSize : Integer); override;
public
class Function DigestSize : Integer; override;
end;
{ TELFHash }
TELFHash = class (AHash)
protected
Procedure InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer); override;
Procedure ProcessBuf (const Buf; const BufSize : Integer); override;
public
class Function DigestSize : Integer; override;
end;
{ TMD5Hash }
TMD5Hash = class (AHash)
protected
Procedure InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer); override;
Procedure ProcessBuf (const Buf; const BufSize : Integer); override;
Procedure ProcessFinalBuf (const Buf; const BufSize : Integer; const TotalSize : Int64); override;
public
class Function DigestSize : Integer; override;
end;
{ THMAC_MD5Hash }
THMAC_MD5Hash = class (AHash)
protected
FKey : String;
Procedure InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer); override;
Procedure ProcessBuf (const Buf; const BufSize : Integer); override;
Procedure ProcessFinalBuf (const Buf; const BufSize : Integer; const TotalSize : Int64); override;
public
class Function DigestSize : Integer; override;
Destructor Destroy; override;
end;
{ TSHA1Hash }
TSHA1Hash = class (AHash)
protected
Procedure InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer); override;
Procedure ProcessBuf (const Buf; const BufSize : Integer); override;
Procedure ProcessFinalBuf (const Buf; const BufSize : Integer; const TotalSize : Int64); override;
public
class Function DigestSize : Integer; override;
end;
{ THMAC_SHA1Hash }
THMAC_SHA1Hash = class (AHash)
protected
FKey : String;
Procedure InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer); override;
Procedure ProcessBuf (const Buf; const BufSize : Integer); override;
Procedure ProcessFinalBuf (const Buf; const BufSize : Integer; const TotalSize : Int64); override;
public
class Function DigestSize : Integer; override;
Destructor Destroy; override;
end;
{ }
{ THashType }
{ }
type
THashType = (hashChecksum32, hashXOR8, hashXOR16, hashXOR32,
hashCRC16, hashCRC32,
hashELF,
hashMD5, hashSHA1,
hashHMAC_MD5, hashHMAC_SHA1);
{ }
{ GetHashClassByType }
{ }
Function GetHashClassByType (const HashType : THashType) : THashClass;
Function GetDigestSize (const HashType : THashType) : Integer;
{ }
{ CalculateHash }
{ }
Procedure CalculateHash (const HashType : THashType;
const Buf; const BufSize : Integer; const Digest : Pointer;
const Key : Pointer = nil; const KeySize : Integer = 0); overload;
Procedure CalculateHash (const HashType : THashType;
const Buf; const BufSize : Integer;
const Digest : Pointer; const Key : String = ''); overload;
Procedure CalculateHash (const HashType : THashType;
const Buf : String; const Digest : Pointer;
const Key : String = ''); overload;
{ }
{ HashString }
{ }
{ HashString is a fast general purpose ASCII string hashing function. }
{ It returns a 32 bit value in the range 0 to Slots - 1. If Slots = 0 then }
{ the full 32 bit value is returned. }
{ If CaseSensitive = False then HashString will return the same hash value }
{ regardless of the case of the characters in the string. }
{ }
{ The implementation is based on CRC32. It uses up to 48 characters from }
{ the string (first 16 characters, last 16 characters and 16 characters }
{ uniformly sampled from the remaining characters) to calculate the hash }
{ value. }
{ }
Function HashString (const StrBuf : Pointer; const StrLength : Integer;
const Slots : LongWord = 0; const CaseSensitive : Boolean = True) : LongWord; overload;
Function HashString (const S : String; const Slots : LongWord = 0;
const CaseSensitive : Boolean = True) : LongWord; overload;
implementation
{ }
{ Hash errors }
{ }
const
hashErrorMessages : Array [0..hashMAX_ERROR] of String = (
'',
'Internal error',
'Invalid hash type',
'Invalid buffer',
'Invalid buffer size',
'Invalid digest',
'Invalid key',
'Invalid file name',
'File open error',
'File seek error',
'File read error',
'Not a keyed hash type',
'Too many open handles',
'Invalid handle');
Function GetHashErrorMessage (const ErrorCode : LongWord) : PChar;
Begin
if (ErrorCode = hashNoError) or (ErrorCode > hashMAX_ERROR) then
Result := nil else
Result := PChar (hashErrorMessages [ErrorCode]);
End;
{ }
{ EHashError }
{ }
Constructor EHashError.Create (const ErrorCode : LongWord; const Msg : String);
Begin
FErrorCode := ErrorCode;
if (Msg = '') and (ErrorCode <= hashMAX_ERROR) then
inherited Create (hashErrorMessages [ErrorCode]) else
inherited Create (Msg);
End;
{ }
{ Checksum hashing }
{ }
{$IFDEF CPU_INTEL386}
Function CalcChecksum32 (const Buf; const BufSize : Integer) : LongWord;
Asm
or eax, eax // eax = Buf
jz @fin
or edx, edx // edx = BufSize
jbe @finz
push esi
mov esi, eax
add esi, edx
xor eax, eax
xor ecx, ecx
@l1:
dec esi
mov cl, [esi]
add eax, ecx
dec edx
jnz @l1
pop esi
@fin:
ret
@finz:
xor eax, eax
End;
{$ELSE}
Function CalcChecksum32 (const Buf; const BufSize : Integer) : LongWord;
var I : Integer;
P : PByte;
Begin
Result := 0;
P := @Buf;
For I := 1 to BufSize do
begin
Inc (Result, P^);
Inc (P);
end;
End;
{$ENDIF}
Function CalcChecksum32 (const Buf : String) : LongWord;
Begin
Result := CalcChecksum32 (Pointer (Buf)^, Length (Buf));
End;
{ }
{ XOR hashing }
{ }
{$IFDEF CPU_INTEL386}
Function XOR32Buf (const Buf; const BufSize : Integer) : LongWord;
Asm
or eax, eax
jz @fin
or edx, edx
jz @finz
push esi
mov esi, eax
xor eax, eax
mov ecx, edx
shr ecx, 2
jz @rest
@l1:
xor eax, [esi]
add esi, 4
dec ecx
jnz @l1
@rest:
and edx, 3
jz @finp
xor al, [esi]
dec edx
jz @finp
inc esi
xor ah, [esi]
dec edx
jz @finp
inc esi
mov dl, [esi]
shl edx, 16
xor eax, edx
@finp:
pop esi
ret
@finz:
xor eax, eax
@fin:
ret
End;
{$ELSE}
Function XOR32Buf (const Buf; const BufSize : Integer) : LongWord;
var I : Integer;
L : Byte;
P : PChar;
Begin
Result := 0;
L := 0;
P := @Buf;
For I := 1 to BufSize do
begin
Result := Result xor (Byte (P^) shl L);
Inc (L, 8);
if L = 32 then
L := 0;
Inc (P);
end;
End;
{$ENDIF}
Function CalcXOR8 (const Buf; const BufSize : Integer) : Byte;
var L : LongWord;
Begin
L := XOR32Buf (Buf, BufSize);
Result := Byte (L) xor
Byte (L shr 8) xor
Byte (L shr 16) xor
Byte (L shr 24);
End;
Function CalcXOR8 (const Buf : String) : Byte;
Begin
Result := CalcXOR8 (Pointer (Buf)^, Length (Buf));
End;
Function CalcXOR16 (const Buf; const BufSize : Integer) : Word;
var L : LongWord;
Begin
L := XOR32Buf (Buf, BufSize);
Result := Word (L) xor
Word (L shr 16);
End;
Function CalcXOR16 (const Buf : String) : Word;
Begin
Result := CalcXOR16 (Pointer (Buf)^, Length (Buf));
End;
Function CalcXOR32 (const Buf; const BufSize : Integer) : LongWord;
Begin
Result := XOR32Buf (Buf, BufSize);
End;
Function CalcXOR32 (const Buf : String) : LongWord;
Begin
Result := XOR32Buf (Pointer (Buf)^, Length (Buf));
End;
{ }
{ CRC 16 hashing }
{ }
const
CRC16Table : Array [Byte] of Word = (
$0000, $1021, $2042, $3063, $4084, $50a5, $60c6, $70e7,
$8108, $9129, $a14a, $b16b, $c18c, $d1ad, $e1ce, $f1ef,
$1231, $0210, $3273, $2252, $52b5, $4294, $72f7, $62d6,
$9339, $8318, $b37b, $a35a, $d3bd, $c39c, $f3ff, $e3de,
$2462, $3443, $0420, $1401, $64e6, $74c7, $44a4, $5485,
$a56a, $b54b, $8528, $9509, $e5ee, $f5cf, $c5ac, $d58d,
$3653, $2672, $1611, $0630, $76d7, $66f6, $5695, $46b4,
$b75b, $a77a, $9719, $8738, $f7df, $e7fe, $d79d, $c7bc,
$48c4, $58e5, $6886, $78a7, $0840, $1861, $2802, $3823,
$c9cc, $d9ed, $e98e, $f9af, $8948, $9969, $a90a, $b92b,
$5af5, $4ad4, $7ab7, $6a96, $1a71, $0a50, $3a33, $2a12,
$dbfd, $cbdc, $fbbf, $eb9e, $9b79, $8b58, $bb3b, $ab1a,
$6ca6, $7c87, $4ce4, $5cc5, $2c22, $3c03, $0c60, $1c41,
$edae, $fd8f, $cdec, $ddcd, $ad2a, $bd0b, $8d68, $9d49,
$7e97, $6eb6, $5ed5, $4ef4, $3e13, $2e32, $1e51, $0e70,
$ff9f, $efbe, $dfdd, $cffc, $bf1b, $af3a, $9f59, $8f78,
$9188, $81a9, $b1ca, $a1eb, $d10c, $c12d, $f14e, $e16f,
$1080, $00a1, $30c2, $20e3, $5004, $4025, $7046, $6067,
$83b9, $9398, $a3fb, $b3da, $c33d, $d31c, $e37f, $f35e,
$02b1, $1290, $22f3, $32d2, $4235, $5214, $6277, $7256,
$b5ea, $a5cb, $95a8, $8589, $f56e, $e54f, $d52c, $c50d,
$34e2, $24c3, $14a0, $0481, $7466, $6447, $5424, $4405,
$a7db, $b7fa, $8799, $97b8, $e75f, $f77e, $c71d, $d73c,
$26d3, $36f2, $0691, $16b0, $6657, $7676, $4615, $5634,
$d94c, $c96d, $f90e, $e92f, $99c8, $89e9, $b98a, $a9ab,
$5844, $4865, $7806, $6827, $18c0, $08e1, $3882, $28a3,
$cb7d, $db5c, $eb3f, $fb1e, $8bf9, $9bd8, $abbb, $bb9a,
$4a75, $5a54, $6a37, $7a16, $0af1, $1ad0, $2ab3, $3a92,
$fd2e, $ed0f, $dd6c, $cd4d, $bdaa, $ad8b, $9de8, $8dc9,
$7c26, $6c07, $5c64, $4c45, $3ca2, $2c83, $1ce0, $0cc1,
$ef1f, $ff3e, $cf5d, $df7c, $af9b, $bfba, $8fd9, $9ff8,
$6e17, $7e36, $4e55, $5e74, $2e93, $3eb2, $0ed1, $1ef0);
Function CRC16Byte (const CRC16 : Word; const Octet : Byte) : Word;
Begin
Result := CRC16Table [Byte (Hi (CRC16) xor Octet)] xor Word (CRC16 shl 8);
End;
Function CRC16Buf (const CRC16 : Word; const Buf; const BufSize : Integer) : Word;
var I : Integer;
P : PByte;
Begin
Result := CRC16;
P := @Buf;
For I := 1 to BufSize do
begin
Result := CRC16Byte (Result, P^);
Inc (P);
end;
End;
Procedure CRC16Init (var CRC16 : Word);
Begin
CRC16 := $FFFF;
End;
Function CalcCRC16 (const Buf; const BufSize : Integer) : Word;
Begin
CRC16Init (Result);
Result := CRC16Buf (Result, Buf, BufSize);
End;
Function CalcCRC16 (const Buf : String) : Word;
Begin
Result := CalcCRC16 (Pointer (Buf)^, Length (Buf));
End;
{ }
{ CRC 32 hashing }
{ }
var
CRC32TableInit : Boolean = False;
CRC32Table : Array [Byte] of LongWord;
CRC32Poly : LongWord = $EDB88320;
Procedure InitCRC32Table;
var I, J : Byte;
R : LongWord;
Begin
For I := $00 to $FF do
begin
R := I;
For J := 8 downto 1 do
if R and 1 <> 0 then
R := (R shr 1) xor CRC32Poly else
R := R shr 1;
CRC32Table [I] := R;
end;
CRC32TableInit := True;
End;
Procedure SetCRC32Poly (const Poly : LongWord);
Begin
CRC32Poly := Poly;
CRC32TableInit := False;
End;
Function CalcCRC32Byte (const CRC32 : LongWord; const Octet : Byte) : LongWord;
Begin
Result := CRC32Table [Byte (CRC32) xor Octet] xor ((CRC32 shr 8) and $00FFFFFF);
End;
Function CRC32Byte (const CRC32 : LongWord; const Octet : Byte) : LongWord;
Begin
if not CRC32TableInit then
InitCRC32Table;
Result := CalcCRC32Byte (CRC32, Octet);
End;
Function CRC32Buf (const CRC32 : LongWord; const Buf; const BufSize : Integer) : LongWord;
var P : PByte;
I : Integer;
Begin
if not CRC32TableInit then
InitCRC32Table;
P := @Buf;
Result := CRC32;
For I := 1 to BufSize do
begin
Result := CalcCRC32Byte (Result, P^);
Inc (P);
end;
End;
Function CRC32BufNoCase (const CRC32 : LongWord; const Buf; const BufSize : Integer) : LongWord;
var P : PByte;
I : Integer;
C : Byte;
Begin
if not CRC32TableInit then
InitCRC32Table;
P := @Buf;
Result := CRC32;
For I := 1 to BufSize do
begin
C := P^;
if Char (C) in ['A'..'Z'] then
C := C or 32;
Result := CalcCRC32Byte (Result, C);
Inc (P);
end;
End;
Procedure CRC32Init (var CRC32 : LongWord);
Begin
CRC32 := $FFFFFFFF;
End;
Function CalcCRC32 (const Buf; const BufSize : Integer) : LongWord;
Begin
CRC32Init (Result);
Result := not CRC32Buf (Result, Buf, BufSize);
End;
Function CalcCRC32 (const Buf : String) : LongWord;
Begin
Result := CalcCRC32 (Pointer (Buf)^, Length (Buf));
End;
{ }
{ ELF hashing }
{ }
Procedure ELFInit (var Digest : LongWord);
Begin
Digest := 0;
End;
Function ELFBuf (const Digest : LongWord; const Buf; const BufSize : Integer) : LongWord;
var I : Integer;
P : PByte;
X : LongWord;
Begin
Result := Digest;
P := @Buf;
For I := 1 to BufSize do
begin
Result := (Result shl 4) + P^;
Inc (P);
X := Result and $F0000000;
if X <> 0 then
Result := Result xor (X shr 24);
Result := Result and (not X);
end;
End;
Function CalcELF (const Buf; const BufSize : Integer) : LongWord;
Begin
Result := ELFBuf (0, Buf, BufSize);
End;
Function CalcELF (const Buf : String) : LongWord;
Begin
Result := CalcELF (Pointer (Buf)^, Length (Buf));
End;
{ }
{ ISBN checksum }
{ }
Function IsValidISBN (const S : String) : Boolean;
var I, L, M, D, C : Integer;
P : PChar;
Begin
L := Length (S);
if L < 10 then // too few digits
begin
Result := False;
exit;
end;
M := 10;
C := 0;
P := Pointer (S);
For I := 1 to L do
begin
if (P^ in ['0'..'9']) or ((M = 1) and (P^ in ['x', 'X'])) then
begin
if M = 0 then // too many digits
begin
Result := False;
exit;
end;
if P^ in ['x', 'X'] then
D := 10 else
D := Ord (P^) - Ord ('0');
Inc (C, M * D);
Dec (M);
end;
Inc (P);
end;
if M > 0 then // too few digits
begin
Result := False;
exit;
end;
Result := C mod 11 = 0;
End;
{ }
{ LUHN checksum }
{ }
Function IsValidLUHN (const S : String) : Boolean;
var P : PChar;
I, L, M, C, D : Integer;
R : Boolean;
Begin
L := Length (S);
if L = 0 then
begin
Result := False;
exit;
end;
P := Pointer (S);
Inc (P, L - 1);
C := 0;
M := 0;
R := False;
For I := 1 to L do
begin
if P^ in ['0'..'9'] then
begin
D := Ord (P^) - Ord ('0');
if R then
begin
D := D * 2;
D := (D div 10) + (D mod 10);
end;
Inc (C, D);
Inc (M);
R := not R;
end;
Dec (P);
end;
Result := (M >= 1) and (C mod 10 = 0);
End;
{ }
{ Digests }
{ }
Procedure DigestToHexBuf (const Digest; const Size : Integer; const Buf);
const s_HexDigitsLower : String [16] = '0123456789abcdef';
var I : Integer;
P : PChar;
Q : PByte;
Begin
P := @Buf;;
Assert (Assigned (P), 'Assigned (Buf)');
Q := @Digest;
Assert (Assigned (Q), 'Assigned (Digest)');
For I := 0 to Size - 1 do
begin
P^ := s_HexDigitsLower [Q^ shr 4 + 1];
Inc (P);
P^ := s_HexDigitsLower [Q^ and 15 + 1];
Inc (P);
Inc (Q);
end;
End;
Function DigestToHex (const Digest; const Size : Integer) : String;
Begin
SetLength (Result, Size * 2);
DigestToHexBuf (Digest, Size, Pointer (Result)^);
End;
Function Digest128Equal (const Digest1, Digest2 : T128BitDigest) : Boolean;
var I : Integer;
Begin
For I := 0 to 3 do
if Digest1.Longs[I] <> Digest2.Longs[I] then
begin
Result := False;
exit;
end;
Result := True;
End;
Function Digest160Equal (const Digest1, Digest2 : T160BitDigest) : Boolean;
var I : Integer;
Begin
For I := 0 to 4 do
if Digest1.Longs[I] <> Digest2.Longs[I] then
begin
Result := False;
exit;
end;
Result := True;
End;
{ }
{ MD5 hashing }
{ }
const
MD5Table_1 : Array [0..15] of LongWord = (
$D76AA478, $E8C7B756, $242070DB, $C1BDCEEE,
$F57C0FAF, $4787C62A, $A8304613, $FD469501,
$698098D8, $8B44F7AF, $FFFF5BB1, $895CD7BE,
$6B901122, $FD987193, $A679438E, $49B40821);
MD5Table_2 : Array [0..15] of LongWord = (
$F61E2562, $C040B340, $265E5A51, $E9B6C7AA,
$D62F105D, $02441453, $D8A1E681, $E7D3FBC8,
$21E1CDE6, $C33707D6, $F4D50D87, $455A14ED,
$A9E3E905, $FCEFA3F8, $676F02D9, $8D2A4C8A);
MD5Table_3 : Array [0..15] of LongWord = (
$FFFA3942, $8771F681, $6D9D6122, $FDE5380C,
$A4BEEA44, $4BDECFA9, $F6BB4B60, $BEBFBC70,
$289B7EC6, $EAA127FA, $D4EF3085, $04881D05,
$D9D4D039, $E6DB99E5, $1FA27CF8, $C4AC5665);
MD5Table_4 : Array [0..15] of LongWord = (
$F4292244, $432AFF97, $AB9423A7, $FC93A039,
$655B59C3, $8F0CCC92, $FFEFF47D, $85845DD1,
$6FA87E4F, $FE2CE6E0, $A3014314, $4E0811A1,
$F7537E82, $BD3AF235, $2AD7D2BB, $EB86D391);
{ Calculates a MD5 Digest (16 bytes) given a Buffer (64 bytes) }
{$Q-}
Procedure TransformMD5Buffer (var Digest : T128BitDigest; const Buffer);
var A, B, C, D : LongWord;
P : PLongWord;
I : Integer;
J : Byte;
Buf : Array [0..15] of LongWord absolute Buffer;
Begin
A := Digest.Longs [0];
B := Digest.Longs [1];
C := Digest.Longs [2];
D := Digest.Longs [3];
P := @MD5Table_1;
For I := 0 to 3 do
begin
J := I * 4;
Inc (A, Buf [J] + P^ + (D xor (B and (C xor D)))); A := A shl 7 or A shr 25 + B; Inc (P);
Inc (D, Buf [J + 1] + P^ + (C xor (A and (B xor C)))); D := D shl 12 or D shr 20 + A; Inc (P);
Inc (C, Buf [J + 2] + P^ + (B xor (D and (A xor B)))); C := C shl 17 or C shr 15 + D; Inc (P);
Inc (B, Buf [J + 3] + P^ + (A xor (C and (D xor A)))); B := B shl 22 or B shr 10 + C; Inc (P);
end;
P := @MD5Table_2;
For I := 0 to 3 do
begin
J := I * 4;
Inc (A, Buf [J + 1] + P^ + (C xor (D and (B xor C)))); A := A shl 5 or A shr 27 + B; Inc (P);
Inc (D, Buf [(J + 6) mod 16] + P^ + (B xor (C and (A xor B)))); D := D shl 9 or D shr 23 + A; Inc (P);
Inc (C, Buf [(J + 11) mod 16] + P^ + (A xor (B and (D xor A)))); C := C shl 14 or C shr 18 + D; Inc (P);
Inc (B, Buf [J] + P^ + (D xor (A and (C xor D)))); B := B shl 20 or B shr 12 + C; Inc (P);
end;
P := @MD5Table_3;
For I := 0 to 3 do
begin
J := 16 - (I * 4);
Inc (A, Buf [(J + 5) mod 16] + P^ + (B xor C xor D)); A := A shl 4 or A shr 28 + B; Inc (P);
Inc (D, Buf [(J + 8) mod 16] + P^ + (A xor B xor C)); D := D shl 11 or D shr 21 + A; Inc (P);
Inc (C, Buf [(J + 11) mod 16] + P^ + (D xor A xor B)); C := C shl 16 or C shr 16 + D; Inc (P);
Inc (B, Buf [(J + 14) mod 16] + P^ + (C xor D xor A)); B := B shl 23 or B shr 9 + C; Inc (P);
end;
P := @MD5Table_4;
For I := 0 to 3 do
begin
J := 16 - (I * 4);
Inc (A, Buf [J mod 16] + P^ + (C xor (B or not D))); A := A shl 6 or A shr 26 + B; Inc (P);
Inc (D, Buf [(J + 7) mod 16] + P^ + (B xor (A or not C))); D := D shl 10 or D shr 22 + A; Inc (P);
Inc (C, Buf [(J + 14) mod 16] + P^ + (A xor (D or not B))); C := C shl 15 or C shr 17 + D; Inc (P);
Inc (B, Buf [(J + 5) mod 16] + P^ + (D xor (C or not A))); B := B shl 21 or B shr 11 + C; Inc (P);
end;
Inc (Digest.Longs [0], A);
Inc (Digest.Longs [1], B);
Inc (Digest.Longs [2], C);
Inc (Digest.Longs [3], D);
End;
{$IFDEF DEBUG}{$Q+}{$ENDIF}
Procedure MD5InitDigest (var Digest : T128BitDigest);
Begin
Digest.Longs [0] := $67452301; // fixed initialization key
Digest.Longs [1] := $EFCDAB89;
Digest.Longs [2] := $98BADCFE;
Digest.Longs [3] := $10325476;
End;
Procedure MD5Buf (var Digest : T128BitDigest; const Buf; const BufSize : Integer);
var P : PByte;
I, J : Integer;
Begin
I := BufSize;
if I <= 0 then
exit;
Assert (I mod 64 = 0, 'BufSize must be multiple of 64 bytes');
P := @Buf;
For J := 0 to I div 64 - 1 do
begin
TransformMD5Buffer (Digest, P^);
Inc (P, 64);
end;
End;
Procedure ReverseMem (var Buf; const BufSize : Integer);
var I : Integer;
P : PByte;
Q : PByte;
T : Byte;
Begin
P := @Buf;
Q := P;
Inc (Q, BufSize - 1);
For I := 1 to BufSize div 2 do
begin
T := P^;
P^ := Q^;
Q^ := T;
Inc (P);
Dec (Q);
end;
End;
Procedure StdFinalBuf (const Buf; const BufSize : Integer; const TotalSize : Int64; var Buf1, Buf2 : String; const SwapEndian : Boolean);
var P, Q : PByte;
I : Integer;
L : Int64;
Begin
Assert (BufSize < 64, 'Final BufSize must be less than 64 bytes');
Assert (TotalSize >= BufSize, 'TotalSize >= BufSize');
P := @Buf;
SetLength (Buf1, 64);
Q := Pointer (Buf1);
if BufSize > 0 then
begin
Move (P^, Q^, BufSize);
Inc (Q, BufSize);
end;
Q^ := $80;
Inc (Q);
L := Int64 (TotalSize * 8);
if SwapEndian then
ReverseMem (L, 8);
if BufSize + 1 > 64 - Sizeof (Int64) then
begin
FillChar (Q^, 64 - BufSize - 1, #0);
SetLength (Buf2, 64);
Q := Pointer (Buf2);
FillChar (Q^, 64 - Sizeof (Int64), #0);
Inc (Q, 64 - Sizeof (Int64));
PInt64 (Q)^ := L;
end else
begin
I := 64 - Sizeof (Int64) - BufSize - 1;
FillChar (Q^, I, #0);
Inc (Q, I);
PInt64 (Q)^ := L;
Buf2 := '';
end;
End;
Procedure MD5FinalBuf (var Digest : T128BitDigest; const Buf; const BufSize : Integer; const TotalSize : Int64);
var S1, S2 : String;
Begin
StdFinalBuf (Buf, BufSize, TotalSize, S1, S2, False);
TransformMD5Buffer (Digest, Pointer (S1)^);
if S2 <> '' then
TransformMD5Buffer (Digest, Pointer (S2)^);
End;
Function CalcMD5 (const Buf; const BufSize : Integer) : T128BitDigest;
var I, J : Integer;
P : PByte;
Begin
MD5InitDigest (Result);
P := @Buf;
if BufSize <= 0 then
I := 0 else
I := BufSize;
J := (I div 64) * 64;
if J > 0 then
begin
MD5Buf (Result, P^, J);
Inc (P, J);
Dec (I, J);
end;
MD5FinalBuf (Result, P^, I, BufSize);
End;
Function CalcMD5 (const Buf : String) : T128BitDigest;
Begin
Result := CalcMD5 (Pointer (Buf)^, Length (Buf));
End;
Function MD5DigestAsString (const Digest : T128BitDigest) : String;
Begin
SetLength (Result, Sizeof (Digest));
Move (Digest, Pointer (Result)^, Sizeof (Digest));
End;
Function MD5DigestToHex (const Digest : T128BitDigest) : String;
Begin
Result := DigestToHex (Digest, Sizeof (Digest));
End;
{ }
{ HMAC-MD5 keyed hashing }
{ }
Procedure XORBlock (var Buf : String; const XOR8 : Byte);
var I : Integer;
Begin
For I := 1 to Length (Buf) do
Buf [I] := Char (Byte (Buf [I]) xor XOR8);
End;
Procedure SecureClear (var Buf; const BufSize : Integer);
Begin
if BufSize <= 0 then
exit;
// Securely clear memory
FillChar (Buf, BufSize, #$AA);
FillChar (Buf, BufSize, #$55);
FillChar (Buf, BufSize, #0);
End;
Procedure SecureClearStr (var S : String);
Begin
SecureClear (Pointer (S)^, Length (S));
End;
Procedure HMAC_KeyBlock (const Key; const KeySize : Integer; var Buf : String);
var P : PChar;
Begin
Assert (KeySize <= 64, 'KeySize <= 64');
SetLength (Buf, 64);
P := Pointer (Buf);
if KeySize > 0 then
begin
Move (Key, P^, KeySize);
Inc (P, KeySize);
end;
FillChar (P^, 64 - KeySize, #0);
End;
Procedure HMAC_MD5Init (const Key : Pointer; const KeySize : Integer; var Digest : T128BitDigest; var K : String);
var S : String;
D : T128BitDigest;
Begin
MD5InitDigest (Digest);
if KeySize > 64 then
begin
D := CalcMD5 (Key^, KeySize);
HMAC_KeyBlock (D, Sizeof (D), K);
end else
HMAC_KeyBlock (Key^, KeySize, K);
S := K;
XORBlock (S, $36);
TransformMD5Buffer (Digest, Pointer (S)^);
SecureClearStr (S);
End;
Procedure HMAC_MD5Buf (var Digest : T128BitDigest; const Buf; const BufSize : Integer);
Begin
MD5Buf (Digest, Buf, BufSize);
End;
Procedure HMAC_MD5FinalBuf (const K : String; var Digest : T128BitDigest; const Buf; const BufSize : Integer; const TotalSize : Int64);
var S : String;
Begin
MD5FinalBuf (Digest, Buf, BufSize, TotalSize + 64);
S := K;
XORBlock (S, $5C);
Digest := CalcMD5 (S + MD5DigestAsString (Digest));
SecureClearStr (S);
End;
Function CalcHMAC_MD5 (const Key : Pointer; const KeySize : Integer; const Buf; const BufSize : Integer) : T128BitDigest;
var I, J : Integer;
P : PByte;
K : String;
Begin
HMAC_MD5Init (Key, KeySize, Result, K);
P := @Buf;
if BufSize <= 0 then
I := 0 else
I := BufSize;
J := (I div 64) * 64;
if J > 0 then
begin
HMAC_MD5Buf (Result, P^, J);
Inc (P, J);
Dec (I, J);
end;
HMAC_MD5FinalBuf (K, Result, P^, I, BufSize);
SecureClearStr (K);
End;
Function CalcHMAC_MD5 (const Key : String; const Buf; const BufSize : Integer) : T128BitDigest;
Begin
Result := CalcHMAC_MD5 (Pointer (Key), Length (Key), Buf, BufSize);
End;
Function CalcHMAC_MD5 (const Key, Buf : String) : T128BitDigest;
Begin
Result := CalcHMAC_MD5 (Key, Pointer (Buf)^, Length (Buf));
End;
{ }
{ SHA hashing }
{ }
Procedure SHA1InitDigest (var Digest : T160BitDigest);
var P : P128BitDigest;
Begin
P := @Digest;
MD5InitDigest (P^);
Digest.Longs [4] := $C3D2E1F0;
End;
Function SwapEndian (const Value : LongWord) : LongWord;
Asm
XCHG AH, AL
ROL EAX, 16
XCHG AH, AL
End;
Procedure SwapEndianBuf (var Buf; const Count : Integer);
var P : PLongWord;
I : Integer;
Begin
P := @Buf;
For I := 1 to Count do
begin
P^ := SwapEndian (P^);
Inc (P);
end;
End;
Function RotateLeftBits (const Value : LongWord; const Bits : Byte) : LongWord;
Asm
MOV CL, DL
ROL EAX, CL
End;
{ Calculates a SHA Digest (20 bytes) given a Buffer (64 bytes) }
{$Q-}
Procedure TransformSHABuffer (var Digest : T160BitDigest; const Buffer; const SHA1 : Boolean);
var A, B, C, D, E : LongWord;
W : Array [0..79] of LongWord;
P, Q : PLongWord;
I : Integer;
J : LongWord;
Begin
P := @Buffer;
Q := @W;
For I := 0 to 15 do
begin
Q^ := SwapEndian (P^);
Inc (P);
Inc (Q);
end;
For I := 0 to 63 do
begin
P := Q;
Dec (P, 16);
J := P^;
Inc (P, 2);
J := J xor P^;
Inc (P, 6);
J := J xor P^;
Inc (P, 5);
J := J xor P^;
if SHA1 then
J := RotateLeftBits (J, 1);
Q^ := J;
Inc (Q);
end;
A := Digest.Longs [0];
B := Digest.Longs [1];
C := Digest.Longs [2];
D := Digest.Longs [3];
E := Digest.Longs [4];
P := @W;
For I := 0 to 3 do
begin
Inc (E, (A shl 5 or A shr 27) + (D xor (B and (C xor D))) + P^ + $5A827999); B := B shr 2 or B shl 30; Inc (P);
Inc (D, (E shl 5 or E shr 27) + (C xor (A and (B xor C))) + P^ + $5A827999); A := A shr 2 or A shl 30; Inc (P);
Inc (C, (D shl 5 or D shr 27) + (B xor (E and (A xor B))) + P^ + $5A827999); E := E shr 2 or E shl 30; Inc (P);
Inc (B, (C shl 5 or C shr 27) + (A xor (D and (E xor A))) + P^ + $5A827999); D := D shr 2 or D shl 30; Inc (P);
Inc (A, (B shl 5 or B shr 27) + (E xor (C and (D xor E))) + P^ + $5A827999); C := C shr 2 or C shl 30; Inc (P);
end;
For I := 0 to 3 do
begin
Inc (E, (A shl 5 or A shr 27) + (D xor B xor C) + P^ + $6ED9EBA1); B := B shr 2 or B shl 30; Inc (P);
Inc (D, (E shl 5 or E shr 27) + (C xor A xor B) + P^ + $6ED9EBA1); A := A shr 2 or A shl 30; Inc (P);
Inc (C, (D shl 5 or D shr 27) + (B xor E xor A) + P^ + $6ED9EBA1); E := E shr 2 or E shl 30; Inc (P);
Inc (B, (C shl 5 or C shr 27) + (A xor D xor E) + P^ + $6ED9EBA1); D := D shr 2 or D shl 30; Inc (P);
Inc (A, (B shl 5 or B shr 27) + (E xor C xor D) + P^ + $6ED9EBA1); C := C shr 2 or C shl 30; Inc (P);
end;
For I := 0 to 3 do
begin
Inc (E, (A shl 5 or A shr 27) + ((B and C) or (D and (B or C))) + P^ + $8F1BBCDC); B := B shr 2 or B shl 30; Inc (P);
Inc (D, (E shl 5 or E shr 27) + ((A and B) or (C and (A or B))) + P^ + $8F1BBCDC); A := A shr 2 or A shl 30; Inc (P);
Inc (C, (D shl 5 or D shr 27) + ((E and A) or (B and (E or A))) + P^ + $8F1BBCDC); E := E shr 2 or E shl 30; Inc (P);
Inc (B, (C shl 5 or C shr 27) + ((D and E) or (A and (D or E))) + P^ + $8F1BBCDC); D := D shr 2 or D shl 30; Inc (P);
Inc (A, (B shl 5 or B shr 27) + ((C and D) or (E and (C or D))) + P^ + $8F1BBCDC); C := C shr 2 or C shl 30; Inc (P);
end;
For I := 0 to 3 do
begin
Inc (E, (A shl 5 or A shr 27) + (D xor B xor C) + P^ + $CA62C1D6); B := B shr 2 or B shl 30; Inc (P);
Inc (D, (E shl 5 or E shr 27) + (C xor A xor B) + P^ + $CA62C1D6); A := A shr 2 or A shl 30; Inc (P);
Inc (C, (D shl 5 or D shr 27) + (B xor E xor A) + P^ + $CA62C1D6); E := E shr 2 or E shl 30; Inc (P);
Inc (B, (C shl 5 or C shr 27) + (A xor D xor E) + P^ + $CA62C1D6); D := D shr 2 or D shl 30; Inc (P);
Inc (A, (B shl 5 or B shr 27) + (E xor C xor D) + P^ + $CA62C1D6); C := C shr 2 or C shl 30; Inc (P);
end;
Inc (Digest.Longs [0], A);
Inc (Digest.Longs [1], B);
Inc (Digest.Longs [2], C);
Inc (Digest.Longs [3], D);
Inc (Digest.Longs [4], E);
End;
{$IFDEF DEBUG}{$Q+}{$ENDIF}
Procedure SHA1Buf (var Digest : T160BitDigest; const Buf; const BufSize : Integer);
var P : PByte;
I, J : Integer;
Begin
I := BufSize;
if I <= 0 then
exit;
Assert (I mod 64 = 0, 'BufSize must be multiple of 64 bytes');
P := @Buf;
For J := 0 to I div 64 - 1 do
begin
TransformSHABuffer (Digest, P^, True);
Inc (P, 64);
end;
End;
Procedure SHA1FinalBuf (var Digest : T160BitDigest; const Buf; const BufSize : Integer; const TotalSize : Int64);
var S1, S2 : String;
Begin
StdFinalBuf (Buf, BufSize, TotalSize, S1, S2, True);
TransformSHABuffer (Digest, Pointer (S1)^, True);
if S2 <> '' then
TransformSHABuffer (Digest, Pointer (S2)^, True);
SwapEndianBuf (Digest, Sizeof (Digest) div Sizeof (LongWord));
End;
Function CalcSHA1 (const Buf; const BufSize : Integer) : T160BitDigest;
var I, J : Integer;
P : PByte;
Begin
SHA1InitDigest (Result);
P := @Buf;
if BufSize <= 0 then
I := 0 else
I := BufSize;
J := (I div 64) * 64;
if J > 0 then
begin
SHA1Buf (Result, P^, J);
Inc (P, J);
Dec (I, J);
end;
SHA1FinalBuf (Result, P^, I, BufSize);
End;
Function CalcSHA1 (const Buf : String) : T160BitDigest;
Begin
Result := CalcSHA1 (Pointer (Buf)^, Length (Buf));
End;
Function SHA1DigestAsString (const Digest : T160BitDigest) : String;
Begin
SetLength (Result, Sizeof (Digest));
Move (Digest, Pointer (Result)^, Sizeof (Digest));
End;
Function SHA1DigestToHex (const Digest : T160BitDigest) : String;
Begin
Result := DigestToHex (Digest, Sizeof (Digest));
End;
{ }
{ HMAC-SHA1 keyed hashing }
{ }
Procedure HMAC_SHA1Init (const Key : Pointer; const KeySize : Integer; var Digest : T160BitDigest; var K : String);
var D : T160BitDigest;
S : String;
Begin
SHA1InitDigest (Digest);
if KeySize > 64 then
begin
D := CalcSHA1 (Key^, KeySize);
HMAC_KeyBlock (D, Sizeof (D), K);
end else
HMAC_KeyBlock (Key^, KeySize, K);
S := K;
XORBlock (S, $36);
TransformSHABuffer (Digest, Pointer (S)^, True);
SecureClearStr (S);
End;
Procedure HMAC_SHA1Buf (var Digest : T160BitDigest; const Buf; const BufSize : Integer);
Begin
SHA1Buf (Digest, Buf, BufSize);
End;
Procedure HMAC_SHA1FinalBuf (const K : String; var Digest : T160BitDigest; const Buf; const BufSize : Integer; const TotalSize : Int64);
var S : String;
Begin
SHA1FinalBuf (Digest, Buf, BufSize, TotalSize + 64);
S := K;
XORBlock (S, $5C);
Digest := CalcSHA1 (S + SHA1DigestAsString (Digest));
SecureClearStr (S);
End;
Function CalcHMAC_SHA1 (const Key : Pointer; const KeySize : Integer; const Buf; const BufSize : Integer) : T160BitDigest;
var I, J : Integer;
P : PByte;
K : String;
Begin
HMAC_SHA1Init (Key, KeySize, Result, K);
P := @Buf;
if BufSize <= 0 then
I := 0 else
I := BufSize;
J := (I div 64) * 64;
if J > 0 then
begin
HMAC_SHA1Buf (Result, P^, J);
Inc (P, J);
Dec (I, J);
end;
HMAC_SHA1FinalBuf (K, Result, P^, I, BufSize);
SecureClearStr (K);
End;
Function CalcHMAC_SHA1 (const Key : String; const Buf; const BufSize : Integer) : T160BitDigest;
Begin
Result := CalcHMAC_SHA1 (Pointer (Key), Length (Key), Buf, BufSize);
End;
Function CalcHMAC_SHA1 (const Key, Buf : String) : T160BitDigest;
Begin
Result := CalcHMAC_SHA1 (Key, Pointer (Buf)^, Length (Buf));
End;
{ }
{ CalculateHash }
{ }
Procedure CalculateHash (const HashType : THashType;
const Buf; const BufSize : Integer;
const Digest : Pointer;
const Key : Pointer; const KeySize : Integer);
Begin
if KeySize > 0 then
Case HashType of
hashHMAC_MD5 : P128BitDigest (Digest)^ := CalcHMAC_MD5 (Key, KeySize, Buf, BufSize);
hashHMAC_SHA1 : P160BitDigest (Digest)^ := CalcHMAC_SHA1 (Key, KeySize, Buf, BufSize);
else
raise EHashError.Create (hashNotKeyedHashType);
end
else
Case HashType of
hashChecksum32 : PLongWord (Digest)^ := CalcChecksum32 (Buf, BufSize);
hashXOR8 : PByte (Digest)^ := CalcXOR8 (Buf, BufSize);
hashXOR16 : PWord (Digest)^ := CalcXOR16 (Buf, BufSize);
hashXOR32 : PLongWord (Digest)^ := CalcXOR32 (Buf, BufSize);
hashCRC16 : PWord (Digest)^ := CalcCRC16(Buf, BufSize);
hashCRC32 : PLongWord (Digest)^ := CalcCRC32 (Buf, BufSize);
hashMD5 : P128BitDigest (Digest)^ := CalcMD5 (Buf, BufSize);
hashSHA1 : P160BitDigest (Digest)^ := CalcSHA1 (Buf, BufSize);
hashHMAC_MD5 : P128BitDigest (Digest)^ := CalcHMAC_MD5 (nil, 0, Buf, BufSize);
hashHMAC_SHA1 : P160BitDigest (Digest)^ := CalcHMAC_SHA1 (nil, 0, Buf, BufSize);
else
raise EHashError.Create (hashInvalidHashType);
end;
End;
Procedure CalculateHash (const HashType : THashType; const Buf; const BufSize : Integer; const Digest : Pointer; const Key : String);
Begin
CalculateHash (HashType, Buf, BufSize, Digest, Pointer (Key), Length (Key));
End;
Procedure CalculateHash (const HashType : THashType; const Buf : String; const Digest : Pointer; const Key : String);
Begin
CalculateHash (HashType, Pointer (Buf)^, Length (Buf), Digest, Key);
End;
{ }
{ AHash }
{ }
Procedure AHash.ProcessFinalBuf (const Buf; const BufSize : Integer; const TotalSize : Int64);
Begin
ProcessBuf (Buf, BufSize);
End;
Procedure AHash.Init (const Digest : Pointer; const Key : Pointer; const KeySize : Integer);
Begin
Assert (Assigned (Digest), 'Assigned (Digest)');
FDigest := Digest;
FTotalSize := 0;
InitHash (Digest, Key, KeySize);
End;
Procedure AHash.Init (const Digest : Pointer; const Key : String);
Begin
Init (Digest, Pointer (Key), Length (Key));
End;
Procedure AHash.HashBuf (const Buf; const BufSize : Integer; const FinalBuf : Boolean);
var I : Integer;
P : PChar;
Begin
Inc (FTotalSize, BufSize);
P := @Buf;
I := (BufSize div 64) * 64;
if I > 0 then
begin
ProcessBuf (P^, I);
Inc (P, I);
end;
I := BufSize mod 64;
if FinalBuf then
ProcessFinalBuf (P^, I, FTotalSize) else
if I > 0 then
raise EHashError.Create (hashInvalidBufferSize, 'Buffer must be multiple of 64 bytes');
End;
Procedure AHash.HashFile (const FileName : String; const Offset : Int64; const MaxCount : Int64);
const ChunkSize = 8192;
var Handle : Integer;
Buf : Pointer;
I, C : Integer;
Left : Int64;
Fin : Boolean;
Begin
if FileName = '' then
raise EHashError.Create (hashInvalidFileName);
Handle := FileOpen (FileName, fmOpenReadWrite or fmShareDenyNone);
if Handle = -1 then
raise EHashError.Create (hashFileOpenError);
if Offset > 0 then
I := FileSeek (Handle, Offset, 0) else
if Offset < 0 then
I := FileSeek (Handle, Offset, 2) else
I := 0;
if I = -1 then
raise EHashError.Create (hashFileSeekError);
try
GetMem (Buf, ChunkSize);
try
if MaxCount < 0 then
Left := High (Int64) else
Left := MaxCount;
Repeat
if Left > ChunkSize then
C := ChunkSize else
C := Left;
if C = 0 then
begin
I := 0;
Fin := True;
end else
begin
I := FileRead (Handle, Buf^, C);
if I = -1 then
raise EHashError.Create (hashFileReadError);
Dec (Left, I);
Fin := (I < C) or (Left <= 0);
end;
HashBuf (Buf^, I, Fin);
Until Fin;
finally
FreeMem (Buf, ChunkSize);
end;
finally
FileClose (Handle);
end;
End;
{ }
{ TChecksum32Hash }
{ }
Procedure TChecksum32Hash.InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer);
Begin
PLongWord (Digest)^ := 0;
End;
Procedure TChecksum32Hash.ProcessBuf (const Buf; const BufSize : Integer);
Begin
PLongWord (FDigest)^ := PLongWord (FDigest)^ + CalcChecksum32 (Buf, BufSize);
End;
class Function TChecksum32Hash.DigestSize : Integer;
Begin
Result := 4;
End;
{ }
{ TXOR8Hash }
{ }
Procedure TXOR8Hash.InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer);
Begin
PByte (Digest)^ := 0;
End;
Procedure TXOR8Hash.ProcessBuf (const Buf; const BufSize : Integer);
Begin
PByte (FDigest)^ := PByte (FDigest)^ xor CalcXOR8 (Buf, BufSize);
End;
class Function TXOR8Hash.DigestSize : Integer;
Begin
Result := 1;
End;
{ }
{ TXOR16Hash }
{ }
Procedure TXOR16Hash.InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer);
Begin
PWord (Digest)^ := 0;
End;
Procedure TXOR16Hash.ProcessBuf (const Buf; const BufSize : Integer);
Begin
PWord (FDigest)^ := PWord (FDigest)^ xor CalcXOR16 (Buf, BufSize);
End;
class Function TXOR16Hash.DigestSize : Integer;
Begin
Result := 2;
End;
{ }
{ TXOR32Hash }
{ }
Procedure TXOR32Hash.InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer);
Begin
PLongWord (Digest)^ := 0;
End;
Procedure TXOR32Hash.ProcessBuf (const Buf; const BufSize : Integer);
Begin
PLongWord (FDigest)^ := PLongWord (FDigest)^ xor CalcXOR32 (Buf, BufSize);
End;
class Function TXOR32Hash.DigestSize : Integer;
Begin
Result := 4;
End;
{ }
{ TCRC16Hash }
{ }
Procedure TCRC16Hash.InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer);
Begin
CRC16Init (PWord (Digest)^);
End;
Procedure TCRC16Hash.ProcessBuf (const Buf; const BufSize : Integer);
Begin
PWord (FDigest)^ := CRC16Buf (PWord (FDigest)^, Buf, BufSize);
End;
class Function TCRC16Hash.DigestSize : Integer;
Begin
Result := 2;
End;
{ }
{ TCRC32Hash }
{ }
Procedure TCRC32Hash.InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer);
Begin
CRC32Init (PLongWord (Digest)^);
End;
Procedure TCRC32Hash.ProcessBuf (const Buf; const BufSize : Integer);
Begin
PLongWord (FDigest)^ := CRC32Buf (PLongWord (FDigest)^, Buf, BufSize);
End;
class Function TCRC32Hash.DigestSize : Integer;
Begin
Result := 4;
End;
{ }
{ TELFHash }
{ }
Procedure TELFHash.InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer);
Begin
ELFInit (PLongWord (Digest)^);
End;
Procedure TELFHash.ProcessBuf (const Buf; const BufSize : Integer);
Begin
PLongWord (FDigest)^ := ELFBuf (PLongWord (FDigest)^, Buf, BufSize);
End;
class Function TELFHash.DigestSize : Integer;
Begin
Result := 4;
End;
{ }
{ TMD5Hash }
{ }
Procedure TMD5Hash.InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer);
Begin
MD5InitDigest (P128BitDigest (FDigest)^);
End;
Procedure TMD5Hash.ProcessBuf (const Buf; const BufSize : Integer);
Begin
MD5Buf (P128BitDigest (FDigest)^, Buf, BufSize);
End;
Procedure TMD5Hash.ProcessFinalBuf (const Buf; const BufSize : Integer; const TotalSize : Int64);
Begin
MD5FinalBuf (P128BitDigest (FDigest)^, Buf, BufSize, TotalSize);
End;
class Function TMD5Hash.DigestSize : Integer;
Begin
Result := 16;
End;
{ }
{ THMAC_MD5Hash }
{ }
Destructor THMAC_MD5Hash.Destroy;
Begin
SecureClearStr (FKey);
inherited Destroy;
End;
Procedure THMAC_MD5Hash.InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer);
Begin
HMAC_MD5Init (Key, KeySize, P128BitDigest (FDigest)^, FKey);
End;
Procedure THMAC_MD5Hash.ProcessBuf (const Buf; const BufSize : Integer);
Begin
HMAC_MD5Buf (P128BitDigest (FDigest)^, Buf, BufSize);
End;
Procedure THMAC_MD5Hash.ProcessFinalBuf (const Buf; const BufSize : Integer; const TotalSize : Int64);
Begin
HMAC_MD5FinalBuf (FKey, P128BitDigest (FDigest)^, Buf, BufSize, TotalSize);
End;
class Function THMAC_MD5Hash.DigestSize : Integer;
Begin
Result := 16;
End;
{ }
{ TSHA1Hash }
{ }
Procedure TSHA1Hash.InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer);
Begin
SHA1InitDigest (P160BitDigest (FDigest)^);
End;
Procedure TSHA1Hash.ProcessBuf (const Buf; const BufSize : Integer);
Begin
SHA1Buf (P160BitDigest (FDigest)^, Buf, BufSize);
End;
Procedure TSHA1Hash.ProcessFinalBuf (const Buf; const BufSize : Integer; const TotalSize : Int64);
Begin
SHA1FinalBuf (P160BitDigest (FDigest)^, Buf, BufSize, TotalSize);
End;
class Function TSHA1Hash.DigestSize : Integer;
Begin
Result := 20;
End;
{ }
{ THMAC_SHA1Hash }
{ }
Destructor THMAC_SHA1Hash.Destroy;
Begin
SecureClearStr (FKey);
inherited Destroy;
End;
Procedure THMAC_SHA1Hash.InitHash (const Digest : Pointer; const Key : Pointer; const KeySize : Integer);
Begin
HMAC_SHA1Init (Key, KeySize, P160BitDigest (FDigest)^, FKey);
End;
Procedure THMAC_SHA1Hash.ProcessBuf (const Buf; const BufSize : Integer);
Begin
HMAC_SHA1Buf (P160BitDigest (FDigest)^, Buf, BufSize);
End;
Procedure THMAC_SHA1Hash.ProcessFinalBuf (const Buf; const BufSize : Integer; const TotalSize : Int64);
Begin
HMAC_SHA1FinalBuf (FKey, P160BitDigest (FDigest)^, Buf, BufSize, TotalSize);
End;
class Function THMAC_SHA1Hash.DigestSize : Integer;
Begin
Result := 20;
End;
{ }
{ HashString }
{ }
Function HashString (const StrBuf : Pointer; const StrLength : Integer; const Slots : LongWord; const CaseSensitive : Boolean) : LongWord;
var P : PChar;
I, J : Integer;
Procedure CRC32StrBuf (const Size : Integer);
Begin
if CaseSensitive then
Result := CRC32Buf (Result, P^, Size) else
Result := CRC32BufNoCase (Result, P^, Size);
End;
Begin
// Return 0 for an empty string
Result := 0;
if (StrLength <= 0) or not Assigned (StrBuf) then
exit;
if not CRC32TableInit then
InitCRC32Table;
Result := $FFFFFFFF;
P := StrBuf;
if StrLength <= 48 then // Hash everything for short strings
CRC32StrBuf (StrLength) else
begin
// Hash first 16 bytes
CRC32StrBuf (16);
// Hash last 16 bytes
Inc (P, StrLength - 16);
CRC32StrBuf (16);
// Hash 16 bytes sampled from rest of string
I := (StrLength - 48) div 16;
P := StrBuf;
Inc (P, 16);
For J := 1 to 16 do
begin
CRC32StrBuf (1);
Inc (P, I + 1);
end;
end;
// Mod into slots
if (Slots <> 0) and (Slots <> High (LongWord)) then
Result := Result mod Slots;
End;
Function HashString (const S : String; const Slots : LongWord; const CaseSensitive : Boolean) : LongWord;
Begin
Result := HashString (Pointer (S), Length (S), Slots, CaseSensitive);
End;
{ }
{ Hash by THashType }
{ }
const
HashTypeClasses : Array [THashType] of THashClass = (
TChecksum32Hash, TXOR8Hash, TXOR16Hash, TXOR32Hash,
TCRC16Hash, TCRC32Hash, TELFHash,
TMD5Hash, TSHA1Hash,
THMAC_MD5Hash, THMAC_SHA1Hash);
Function GetHashClassByType (const HashType : THashType) : THashClass;
Begin
Result := HashTypeClasses [HashType];
End;
Function GetDigestSize (const HashType : THashType) : Integer;
Begin
Result := GetHashClassByType (HashType).DigestSize;
End;
{ }
{ Self testing code }
{ }
{$IFDEF SELFTEST}
Procedure Test_Unit (const U : TUnit);
var S, T : String;
Begin
With U do
begin
TestID := 'Hash';
AssertEq (CalcChecksum32 (''), 0, 'CalcChecksum32');
AssertEq (CalcChecksum32 ('A'), 65, 'CalcChecksum32');
AssertEq (CalcChecksum32 ('Delphi Fundamentals'), 1880, 'CalcChecksum32');
AssertEq (CalcXOR8 (''), 0, 'CalcXOR8');
AssertEq (CalcXOR8 ('A'), 65, 'CalcXOR8');
AssertEq (CalcXOR8 ('Delphi Fundamentals'), 40, 'CalcXOR8');
AssertEq (CalcXOR16 (''), 0, 'CalcXOR16');
AssertEq (CalcXOR16 ('A'), 65, 'CalcXOR16');
AssertEq (CalcXOR16 ('AB'), $4241, 'CalcXOR16');
AssertEq (CalcXOR16 ('Delphi Fundamentals'), $4860, 'CalcXOR16');
AssertEq (CalcXOR32 (''), 0, 'CalcXOR32');
AssertEq (CalcXOR32 ('A'), 65, 'CalcXOR32');
AssertEq (CalcXOR32 ('ABCD'), $44434241, 'CalcXOR32');
AssertEq (CalcXOR32 ('Delphi Fundamentals'), $23356B55, 'CalcXOR32');
AssertEq (CalcCRC16 (''), $FFFF, 'CalcCRC16');
AssertEq (CalcCRC16 ('Delphi Fundamentals'), 18831, 'CalcCRC16');
AssertEq (CalcCRC32 (''), 0, 'CalcCRC32');
AssertEq (CalcCRC32 ('Delphi Fundamentals'), 3810393938, 'CalcCRC32');
AssertEq (MD5DigestToHex (CalcMD5 ('')), 'd41d8cd98f00b204e9800998ecf8427e', 'CalcMD5');
AssertEq (MD5DigestToHex (CalcMD5 ('Delphi Fundamentals')), 'ea98b65da23d19756d46a36faa481dd8', 'CalcMD5');
AssertEq (SHA1DigestToHex (CalcSHA1 ('')), 'da39a3ee5e6b4b0d3255bfef95601890afd80709', 'CalcSHA1');
AssertEq (SHA1DigestToHex (CalcSHA1 ('Delphi Fundamentals')), '6c412217909d2767d36a6bbeab5e50e14b19b941', 'CalcSHA1');
AssertEq (MD5DigestToHex (CalcHMAC_MD5 ('', '')), '74e6f7298a9c2d168935f58c001bad88', 'CalcHMAC_MD5');
AssertEq (MD5DigestToHex (CalcHMAC_MD5 ('', 'Delphi Fundamentals')), 'b9da02d5f94bd6eac410708a72b05d9f', 'CalcHMAC_MD5');
AssertEq (MD5DigestToHex (CalcHMAC_MD5 ('Delphi Fundamentals', '')), 'a09f3300c236156d27f4d031db7e91ce', 'CalcHMAC_MD5');
AssertEq (MD5DigestToHex (CalcHMAC_MD5 ('Delphi', 'Fundamentals')), '1c4e8a481c2c781eb43ca58d9324c37d', 'CalcHMAC_MD5');
AssertEq (SHA1DigestToHex (CalcHMAC_SHA1 ('', '')), 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', 'CalcHMAC_SHA1');
AssertEq (SHA1DigestToHex (CalcHMAC_SHA1 ('', 'Delphi Fundamentals')), '62f9196071f587cde151d8b99919ed0f6e51bf26', 'CalcHMAC_SHA1');
AssertEq (SHA1DigestToHex (CalcHMAC_SHA1 ('Delphi Fundamentals', '')), 'e4dbfa59f410ee75c368c1ba6df1a2c701e0cea0', 'CalcHMAC_SHA1');
AssertEq (SHA1DigestToHex (CalcHMAC_SHA1 ('Delphi', 'Fundamentals')), 'fa96341a0b790f3a6f3248b7053372ede8d41e7c', 'CalcHMAC_SHA1');
AssertEq (HashString ('Delphi Fundamentals', 0, False),
HashString ('dELPHI fundamentalS', 0, False), 'HashString');
AssertEq (HashString ('Delphi Fundamentals', 0, True), 484573357);
AssertEq (IsValidISBN ('3880530025'), True, 'ISBN');
AssertEq (IsValidLUHN ('49927398716'), True, 'ISBN');
// Test cases from RFC 2202
AssertEq (MD5DigestToHex (CalcHMAC_MD5 ('Jefe', 'what do ya want for nothing?')), '750c783e6ab0b503eaa86e310a5db738', 'CalcHMAC_MD5');
SetLength (S, 16); FillChar (Pointer (S)^, 16, #$0B);
AssertEq (MD5DigestToHex (CalcHMAC_MD5 (S, 'Hi There')), '9294727a3638bb1c13f48ef8158bfc9d', 'CalcHMAC_MD5');
SetLength (S, 16); FillChar (Pointer (S)^, 16, #$AA);
SetLength (T, 50); FillChar (Pointer (T)^, 50, #$DD);
AssertEq (MD5DigestToHex (CalcHMAC_MD5 (S, T)), '56be34521d144c88dbb8c733f0e8b3f6', 'CalcHMAC_MD5');
SetLength (S, 80); FillChar (Pointer (S)^, 80, #$AA);
AssertEq (MD5DigestToHex (CalcHMAC_MD5 (S, 'Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data')), '6f630fad67cda0ee1fb1f562db3aa53e', 'CalcHMAC_MD5');
AssertEq (SHA1DigestToHex (CalcHMAC_SHA1 ('Jefe', 'what do ya want for nothing?')), 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79', 'CalcHMAC_SHA1');
SetLength (S, 20); FillChar (Pointer (S)^, 20, #$0B);
AssertEq (SHA1DigestToHex (CalcHMAC_SHA1 (S, 'Hi There')), 'b617318655057264e28bc0b6fb378c8ef146be00', 'CalcHMAC_SHA1');
SetLength (S, 80); FillChar (Pointer (S)^, 80, #$AA);
AssertEq (SHA1DigestToHex (CalcHMAC_SHA1 (S, 'Test Using Larger Than Block-Size Key - Hash Key First')), 'aa4ae5e15272d00e95705637ce8a3b55ed402112', 'CalcHMAC_SHA1');
end;
End;
{$ENDIF}
end.
|
unit UCtrlMediaPlayers;
interface
uses
MPlayer, Classes, WavePlayer;
const
NUM_MPLAYERS = 1; // número de players para cada som;
// a idéia de criar múltiplos players para um som é
// para permitir um curto intervalo entre um mesmo som
type
TCtrlMediaPlayer = class
private
// FMP: array [0..NUM_MPLAYERS-1] of TWavePlayer;
// FMP: array [0..NUM_MPLAYERS-1] of TMediaPlayer;
// FIndToque: Integer;
// FWavePlayer: TWavePlayer;
FResStream: TResourceStream;
public
constructor Cria(Nome: String);
destructor Destroy; override;
procedure Toque;
end;
implementation
uses
SysUtils, MMSystem, port_UFrmDSL, port_Recursos, port_PasTokens,
port_PascalInterpreter;
//var
// CntNomeMM: Integer; // usado na identificaçao dos media players criados
{ TCtrlMediaPlayer }
constructor TCtrlMediaPlayer.Cria(Nome: String);
//var
// I: Integer;
// NomeArq: String;
begin
try
FResStream := TResourceStream.Create(HInstance, Nome, 'WAVE');
except
raise EInterpreterException.Create(sFalhaToqSom + ' (' + Nome + ')', 1, 1, nil);
end;
// for I := 0 to NUM_MPLAYERS - 1 do
// begin
// ResStream.Position := 0;
(*
FMP[I] := TWavePlayer.Create;
FMP[I].Source := ResStream;
FMP[I].Open;
*)
(*
NomeArq := Recursos.NomeArqTemporario();
ResStream.Position := 0;
ResStream.SaveToFile(NomeArq);
FMP[I] := TMediaPlayer.Create(nil);
// Inc(CntNomeMM);
// FMP[I].Name := 'MM' + IntToStr(CntNomeMM);
FMP[I].SetBounds(-1000, -1000, 100, 100);
FMP[I].Parent := FrmDSL;
// FMP[I].Visible := True;
FMP[I].DeviceType := dtWaveAudio;
FMP[I].FileName := NomeArq;
FMP[I].Open;
end;
*)
end;
destructor TCtrlMediaPlayer.Destroy;
begin
FResStream.Free;
inherited;
end;
procedure TCtrlMediaPlayer.Toque;
begin
PlaySound(FResStream.Memory, HInstance, SND_ASYNC or
SND_MEMORY or
SND_NODEFAULT or
SND_NOWAIT);
// if FMP[FIndToque].Mode <> mpStopped then
// FMP[FIndToque].Stop;
// FMP[FIndToque].Play;
// FIndToque := (FIndToque + 1) mod NUM_MPLAYERS;
// FWavePlayer.Play;
end;
end.
|
unit ncaFrmNFeDepend;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.Menus, Vcl.StdCtrls,
cxButtons, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel,
LMDSimplePanel, cxLabel;
type
TFrmNFeDepend = class(TForm)
lbPrompt: TcxLabel;
LMDSimplePanel4: TLMDSimplePanel;
btnSalvar: TcxButton;
lbInfo: TcxLabel;
btnCancelar: TcxButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnSalvarClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
private
{ Private declarations }
class function TipoNFStr: String;
public
{ Public declarations }
class function DependOk: Boolean;
end;
var
FrmNFeDepend: TFrmNFeDepend;
implementation
{$R *.dfm}
uses ncaDM, ncaProgressoDepend, ncClassesBase;
procedure TFrmNFeDepend.btnCancelarClick(Sender: TObject);
var S: String;
begin
ShowMessage('A emissão de NF-e está ativada para sua loja. É necessário instalar componentes adicionais para emissão de NF, sem isso não é possível realizar novas vendas');
Close;
end;
procedure TFrmNFeDepend.btnSalvarClick(Sender: TObject);
begin
NotifySucessoDepend := True;
ncaDM.NotityErroDepend := True;
Dados.CM.InstalaNFeDepend;
ModalResult := mrOk;
end;
class function TFrmNFeDepend.DependOk: Boolean;
begin
Result := True;
with Dados do begin
if not tNFConfigEmitirNFe.Value then Exit;
Result := tNFConfigDependNFeOk.Value;
end;
if not Result then begin
if Assigned(panProgressoDepend) then
ShowMessage('Para realizar vendas é necessário aguardar o término da instalação dos arquivos necessários para emissão de NF-e')
else
TFrmNFeDepend.Create(nil).ShowModal;
end;
end;
procedure TFrmNFeDepend.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
class function TFrmNFeDepend.TipoNFStr: String;
begin
Result := 'NF-e';
end;
end.
|
unit CwAs.Xml.XmlUtils;
interface
// KOmmentar
uses SysUtils, Xml.XMLIntf;
type
TXMLUtil = class(TObject)
class var
FFormat: TFormatSettings;
private
public
class constructor Create;
class function DateTimeToXML(aDateTime: TDateTime): string;
class function DoubleToVar(const aValue: Double): Variant;
class function FindChildNode(const aNode: IXMLNode; const aElementName: string; out aResultNode: IXMLNode): boolean;
class function GetChildValue(const aNode: IXMLNode; const aElementName: string): variant;
class function GetChildValueAsString(const aNode: IXMLNode; const aElementName: string): string;
class function GetChildValueAsInteger(const aNode: IXMLNode; const aElementName: string): integer;
class function GetChildValueAsDouble(const aNode: IXMLNode; const aElementName: string): double;
class function GetChildValueAsBoolean(const aNode: IXMLNode; const aElementName: string): Boolean;
class procedure StringToXml(var aString: string);
class function VarToDouble(const aDoubleVar: variant): double; static;
class function VarToInteger(const aIntVar: variant): Integer; static;
class function XMLToDateTime(aStringDate: String): TDateTime;
class procedure XmlToString(var aString: string); //Ikke i bruk. "Motsvarende" til StringToXml
end;
implementation
uses
Variants;
const
XML_ACTUAL: Array [0..4] of String = ('&','<','>', '"','''');
XML_TRANSFORM: Array [0..4] of String = ('&','<', '>', '"', ''');
class constructor TXMLUtil.Create;
begin
FFormat := TFormatSettings.Create;
FFormat.DecimalSeparator := '.';
end;
class function TXMLUtil.DateTimeToXML(aDateTime: TDateTime): string;
begin
{
Kan opgså gjøre det slik, men da legges tidsforskjell/tidssone til bakerst i strengen. Siden vi ikke vet helt hvordan
vi skal takle dette, og vi ikke gidder å tenke på det akkurat nå, lar vi opprinnelig kode være som før.
function DateTimeToXML(aDateTime: TDateTime): string;
var
vXSDateTime: TXSDateTime;
begin
vXSDateTime := TXSDateTime.Create;
try
vXSDateTime.AsDateTime := aDateTime;
Result := vXSDateTime.NativeToXS;
finally
vXSDateTime.Free;
end;
end;
}
if aDateTime = 0 then result := ''
else
begin
Result := FormatDateTime('yyyy-mm-dd',aDateTime);
if Frac(aDateTime) <> 0 then result := result + 'T' +
FormatDateTime('hh":"nn":"ss',aDateTime);
end;
end;
class function TXMLUtil.DoubleToVar(const aValue: Double): Variant;
begin
Result := FloatToStr(aValue, FFormat);
end;
class function TXMLUtil.FindChildNode(const aNode: IXMLNode; const aElementName: string; out aResultNode: IXMLNode):
boolean;
var
I: Integer;
vNode: IXMLNode;
begin
aResultNode := nil;
// Ikke casesensitive søk etter childe nodes
for I := 0 to aNode.ChildNodes.Count - 1 do
begin
vNode := aNode.ChildNodes.Get(I);
if (CompareText(vNode.LocalName,aElementName) = 0)
or (CompareText(vNode.NodeName,aElementName) = 0)
then
begin
aResultNode := vNode;
exit(true);
end;
end;
result := false;
end;
class function TXMLUtil.GetChildValue(const aNode: IXMLNode; const aElementName: string): variant;
var
vNode: IXMLNode;
begin
if FindChildNode(aNode,aElementName,vNode) then
result := vNode.NodeValue
else
result := null;
end;
class function TXMLUtil.GetChildValueAsString(const aNode: IXMLNode; const aElementName: string): string;
begin
result := VarToStr(GetChildValue(aNode, aElementName));
end;
class function TXMLUtil.GetChildValueAsInteger(const aNode: IXMLNode; const aElementName: string): integer;
begin
result := VarToInteger(GetChildValue(aNode, aElementName));
end;
class function TXMLUtil.GetChildValueAsDouble(const aNode: IXMLNode; const aElementName: string): double;
begin
result := VarToDouble(GetChildValue(aNode, aElementName));
end;
class function TXMLUtil.GetChildValueAsBoolean(const aNode: IXMLNode; const aElementName: string): Boolean;
begin
result := VarToStr(GetChildValue(aNode, aElementName)) = 'true';
end;
class procedure TXMLUtil.StringToXml(var aString: string);
var
I: Integer;
begin
if not(aString = EmptyStr) then
for I :=0 to High(XML_ACTUAL) do aString := StringReplace(aString, XML_ACTUAL[I], XML_TRANSFORM[I], [rfReplaceAll, rfIgnoreCase]);
end;
class function TXMLUtil.VarToDouble(const aDoubleVar: variant): double;
begin
if VarIsNull(aDoubleVar) or VarIsEmpty(aDoubleVar) then
Result := 0
else
result := StrToFloat(aDoubleVar,FFormat);
end;
class function TXMLUtil.VarToInteger(const aIntVar: variant): Integer;
begin
if VarIsNull(aIntVar) or VarIsEmpty(aIntVar) then
Result := 0
else
result := aIntVar;
end;
(*
function CheckValidDate(aDate: variant): Variant;
begin
if VarType(aDate) <> varDate then Result := 0.0
else Result := aDate;
end;
*)
class function TXMLUtil.XMLToDateTime(aStringDate: String): TDateTime;
begin
{
Kan også gjøre det slik, emn kutter det ut pga problemstillinger rundt lagring av tidssone (se DateTimeToXML)
function XMLToDateTime(aStringDate: String): TDateTime;
var
vXSDateTime: TXSDateTime;
begin
vXSDateTime := TXSDateTime.Create;
try
vXSDateTime.XSToNative(aStringDate);
Result := vXSDateTime.AsDateTime;
finally
vXSDateTime.Free;
end;
end;
}
if aStringDate = '' then result := 0
else
begin
//try SB: Fjernet 04.03.2014
Result := EncodeDate(StrToInt(Copy(aStringDate,1,4)), StrToInt(Copy(aStringDate,6,2)), StrToInt(Copy(aStringDate,9,2)) );
if Copy(aStringDate,12,2) > '' then Result := Result + EncodeTime(StrToInt(Copy(aStringDate,12,2)), StrToInt(Copy(aStringDate,15,2)), StrToInt(Copy(aStringDate,18,2)), 0 );
//except
//end;
end;
end;
class procedure TXMLUtil.XmlToString(var aString: string);
var
I: Integer;
begin
if not(aString = EmptyStr) and (Pos('&', aString) > 0) then
for I :=0 to High(XML_ACTUAL) do aString := StringReplace(aString, XML_TRANSFORM[I], XML_ACTUAL[I], [rfReplaceAll, rfIgnoreCase]);
end;
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit BindCompProperties;
interface
uses
System.SysUtils, System.Classes, Data.Bind.Components,
System.Rtti, System.Generics.Collections, System.TypInfo;
type
TEnumeratePropertyProc = function(LProperty: TRttiProperty; AParentType: TRttiType; AParentProperties: TList<TRttiProperty>;
var AEnumChildren: Boolean): Boolean of object;
TDataBindingComponentPropertyNames = class
private
FList: TList<string>;
FHasProperties: Boolean;
FComponent: TObject;
procedure UpdatePropertyNames;
function ListEnumeratePropertyCallback(AProperty: TRttiProperty;
AParentType: TRttiType; AParentProperties: TList<TRttiProperty>;
var LEnumChildren: Boolean): Boolean;
function HasEnumeratePropertyCallback(AProperty: TRttiProperty;
AParentType: TRttiType; AParentProperties: TList<TRttiProperty>;
var LEnumChildren: Boolean): Boolean;
function GetPropertyNames: TArray<string>;
function FilterProperty(AProperty: TRttiProperty): Boolean;
function GetHasProperties: Boolean;
public
constructor Create(AComponent: TObject);
destructor Destroy; override;
property PropertyNames: TArray<string> read GetPropertyNames;
property HasProperties: Boolean read GetHasProperties;
end;
procedure EnumeratePropertyNames(AType: TRttiType; AProc: TEnumeratePropertyProc); overload; forward;
procedure EnumeratePropertyNames(AObject: TObject; AProc: TEnumeratePropertyProc); overload; forward;
implementation
procedure EnumeratePropertyNames(AType: TRttiType; AParentProperty: TRttiProperty; AParentTypes: TList<TRttiType>;
AParentProperties: TList<TRttiProperty>;
AProc: TEnumeratePropertyProc); overload;
var
LProperties: TArray<TRttiProperty>;
LField: TRttiProperty;
LParentTypes: TList<TRttiType>;
LParentProperties: TList<TRttiProperty>;
LEnumChildren: Boolean;
begin
LProperties := AType.GetProperties;
if Length(LProperties) > 0 then
begin
if AParentTypes.Contains(AType) then
begin
// Recursive
Exit;
end;
if AParentProperty <> nil then
AParentProperties.Add(AParentProperty);
AParentTypes.Add(AType);
for LField in LProperties do
begin
LParentTypes := TList<TRttiType>.Create(AParentTypes);
LParentProperties := TList<TRttiProperty>.Create(AParentProperties);
try
LEnumChildren := True;
if not AProc(LField, LParentTypes[0], LParentProperties, LEnumChildren) then
break;
if LEnumChildren then
EnumeratePropertyNames(LField.PropertyType, LField, LParentTypes, LParentProperties, AProc);
finally
LParentTypes.Free;
LParentProperties.Free;
end;
end;
end;
end;
procedure EnumeratePropertyNames(AType: TRttiType; AProc: TEnumeratePropertyProc); overload;
var
LParentTypes: TList<TRttiType>;
LParentProperties: TList<TRttiProperty>;
begin
LParentTypes := TList<TRttiType>.Create;
LParentProperties := TList<TRttiProperty>.Create;
try
EnumeratePropertyNames(AType, nil, LParentTypes, LParentProperties, AProc);
finally
LParentTypes.Free;
LParentProperties.Free;
end;
end;
procedure EnumeratePropertyNames(AObject: TObject; AProc: TEnumeratePropertyProc); overload;
var
LContext: TRttiContext;
LType: TRttiInstanceType;
begin
LType := LContext.GetType(AObject.ClassType) as TRttiInstanceType;
EnumeratePropertyNames(LType, AProc);
end;
constructor TDataBindingComponentPropertyNames.Create(AComponent: TObject);
begin
Assert(AComponent <> nil);
FComponent := AComponent;
end;
destructor TDataBindingComponentPropertyNames.Destroy;
begin
FList.Free;
inherited;
end;
function TDataBindingComponentPropertyNames.FilterProperty(AProperty: TRttiProperty): Boolean;
begin
Result := False;
if not AProperty.IsWritable then
Exit;
if AProperty.Visibility = TMemberVisibility.mvPrivate then
Exit;
if AProperty.Visibility = TMemberVisibility.mvProtected then
Exit;
Result := False;
case AProperty.PropertyType.TypeKind of
tkUnknown: ;
tkInteger: Result := True;
tkChar: Result := True;
tkEnumeration: Result := True;
tkFloat: Result := True;
tkString: Result := True;
tkSet: Result := True;
tkClass: ;
tkMethod: ;
tkWChar: Result := True;
tkLString: Result := True;
tkWString: Result := True;
tkVariant: Result := True;
tkArray: ;
tkRecord: ;
tkInterface: ;
tkInt64: Result := True;
tkDynArray: ;
tkUString: Result := True;
tkClassRef: ;
tkPointer: ;
tkProcedure: ;
end;
end;
function TDataBindingComponentPropertyNames.HasEnumeratePropertyCallback(
AProperty: TRttiProperty; AParentType: TRttiType;
AParentProperties: TList<TRttiProperty>; var LEnumChildren: Boolean): Boolean;
begin
LEnumChildren := False;
if not FilterProperty(AProperty) then
Exit(True);
FHasProperties := True;
Exit(False);
end;
function TDataBindingComponentPropertyNames.ListEnumeratePropertyCallback(AProperty: TRttiProperty; AParentType: TRttiType; AParentProperties: TList<TRttiProperty>;
var LEnumChildren: Boolean): Boolean;
var
LName: string;
LParentProperty: TRttiProperty;
begin
LEnumChildren := False;
if not FilterProperty(AProperty) then
Exit(True);
try
for LParentProperty in AParentProperties do
if LName <> '' then
LName := LName + '.' + LParentProperty.Name
else
LName := LParentProperty.Name;
if LName <> '' then
LName := LName + '.' + AProperty.Name
else
LName := AProperty.Name;
except
LName := AProperty.Name;
end;
if not FList.Contains(LName) then
FList.Add(LName);
Result := True;
end;
function TDataBindingComponentPropertyNames.GetHasProperties: Boolean;
begin
FHasProperties := False;
EnumeratePropertyNames(FComponent, HasEnumeratePropertyCallback);
Result := FHasProperties;
end;
function TDataBindingComponentPropertyNames.GetPropertyNames: TArray<string>;
begin
if FList = nil then
begin
FList := TList<string>.Create;
UpdatePropertyNames;
end;
Result := FList.ToArray;
end;
procedure TDataBindingComponentPropertyNames.UpdatePropertyNames;
begin
FList.Clear;
EnumeratePropertyNames(FComponent, ListEnumeratePropertyCallback);
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit System.Contnrs;
interface
uses
System.SysUtils, System.Classes;
type
{ TObjectList class }
TObjectList = class(TList)
private
FOwnsObjects: Boolean;
protected
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
function GetItem(Index: Integer): TObject; inline;
procedure SetItem(Index: Integer; AObject: TObject); inline;
public
constructor Create; overload;
constructor Create(AOwnsObjects: Boolean); overload;
function Add(AObject: TObject): Integer; inline;
function Extract(Item: TObject): TObject; inline;
function ExtractItem(Item: TObject; Direction: TList.TDirection): TObject; inline;
function Remove(AObject: TObject): Integer; overload; inline;
function RemoveItem(AObject: TObject; ADirection: TList.TDirection): Integer; inline;
function IndexOf(AObject: TObject): Integer; inline;
function IndexOfItem(AObject: TObject; ADirection: TList.TDirection): Integer; inline;
function FindInstanceOf(AClass: TClass; AExact: Boolean = True; AStartAt: Integer = 0): Integer;
procedure Insert(Index: Integer; AObject: TObject); inline;
function First: TObject; inline;
function Last: TObject; inline;
property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects;
property Items[Index: Integer]: TObject read GetItem write SetItem; default;
end;
{ TComponentList class }
TComponentList = class(TObjectList)
private
FNexus: TComponent;
protected
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
function GetItems(Index: Integer): TComponent; inline;
procedure SetItems(Index: Integer; AComponent: TComponent); inline;
procedure HandleFreeNotify(Sender: TObject; AComponent: TComponent);
public
constructor Create; overload;
constructor Create(AOwnsObjects: Boolean); overload;
destructor Destroy; override;
function Add(AComponent: TComponent): Integer; inline;
function Extract(Item: TComponent): TComponent; inline;
function ExtractItem(Item: TComponent; Direction: TList.TDirection): TComponent; inline;
function Remove(AComponent: TComponent): Integer; inline;
function RemoveItem(AComponent: TComponent; ADirection: TList.TDirection): Integer; inline;
function IndexOf(AComponent: TComponent): Integer; inline;
function IndexOfItem(AComponent: TComponent; ADirection: TList.TDirection): Integer; inline;
function First: TComponent; inline;
function Last: TComponent; inline;
procedure Insert(Index: Integer; AComponent: TComponent); inline;
property Items[Index: Integer]: TComponent read GetItems write SetItems; default;
end;
{ TClassList class }
TClassList = class(TList)
protected
function GetItems(Index: Integer): TClass; inline;
procedure SetItems(Index: Integer; AClass: TClass); inline;
public
function Add(AClass: TClass): Integer; inline;
function Extract(Item: TClass): TClass; inline;
function ExtractItem(Item: TClass; Direction: TList.TDirection): TClass; inline;
function Remove(AClass: TClass): Integer; inline;
function RemoveItem(AClass: TClass; ADirection: TList.TDirection): Integer; inline;
function IndexOf(AClass: TClass): Integer; inline;
function IndexOfItem(AClass: TClass; ADirection: TList.TDirection): Integer; inline;
function First: TClass; inline;
function Last: TClass; inline;
procedure Insert(Index: Integer; AClass: TClass); inline;
property Items[Index: Integer]: TClass read GetItems write SetItems; default;
end;
{ TOrdered class }
TOrderedList = class(TObject)
private
FList: TList;
protected
procedure PushItem(AItem: Pointer); virtual; abstract;
function PopItem: Pointer; virtual;
function PeekItem: Pointer; virtual;
property List: TList read FList;
public
constructor Create;
destructor Destroy; override;
function Count: Integer;
function AtLeast(ACount: Integer): Boolean;
function Push(AItem: Pointer): Pointer;
function Pop: Pointer; inline;
function Peek: Pointer; inline;
end;
{ TStack class }
TStack = class(TOrderedList)
protected
procedure PushItem(AItem: Pointer); override;
end;
{ TObjectStack class }
TObjectStack = class(TStack)
public
function Push(AObject: TObject): TObject; inline;
function Pop: TObject; inline;
function Peek: TObject; inline;
end;
{ TQueue class }
TQueue = class(TOrderedList)
protected
procedure PushItem(AItem: Pointer); override;
end;
{ TObjectQueue class }
TObjectQueue = class(TQueue)
public
function Push(AObject: TObject): TObject; inline;
function Pop: TObject; inline;
function Peek: TObject; inline;
end;
{ TBucketList, Hashed associative list }
TCustomBucketList = class;
TBucketItem = record
Item, Data: Pointer;
end;
TBucketItemArray = array of TBucketItem;
TBucket = record
Count: Integer;
Items: TBucketItemArray;
end;
TBucketArray = array of TBucket;
TBucketProc = procedure (AInfo, AItem, AData: Pointer; out AContinue: Boolean);
TBucketEvent = procedure (AItem, AData: Pointer; out AContinue: Boolean) of object;
TCustomBucketList = class(TObject)
private
FBuckets: TBucketArray;
FBucketCount: Integer;
FListLocked: Boolean;
FClearing: Boolean;
function GetData(AItem: Pointer): Pointer;
procedure SetData(AItem: Pointer; const AData: Pointer);
procedure SetBucketCount(const Value: Integer);
protected
property Buckets: TBucketArray read FBuckets;
property BucketCount: Integer read FBucketCount write SetBucketCount;
function BucketFor(AItem: Pointer): Integer; virtual; abstract;
function FindItem(AItem: Pointer; out ABucket, AIndex: Integer): Boolean; virtual;
function AddItem(ABucket: Integer; AItem, AData: Pointer): Pointer; virtual;
function DeleteItem(ABucket: Integer; AIndex: Integer): Pointer; virtual;
public
destructor Destroy; override;
procedure Clear;
function Add(AItem, AData: Pointer): Pointer;
function Remove(AItem: Pointer): Pointer;
function ForEach(AProc: TBucketProc; AInfo: Pointer = nil): Boolean; overload;
function ForEach(AEvent: TBucketEvent): Boolean; overload;
procedure Assign(AList: TCustomBucketList);
function Exists(AItem: Pointer): Boolean;
function Find(AItem: Pointer; out AData: Pointer): Boolean;
property Data[AItem: Pointer]: Pointer read GetData write SetData; default;
end;
{ TBucketList }
TBucketListSizes = (bl2, bl4, bl8, bl16, bl32, bl64, bl128, bl256);
TBucketList = class(TCustomBucketList)
private
FBucketMask: Byte;
protected
function BucketFor(AItem: Pointer): Integer; override;
public
constructor Create(ABuckets: TBucketListSizes = bl16);
end;
{ TObjectBucketList }
TObjectBucketList = class(TBucketList)
protected
function GetData(AItem: TObject): TObject;
procedure SetData(AItem: TObject; const AData: TObject);
public
function Add(AItem, AData: TObject): TObject;
function Remove(AItem: TObject): TObject;
property Data[AItem: TObject]: TObject read GetData write SetData; default;
end;
TIntegerBucketList = class(TBucketList)
protected
function GetData(AItem: NativeInt): NativeInt;
procedure SetData(AItem: NativeInt; const AData: NativeInt);
public
function Add(AItem, AData: NativeInt): NativeInt;
function Remove(AItem: NativeInt): NativeInt;
property Data[AItem: NativeInt]: NativeInt read GetData write SetData; default;
end;
{ Easy access error message }
procedure RaiseListError(const ATemplate: string; const AData: array of const); deprecated;
implementation
uses
System.RTLConsts, System.Math;
{ Easy access error message }
procedure RaiseListError(const ATemplate: string; const AData: array of const);
begin
raise EListError.CreateFmt(ATemplate, AData);
end;
{ TObjectList }
function TObjectList.Add(AObject: TObject): Integer;
begin
Result := inherited Add(AObject);
end;
constructor TObjectList.Create;
begin
inherited Create;
FOwnsObjects := True;
end;
constructor TObjectList.Create(AOwnsObjects: Boolean);
begin
inherited Create;
FOwnsObjects := AOwnsObjects;
end;
function TObjectList.Extract(Item: TObject): TObject;
begin
Result := TObject(inherited Extract(Item));
end;
function TObjectList.ExtractItem(Item: TObject; Direction: TList.TDirection): TObject;
begin
Result := TObject(inherited ExtractItem(Item, Direction));
end;
function TObjectList.FindInstanceOf(AClass: TClass; AExact: Boolean;
AStartAt: Integer): Integer;
var
I: Integer;
begin
Result := -1;
for I := AStartAt to Count - 1 do
if (AExact and
(Items[I].ClassType = AClass)) or
(not AExact and
Items[I].InheritsFrom(AClass)) then
begin
Result := I;
break;
end;
end;
function TObjectList.First: TObject;
begin
Result := TObject(inherited First);
end;
function TObjectList.GetItem(Index: Integer): TObject;
begin
Result := inherited Items[Index];
end;
function TObjectList.IndexOf(AObject: TObject): Integer;
begin
Result := inherited IndexOf(AObject);
end;
function TObjectList.IndexOfItem(AObject: TObject; ADirection: TList.TDirection): Integer;
begin
Result := inherited IndexOfItem(AObject, ADirection);
end;
procedure TObjectList.Insert(Index: Integer; AObject: TObject);
begin
inherited Insert(Index, AObject);
end;
function TObjectList.Last: TObject;
begin
Result := TObject(inherited Last);
end;
procedure TObjectList.Notify(Ptr: Pointer; Action: TListNotification);
begin
if (Action = lnDeleted) and OwnsObjects then
TObject(Ptr).Free;
inherited Notify(Ptr, Action);
end;
function TObjectList.Remove(AObject: TObject): Integer;
begin
Result := inherited Remove(AObject);
end;
function TObjectList.RemoveItem(AObject: TObject; ADirection: TList.TDirection): Integer;
begin
Result := inherited RemoveItem(AObject, ADirection);
end;
procedure TObjectList.SetItem(Index: Integer; AObject: TObject);
begin
inherited Items[Index] := AObject;
end;
{ TComponentListNexus }
{ used by TComponentList to get free notification }
type
TComponentListNexusEvent = procedure(Sender: TObject; AComponent: TComponent) of object;
TComponentListNexus = class(TComponent)
private
FOnFreeNotify: TComponentListNexusEvent;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
property OnFreeNotify: TComponentListNexusEvent read FOnFreeNotify write FOnFreeNotify;
end;
{ TComponentListNexus }
procedure TComponentListNexus.Notification(AComponent: TComponent; Operation: TOperation);
begin
if (Operation = opRemove) and Assigned(FOnFreeNotify) then
FOnFreeNotify(Self, AComponent);
inherited Notification(AComponent, Operation);
end;
{ TComponentList }
// The following two forwarding constructors are to resolve
// QC:2298 (http://qc.embarcadero.com/wc/qcmain.aspx?d=2298)
// The real issue is more generic and described in QC:29735
// (http://qc.embarcadero.com/wc/qcmain.aspx?d=29735). When
// the latter is resolved, these constructors can be removed
constructor TComponentList.Create;
begin
inherited;
end;
constructor TComponentList.Create(AOwnsObjects: Boolean);
begin
inherited;
end;
function TComponentList.Add(AComponent: TComponent): Integer;
begin
Result := inherited Add(AComponent);
end;
destructor TComponentList.Destroy;
begin
inherited Destroy;
FNexus.Free;
end;
function TComponentList.Extract(Item: TComponent): TComponent;
begin
Result := TComponent(inherited Extract(Item));
end;
function TComponentList.ExtractItem(Item: TComponent; Direction: TList.TDirection): TComponent;
begin
Result := TComponent(inherited ExtractItem(Item, Direction));
end;
function TComponentList.First: TComponent;
begin
Result := TComponent(inherited First);
end;
function TComponentList.GetItems(Index: Integer): TComponent;
begin
Result := TComponent(inherited Items[Index]);
end;
procedure TComponentList.HandleFreeNotify(Sender: TObject; AComponent: TComponent);
begin
Extract(AComponent);
end;
function TComponentList.IndexOf(AComponent: TComponent): Integer;
begin
Result := inherited IndexOf(AComponent);
end;
function TComponentList.IndexOfItem(AComponent: TComponent; ADirection: TList.TDirection): Integer;
begin
Result := inherited IndexOfItem(AComponent, ADirection);
end;
procedure TComponentList.Insert(Index: Integer; AComponent: TComponent);
begin
inherited Insert(Index, AComponent);
end;
function TComponentList.Last: TComponent;
begin
Result := TComponent(inherited Last);
end;
procedure TComponentList.Notify(Ptr: Pointer; Action: TListNotification);
begin
if not Assigned(FNexus) then
begin
FNexus := TComponentListNexus.Create(nil);
TComponentListNexus(FNexus).OnFreeNotify := HandleFreeNotify;
end;
case Action of
lnAdded:
if Ptr <> nil then
TComponent(Ptr).FreeNotification(FNexus);
lnExtracted,
lnDeleted:
if Ptr <> nil then
TComponent(Ptr).RemoveFreeNotification(FNexus);
end;
inherited Notify(Ptr, Action);
end;
function TComponentList.Remove(AComponent: TComponent): Integer;
begin
Result := inherited Remove(AComponent);
end;
function TComponentList.RemoveItem(AComponent: TComponent; ADirection: TList.TDirection): Integer;
begin
Result := inherited RemoveItem(AComponent, ADirection);
end;
procedure TComponentList.SetItems(Index: Integer; AComponent: TComponent);
begin
inherited Items[Index] := AComponent;
end;
{ TClassList }
function TClassList.Add(AClass: TClass): Integer;
begin
Result := inherited Add(AClass);
end;
function TClassList.Extract(Item: TClass): TClass;
begin
Result := TClass(inherited Extract(Item));
end;
function TClassList.ExtractItem(Item: TClass; Direction: TList.TDirection): TClass;
begin
Result := TClass(inherited ExtractItem(Item, Direction));
end;
function TClassList.First: TClass;
begin
Result := TClass(inherited First);
end;
function TClassList.GetItems(Index: Integer): TClass;
begin
Result := TClass(inherited Items[Index]);
end;
function TClassList.IndexOf(AClass: TClass): Integer;
begin
Result := inherited IndexOf(AClass);
end;
function TClassList.IndexOfItem(AClass: TClass; ADirection: TList.TDirection): Integer;
begin
Result := inherited IndexOfItem(AClass, ADirection);
end;
procedure TClassList.Insert(Index: Integer; AClass: TClass);
begin
inherited Insert(Index, AClass);
end;
function TClassList.Last: TClass;
begin
Result := TClass(inherited Last);
end;
function TClassList.Remove(AClass: TClass): Integer;
begin
Result := inherited Remove(AClass);
end;
function TClassList.RemoveItem(AClass: TClass; ADirection: TList.TDirection): Integer;
begin
Result := inherited RemoveItem(AClass, ADirection);
end;
procedure TClassList.SetItems(Index: Integer; AClass: TClass);
begin
inherited Items[Index] := AClass;
end;
{ TOrderedList }
function TOrderedList.AtLeast(ACount: integer): boolean;
begin
Result := List.Count >= ACount;
end;
function TOrderedList.Peek: Pointer;
begin
Result := PeekItem;
end;
function TOrderedList.Pop: Pointer;
begin
Result := PopItem;
end;
function TOrderedList.Push(AItem: Pointer): Pointer;
begin
PushItem(AItem);
Result := AItem;
end;
function TOrderedList.Count: Integer;
begin
Result := List.Count;
end;
constructor TOrderedList.Create;
begin
inherited Create;
FList := TList.Create;
end;
destructor TOrderedList.Destroy;
begin
List.Free;
inherited Destroy;
end;
function TOrderedList.PeekItem: Pointer;
begin
Result := List[List.Count-1];
end;
function TOrderedList.PopItem: Pointer;
begin
Result := PeekItem;
List.Delete(List.Count-1);
end;
{ TStack }
procedure TStack.PushItem(AItem: Pointer);
begin
List.Add(AItem);
end;
{ TObjectStack }
function TObjectStack.Peek: TObject;
begin
Result := TObject(inherited Peek);
end;
function TObjectStack.Pop: TObject;
begin
Result := TObject(inherited Pop);
end;
function TObjectStack.Push(AObject: TObject): TObject;
begin
Result := TObject(inherited Push(AObject));
end;
{ TQueue }
procedure TQueue.PushItem(AItem: Pointer);
begin
List.Insert(0, AItem);
end;
{ TObjectQueue }
function TObjectQueue.Peek: TObject;
begin
Result := TObject(inherited Peek);
end;
function TObjectQueue.Pop: TObject;
begin
Result := TObject(inherited Pop);
end;
function TObjectQueue.Push(AObject: TObject): TObject;
begin
Result := TObject(inherited Push(AObject));
end;
{ TCustomBucketList }
function TCustomBucketList.Add(AItem, AData: Pointer): Pointer;
var
LBucket: Integer;
LIndex: Integer;
begin
if FListLocked then
raise EListError.Create(SBucketListLocked);
if FindItem(AItem, LBucket, LIndex) then
raise EListError.CreateFmt(SDuplicateItem, [Integer(AItem)])
else
Result := AddItem(LBucket, AItem, AData);
end;
function TCustomBucketList.AddItem(ABucket: Integer; AItem, AData: Pointer): Pointer;
var
LDelta, LSize: Integer;
begin
with Buckets[ABucket] do
begin
LSize := Length(Items);
if Count = LSize then
begin
if LSize > 64 then
LDelta := LSize div 4
else if LSize > 8 then
LDelta := 16
else
LDelta := 4;
SetLength(Items, LSize + LDelta);
end;
with Items[Count] do
begin
Item := AItem;
Data := AData;
end;
Inc(Count);
end;
Result := AData;
end;
procedure AssignProc(AInfo, AItem, AData: Pointer; out AContinue: Boolean);
begin
TCustomBucketList(AInfo).Add(AItem, AData);
end;
procedure TCustomBucketList.Assign(AList: TCustomBucketList);
begin
Clear;
AList.ForEach(AssignProc, Self);
end;
procedure TCustomBucketList.Clear;
var
LBucket, LIndex: Integer;
begin
if FListLocked then
raise EListError.Create(SBucketListLocked);
FClearing := True;
try
for LBucket := 0 to BucketCount - 1 do
begin
for LIndex := Buckets[LBucket].Count - 1 downto 0 do
DeleteItem(LBucket, LIndex);
SetLength(Buckets[LBucket].Items, 0);
Buckets[LBucket].Count := 0;
end;
finally
FClearing := False;
end;
end;
function TCustomBucketList.DeleteItem(ABucket, AIndex: Integer): Pointer;
begin
with Buckets[ABucket] do
begin
Result := Items[AIndex].Data;
if not FClearing then
begin
if Count = 1 then
SetLength(Items, 0)
else if AIndex < (Count - 1) then
System.Move(Items[AIndex + 1], Items[AIndex],
(Count - 1 - AIndex) * SizeOf(TBucketItem));
Dec(Count);
end;
end;
end;
destructor TCustomBucketList.Destroy;
begin
Clear;
inherited Destroy;
end;
function TCustomBucketList.Exists(AItem: Pointer): Boolean;
var
LBucket, LIndex: Integer;
begin
Result := FindItem(AItem, LBucket, LIndex);
end;
function TCustomBucketList.Find(AItem: Pointer; out AData: Pointer): Boolean;
var
LBucket, LIndex: Integer;
begin
Result := FindItem(AItem, LBucket, LIndex);
if Result then
AData := Buckets[LBucket].Items[LIndex].Data;
end;
function TCustomBucketList.FindItem(AItem: Pointer; out ABucket, AIndex: Integer): Boolean;
var
I: Integer;
begin
Result := False;
ABucket := BucketFor(AItem);
with FBuckets[ABucket] do
for I := 0 to Count - 1 do
if Items[I].Item = AItem then
begin
AIndex := I;
Result := True;
Break;
end;
end;
function TCustomBucketList.ForEach(AProc: TBucketProc; AInfo: Pointer): Boolean;
var
LBucket, LIndex: Integer;
LOldListLocked: Boolean;
begin
Result := True;
LOldListLocked := FListLocked;
FListLocked := True;
try
for LBucket := 0 to BucketCount - 1 do
with Buckets[LBucket] do
for LIndex := Count - 1 downto 0 do
begin
with Items[LIndex] do
AProc(AInfo, Item, Data, Result);
if not Result then
Exit;
end;
finally
FListLocked := LOldListLocked;
end;
end;
function TCustomBucketList.ForEach(AEvent: TBucketEvent): Boolean;
var
LBucket, LIndex: Integer;
LOldListLocked: Boolean;
begin
Result := True;
LOldListLocked := FListLocked;
FListLocked := True;
try
for LBucket := 0 to BucketCount - 1 do
with Buckets[LBucket] do
for LIndex := Count - 1 downto 0 do
begin
with Items[LIndex] do
AEvent(Item, Data, Result);
if not Result then
Exit;
end;
finally
FListLocked := LOldListLocked;
end;
end;
function TCustomBucketList.GetData(AItem: Pointer): Pointer;
var
LBucket, LIndex: Integer;
begin
if not FindItem(AItem, LBucket, LIndex) then
raise EListError.CreateFmt(SItemNotFound, [Integer(AItem)]);
Result := Buckets[LBucket].Items[LIndex].Data;
end;
function TCustomBucketList.Remove(AItem: Pointer): Pointer;
var
LBucket, LIndex: Integer;
begin
if FListLocked then
raise EListError.Create(SBucketListLocked);
Result := nil;
if FindItem(AItem, LBucket, LIndex) then
Result := DeleteItem(LBucket, LIndex);
end;
procedure TCustomBucketList.SetBucketCount(const Value: Integer);
begin
if Value <> FBucketCount then
begin
FBucketCount := Value;
SetLength(FBuckets, FBucketCount);
end;
end;
procedure TCustomBucketList.SetData(AItem: Pointer; const AData: Pointer);
var
LBucket, LIndex: Integer;
begin
if not FindItem(AItem, LBucket, LIndex) then
raise EListError.CreateFmt(SItemNotFound, [Integer(AItem)]);
Buckets[LBucket].Items[LIndex].Data := AData;
end;
{ TBucketList }
function TBucketList.BucketFor(AItem: Pointer): Integer;
begin
// this can be overridden with your own calculation but remember to
// keep it in sync with your bucket count.
Result := Integer((IntPtr(AItem) shr 8) and FBucketMask);
end;
constructor TBucketList.Create(ABuckets: TBucketListSizes);
const
cBucketMasks: array [TBucketListSizes] of Byte =
($01, $03, $07, $0F, $1F, $3F, $7F, $FF);
begin
inherited Create;
FBucketMask := CBucketMasks[ABuckets];
BucketCount := FBucketMask + 1;
end;
{ TObjectBucketList }
function TObjectBucketList.Add(AItem, AData: TObject): TObject;
begin
Result := TObject(inherited Add(AItem, AData));
end;
function TObjectBucketList.GetData(AItem: TObject): TObject;
begin
Result := TObject(inherited Data[AItem]);
end;
function TObjectBucketList.Remove(AItem: TObject): TObject;
begin
Result := TObject(inherited Remove(AItem));
end;
procedure TObjectBucketList.SetData(AItem: TObject; const AData: TObject);
begin
inherited Data[AItem] := AData;
end;
{ TIntegerBucketList }
function TIntegerBucketList.Add(AItem, AData: NativeInt): NativeInt;
begin
Result := IntPtr(inherited Add(Pointer(AItem), Pointer(AData)));
end;
function TIntegerBucketList.GetData(AItem: NativeInt): NativeInt;
begin
Result := IntPtr(inherited Data[Pointer(AItem)]);
end;
function TIntegerBucketList.Remove(AItem: NativeInt): NativeInt;
begin
Result := IntPtr(inherited Remove(Pointer(AItem)));
end;
procedure TIntegerBucketList.SetData(AItem: NativeInt; const AData: NativeInt);
begin
inherited Data[Pointer(AItem)] := Pointer(AData);
end;
end.
|
.info
.source "EnchantItYourWay_ItemsContainer.psc"
.modifyTime 1636336687
.compileTime 1636337028
.user "mrowr"
.computer "MROWR-PURR"
.endInfo
.userFlagsRef
.flag conditional 1
.flag hidden 0
.endUserFlagsRef
.objectTable
.object EnchantItYourWay_ItemsContainer ObjectReference
.userFlags 0
.docString ""
.autoState
.variableTable
.variable ::ModQuestScript_var enchantityourway
.userFlags 0
.initialValue None
.endVariable
.endVariableTable
.propertyTable
.property ModQuestScript EnchantItYourWay auto
.userFlags 0
.docString ""
.autoVar ::ModQuestScript_var
.endProperty
.endPropertyTable
.stateTable
.state
.function GetState
.userFlags 0
.docString "Function that returns the current state"
.return String
.paramTable
.endParamTable
.localTable
.endLocalTable
.code
RETURN ::state
.endCode
.endFunction
.function GotoState
.userFlags 0
.docString "Function that switches this object to the specified state"
.return None
.paramTable
.param newState String
.endParamTable
.localTable
.local ::NoneVar None
.endLocalTable
.code
CALLMETHOD onEndState self ::NoneVar
ASSIGN ::state newState
CALLMETHOD onBeginState self ::NoneVar
.endCode
.endFunction
.function OnItemRemoved
.userFlags 0
.docString ""
.return NONE
.paramTable
.param item Form
.param count int
.param akItemReference ObjectReference
.param akDestContainer ObjectReference
.endParamTable
.localTable
.local ::temp0 bool
.local ::temp1 form
.local ::nonevar none
.endLocalTable
.code
PROPGET CurrentlyChoosingItemFromInventory ::ModQuestScript_var ::temp0 ;@line 6
JUMPF ::temp0 label1 ;@line 6
ASSIGN ::temp1 item ;@line 7
PROPSET CurrentlySelectedItemFromInventory ::ModQuestScript_var ::temp1 ;@line 7
CALLSTATIC input TapKey ::nonevar 1 ;@line 8
JUMP label0
label1:
label0:
.endCode
.endFunction
.endState
.endStateTable
.endObject
.endObjectTable |
unit ATabelaPreco;
{ Autor: Douglas Thomas Jacobsen
Data Criação: 19/10/1999;
Função: Cadastrar um novo Caixa
Data Alteração:
Alterado por:
Motivo alteração:
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
Componentes1, ExtCtrls, PainelGradiente, BotaoCadastro, Constantes,
StdCtrls, Buttons, Db, DBTables, Tabela, Mask, DBCtrls, Grids, DBGrids,
DBKeyViolation, Localizacao, DBClient, FMTBcd, SqlExpr;
type
TFTabelaPreco = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
MoveBasico1: TMoveBasico;
BotaoCadastrar1: TBotaoCadastrar;
BAlterar: TBotaoAlterar;
BotaoGravar1: TBotaoGravar;
BotaoCancelar1: TBotaoCancelar;
DATATabela: TDataSource;
Label3: TLabel;
EEmpresa: TDBEditColor;
Bevel1: TBevel;
Label1: TLabel;
EConsulta: TLocalizaEdit;
CADTabelaPreco: TSQL;
BFechar: TBitBtn;
GGrid: TGridIndice;
ValidaGravacao: TValidaGravacao;
Label4: TLabel;
DBEditColor1: TDBEditColor;
CADTabelaPrecoI_COD_EMP: TFMTBCDField;
CADTabelaPrecoI_COD_TAB: TFMTBCDField;
CADTabelaPrecoC_NOM_TAB: TWideStringField;
CADTabelaPrecoD_DAT_MOV: TSQLTimeStampField;
CADTabelaPrecoC_OBS_TAB: TWideStringField;
Label2: TLabel;
Label5: TLabel;
DBEditColor3: TDBEditColor;
DBMemoColor1: TDBMemoColor;
Label6: TLabel;
Label7: TLabel;
EditLocaliza4: TEditLocaliza;
SpeedButton3: TSpeedButton;
Label8: TLabel;
Localiza: TConsultaPadrao;
NovaTabela: TSQL;
Tabela: TSQL;
BitBtn1: TBitBtn;
PainelTempo1: TPainelTempo;
CADTabelaPrecoD_ULT_ALT: TSQLTimeStampField;
ECodTabela: TDBEditColor;
Aux: TSQLQuery;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CADTabelaPrecoAfterInsert(DataSet: TDataSet);
procedure CADTabelaPrecoAfterPost(DataSet: TDataSet);
procedure CADTabelaPrecoAfterEdit(DataSet: TDataSet);
procedure BFecharClick(Sender: TObject);
procedure CADTabelaPrecoAfterCancel(DataSet: TDataSet);
procedure GGridOrdem(Ordem: String);
procedure EConsultaSelect(Sender: TObject);
procedure EditLocaliza4Select(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure EEmpresaChange(Sender: TObject);
procedure CADTabelaPrecoBeforePost(DataSet: TDataSet);
private
CodNovaTabela : Integer;
Inseriu : Boolean;
procedure ConfiguraConsulta( acao : Boolean);
procedure adicionatabela( codigoTabela : integer);
procedure AdicionaTabelaServico(VpaCodTabela: integer);
function RProximoCodigoTabelaDisponivel(VpaCodEmpresa : Integer) : Integer;
public
{ Public declarations }
end;
var
FTabelaPreco: TFTabelaPreco;
implementation
uses APrincipal, funsql, constMsg, UnSistema;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFTabelaPreco.FormCreate(Sender: TObject);
begin
LimpaSQLTabela( CADTabelaPreco );
AdicionaSQLTabela( CADTabelaPreco, ' Select * from CadTabelaPreco ' +
' where i_cod_emp = ' + IntToStr(varia.CodigoEmpresa) );
AdicionaSQLTabela( CADTabelaPreco,' Order By i_cod_tab ');
AbreTabela(CADTabelaPreco);
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFTabelaPreco.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FechaTabela(CADTabelaPreco);
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações da Tabela
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{***********************Gera o proximo codigo disponível***********************}
procedure TFTabelaPreco.CADTabelaPrecoAfterInsert(DataSet: TDataSet);
begin
ECodTabela.ReadOnly := FALSE;
ConfiguraConsulta(False);
CadTabelaPrecoI_COD_TAB.AsInteger := RProximoCodigoTabelaDisponivel(Varia.CodigoEmpresa);
CADTabelaPrecoI_COD_EMP.AsInteger := Varia.CodigoEmpresa;
CADTabelaPrecoD_DAT_MOV.AsDateTime := date;
CodNovaTabela := CADTabelaPrecoI_COD_TAB.AsInteger;
Inseriu := true;
end;
{******************************Atualiza a tabela*******************************}
procedure TFTabelaPreco.CADTabelaPrecoAfterPost(DataSet: TDataSet);
begin
Sistema.MarcaTabelaParaImportar('CADTABELAPRECO');
EConsulta.AtualizaTabela;
ConfiguraConsulta(True);
if ( Inseriu ) then
adicionatabela( CodNovaTabela );
end;
{********************* antes de gravar o registro ****************************}
procedure TFTabelaPreco.CADTabelaPrecoBeforePost(DataSet: TDataSet);
begin
CADTabelaPrecoD_ULT_ALT.AsDateTime := Sistema.RDataServidor;
end;
{*********************Coloca o campo chave em read-only************************}
procedure TFTabelaPreco.CADTabelaPrecoAfterEdit(DataSet: TDataSet);
begin
ECodTabela.ReadOnly := true;
ConfiguraConsulta(False);
Inseriu := false;
end;
{ ********************* quando cancela a operacao *************************** }
procedure TFTabelaPreco.CADTabelaPrecoAfterCancel(DataSet: TDataSet);
begin
ConfiguraConsulta(True);
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{****************************Fecha o Formulario corrente***********************}
procedure TFTabelaPreco.BFecharClick(Sender: TObject);
begin
Close;
end;
{****** configura a consulta, caso edit ou insert enabled = false *********** }
procedure TFTabelaPreco.ConfiguraConsulta( acao : Boolean);
begin
Label1.Enabled := acao;
EConsulta.Enabled := acao;
GGrid.Enabled := acao;
end;
{ *************** retorno da order by ************************************* }
procedure TFTabelaPreco.GGridOrdem(Ordem: String);
begin
EConsulta.AOrdem := ordem;
end;
{************** valida a gravacao da tabela ********************************* }
procedure TFTabelaPreco.EEmpresaChange(Sender: TObject);
begin
if (CADTabelaPreco.State in [dsInsert, dsEdit]) then
ValidaGravacao.Execute;
end;
{************** select de consulta da tabela ******************************** }
procedure TFTabelaPreco.EConsultaSelect(Sender: TObject);
begin
EConsulta.ASelect.Clear;
EConsulta.ASelect.Add( ' Select * from CadTabelaPreco ' +
' where i_cod_emp = ' + IntToStr(varia.CodigoEmpresa) +
' and c_nom_tab like ''@%''' );
end;
procedure TFTabelaPreco.EditLocaliza4Select(Sender: TObject);
begin
EditLocaliza4.ASelectValida.Clear;
EditLocaliza4.ASelectValida.Add( ' Select * from CadTabelaPreco ' +
' where i_cod_emp = ' + IntToStr(varia.CodigoEmpresa) +
' and i_cod_tab = @ ' );
EditLocaliza4.ASelectLocaliza.Clear;
EditLocaliza4.ASelectLocaliza.Add( ' Select * from CadTabelaPreco ' +
' where i_cod_emp = ' + IntToStr(varia.CodigoEmpresa) +
' and c_nom_tab like ''@%''' );
end;
{ ******************** cria um novo movimento de tabela ********************* }
procedure TFTabelaPreco.adicionatabela( codigoTabela : integer);
begin
PainelTempo1.Execute('Gerando tabela de preço dos Produtos');
LimpaSQLTabela(Tabela);
if EditLocaliza4.text <> '' then
begin
AdicionaSQLTabela(Tabela, ' SELECT ' +
' MOV.I_SEQ_PRO, MOV.I_COD_MOE , MOV.I_COD_TAM, MOV.I_COD_COR, ' +
' MOV.N_VLR_VEN, MOV.N_PER_MAX, MOV.C_CIF_MOE, MOV.I_COD_CLI ' +
' FROM ' +
' MOVTABELAPRECO MOV ' +
' WHERE MOV.I_COD_EMP = ' + IntTostr(varia.CodigoEmpresa) +
' AND MOV.I_COD_TAB = ' + EditLocaliza4.text);
end
else
AdicionaSQLTabela(Tabela, ' SELECT PRO.I_SEQ_PRO, N_PER_MAX FROM ' +
' CADPRODUTOS PRO ' +
' WHERE PRO.I_COD_EMP = ' + IntTostr(varia.CodigoEmpresa) );
AbreTabela(Tabela);
AdicionaSQLAbreTabela(NovaTabela, ' Select * from MovTabelaPreco ' );
while not Tabela.Eof do
begin
NovaTabela.insert;
NovaTabela.FieldByName('I_COD_EMP').AsInteger := varia.CodigoEmpresa;
NovaTabela.FieldByName('I_COD_TAB').AsInteger := codigoTabela;
NovaTabela.FieldByName('I_SEQ_PRO').AsInteger := Tabela.fieldByName('I_SEQ_PRO').AsInteger;
NovaTabela.FieldByName('D_ULT_ALT').AsDateTime := Sistema.RDataServidor;
NovaTabela.FieldByName('I_COD_TAM').AsInteger := 0;
NovaTabela.FieldByName('I_COD_MOE').Value := Varia.MoedaBase;
NovaTabela.FieldByName('C_CIF_MOE').Value := CurrencyString;
NovaTabela.FieldByName('I_COD_CLI').AsInteger := 0;
NovaTabela.FieldByName('I_COD_COR').AsInteger := 0;
if EditLocaliza4.Text <> '' then
begin
if Tabela.fieldByName('I_COD_MOE').AsInteger <> 0 then
NovaTabela.FieldByName('I_COD_MOE').Value := Tabela.fieldByName('I_COD_MOE').Value;
NovaTabela.FieldByName('N_VLR_VEN').Value := Tabela.fieldByName('N_VLR_VEN').Value;
NovaTabela.FieldByName('N_PER_MAX').Value := Tabela.fieldByName('N_PER_MAX').Value;
NovaTabela.FieldByName('C_CIF_MOE').Value := Tabela.fieldByName('C_CIF_MOE').Value;
NovaTabela.FieldByName('I_COD_CLI').AsInteger := Tabela.fieldByName('I_COD_CLI').AsInteger;
NovaTabela.FieldByName('I_COD_TAM').AsInteger := Tabela.fieldByName('I_COD_TAM').AsInteger;
NovaTabela.FieldByName('I_COD_COR').AsInteger := Tabela.fieldByName('I_COD_COR').AsInteger;
end;
NovaTabela.post;
tabela.next;
end;
PainelTempo1.fecha;
Sistema.MarcaTabelaParaImportar('MOVTABELAPRECO');
AdicionaTabelaServico(codigoTabela);
end;
{******************* adiciona a tabela de servico *****************************}
procedure TFTabelaPreco.AdicionaTabelaServico(VpaCodTabela : integer);
begin
PainelTempo1.Execute('Gerando tabela de preço dos Serviços');
LimpaSQLTabela(Tabela);
if EditLocaliza4.text <> '' then
begin
AdicionaSQLTabela(Tabela, ' SELECT ' +
' Ser.I_Cod_Ser, MOV.I_COD_MOE , ' +
' MOV.N_VLR_VEN, MOV.C_CIF_MOE ' +
' FROM ' +
' MOVTABELAPRECOSERVICO MOV, CADServico Ser ' +
' WHERE ' + SQLTextoRightJoin('MOV.I_Cod_Ser','Ser.I_Cod_Ser')+
' AND Ser.I_COD_EMP = ' + IntTostr(varia.CodigoEmpresa) +
' AND MOV.I_COD_TAB = ' + EditLocaliza4.text );
end
else
AdicionaSQLTabela(Tabela, ' SELECT Ser.I_COD_SER FROM ' +
' CADSERVICO SER ' +
' WHERE SER.I_COD_EMP = ' + IntTostr(varia.CodigoEmpresa) );
AbreTabela(Tabela);
AdicionaSQLAbreTabela(NovaTabela, ' Select * from MovTabelaPrecoServico ' );
while not Tabela.Eof do
begin
NovaTabela.insert;
NovaTabela.FieldByName('I_COD_EMP').AsInteger := varia.CodigoEmpresa;
NovaTabela.FieldByName('I_COD_TAB').AsInteger := VpaCodTabela;
NovaTabela.FieldByName('I_COD_SER').AsInteger := Tabela.fieldByName('I_COD_SER').AsInteger;
NovaTabela.FieldByName('I_COD_MOE').Value := Varia.MoedaBase;
NovaTabela.FieldByName('C_CIF_MOE').Value := CurrencyString;
if EditLocaliza4.Text <> '' then
begin
if Tabela.fieldByName('I_COD_MOE').AsInteger <> 0 then
begin
NovaTabela.FieldByName('C_CIF_MOE').Value := Tabela.fieldByName('C_CIF_MOE').Value;
NovaTabela.FieldByName('I_COD_MOE').Value := Tabela.fieldByName('I_COD_MOE').Value;
end;
NovaTabela.FieldByName('N_VLR_VEN').Value := Tabela.fieldByName('N_VLR_VEN').Value;
end;
NovaTabela.post;
tabela.next;
end;
PainelTempo1.fecha;
end;
{************* deleta um tabela de preco *********************************** }
function TFTabelaPreco.RProximoCodigoTabelaDisponivel(VpaCodEmpresa : Integer) : Integer;
begin
AdicionaSQlAbreTabela(Aux,'Select MAX(I_COD_TAB) ULTIMO from CADTABELAPRECO '+
' Where I_COD_EMP = '+IntToStr(VpaCodEmpresa));
result := Aux.FieldByName('ULTIMO').Asinteger+1;
Aux.close;
end;
{************* deleta um tabela de preco *********************************** }
procedure TFTabelaPreco.BitBtn1Click(Sender: TObject);
begin
if confirmacao(CT_DeletaRegistro + CADTabelaPrecoC_NOM_TAB.AsString + '" !!!') then
begin
ExecutaComandoSql(Tabela,' Delete MovTabelaPreco where i_cod_emp = ' + IntToStr(Varia.CodigoEmpresa) +
' and i_cod_tab = ' + CADTabelaPrecoI_COD_TAB.AsString + ' ');
ExecutaComandoSql(Tabela,' Delete MovTabelaPrecoServico '+
' Where i_cod_emp = '+IntToStr(Varia.CodigoEmpresa) +
' and i_cod_tab = ' + CADTabelaPrecoI_COD_TAB.AsString);
ExecutaComandoSql(Tabela, ' Delete CadTabelaPreco where i_cod_emp = ' + IntTostr(Varia.CodigoEmpresa) +
' and i_cod_tab = ' + CADTabelaPrecoI_COD_TAB.AsString );
EConsulta.AtualizaTabela;
end;
end;
Initialization
RegisterClasses([TFTabelaPreco]);
end.
|
unit Comum.WindowsUtils;
interface
uses
Windows, Forms, SysUtils, ShellAPI;
type
IWindowsUtils = interface
['{99AA9859-B23F-4736-91EA-4D5B992679DB}']
function getTempFile(const Extension: string): string;
procedure OpenFile(AFile: TFileName; TypeForm: Integer = SW_NORMAL);
procedure OpenFileAndWait(AFile: TFileName; TypeForm: Integer = SW_NORMAL);
function ShellExecuteAndWait(Operation, FileName, Parameter, Directory: PAnsiChar; Show: Word; bWait: Boolean): Longint;
end;
TWindowsUtils = class(TInterfacedObject, IWindowsUtils)
public
class function new(): IWindowsUtils;
function getTempFile(const Extension: string): string;
procedure OpenFile(AFile: TFileName; TypeForm: Integer = SW_NORMAL);
procedure OpenFileAndWait(AFile: TFileName; TypeForm: Integer = SW_NORMAL);
function ShellExecuteAndWait(Operation, FileName, Parameter, Directory: PAnsiChar; Show: Word; bWait: Boolean): Longint;
end;
implementation
{ TWindowsUtils }
class function TWindowsUtils.new(): IWindowsUtils;
begin
Result := Self.Create;
end;
function TWindowsUtils.getTempFile(const Extension: string): string;
var
Buffer: array[0..MAX_PATH] of Char;
begin
repeat
GetTempPath(SizeOf(Buffer) - 1, Buffer);
GetTempFileName(Buffer, '~', 0, Buffer);
Result := ChangeFileExt(Buffer, Extension);
until not FileExists(Result);
end;
procedure TWindowsUtils.OpenFile(AFile: TFileName; TypeForm: Integer = SW_NORMAL);
var
Pdir: PChar;
begin
GetMem(Pdir, 256);
StrPCopy(Pdir, AFile);
ShellExecute(0, nil, Pchar(AFile), nil, Pdir, TypeForm);
FreeMem(Pdir, 256);
end;
procedure TWindowsUtils.OpenFileAndWait(AFile: TFileName; TypeForm: Integer);
var
Pdir: PChar;
begin
GetMem(Pdir, 256);
StrPCopy(Pdir, AFile);
ShellExecuteAndWait(nil, Pchar(AFile), nil, Pdir, TypeForm, True);
FreeMem(Pdir, 256);
end;
function TWindowsUtils.ShellExecuteAndWait(Operation, FileName, Parameter, Directory: PAnsiChar; Show: Word; bWait: Boolean): Longint;
var
bOK: Boolean;
Info: TShellExecuteInfo;
begin
FillChar(Info, SizeOf(Info), Chr(0));
Info.cbSize := SizeOf(Info);
Info.fMask := SEE_MASK_NOCLOSEPROCESS;
Info.lpVerb := PChar(Operation);
Info.lpFile := PChar(FileName);
Info.lpParameters := PChar(Parameter);
Info.lpDirectory := PChar(Directory);
Info.nShow := Show;
bOK := Boolean(ShellExecuteEx(@Info));
if bOK then
begin
if bWait then
begin
while WaitForSingleObject(Info.hProcess, 100) = WAIT_TIMEOUT do
Application.ProcessMessages;
bOK := GetExitCodeProcess(Info.hProcess, DWORD(Result));
end
else
Result := 0;
end;
if not bOK then
Result := -1;
end;
end.
|
unit uPostagensModel;
interface
uses
FireDAC.Comp.Client,uPostagensDAO, System.SysUtils;
type
TPostagensModel = class
private
FID: Integer;
FCodigoUsuario: integer;
FTituloPostagem : string;
FPostagem : string;
FPostagemDAO : TPostagensDAO;
public
function Exibir(): TFDQuery;
function Excluir(pId: Integer): Boolean;
function Alterar(pIdUsario, pId : Integer; pTituloPostagem, pPostagem : string): Boolean;
function Inserir (pIdUsario, pId : Integer; pTituloPostagem, pPostagem : string) : Boolean;
function CriarBanco(pBancoDados : string ): Boolean;
function ExecutaScript(): Boolean;
constructor Create;
destructor Destroy; override;
end;
implementation
{ TPostagensModel }
function TPostagensModel.Alterar(pIdUsario, pId : Integer; pTituloPostagem, pPostagem : string): Boolean;
begin
Result := FPostagemDAO.Alterar(pIdUsario, pId, pTituloPostagem, pPostagem);
end;
constructor TPostagensModel.Create;
begin
FPostagemDAO := TPostagensDAO.Create();
end;
function TPostagensModel.CriarBanco(pBancoDados: string): Boolean;
begin
Result := FPostagemDAO.CriarBanco(pBancoDados);
end;
destructor TPostagensModel.Destroy;
begin
FPostagemDAO.Free;
inherited;
end;
function TPostagensModel.Excluir(pId: Integer): Boolean;
begin
Result := FPostagemDAO.Excluir(pId);
end;
function TPostagensModel.ExecutaScript: Boolean;
begin
Result := FPostagemDAO.ExecutaScript;
end;
function TPostagensModel.Exibir : TFDQuery;
begin
Result := FPostagemDAO.Exibir;
end;
function TPostagensModel.Inserir(pIdUsario, pId: Integer; pTituloPostagem, pPostagem: string): Boolean;
begin
Result := FPostagemDAO.Inserir(pIdUsario, pId, pTituloPostagem, pPostagem);
end;
end.
|
unit OperatorsTypes;
interface
uses
SysUtils;
type
TPointRecord = record
private
x, y: Integer;
public
procedure SetValue (x1, y1: Integer);
class operator Add (a, b: TPointRecord): TPointRecord;
class operator Explicit (a: TPointRecord) : string;
class operator Implicit (x1: Integer): TPointRecord;
end;
type
TPointRecord2 = record
private
x, y: Integer;
public
class operator Explicit (a: TPointRecord2) : string;
procedure SetValue (x1, y1: Integer);
// commutativity
class operator Add (a: TPointRecord2; b: Integer): TPointRecord2;
class operator Add (b: Integer; a: TPointRecord2): TPointRecord2;
end;
implementation
{ TPointRecord }
class operator TPointRecord.Add(a, b: TPointRecord): TPointRecord;
begin
Result.x := a.x + b.x;
Result.y := a.y + b.y;
end;
class operator TPointRecord.Explicit(a: TPointRecord): string;
begin
Result := Format('(%d:%d)', [a.x, a.y]);
end;
class operator TPointRecord.Implicit(x1: Integer): TPointRecord;
begin
Result.x := x1;
Result.y := 10;
end;
procedure TPointRecord.SetValue(x1, y1: Integer);
begin
x := x1;
y := y1;
end;
{ TPointRecord2 }
procedure TPointRecord2.SetValue(x1, y1: Integer);
begin
x := x1;
y := y1;
end;
class operator TPointRecord2.Add(a: TPointRecord2; b: Integer): TPointRecord2;
begin
Result.x := a.x + b;
Result.y := a.y + b;
end;
class operator TPointRecord2.Add(b: Integer; a: TPointRecord2): TPointRecord2;
begin
Result := a + b; // implement commutativity
end;
class operator TPointRecord2.Explicit(a: TPointRecord2): string;
begin
Result := Format('(%d:%d)', [a.x, a.y]);
end;
end.
|
unit SpeakingForm;
interface
uses
TestClasses,
SpeakingSQLUnit,
QuestionSelectFrame,
SoundFrame,
QuestionInputFrame,
ButtonsFrame,
Generics.Collections,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls, DSPack, Buttons;
type
TfrSpeaking = class(TForm)
PanelBottom: TPanel;
frmQuestionSelect: TfrmQuestionSelect;
frmQuestionInput: TfrmQuestionInput;
frmSound: TfrmSound;
FrmButtons: TFrmButtons;
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FTest : TTest;
FSpeakingData: TObjectList<TQuiz>;
FSpeakingSQL : TSpeakingData;
procedure On_QuestionSelect(Sender: TObject);
procedure On_QuestionAdd(Sender: TObject);
procedure On_QuestionInsert(var IsNull: Boolean);
procedure On_QuestionUpdate(var IsNull: Boolean);
procedure On_QuestionDelete(var IsNull: Boolean);
procedure NextQuestionSetting;
procedure Initialize;
public
procedure SetSpeakingIndex(Test: TTest);
end;
var
frSpeaking: TfrSpeaking;
implementation
{$R *.dfm}
// Speaking Form 생성
procedure TfrSpeaking.FormCreate(Sender: TObject);
begin
frmQuestionSelect.OnQuestionSelect := On_QuestionSelect;
frmButtons.OnUpdate := On_QuestionUpdate;
frmButtons.OnInsert := On_QuestionInsert;
frmButtons.OnDelete := On_QuestionDelete;
frmButtons.OnNewQuestion := On_QuestionAdd;
FSpeakingSQL := TSpeakingData.Create;
frmSound.Part := qpSpeaking;
end;
// Speaking Form 소멸
procedure TfrSpeaking.FormDestroy(Sender: TObject);
begin
FSpeakingData.Free;
FSpeakingSQL.Free;
end;
// FTestIndex 값 지정
procedure TfrSpeaking.SetSpeakingIndex(Test: TTest);
begin
FTest := Test;
Initialize;
end;
// Speaking Form Defult 값 지정
procedure TfrSpeaking.Initialize;
begin
FreeAndNil(FSpeakingData);
FSpeakingData := FSpeakingSQL.Select(FTest.Idx);
frmQuestionInput.ClearInput;
frmQuestionSelect.NumberListing(FSpeakingData);
frmSound.Test := FTest;
end;
// 다음 문제 셋팅
procedure TfrSpeaking.NextQuestionSetting;
begin
frmQuestionInput.QuestionSet(frmQuestionSelect.Numbering + 1);
FrmButtons.InsertOn;
frmQuestionSelect.SetIndex;
end;
// SpeakingSelect Frame에 값 입력
procedure TfrSpeaking.On_QuestionSelect(Sender: TObject);
begin
FrmButtons.QueAddOn;
frmQuestionInput.Binding(TQuiz(Sender));
frmSound.SelectedQuestion := TQuiz(Sender);
end;
// 문제추가 클릭
procedure TfrSpeaking.On_QuestionAdd(Sender: TObject);
begin
if FTest.Idx = 0 then
begin
ShowMessage('좌측메뉴를 먼저 선택해 주세요');
exit;
end;
NextQuestionSetting;
end;
// 입력 클릭
procedure TfrSpeaking.On_QuestionInsert(var IsNull: Boolean);
var
InsertSpeaking: TSpeaking;
begin
IsNull := frmQuestionInput.IsNull;
if IsNull then Exit;
InsertSpeaking := TSpeaking.Create;
try
InsertSpeaking.Idx := FTest.Idx;
InsertSpeaking.QuizNumber := frmQuestionInput.Number;
InsertSpeaking.Quiz := frmQuestionInput.Question;
InsertSpeaking.ResponseTime := 300;
FSpeakingSQL.Insert(InsertSpeaking);
finally
InsertSpeaking.Free;
end;
Initialize;
NextQuestionSetting;
end;
// 수정 클릭
procedure TfrSpeaking.On_QuestionUpdate(var IsNull: Boolean);
var
UpdateSpeaking: TSpeaking;
begin
IsNull := frmQuestionInput.IsNull;
if IsNull then Exit;
if messagedlg('정말 수정하시겠습니까?', mtWarning, mbYesNo,0)= mryes then
begin
UpdateSpeaking := TSpeaking.Create;
try
UpdateSpeaking.Idx := FTest.Idx;
UpdateSpeaking.QuizNumber := frmQuestionInput.Number;
UpdateSpeaking.Quiz := frmQuestionInput.Question;
UpdateSpeaking.ResponseTime := 300;
FSpeakingSQL.Update(UpdateSpeaking);
finally
UpdateSpeaking.Free;
end;
Initialize;
end;
end;
// 삭제 클릭
procedure TfrSpeaking.On_QuestionDelete(var IsNull: Boolean);
begin
IsNull := frmQuestionInput.IsNull;
if IsNull then Exit;
if MessageDlg('정말 삭제하시겠습니까?', mtWarning, mbYesNo,0)= mrYes then
begin
FSpeakingSQL.Delete(StrToInt(frmQuestionSelect.cbNumberSelect.Text), FTest.Idx);
Initialize;
end;
end;
end.
|
unit RectGrid;
{$MODE Delphi}
interface
uses SysUtils, Classes, LCLIntf, LCLType, LMessages, Contnrs, xml;
type
TSliceType = (stNone, stHorizontal, stVertical);
TRectGrid = class;
TRectGridList = class
private
FList: TObjectList;
function GetItem(Index: Integer): TRectGrid;
function GetCount: Integer;
protected
procedure Remove(rg: TRectGrid);
procedure Insert(Index: Integer; rg: TRectGrid);
procedure Add(rg: TRectGrid);
public
constructor Create;
destructor Destroy; override;
procedure Clear;
function IndexOf(rg: TRectGrid): Integer;
property Items[Index: Integer]: TRectGrid read GetItem; default;
property Count: Integer read GetCount;
end;
TRectGrid = class
private
FRect: TRect;
FKids: TRectGridList;
FName: String;
FSliceType: TSliceType;
FParent: TRectGrid;
FSingleColor: DWORD;
FIsSingleColor: Boolean;
FIsBackground: Boolean;
FAttributes: TStringList;
function GetAttribute(const AttrName: String): String;
procedure SetAttribute(const AttrName: String; const Value: String);
function IsSliced: Boolean;
function NewKid(const rt: TRect): TRectGrid;
public
constructor Create(const rt: TRect);
destructor Destroy; override;
function RectFromPos(const Pt: TPoint): TRectGrid;
procedure RectsFromX(const X: Integer; list: TObjectList);
procedure RectsFromY(const Y: Integer; list: TObjectList);
procedure SliceHorizontal(const Y: Integer);
procedure SliceVertical(const X: Integer);
procedure GroupKids(FromIndex, ToIndex: Integer);
procedure LoadFromXML(me: TXMLNode);
procedure SaveToXML(parent: TXMLNode);
property Parent: TRectGrid read FParent;
property Rect: TRect read FRect;
property Kids: TRectGridList read FKids;
property Sliced: Boolean read IsSliced;
property SliceType: TSliceType read FSliceType;
property Name: String read FName write FName;
property IsSingleColor: Boolean read FIsSingleColor write FIsSingleColor;
property SingleColor: DWORD read FSingleColor write FSingleColor;
property IsBackground: Boolean read FIsBackground write FIsBackground;
property Attributes[const AttrName: String]: String
read GetAttribute write SetAttribute;
end;
implementation
uses FileUtils;
constructor TRectGridList.Create;
begin
FList := TObjectList.Create;
end;
destructor TRectGridList.Destroy;
begin
FList.Free;
end;
function TRectGridList.GetCount: Integer;
begin
Result := FList.Count;
end;
function TRectGridList.GetItem(Index: Integer): TRectGrid;
begin
Result := TRectGrid(FList.Items[Index]);
end;
function TRectGridList.IndexOf(rg: TRectGrid): Integer;
begin
Result := FList.IndexOf(rg);
end;
procedure TRectGridList.Insert(Index: Integer; rg: TRectGrid);
begin
FList.Insert(Index, rg);
end;
procedure TRectGridList.Add(rg: TRectGrid);
begin
FList.Add(rg);
end;
procedure TRectGridList.Remove(rg: TRectGrid);
begin
FList.Remove(rg);
end;
procedure TRectGridList.Clear;
begin
FList.Clear;
end;
constructor TRectGrid.Create(const rt: TRect);
begin
Self.FRect := rt;
FKids := TRectGridList.Create;
FSliceType := stNone;
FParent := nil;
FAttributes := TStringList.Create;
end;
destructor TRectGrid.Destroy;
begin
if FParent <> nil then
FParent.FKids.Remove(Self);
FKids.Free;
FAttributes.Free;
inherited Destroy;
end;
function TRectGrid.GetAttribute(const AttrName: String): String;
begin
Result := FAttributes.Values[AttrName];
end;
procedure TRectGrid.SetAttribute(const AttrName: String; const Value: String);
begin
FAttributes.Values[AttrName] := Value;
end;
function TRectGrid.IsSliced: Boolean;
begin
Result := FKids.Count >= 2;
end;
function TRectGrid.RectFromPos(const Pt: TPoint): TRectGrid;
var
i: Integer;
begin
Result := nil;
if PtInRect(FRect, pt) then
begin
if Sliced then
begin
for i := 0 to FKids.Count - 1 do
begin
Result := TRectGrid(FKids[i]).RectFromPos(pt);
if Result <> nil then
Break;
end;
end
else
begin
Result := Self;
end;
end;
end;
procedure TRectGrid.RectsFromX(const X: Integer; list: TObjectList);
var
i: Integer;
begin
if (FRect.Left <= X) and (X <= FRect.Right) then
if (not Sliced) then
list.Add(Self)
else
begin
for i := 0 to FKids.Count - 1 do
TRectGrid(FKids[i]).RectsFromX(X, list);
end;
end;
procedure TRectGrid.RectsFromY(const Y: Integer; list: TObjectList);
var
i: Integer;
begin
if (FRect.Top <= Y) and (Y <= FRect.Bottom) then
if (not Sliced) then
list.Add(Self)
else
begin
for i := 0 to FKids.Count - 1 do
TRectGrid(FKids[i]).RectsFromY(Y, list);
end;
end;
function TRectGrid.NewKid(const rt: TRect): TRectGrid;
begin
Result := TRectGrid.Create(rt);
Result.FParent := Self;
end;
procedure TRectGrid.SliceHorizontal(const Y: Integer);
var
parentIndex: Integer;
rtA, rtB: TRect;
begin
if (FRect.Top > Y) or (Y > FRect.Bottom) then
raise Exception.Create('Invalid Y coordinate');
if (Sliced) then
raise Exception.Create('Already sliced');
rtA := Classes.Rect(FRect.Left, FRect.Top, FRect.Right, Y);
rtB := Classes.Rect(FRect.Left, Y, FRect.Right, FRect.Bottom);
if (FParent <> nil) and (FParent.FSliceType = stHorizontal) then
begin
parentIndex := FParent.FKids.IndexOf(Self);
if parentIndex = -1 then
raise Exception.Create('Kid was not found in parent list');
FParent.FKids.Insert(parentIndex, FParent.NewKid(rtA));
FRect := rtB;
end
else
begin
FKids.Add(NewKid(rtA));
FKids.Add(NewKid(rtB));
FSliceType := stHorizontal;
end;
end;
procedure TRectGrid.SliceVertical(const X: Integer);
var
parentIndex: Integer;
rtA, rtB: TRect;
begin
if (FRect.Left > X) or (X > FRect.Right) then
raise Exception.Create('Invalid X coordinate');
if (Sliced) then
raise Exception.Create('Already sliced');
rtA := Classes.Rect(FRect.Left, FRect.Top, X, FRect.Bottom);
rtB := Classes.Rect(X, FRect.Top, FRect.Right, FRect.Bottom);
if (FParent <> nil) and (FParent.FSliceType = stVertical) then
begin
parentIndex := FParent.FKids.IndexOf(Self);
if parentIndex = -1 then
raise Exception.Create('Kid was not found in parent list');
FParent.FKids.Insert(parentIndex, FParent.NewKid(rtA));
FRect := rtB;
end
else
begin
FKids.Add(NewKid(rtA));
FKids.Add(NewKid(rtB));
FSliceType := stVertical;
end;
end;
procedure TRectGrid.LoadFromXML(me: TXMLNode);
const
strSlice: array [TSliceType] of String = ('stNone', 'stHorizontal', 'stVertical');
var
i: Integer;
rg: TRectGrid;
tmp: String;
enum: TXMLNodeEnum;
strName, strValue: String;
begin
Self.Name := me.Attributes['Name'];
tmp := me.Attributes['SliceType'];
if (tmp = 'stNone') then
FSliceType := stNone
else if (tmp = 'stHorizontal') then
FSliceType := stHorizontal
else if (tmp = 'stVertical') then
FSliceType := stVertical
else
raise Exception.Create('Invalid slice type ' + tmp + ' was specified');
FRect.Left := StrToInt(me.Attributes['Left']);
FRect.Top := StrToInt(me.Attributes['Top']);
FRect.Right := StrToInt(me.Attributes['Right']);
FRect.Bottom := StrToInt(me.Attributes['Bottom']);
FIsBackground := me.Attributes['IsBackground'] = 'true';
tmp := me.Attributes['SingleColor'];
if tmp <> '' then
begin
FSingleColor := StrToInt(tmp);
FIsSingleColor := True;
end
else
FIsSingleColor := False;
FKids.Clear;
enum := me.GetNodesByName('attr');
for i := 0 to enum.Count - 1 do
begin
strName := enum[i].Attributes['name'];
strValue := enum[i].Attributes['value'];
Self.Attributes[strName] := strValue;
end;
enum.Free;
enum := me.GetNodesByName('cell');
for i := 0 to enum.Count - 1 do
begin
rg := NewKid(Classes.Rect(0, 0, 0, 0));
rg.LoadFromXML(enum[i]);
FKids.Add(rg);
end;
enum.Free;
end;
procedure TRectGrid.SaveToXML(parent: TXMLNode);
const
strSlice: array [TSliceType] of String = ('stNone', 'stHorizontal', 'stVertical');
var
i: Integer;
me, attrNode: TXMLNode;
strName, strValue: String;
begin
me := parent.AddChild;
me.Name := 'cell';
me.Attributes['Name'] := FName;
me.Attributes['SliceType'] := strSlice[FSliceType];
me.Attributes['Left'] := IntToStr(FRect.Left);
me.Attributes['Top'] := IntToStr(FRect.Top);
me.Attributes['Right'] := IntToStr(FRect.Right);
me.Attributes['Bottom'] := IntToStr(FRect.Bottom);
if (IsSingleColor) then
me.Attributes['SingleColor'] := IntToStr(SingleColor);
if (IsBackground) then
me.Attributes['IsBackground'] := 'true';
for i := 0 to FAttributes.Count - 1 do
begin
strName := FAttributes.Names[i];
strValue := FAttributes.Values[strName];
if (strName <> '') and (strValue <> '') then
begin
attrNode := me.AddChild;
attrNode.Name := 'attr';
attrNode.Attributes['name'] := strName;
attrNode.Attributes['value'] := strValue;
end;
end;
for i := 0 to FKids.Count - 1 do
FKids[i].SaveToXML(me);
end;
procedure TRectGrid.GroupKids(FromIndex, ToIndex: Integer);
var
rt: TRect;
newParent, rg: TRectGrid;
i: Integer;
begin
rt.Left := FKids[FromIndex].FRect.Left;
rt.Top := FKids[FromIndex].FRect.Top;
rt.Right := FKids[ToIndex].FRect.Right;
rt.Bottom := FKids[ToIndex].FRect.Bottom;
newParent := TRectGrid.Create(rt);
newParent.FSliceType := Self.FSliceType;
newParent.FParent := Self;
for i := FromIndex to ToIndex do
begin
rg := FKids[FromIndex]; { because we extract FromIndex }
FKids.FList.Extract(rg);
newParent.FKids.Add(rg);
rg.FParent := newParent;
end;
FKids.Insert(FromIndex, newParent);
end;
end.
|
unit PascalCoin.RPC.Test.Operations;
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.Edit, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FMX.Layouts,
FMX.ListBox, System.Rtti, FMX.Grid.Style, FMX.Grid;
type
TOperationsFrame = class(TFrame)
Label1: TLabel;
AccountNumber: TEdit;
Button1: TButton;
Memo1: TMemo;
CheckBox1: TCheckBox;
ListBox1: TListBox;
Layout1: TLayout;
Layout2: TLayout;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.fmx}
uses PascalCoin.RPC.Interfaces,PascalCoin.Utils.Interfaces,
PascalCoin.RPC.Test.DM, Spring.Container;
procedure TOperationsFrame.Button1Click(Sender: TObject);
var lAPI: IPascalCoinAPI;
lAN: Cardinal;
lOps: IPascalCoinList<IPascalCoinOperation>;
lOp: IPascalCoinOperation;
lStart: Integer;
I: Integer;
lTools: IPascalCoinTools;
S: String;
begin
if CheckBox1.IsChecked then
lStart := -1
else
lStart := 0;
lAPI :=GlobalContainer.Resolve<IPascalCoinAPI>.URI(DM.URI);
lAN := AccountNumber.Text.ToInt64;
lOPs := lAPI.getaccountoperations(lAN, 100, lStart);
Memo1.ClearContent;
Memo1.Lines.Text := lAPI.JSONResultStr;
lTools := GlobalContainer.Resolve<IPascalCoinTools>;
ListBox1.BeginUpdate;
for I := 0 to lOps.Count - 1 do
begin
lOp := lOps[I];
if lOp.time = 0 then
S := 'pending'
else
S := DateTimeToStr(lTools.UnixToLocalDate(lOp.Time));
S := S + ' | ' + lOp.block.ToString + '/' + lOp.opblock.ToString;
S := S + ' | ' + lOp.optxt;
ListBox1.Items.Add(S);
end;
ListBox1.EndUpdate;
end;
end.
|
unit MainModule;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteDef, FireDAC.UI.Intf, FireDAC.FMXUI.Wait, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.Phys.Intf,
FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, Data.DB, FireDAC.Comp.Client, FireDAC.Comp.UI, FireDAC.Phys.SQLite, System.iOUtils,
System.Generics.Collections, ubaby, FireDAC.Comp.ScriptCommands, FireDAC.Stan.Util, FireDAC.Comp.Script, FMX.graphics;
type
TDMMainModule = class(TDataModule)
FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
FDScript1: TFDScript;
private
function checkIDexist(const AID: Integer): Boolean;
{ Private declarations }
public
{ Public declarations }
function SqlitConnection(): TFDConnection;
function GetBabyList(): TList<TBaby>;
procedure DeleteBaby(BabyId: Integer);
procedure AddBaby(Baby: TBaby);
procedure SetBabyPresent(AID: Integer; APresent: Boolean);
end;
var
DMMainModule: TDMMainModule;
implementation
uses Uscript;
{ %CLASSGROUP 'FMX.Controls.TControl' }
{$R *.dfm}
function TDMMainModule.checkIDexist(const AID: Integer): Boolean;
var
FDQuery1: TFDQuery;
begin
Result := False;
TRY
FDQuery1 := TFDQuery.Create(Self);
FDQuery1.Connection := SqlitConnection();
FDQuery1.SQL.Text := 'Select * from Babys where ID=:ID';
FDQuery1.ParamByName('ID').AsInteger := AID;
FDQuery1.Open;
Result := (FDQuery1.RecordCount >= 1)
FINALLY
FDQuery1.Connection.Close;
FDQuery1.Connection.Free;
FDQuery1.Close;
FDQuery1.Free;
END;
end;
procedure TDMMainModule.AddBaby(Baby: TBaby);
var
FDQuery1: TFDQuery;
MemStream: TMemoryStream;
begin
TRY
if checkIDexist(Baby.id) = true then
begin
raise Exception.Create('ID alredy exist !');
exit;
end;
FDQuery1 := TFDQuery.Create(Self);
FDQuery1.Connection := SqlitConnection();
FDQuery1.SQL.Text := 'INSERT INTO Babys (ID,FirstName, LastName,Age,Present,ProfileImage) VALUES (:ID,:FirstName,:LastName,:Age,:Present,:ProfileImage)';
FDQuery1.ParamByName('ID').AsInteger := Baby.id;
FDQuery1.ParamByName('FirstName').AsString := Baby.FirstName;
FDQuery1.ParamByName('LastName').AsString := Baby.LastName;
FDQuery1.ParamByName('Age').AsSingle := Baby.Age;
FDQuery1.ParamByName('Present').AsBoolean := Baby.Present;
if (Baby.profileImage <> nil) then
begin
try
MemStream := TMemoryStream.Create;
try
Baby.ProfileBitmap.SaveToStream(MemStream);
MemStream.Seek(0, 0);
FDQuery1.ParamByName('ProfileImage').LoadFromStream(MemStream, ftBlob);
except
on e: Exception do
begin
// ShowMessage(e.Message);
end;
end;
finally
MemStream.Free;
end;
end
else
begin
try
FDQuery1.ParamByName('ProfileImage').Assign(nil);
except
exit;
end;
end;
FDQuery1.ExecSQL;
FINALLY
FDQuery1.Connection.Close;
FDQuery1.Connection.Free;
FDQuery1.Close;
FDQuery1.Free;
END;
end;
procedure TDMMainModule.SetBabyPresent(AID: Integer; APresent: Boolean);
var
FDQuery1: TFDQuery;
MemStream: TMemoryStream;
begin
TRY
FDQuery1 := TFDQuery.Create(Self);
FDQuery1.Connection := SqlitConnection();
FDQuery1.SQL.Text := 'Update Babys set Present=:Pre where ID=:ID';
FDQuery1.ParamByName('ID').AsInteger := AID;
FDQuery1.ParamByName('Pre').AsBoolean := APresent;
FDQuery1.ExecSQL;
FINALLY
FDQuery1.Connection.Close;
FDQuery1.Connection.Free;
FDQuery1.Close;
FDQuery1.Free;
END;
end;
procedure TDMMainModule.DeleteBaby(BabyId: Integer);
var
FDQuery1: TFDQuery;
begin
TRY
FDQuery1 := TFDQuery.Create(Self);
FDQuery1.Connection := SqlitConnection();
FDQuery1.SQL.Text := Format('DELETE FROM babys WHERE Id=%d', [BabyId]);
FDQuery1.ExecSQL;
FINALLY
FDQuery1.Connection.Close;
FDQuery1.Connection.Free;
FDQuery1.Close;
FDQuery1.Free;
END;
end;
function TDMMainModule.SqlitConnection(): TFDConnection;
var
dbPath: string;
const
DBFILE = 'DBBabys.db';
begin
{$IFDEF MSWINDOWS}
dbPath := TPath.Combine(ExpandFileName(GetCurrentDir), DBFILE);
{$ELSE}
dbPath := TPath.GetDocumentsPath + PathDelim + DBFILE;
{$ENDIF}
Result := TFDConnection.Create(Self);
Result.Params.Add('Database=' + dbPath);
Result.DriverName := 'SQLite';
Result.LoginPrompt := False;
Result.Open();
end;
function ConvertBytetoBitmap(ABlob: TField): Tbitmap;
var
bmp: Tbitmap;
BlobStream: TStream;
FDQuery1: TFDQuery;
begin
FDQuery1 := TFDQuery.Create(nil);
bmp := Tbitmap.Create;
try
// access a stream from a blob like this
BlobStream := FDQuery1.CreateBlobStream(ABlob, TBlobStreamMode.bmRead);
bmp.LoadFromStream(BlobStream);
Result := bmp;
finally
BlobStream.Free;
FDQuery1.Free;
end;
end;
function TDMMainModule.GetBabyList(): TList<TBaby>;
var
mUser: TBaby;
FDQuery1: TFDQuery;
begin
TRY
Result := TList<TBaby>.Create();
FDQuery1 := TFDQuery.Create(Self);
FDQuery1.Connection := SqlitConnection();
FDQuery1.SQL.Text := 'SELECT * FROM Babys';
FDQuery1.Open;
while not FDQuery1.EOF do
begin
Result.Add(TBaby.Create(FDQuery1.FieldByName('Id').AsInteger, FDQuery1.FieldByName('FirstName').AsString, FDQuery1.FieldByName('LastName').AsString,
FDQuery1.FieldByName('Age').AsSingle, ConvertBytetoBitmap(FDQuery1.FieldByName('ProfileImage')), FDQuery1.FieldByName('Present').AsBoolean));
FDQuery1.Next;
end;
FINALLY
FDQuery1.Connection.Close;
FDQuery1.Connection.Free;
FDQuery1.Close;
FDQuery1.Free;
END;
end;
end.
|
unit UDaftarPembayaranHutang;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, Grids,
DBGrids, SMDBGrid, RzButton, StdCtrls, Mask, RzEdit, RzLabel, ExtCtrls,
RzPanel, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxStyles, dxSkinsCore, dxSkinsDefaultPainters, dxSkinscxPCPainter,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxDBData,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel,
cxClasses, cxGridCustomView, cxGrid, dxSkinBlack, dxSkinBlue,
dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinFoggy,
dxSkinGlassOceans, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky,
dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green,
dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinPumpkin, dxSkinSeven,
dxSkinSharp, dxSkinSilver, dxSkinSpringTime, dxSkinStardust,
dxSkinSummer2008, dxSkinValentine, dxSkinXmas2008Blue, cxPC, cxTextEdit,
cxCheckBox;
type
TFrm_DaftarPembayaranHutangUsaha = class(TForm)
RzPanel1: TRzPanel;
RzPanel2: TRzPanel;
BtnSelesai: TRzBitBtn;
QData: TZQuery;
DSData: TDataSource;
BtnHapus: TRzBitBtn;
Q1: TZQuery;
dbgdata: TcxGrid;
dbgdataDBTableView1: TcxGridDBTableView;
dbgdataLevel1: TcxGridLevel;
QDatanokontak: TLargeintField;
QDatatglbayar: TDateField;
QDatatotal: TFloatField;
QDatanamauser: TStringField;
QDatanamakontak: TStringField;
dbgdataDBTableView1nokaskeluar: TcxGridDBColumn;
dbgdataDBTableView1tglbayar: TcxGridDBColumn;
dbgdataDBTableView1total: TcxGridDBColumn;
dbgdataDBTableView1namakontak: TcxGridDBColumn;
BtnPerincian: TRzBitBtn;
QDatanopembayaranhutang: TLargeintField;
QDatanokas: TLargeintField;
QDatagiro: TSmallintField;
BtnUpdate: TRzToolButton;
BtnFilter: TRzToolButton;
QDatakodepembayaranhutang: TStringField;
BtnCetak: TRzBitBtn;
QDatanokastransit: TLargeintField;
QDataapprove: TSmallintField;
QDatacair: TSmallintField;
QDataiscancel: TSmallintField;
dbgdataDBTableView1approve: TcxGridDBColumn;
dbgdataDBTableView1cair: TcxGridDBColumn;
dbgdataDBTableView1iscancel: TcxGridDBColumn;
BtnApprove: TRzBitBtn;
procedure BtnFilterClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure BtnSelesaiClick(Sender: TObject);
procedure BtnHapusClick(Sender: TObject);
procedure BtnPerincianClick(Sender: TObject);
procedure BtnUpdateClick(Sender: TObject);
procedure dbgdataDBTableView1DblClick(Sender: TObject);
procedure BtnCetakClick(Sender: TObject);
procedure BtnApproveClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure RefreshQ;
end;
var
Frm_DaftarPembayaranHutangUsaha: TFrm_DaftarPembayaranHutangUsaha;
datedari,datesampai:string;
implementation
uses UDM, UPembayaranHutang, UFTanggal, UMain, NxCells;
{$R *.dfm}
{ TFrm_DaftarPembayaranHutangUsaha }
procedure TFrm_DaftarPembayaranHutangUsaha.RefreshQ;
begin
with QData do begin
Close;
ParamByName('tkd').Value := datedari;
ParamByName('tks').Value := datesampai;
Open;
end;
end;
procedure TFrm_DaftarPembayaranHutangUsaha.BtnFilterClick(Sender: TObject);
begin
Application.CreateForm(TFTanggal, FTanggal);
with FTanggal do begin
if ShowModal=mrok then begin
datedari := FormatDateTime('yyyy-mm-dd',FTanggal.dtpdari.Date);
datesampai := FormatDateTime('yyyy-mm-dd',FTanggal.dtpsampai.Date);
RefreshQ;
end;
end;
end;
procedure TFrm_DaftarPembayaranHutangUsaha.FormShow(Sender: TObject);
begin
datedari := FormatDateTime('yyyy-mm-dd',DM.FDOM(Date));
datesampai := FormatDateTime('yyyy-mm-dd',DM.LastDayCurrMon(Date));
RzPanel1.Caption := 'Daftar Pembayaran Hutang Usaha';
RefreshQ;
end;
procedure TFrm_DaftarPembayaranHutangUsaha.BtnSelesaiClick(
Sender: TObject);
var
ts: TcxTabSheet;
begin
ts := (Self.parent as TcxTabSheet);
Frm_Main.CloseTab(Self, ts);
end;
procedure TFrm_DaftarPembayaranHutangUsaha.BtnHapusClick(Sender: TObject);
begin
if QData.IsEmpty then Exit;
if DM.CekAkses(Frm_Main.txtuser.Caption,'Pembelian9')=False then begin
MessageDlg('Anda tidak memiliki akses !',mtError,[mbOK],0);
Exit;
end;
{if DM.CekPeriode(QData.FieldValues['tgltransaksi'])=0 then begin
MessageDlg('Anda tidak diperkenankan mengubah transaksi sebelum periode akuntansi yang sedang aktif',mtError,[mbOK],0);
Exit;
end; }
{if MessageDlg('Hapus transaksi ?'#10#13'Perhatian: Perubahan setelah dihapus tidak bisa dibatalkan/dikembalikan!',mtConfirmation,[mbYes,mbNo],0)=mryes then begin
with TZQuery.Create(Self)do begin
Connection := dm.Con;
if QData.FieldValues['giro'] = 1 then begin
Close;
SQL.Clear;
SQL.Text := 'select * from tbl_giro where noreferensi=:a and tipe=:b';
ParamByName('a').Value := QData.FieldValues['nopembayaranhutang'];
ParamByName('b').Value := 'CD';
Open;
if FieldValues['posting'] = 1 then begin
MessageDlg('Data pembayaran hutang tidak dapat dihapus, karena giro telah cair!',mtError,[mbOK],0);
Free;
Exit;
end;
end;
Close;
SQL.Clear;
SQL.Text := 'delete from tbl_bukubesarakun where noreferensi=:np and tipe=:t';
ParamByName('np').Value := QData.FieldValues['nopembayaranhutang'];
ParamByName('t').Value := 'CD';
ExecSQL;
Close;
SQL.Clear;
SQL.Text := 'delete from tbl_bukubesarkontak where noreferensi=:np and tipe=:t';
ParamByName('np').Value := QData.FieldValues['nopembayaranhutang'];
ParamByName('t').Value := 'CD';
ExecSQL;
Close;
SQL.Clear;
SQL.Text := 'delete from tbl_giro where noreferensi=:np and tipe=:t';
ParamByName('np').Value := QData.FieldValues['nopembayaranhutang'];
ParamByName('t').Value := 'CD';
ExecSQL;
Close;
SQL.Clear;
SQL.Text := 'delete from tbl_laba where noreferensi=:np and tipe=:t';
ParamByName('np').Value := QData.FieldValues['nopembayaranhutang'];
ParamByName('t').Value := 'CD';
ExecSQL;
Close;
SQL.Clear;
SQL.Text := 'delete from tbl_giro where noreferensi=:np and tipe=:t';
ParamByName('np').Value := QData.FieldValues['nopembayaranhutang'];
ParamByName('t').Value := 'CD';
ExecSQL;
Close;
SQL.Clear;
SQL.Text := 'delete from tbl_pembayaranhutang where nopembayaranhutang=:np';
ParamByName('np').Value := QData.FieldValues['nopembayaranhutang'];
ExecSQL;
Close;
SQL.Clear;
SQL.Text := 'delete from tbl_pembayaranhutangdetail where nopembayaranhutang=:np';
ParamByName('np').Value := QData.FieldValues['nopembayaranhutang'];
ExecSQL;
Free;
RefreshQ;
end;
end; }
if MessageDlg('Transaksi dibatalkan ?',mtConfirmation,[mbYes,mbNo],0)=mryes then begin
if QData.FieldValues['iscancel'] = 0 then begin
if QData.FieldValues['approve'] = 0 then begin
with TZQuery.Create(Self)do begin
Connection := dm.Con;
Close;
SQL.Clear;
SQL.Text := 'update tbl_pembayaranhutang set iscancel=:ic where nopembayaranhutang=:np';
ParamByName('np').Value := QData.FieldValues['nopembayaranhutang'];
ParamByName('ic').Value := 1;
ExecSQL;
Free;
RefreshQ;
end;
end else begin
MessageDlg('Permohonan pembayaran telah disetujui. Transaksi tidak dapat dibatalkan!',mtError,[mbOK],0);
end;
end;
end;
end;
procedure TFrm_DaftarPembayaranHutangUsaha.BtnPerincianClick(
Sender: TObject);
var
i:Integer;
f: TFrm_PembayaranHutang;
ts: TcxTabSheet;
begin
if QData.IsEmpty then Exit;
if DM.CekAkses(Frm_Main.txtuser.Caption,'Pembelian7')=False then begin
MessageDlg('Anda tidak memiliki akses !',mtError,[mbOK],0);
Exit;
end;
if not DM.CekTabOpen('Pembayaran Hutang Usaha') then begin
f := TFrm_PembayaranHutang.Create(Self);
with f do begin
ClearText;
{if DM.CekPeriode(QData.FieldValues['tglbayar'])= 0 then begin
dtptanggal.ReadOnly := True;
end }
with TZQuery.Create(Self)do begin
Connection := DM.con;
Close;
SQL.Clear;
SQL.Text := 'SELECT a.*,IFNULL(b.namakontak,'+QuotedStr('')+')AS namakontak FROM ' +
'(SELECT * FROM tbl_pembayaranhutang where nopembayaranhutang=:np)AS a ' +
'LEFT JOIN tbl_kontak AS b ON b.nokontak=a.nokontak';
ParamByName('np').Value := QData.FieldValues['nopembayaranhutang'];
Open;
LID.Caption := FieldValues['nopembayaranhutang'];
txtreferensi.Text := FieldValues['kodepembayaranhutang'];
txtsupplier.Text := FieldValues['namakontak'];
LSupplier.Caption := FieldValues['nokontak'];
txtsupplier.ReadOnly := True;
dtptanggal.Date := FieldValues['tglbayar'];
LKas.Caption := FieldValues['nokas'];
LKasTransit.Caption := FieldValues['nokastransit'];
if FieldValues['giro']=1 then
cbgiro.Checked := True
else cbgiro.Checked := False;
if FieldValues['approve']=1 then
cbapprove.Checked := True
else cbapprove.Checked := False;
if FieldValues['cair']=1 then
cbcair.Checked := True
else cbcair.Checked := False;
if FieldValues['iscancel']=1 then
cbcancel.Checked := True
else cbcancel.Checked := False;
if cbgiro.Checked = True then begin
Close;
SQL.Clear;
SQL.Text := 'select * from tbl_giro where noreferensi=:a and tipe=:b';
ParamByName('a').Value := LID.Caption;
ParamByName('b').Value := 'CD';
Open;
if FieldValues['posting'] = 1 then begin
cbgiro.Enabled := False;
end;
end;
Close;
SQL.Clear;
SQL.Text := 'select * from tbl_akun where noakun=:a';
ParamByName('a').Value := LKas.Caption;
Open;
txtkas.Text := FieldValues['namaakun'];
BtnRekam.Visible := False;
Close;
SQL.Clear;
SQL.Text := 'select a.*,b.tglpembelianinvoice,b.kodepembelianinvoice,DATE_ADD(b.tglpembelianinvoice,INTERVAL b.duedate DAY) AS tgltempo from ' +
'(select * from tbl_pembayaranhutangdetail where nopembayaranhutang=:nk)as a ' +
'left join tbl_pembelianinvoice as b on b.nopembelianinvoice=a.nopembelianinvoice';
ParamByName('nk').Value := LID.Caption;
Open;
if not IsEmpty then begin
dbgpembayaran.ClearRows;
First;
for i:=0 to RecordCount-1 do begin
dbgpembayaran.AddRow();
dbgpembayaran.Cell[0,i].AsString := FieldValues['kodepembelianinvoice'];
dbgpembayaran.Cell[1,i].AsDateTime := FieldValues['tglpembelianinvoice'];
dbgpembayaran.Cell[2,i].AsDateTime := FieldValues['tgltempo'];
dbgpembayaran.Cell[4,i].AsFloat := FieldValues['jumlahbayar'];
dbgpembayaran.Cell[5,i].AsFloat := FieldValues['selisih'];
dbgpembayaran.Cell[7,i].AsInteger := FieldValues['nopembelianinvoice'];
dbgpembayaran.Cell[8,i].AsInteger := FieldValues['noakunselisih'];
dbgpembayaran.Cell[9,i].AsInteger := FieldValues['noakunhutang'];
Q1.Close;
Q1.SQL.Clear;
Q1.SQL.Text := 'select e.*,e.totalhutang-e.jumlahbayar-e.jumlahretur as sisahutang from ' +
'(select c.*,ifnull(sum(d.jumlahbayar+d.selisih),0)as jumlahbayar from ' +
'(select a.*,ifnull(sum(b.total),0) as jumlahretur from ' +
'(select nopembelianinvoice,tglpembelianinvoice,nokontak,total as totalhutang from tbl_pembelianinvoice where nopembelianinvoice=:np)as a ' +
'left join tbl_returpembelian as b on b.nopembelianinvoice=a.nopembelianinvoice group by a.nopembelianinvoice)as c ' +
'left join (SELECT b.nopembelianinvoice,b.jumlahbayar,b.selisih FROM ' +
'(SELECT * FROM tbl_pembayaranhutang WHERE iscancel=0)AS a ' +
'LEFT JOIN tbl_pembayaranhutangdetail AS b ON b.nopembayaranhutang=a.nopembayaranhutang) as d on d.nopembelianinvoice=c.nopembelianinvoice group by c.nopembelianinvoice)as e where e.totalhutang-e.jumlahbayar-e.jumlahretur<>0';
Q1.ParamByName('np').Value := dbgpembayaran.Cell[0,i].AsString;
Q1.Open;
if Q1.IsEmpty then
dbgpembayaran.Cell[3,i].AsFloat := 0
else dbgpembayaran.Cell[3,i].AsFloat := Q1.FieldValues['sisahutang'];
dbgpembayaran.Cell[3,i].AsFloat := dbgpembayaran.Cell[3,i].AsFloat+dbgpembayaran.Cell[4,i].AsFloat+dbgpembayaran.Cell[5,i].AsFloat;
if dbgpembayaran.Cell[8,i].AsInteger > 0 then begin
Q1.Close;
Q1.SQL.Clear;
Q1.SQL.Text := 'select * from tbl_akun where noakun=:np';
Q1.ParamByName('np').Value := dbgpembayaran.Cell[8,i].AsInteger;
Q1.Open;
dbgpembayaran.Cell[6,i].AsString := Q1.FieldValues['namaakun'];
end;
Next;
end;
end;
UpdateTotal;
Free;
end;
end;
f.ManualDock(Frm_Main.PGMain, Frm_Main.PGMain, alClient);
f.Show;
ts := (f.parent as TcxTabSheet);
Frm_Main.PGMain.ActivePage := ts;
end;
end;
procedure TFrm_DaftarPembayaranHutangUsaha.BtnUpdateClick(Sender: TObject);
begin
RefreshQ;
end;
procedure TFrm_DaftarPembayaranHutangUsaha.dbgdataDBTableView1DblClick(
Sender: TObject);
begin
BtnPerincianClick(nil);
end;
procedure TFrm_DaftarPembayaranHutangUsaha.BtnCetakClick(Sender: TObject);
begin
if QData.IsEmpty then Exit;
if QData.FieldValues['approve'] = 0 then begin
with TZQuery.Create(Self)do begin
Connection := dm.con;
Close;
SQL.Clear;
SQL.Text := 'select * from tbl_terbilang where noreferensi=:np and tipe=:t';
ParamByName('np').Value := QData.FieldValues['nopembayaranhutang'];
ParamByName('t').Value := 'CD';
Open;
if IsEmpty then begin
Close;
SQL.Clear;
SQL.Text := 'insert into tbl_terbilang values (:a,:b,:c)';
ParamByName('a').Value := QData.FieldValues['nopembayaranhutang'];
ParamByName('b').Value := 'CD';
ParamByName('c').Value := DM.ConvKeHuruf(IntToStr(QData.FieldValues['total']));
ExecSQL;
end else begin
Close;
SQL.Clear;
SQL.Text := 'update tbl_terbilang set terbilang=:c where noreferensi=:np and tipe=:t';
ParamByName('np').Value := QData.FieldValues['nopembayaranhutang'];
ParamByName('t').Value := 'CD';
ParamByName('c').Value := DM.ConvKeHuruf(IntToStr(QData.FieldValues['total']));
ExecSQL;
end;
dm.Q_NotaPembayaranHutang.Close;
DM.Q_NotaPembayaranHutang.ParamByName('np').Value := QData.FieldValues['nopembayaranhutang'];;
DM.Q_NotaPembayaranHutang.Open;
dm.Q_NotaTerbilang.Close;
DM.Q_NotaTerbilang.ParamByName('np').Value := QData.FieldValues['nopembayaranhutang'];;
DM.Q_NotaTerbilang.ParamByName('t').Value := 'CD';
DM.Q_NotaTerbilang.Open;
DM.Nota_PembayaranHutang.ShowReport(True);
Free;
end;
end;
end;
procedure TFrm_DaftarPembayaranHutangUsaha.BtnApproveClick(
Sender: TObject);
var
i: Integer;
begin
if QData.IsEmpty then Exit;
if DM.CekAkses(Frm_Main.txtuser.Caption,'Pembelian8')=False then begin
MessageDlg('Anda tidak memiliki akses !',mtError,[mbOK],0);
Exit;
end;
if QData.FieldValues['iscancel'] = 0 then begin
if QData.FieldValues['approve'] = 0 then begin
if MessageDlg('Permohonan Pembayaran telah disetujui ?',mtConfirmation,[mbYes,mbNo],0)=mryes then begin
Screen.Cursor := crSQLWait;
try
dm.con.StartTransaction;
with TZQuery.Create(Self)do begin
Connection := dm.con;
Close;
SQL.Clear;
SQL.Text := 'select a.*,b.tglpembelianinvoice,b.kodepembelianinvoice,DATE_ADD(b.tglpembelianinvoice,INTERVAL b.duedate DAY) AS tgltempo from ' +
'(select * from tbl_pembayaranhutangdetail where nopembayaranhutang=:nk)as a ' +
'left join tbl_pembelianinvoice as b on b.nopembelianinvoice=a.nopembelianinvoice';
ParamByName('nk').Value := QData.FieldValues['nopembayaranhutang'];
Open;
for i:= 0 to RecordCount-1 do begin
DM.InsertBukuBesarAkun(FieldValues['noakunhutang'],Date,'CD',QData.FieldValues['nopembayaranhutang'],'Pembayaran Hutang,'+QData.FieldValues['kodepembayaranhutang'],FieldValues['jumlahbayar'],0);
if FieldValues['selisih']>0 then begin
DM.InsertBukuBesarAkun(FieldValues['noakunselisih'],Date,'CD',QData.FieldValues['nopembayaranhutang'],'Selisih Pembayaran,'+QData.FieldValues['kodepembayaranhutang'],FieldValues['selisih'],0);
end else if FieldValues['selisih']<0 then begin
DM.InsertBukuBesarAkun(FieldValues['noakunselisih'],Date,'CD',QData.FieldValues['nopembayaranhutang'],'Selisih Pembayaran,'+QData.FieldValues['kodepembayaranhutang'],0,Abs(FieldValues['selisih']));
end;
end;
DM.InsertBukuBesarAkun(QData.FieldValues['nokastransit'],Date,'CD',QData.FieldValues['nopembayaranhutang'],'Pembayaran Hutang,'+QData.FieldValues['kodepembayaranhutang'],0,QData.FieldValues['total']);
Close;
SQL.Clear;
SQL.Text := 'update tbl_pembayaranhutang set approve=:ap where nopembayaranhutang=:a';
ParamByName('a').Value := QData.FieldValues['nopembayaranhutang'];
ParamByName('ap').Value := 1;
ExecSQL;
dm.con.Commit;
Screen.Cursor := crDefault;
Free;
end;
except
on E: Exception do begin
dm.con.Rollback;
MessageDlg('Error: ' + E.Message,mtWarning,[mbOk],0);
end;
end;
RefreshQ;
end;
end;
end;
end;
end.
|
unit sNIF.cmdline.DEF;
{ *******************************************************
sNIF
Utilidad para buscar ficheros ofimáticos con
cadenas de caracteres coincidentes con NIF/NIE.
*******************************************************
2012-2018 Ángel Fernández Pineda. Madrid. Spain.
This work is licensed under the Creative Commons
Attribution-ShareAlike 3.0 Unported License. To
view a copy of this license,
visit http://creativecommons.org/licenses/by-sa/3.0/
or send a letter to Creative Commons,
444 Castro Street, Suite 900,
Mountain View, California, 94041, USA.
******************************************************* }
interface
uses
KV.Definition;
var
CmdLineParams: TKeyValueValidator;
const
CMDLINE_CFG = 'Cfg';
CMDLINE_PLANTILLA = 'Plantilla';
CMDLINE_SALIDA = 'Salida';
CMDLINE_ENTRADA_FICHERO = 'FicheroCarpetas';
CMDLINE_ENTRADA_CARPETA = 'Carpeta';
{
En CmdLineParams se definen los parámetros de la línea de comandos
y sus valores admitidos. También sus descripciones.
Los valores leídos del fichero de configuración se constrastarán contra
esta definición en "sNIF.cmdline.pas".
}
implementation
uses
IOUtils,
IOUtilsFix;
var
df: TKeyDefinition;
validadorFichero: TValueValidator;
initialization
validadorFichero := function(const valor: variant): boolean
begin
Result := (Length(valor) > 0) and (valor <> 'true') and
(TPath.isWellFormed(valor, false, false));
end;
CmdLineParams := TKeyValueValidator.Create;
df := CmdLineParams.Add(CMDLINE_CFG, varString);
df.Description :=
'-Cfg <fichero>'#10#13'Toma los parámetros de exploración del fichero indicado.'#10#13'Por omisión, se utilizarán los parámetros por defecto.';
df.ValidValueDescription := 'Ruta a fichero de configuración (véase manual).';
df.OnValidate := validadorFichero;
df := CmdLineParams.Add(CMDLINE_PLANTILLA, varString);
df.Description :=
'-Plantilla <fichero>'#10#13'Genera un fichero de configuración a modo de plantilla para su edición.'#10#13'Incompatible con los demás parámetros.';
df.ValidValueDescription := 'Ruta a fichero';
df.OnValidate := validadorFichero;
df := CmdLineParams.Add(CMDLINE_SALIDA, varString);
df.Description :=
'-Salida <fichero>'#10#13'Fichero resultado de la exploración.';
df.ValidValueDescription := 'Ruta a fichero (formato CSV, codificación UTF-8)';
df.OnValidate := validadorFichero;
df := CmdLineParams.Add(CMDLINE_ENTRADA_FICHERO, varString);
df.Description :=
'-FicheroCarpetas <fichero>'#10#13'Fichero de texto plano que contiene las carpetas a explorar (una por línea).';
df.ValidValueDescription := 'Ruta a fichero de texto plano';
df.OnValidate := validadorFichero;
df := CmdLineParams.Add(CMDLINE_ENTRADA_CARPETA, varString, 0, 65535);
df.Description :=
'-Carpeta "<carpeta>" ["<carpeta>" ... "<Carpeta>"]'#10#13'Carpeta(s) a explorar recursivamente.';
df.ValidValueDescription := 'Ruta a carpeta(s)';
df.OnValidate := function(const valor: variant): boolean
begin
Result := (Length(valor) > 0) and (TPath.isWellFormed(valor, true, false));
end;
finalization
CmdLineParams.Free;
end.
|
unit TestRemoveComment;
{ AFS 10 Nov 2003
Test comment removal }
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestRemoveComment, released November 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 2003 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses
TestFrameWork,
BaseTestProcess;
type
TTestRemoveComment = class(TBaseTestProcess)
private
public
procedure SetUp; override;
published
procedure TestNone;
procedure TestBraces;
procedure TestSlash;
procedure TestBoth;
end;
implementation
uses
JcfStringUtils,
JcfSettings, RemoveComment;
procedure TTestRemoveComment.Setup;
begin
inherited;
JcfFormatSettings.Comments.RemoveEmptyDoubleSlashComments := True;
JcfFormatSettings.Comments.RemoveEmptyCurlyBraceComments := True;
end;
procedure TTestRemoveComment.TestNone;
const
IN_UNIT_TEXT = UNIT_HEADER + UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER + UNIT_FOOTER;
begin
TestProcessResult(TRemoveComment, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestRemoveComment.TestBraces;
const
IN_UNIT_TEXT = UNIT_HEADER +
'{ }' +
UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER +
' ' +
UNIT_FOOTER;
begin
TestProcessResult(TRemoveComment, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestRemoveComment.TestSlash;
const
IN_UNIT_TEXT = UNIT_HEADER +
'// ' + NativeLineBreak +
UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER +
NativeLineBreak +
UNIT_FOOTER;
begin
end;
procedure TTestRemoveComment.TestBoth;
const
IN_UNIT_TEXT = UNIT_HEADER +
'// ' + NativeLineBreak +
'{ }' + NativeLineBreak +
UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER +
' ' + NativeLineBreak +
' ' + NativeLineBreak +
UNIT_FOOTER;
begin
TestProcessResult(TRemoveComment, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
initialization
TestFramework.RegisterTest('Processes', TTestRemoveComment.Suite);
end.
|
unit uFrmPrincipal;
//http://www.planetadelphi.com.br/artigo/137/usando-estrutura-(record),-ponteiro-e-tlist-na-aplica%C3%A7%C3%A3o.
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TPessoa = record
Nome:string;
Email:string;
end;
ptrPessoa = ^TPessoa; //Ponteiro para meu Record.
type
TForm1 = class(TForm)
Label1: TLabel;
edtNome: TEdit;
Label2: TLabel;
edtEmail: TEdit;
btnAdicionar: TButton;
btnMostrar: TButton;
btnExcluir: TButton;
btnConferir: TButton;
ListBox1: TListBox;
Label3: TLabel;
btnModificar: TButton;
procedure FormCreate(Sender: TObject);
procedure btnConferirClick(Sender: TObject);
procedure btnMostrarClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure btnModificarClick(Sender: TObject);
procedure btnAdicionarClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Ponteiro : ptrPessoa; //Var tipo ponteiro da estrutura record pessoa.
listaCadastrados: TList;
procedure operacao(flag:boolean);
procedure limpaLista(var Lista:TList);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TForm1 }
procedure TForm1.limpaLista(var Lista: TList);
var
i:integer;
begin
//Limpa uma TList.
for i:= (Lista.Count -1) downto 0 do
begin
Dispose(Lista.Items[i]);
Lista.Delete(i);
end;
end;
procedure TForm1.operacao(flag: boolean);
begin
if flag then //se for true add um dado na estrutura
begin
Ponteiro := new( ptrPessoa ); //Quando usar ponteiro dar um new para alocar memoria.
Ponteiro^.Nome := edtNome.Text;
Ponteiro^.Email := edtEmail.Text;
ListBox1.Items.Add(
inttostr(listaCadastrados.Add(Ponteiro))+'-'+
inttostr(Integer(Ponteiro))+'-'+
Ponteiro^.Nome+'-'+
Ponteiro^.Email);
end
else //Se for false altera o item.
begin
Ponteiro^.Nome:=edtNome.Text;
Ponteiro^.Email:=edtEmail.Text;
ListBox1.Items.Strings[ListBox1.ItemIndex] := inttostr(listaCadastrados.IndexOf(Ponteiro))
+ ' - ' + IntToStr( Integer( Ponteiro ) )
+ ' - ' + Ponteiro^.Nome
+ ' - ' + Ponteiro^.Email;
end;
// Limpa edits
edtNome.Text := EmptyStr;
edtEmail.Text := EmptyStr;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
listaCadastrados:=TList.Create; //Cria lista de cadastrados.
end;
procedure TForm1.btnConferirClick(Sender: TObject);
var
i:integer;
begin
for i:=0 to listaCadastrados.Count -1 do
begin
Ponteiro:= listaCadastrados.Items[i];
showmessage(
IntToStr( listaCadastrados.IndexOf( Ponteiro ) )
+ ' - ' + IntToStr( Integer( Ponteiro ) )
+ ' - ' + Ponteiro^.Nome
+ ' - ' + Ponteiro^.Email );
end;
end;
procedure TForm1.btnMostrarClick(Sender: TObject);
begin
BtnModificar.Visible := True;
try
// A variável ponteiro recebe o endereço de memória da estrutura guardada no Tlist.
Ponteiro := listaCadastrados.Items[ListBox1.ItemIndex];
EdtNome.Text := Ponteiro^.Nome;
EdtEmail.Text := Ponteiro^.Email;
except
ShowMessage( 'Selecione um item.' );
end;
end;
procedure TForm1.btnExcluirClick(Sender: TObject);
begin
try
listaCadastrados.Delete(ListBox1.ItemIndex);
ListBox1.Items.Delete(ListBox1.ItemIndex);
except
on E : Exception do Abort;
end;
end;
procedure TForm1.btnModificarClick(Sender: TObject);
begin
// Operacao(False) - indica que está alterando um item
Operacao(False);
BtnModificar.Visible := False;
end;
procedure TForm1.btnAdicionarClick(Sender: TObject);
begin
// Operacao(True) - Indica que está adicionando item
Operacao(True);
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLTilePlane<p>
Implements a tiled texture plane.<p>
<b>History : </b><font size=-1><ul>
<li>23/08/10 - Yar - Added OpenGLTokens to uses, replaced OpenGL1x functions to OpenGLAdapter
<li>30/03/07 - DaStr - Added $I GLScene.inc
<li>28/03/07 - DaStr - Renamed parameters in some methods
(thanks Burkhard Carstens) (Bugtracker ID = 1678658)
<li>23/03/07 - DaStr - Added explicit pointer dereferencing
(thanks Burkhard Carstens) (Bugtracker ID = 1678644)
<li>19/08/05 - Mathx - Made index of materials start from 0 not from 1 (thanks to uhfath)
<li>23/03/04 - EG - Added NoZWrite
<li>09/01/04 - EG - Creation
</ul></font>
}
unit GLTilePlane;
interface
{$I GLScene.inc}
uses
Classes, GLScene, GLVectorGeometry, OpenGLTokens, GLContext, GLMaterial,
GLObjects, GLCrossPlatform, GLPersistentClasses, GLVectorLists,
GLRenderContextInfo, XOpenGL;
type
// TGLTiledAreaRow
//
{: Stores row information for a tiled area.<p> }
TGLTiledAreaRow = class (TPersistentObject)
private
{ Private Declarations }
FColMin, FColMax : Integer;
FData : TIntegerList;
protected
{ Protected Declarations }
procedure SetColMin(const val : Integer);
procedure SetColMax(const val : Integer);
function GetCell(col : Integer) : Integer;
procedure SetCell(col, val : Integer);
public
{ Public Declarations }
constructor Create; override;
destructor Destroy; override;
procedure WriteToFiler(writer : TVirtualWriter); override;
procedure ReadFromFiler(reader : TVirtualReader); override;
property Cell[col : Integer] : Integer read GetCell write SetCell; default;
property ColMin : Integer read FColMin write SetColMin;
property ColMax : Integer read FColMax write SetColMax;
property Data : TIntegerList read FData;
procedure Pack;
function Empty : Boolean;
procedure RemapTiles(remapList : TIntegerList);
end;
// TGLTiledArea
//
{: Stores tile information in a tiled area.<p>
Each tile stores an integer value with zero the default value,
assumed as "empty". }
TGLTiledArea = class (TPersistentObject)
private
{ Private Declarations }
FRowMin, FRowMax : Integer;
FRows : TPersistentObjectList;
protected
{ Protected Declarations }
procedure SetRowMin(const val : Integer);
procedure SetRowMax(const val : Integer);
function GetTile(col, row : Integer) : Integer;
procedure SetTile(col, row, val : Integer);
function GetRow(index : Integer) : TGLTiledAreaRow;
public
{ Public Declarations }
constructor Create; override;
destructor Destroy; override;
procedure WriteToFiler(writer : TVirtualWriter); override;
procedure ReadFromFiler(reader : TVirtualReader); override;
property Tile[col, row : Integer] : Integer read GetTile write SetTile; default;
property Row[index : Integer] : TGLTiledAreaRow read GetRow;
property RowMin : Integer read FRowMin write SetRowMin;
property RowMax : Integer read FRowMax write SetRowMax;
procedure Pack;
procedure Clear;
function Empty : Boolean;
procedure RemapTiles(remapList : TIntegerList);
end;
// TGLTilePlane
//
{: A tiled textured plane.<p>
This plane object stores and displays texture tiles that composes it,
and is optimized to minimize texture switches when rendering.<br>
Its bounding dimensions are determined by its painted tile. }
TGLTilePlane = class (TGLImmaterialSceneObject)
private
{ Private Declarations }
FNoZWrite : Boolean;
FTiles : TGLTiledArea;
FMaterialLibrary : TGLMaterialLibrary;
FSortByMaterials : Boolean;
protected
{ Protected Declarations }
procedure SetNoZWrite(const val : Boolean);
procedure SetTiles(const val : TGLTiledArea);
procedure SetMaterialLibrary(const val : TGLMaterialLibrary);
procedure SetSortByMaterials(const val : Boolean);
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DoRender(var ARci : TRenderContextInfo;
ARenderSelf, ARenderChildren : Boolean); override;
procedure BuildList(var rci : TRenderContextInfo); override;
//: Access to the TiledArea data
property Tiles : TGLTiledArea read FTiles write SetTiles;
{: Controls the sorting of tiles by material.<p>
This property should ideally be left always at its default, True,
except for debugging and performance measurement, which is why
it's only public and not published. }
property SortByMaterials : Boolean read FSortByMaterials write SetSortByMaterials;
published
{ Public Declarations }
{: If True the tiles are rendered without writing to the ZBuffer. }
property NoZWrite : Boolean read FNoZWrite write SetNoZWrite;
{: Material library where tiles materials will be stored/retrieved.<p>
The lower 16 bits of the tile integer value is understood as being
the index of the tile's material in the library (material of
index zero is thus unused). }
property MaterialLibrary : TGLMaterialLibrary read FMaterialLibrary write SetMaterialLibrary;
end;
//-------------------------------------------------------------
//-------------------------------------------------------------
//-------------------------------------------------------------
implementation
// ------------------
// ------------------ TGLTiledAreaRow ------------------
// ------------------
// Create
//
constructor TGLTiledAreaRow.Create;
begin
inherited;
FData:=TIntegerList.Create;
FColMin:=0;
FColMax:=-1;
end;
// Destroy
//
destructor TGLTiledAreaRow.Destroy;
begin
FData.Free;
inherited;
end;
// WriteToFiler
//
procedure TGLTiledAreaRow.WriteToFiler(writer : TVirtualWriter);
begin
inherited WriteToFiler(writer);
with writer do begin
WriteInteger(0); // Archive Version 0
WriteInteger(FColMin);
FData.WriteToFiler(writer);
end;
end;
// ReadFromFiler
//
procedure TGLTiledAreaRow.ReadFromFiler(reader : TVirtualReader);
var
archiveVersion : Integer;
begin
inherited ReadFromFiler(reader);
archiveVersion:=reader.ReadInteger;
if archiveVersion=0 then with reader do begin
FColMin:=ReadInteger;
FData.ReadFromFiler(reader);
FColMax:=FColMin+FData.Count-1;
end;
end;
// Pack
//
procedure TGLTiledAreaRow.Pack;
var
i, startSkip : Integer;
begin
startSkip:=MaxInt;
for i:=0 to FData.Count-1 do begin
if FData.List^[i]<>0 then begin
startSkip:=i;
Break;
end;
end;
if startSkip=MaxInt then begin
FData.Clear;
FColMax:=ColMin-1;
end else begin
for i:=FData.Count-1 downto 0 do begin
if FData.List^[i]<>0 then begin
FData.Count:=i+1;
FColMax:=FColMin+FData.Count-1;
Break;
end;
end;
if startSkip>0 then begin
FData.DeleteItems(0, startSkip);
FColMin:=FColMin+startSkip;
end;
end;
end;
// Empty
//
function TGLTiledAreaRow.Empty : Boolean;
begin
Result:=(FData.Count=0);
end;
// RemapTiles
//
procedure TGLTiledAreaRow.RemapTiles(remapList : TIntegerList);
var
i, k : Integer;
begin
for i:=0 to FData.Count-1 do begin
k:=FData[i];
if Cardinal(k)<Cardinal(remapList.Count) then
FData[i]:=remapList[k]
else FData[i]:=0;
end;
end;
// SetColMax
//
procedure TGLTiledAreaRow.SetColMax(const val : Integer);
begin
if val>=ColMin then
FData.Count:=val-ColMin+1
else FData.Clear;
FColMax:=val;
end;
// SetColMin
//
procedure TGLTiledAreaRow.SetColMin(const val : Integer);
begin
if ColMax>=val then begin
if val<ColMin then
FData.InsertNulls(0, ColMin-val)
else FData.DeleteItems(0, val-ColMin);
end else FData.Clear;
FColMin:=val;
end;
// GetCell
//
function TGLTiledAreaRow.GetCell(col : Integer) : Integer;
begin
if (col>=ColMin) and (col<=ColMax) then
Result:=FData[col-ColMin]
else Result:=0;
end;
// SetCell
//
procedure TGLTiledAreaRow.SetCell(col, val : Integer);
var
i : Integer;
begin
i:=col-ColMin;
if Cardinal(i)>=Cardinal(FData.Count) then begin
if ColMin<=ColMax then begin
if col<ColMin then ColMin:=col;
if col>ColMax then ColMax:=col;
end else begin
FColMin:=col;
FColMax:=col;
FData.Add(val);
Exit;
end;
end;
FData[col-ColMin]:=val;
end;
// ------------------
// ------------------ TGLTiledArea ------------------
// ------------------
// Create
//
constructor TGLTiledArea.Create;
begin
inherited;
FRows:=TPersistentObjectList.Create;
FRowMax:=-1;
end;
// Destroy
//
destructor TGLTiledArea.Destroy;
begin
FRows.CleanFree;
inherited;
end;
// WriteToFiler
//
procedure TGLTiledArea.WriteToFiler(writer : TVirtualWriter);
begin
inherited WriteToFiler(writer);
with writer do begin
WriteInteger(0); // Archive Version 0
WriteInteger(FRowMin);
FRows.WriteToFiler(writer);
end;
end;
// ReadFromFiler
//
procedure TGLTiledArea.ReadFromFiler(reader : TVirtualReader);
var
archiveVersion : Integer;
begin
inherited ReadFromFiler(reader);
archiveVersion:=reader.ReadInteger;
if archiveVersion=0 then with reader do begin
FRowMin:=ReadInteger;
FRows.ReadFromFiler(reader);
FRowMax:=FRowMin+FRows.Count-1;
end;
end;
// Pack
//
procedure TGLTiledArea.Pack;
var
i, firstNonNil, lastNonNil : Integer;
r : TGLTiledAreaRow;
begin
// pack all rows, free empty ones, determine 1st and last non-nil
lastNonNil:=-1;
firstNonNil:=FRows.Count;
for i:=0 to FRows.Count-1 do begin
r:=TGLTiledAreaRow(FRows.List^[i]);
if Assigned(r) then begin
r.Pack;
if r.FData.Count=0 then begin
r.Free;
FRows.List^[i]:=nil;
end;
end;
if Assigned(r) then begin
lastNonNil:=i;
if i<firstNonNil then firstNonNil:=i;
end;
end;
if lastNonNil>=0 then begin
FRows.Count:=lastNonNil+1;
FRowMax:=FRowMin+FRows.Count-1;
if firstNonNil>0 then begin
FRowMin:=FRowMin+firstNonNil;
FRows.DeleteItems(0, firstNonNil);
end;
end else FRows.Clear;
end;
// Clear
//
procedure TGLTiledArea.Clear;
begin
FRows.Clean;
FRowMin:=0;
FRowMax:=-1;
end;
// Empty
//
function TGLTiledArea.Empty : Boolean;
begin
Result:=(FRows.Count=0);
end;
// RemapTiles
//
procedure TGLTiledArea.RemapTiles(remapList : TIntegerList);
var
i : Integer;
r : TGLTiledAreaRow;
begin
for i:=0 to FRows.Count-1 do begin
r:=TGLTiledAreaRow(FRows[i]);
if Assigned(r) then
r.RemapTiles(remapList);
end;
end;
// GetTile
//
function TGLTiledArea.GetTile(col, row : Integer) : Integer;
var
i : Integer;
r : TGLTiledAreaRow;
begin
i:=row-RowMin;
if Cardinal(i)<Cardinal(FRows.Count) then begin
r:=TGLTiledAreaRow(FRows[row-RowMin]);
if Assigned(r) then
Result:=r.Cell[col]
else Result:=0;
end else Result:=0;
end;
// SetTile
//
procedure TGLTiledArea.SetTile(col, row, val : Integer);
var
r : TGLTiledAreaRow;
begin
if row<RowMin then RowMin:=row;
if row>RowMax then RowMax:=row;
r:=TGLTiledAreaRow(FRows[row-RowMin]);
if not Assigned(r) then begin
r:=TGLTiledAreaRow.Create;
FRows[row-RowMin]:=r;
end;
r.Cell[col]:=val;
end;
// GetRow
//
function TGLTiledArea.GetRow(index : Integer) : TGLTiledAreaRow;
begin
index:=index-RowMin;
if Cardinal(index)<Cardinal(FRows.Count) then
Result:=TGLTiledAreaRow(FRows[index])
else Result:=nil;
end;
// SetRowMax
//
procedure TGLTiledArea.SetRowMax(const val : Integer);
begin
if val>=RowMin then begin
if val>RowMax then
FRows.AddNils(val-RowMax)
else FRows.DeleteAndFreeItems(val-RowMin+1, FRows.Count);
end else FRows.Clean;
FRowMax:=val;
end;
// SetRowMin
//
procedure TGLTiledArea.SetRowMin(const val : Integer);
begin
if val<=RowMax then begin
if val<RowMin then
FRows.InsertNils(0, RowMin-val)
else FRows.DeleteAndFreeItems(0, val-RowMin);
end else FRows.Clean;
FRowMin:=val;
end;
// ------------------
// ------------------ TGLTilePlane ------------------
// ------------------
// Create
//
constructor TGLTilePlane.Create(AOwner:Tcomponent);
begin
inherited Create(AOwner);
FTiles:=TGLTiledArea.Create;
FSortByMaterials:=True;
end;
// Destroy
//
destructor TGLTilePlane.Destroy;
begin
MaterialLibrary:=nil;
FTiles.Free;
inherited;
end;
// SetNoZWrite
//
procedure TGLTilePlane.SetNoZWrite(const val : Boolean);
begin
if FNoZWrite<>val then begin
FNoZWrite:=val;
StructureChanged;
end;
end;
// SetTiles
//
procedure TGLTilePlane.SetTiles(const val : TGLTiledArea);
begin
if val<>FTiles then begin
FTiles.Assign(val);
StructureChanged;
end;
end;
// SetMaterialLibrary
//
procedure TGLTilePlane.SetMaterialLibrary(const val : TGLMaterialLibrary);
begin
if FMaterialLibrary<>val then begin
if Assigned(FMaterialLibrary) then begin
DestroyHandle;
FMaterialLibrary.RemoveFreeNotification(Self);
end;
FMaterialLibrary:=val;
if Assigned(FMaterialLibrary) then
FMaterialLibrary.FreeNotification(Self);
StructureChanged;
end;
end;
// SetSortByMaterials
//
procedure TGLTilePlane.SetSortByMaterials(const val : Boolean);
begin
FSortByMaterials:=val;
StructureChanged;
end;
// Notification
//
procedure TGLTilePlane.Notification(AComponent: TComponent; Operation: TOperation);
begin
if Operation=opRemove then begin
if AComponent=FMaterialLibrary then
MaterialLibrary:=nil;
end;
inherited;
end;
// DoRender
//
procedure TGLTilePlane.DoRender(var ARci : TRenderContextInfo;
ARenderSelf, ARenderChildren : Boolean);
var
i : Integer;
begin
if (not ListHandleAllocated) and Assigned(FMaterialLibrary) then begin
for i:=0 to MaterialLibrary.Materials.Count-1 do
MaterialLibrary.Materials[i].PrepareBuildList;
end;
inherited;
end;
// BuildList
//
procedure TGLTilePlane.BuildList(var rci : TRenderContextInfo);
type
TQuadListInfo = packed record
x, y : TIntegerList;
end;
procedure IssueQuad(col, row : Integer);
begin
xgl.TexCoord2f(col, row); GL.Vertex2f(col, row);
xgl.TexCoord2f(col+1, row); GL.Vertex2f(col+1, row);
xgl.TexCoord2f(col+1, row+1); GL.Vertex2f(col+1, row+1);
xgl.TexCoord2f(col, row+1); GL.Vertex2f(col, row+1);
end;
var
i, j, row, col, t : Integer;
r : TGLTiledAreaRow;
libMat : TGLLibMaterial;
quadInfos : array of TQuadListInfo;
begin
if MaterialLibrary=nil then Exit;
// initialize infos
GL.Normal3fv(@ZVector);
if FNoZWrite then
rci.GLStates.DepthWriteMask := False;
if SortByMaterials then begin
SetLength(quadInfos, MaterialLibrary.Materials.Count);
for i:=0 to High(quadInfos) do begin //correction in (i:=0) from (i:=1)
quadInfos[i].x:=TIntegerList.Create;
quadInfos[i].y:=TIntegerList.Create;
end;
// collect quads into quadInfos, sorted by material
for row:=Tiles.RowMin to Tiles.RowMax do begin
r:=Tiles.Row[row];
if Assigned(r) then begin
for col:=r.ColMin to r.ColMax do begin
t:=r.Cell[col] and $FFFF;
if (t>-1) and (t<MaterialLibrary.Materials.Count) then begin //correction in (t>-1) from (t>0)
quadInfos[t].x.Add(col);
quadInfos[t].y.Add(row);
end;
end;
end;
end;
// render and cleanup
for i:=0 to High(quadInfos) do begin //correction in (i:=0) from (i:=1)
if quadInfos[i].x.Count>0 then begin
libMat:=MaterialLibrary.Materials[i];
libMat.Apply(rci);
repeat
GL.Begin_(GL_QUADS);
with quadInfos[i] do for j:=0 to x.Count-1 do
IssueQuad(x[j], y[j]);
GL.End_;
until not libMat.UnApply(rci);
end;
quadInfos[i].x.Free;
quadInfos[i].y.Free;
end;
end else begin
// process all quads in order
for row:=Tiles.RowMin to Tiles.RowMax do begin
r:=Tiles.Row[row];
if Assigned(r) then begin
for col:=r.ColMin to r.ColMax do begin
t:=r.Cell[col] and $FFFF;
if (t>-1) and (t<MaterialLibrary.Materials.Count) then begin //correction in (t>-1) from (t>0)
libMat:=MaterialLibrary.Materials[t];
libMat.Apply(rci);
repeat
GL.Begin_(GL_QUADS);
IssueQuad(col, row);
GL.End_;
until not libMat.UnApply(rci);
end;
end;
end;
end;
end;
if FNoZWrite then
rci.GLStates.DepthWriteMask := True;
end;
//-------------------------------------------------------------
//-------------------------------------------------------------
//-------------------------------------------------------------
initialization
//-------------------------------------------------------------
//-------------------------------------------------------------
//-------------------------------------------------------------
RegisterClasses([TGLTilePlane, TGLTiledAreaRow, TGLTiledArea]);
end.
|
unit Model;
interface
{$M+}
uses FireDAC.Comp.client, bDB, System.Generics.Collections, System.Rtti, SysUtils, data.db, System.TypInfo, System.DateUtils,
strutils, bHelper;
Type
TModel = class
strict private
const
ID_FIELD = 'm_id';
FIELD_PREFIX = 'm_';
SETTER_METHOD_PREFIX = '_set';
FOREIGN_KEY_POSTFIX = '_id';
class function getTableName(className: string): string; static;
private
var
aClassTypeInfo: TRttiType;
class function getContext: TRttiContext;
published
/// <summary>
/// Retorna todos os elementos da table
/// </summary>
class function all: Tarray<TObject>; virtual; final;
/// <summary>
/// Retorna todos os elementos que obedecerem
/// os parametros
/// </summary>
/// <param name="Fields">
/// Nomes dos campos na tabela a serem buscados
/// </param>
/// <param name="Values">
/// Valores dos campos passados no parametro `Fields`
/// </param>
/// <returns>
/// array of TObject ou nil
/// </returns>
class function find(fields: array of string; values: array of variant): Tarray<TObject>; virtual; final;
/// <summary>
/// Retorna o primeiro elemento que obedece
/// os parametros
/// </summary>
/// <param name="Fields">
/// Nomes dos campos na tabela a serem buscados
/// </param>
/// <param name="Values">
/// Valores dos campos passados no parametro `Fields`
/// </param>
/// <returns>
/// TObject ou nil
/// </returns>
class function get(fields: array of string; values: array of variant): TObject; virtual; final;
/// <summary>
/// Verifica se existe algum registro com os parametros
/// informados, removendo um registro da busca
/// </summary>
/// <param name="excludeId">
/// Id do objeto a ser excluído da busca
/// </param>
/// <param name="Fields">
/// Nomes dos campos na tabela a serem buscados
/// </param>
/// <param name="Values">
/// Valores dos campos passados no parametro `Fields`
/// </param>
/// <returns>
/// Boolean
/// </returns>
class function exists(excludeId: integer; fields: array of string; values: array of variant): boolean; virtual; final;
/// <summary>
/// Verifica se existe algum registro com os parametros
/// informados
/// </summary>
/// <param name="Fields">
/// Nomes dos campos na tabela a serem buscados
/// </param>
/// <param name="Values">
/// Valores dos campos passados no parametro `Fields`
/// </param>
/// <returns>
/// Boolean
/// </returns>
class function hasAny(fields: array of string; values: array of variant): boolean; virtual; final;
constructor Create(pk: integer = 0); overload; virtual;
procedure save; virtual; final;
procedure delete; virtual; final;
end;
implementation
{ TModel }
constructor TModel.Create(pk: integer);
var
qry: tfdquery;
qryField: TField;
classField: TRttiField;
classSetterMethod: trttimethod;
methodName: string;
begin
inherited Create;
Self.aClassTypeInfo := TModel.getContext.GetType(Self.ClassType);
if pk <> 0 then
begin
qry := TDB.execute('select * from ' + TModel.getTableName(Self.className) + ' where id = ? ', [pk]);
if qry <> nil then
begin
for qryField in qry.fields do
begin
classField := Self.aClassTypeInfo.GetField(FIELD_PREFIX + qryField.fieldName);
if classField <> nil then
begin
methodName := SETTER_METHOD_PREFIX + Uppercase(qryField.fieldName[1]) + copy(qryField.fieldName, 2, length(qryField.fieldName));
classSetterMethod := Self.aClassTypeInfo.GetMethod(methodName);
if classSetterMethod <> nil then
classSetterMethod.Invoke(Self, [TValue.FromVariant(qryField.AsVariant)])
else
begin
if qryField.DataType in [ftDate, ftDateTime] then
classField.SetValue(Self, tdatetime(qryField.Value))
else
classField.SetValue(Self, TValue.FromVariant(qryField.Value));
end;
end;
end;
end
else
raise Exception.Create(Format('Not found record with id = "%d" for Model "%s"', [pk, Self.className]));
end;
end;
procedure TModel.delete;
begin
Self.aClassTypeInfo := TModel.getContext.GetType(Self.ClassType);
TDB.execute('delete from ' + TModel.getTableName(Self.className) + ' where id = ? ',
[Self.aClassTypeInfo.GetField(ID_FIELD).GetValue(Self).asInteger]);
end;
class function TModel.exists(excludeId: integer; fields: array of string; values: array of variant): boolean;
var
qry: tfdquery;
begin
result := false;
qry := TDB.execute('select * from ' + TModel.getTableName(Self.className) + ' ' + TDB.GenWhere(fields) + ' order by id limit 1', values);
if qry <> nil then
result := qry.Fieldbyname('id').asInteger <> excludeId;
end;
class function TModel.all: Tarray<TObject>;
begin
(*
Prettiest way to do this
´select * from tableName where 1 = 1´
*)
result := Self.find(['1'], ['1']);
end;
class function TModel.find(fields: array of string; values: array of variant): Tarray<TObject>;
var
qry: tfdquery;
arrObjects: Tarray<TObject>;
begin
result := nil;
qry := TDB.execute('select * from ' + TModel.getTableName(Self.className) + ' ' + TDB.GenWhere(fields), values);
if qry <> nil then
begin
qry.first;
SetLength(arrObjects, qry.RecordCount);
while not qry.eof do
begin
arrObjects[qry.RecNo - 1] := Self.Create(qry.fields[0].asInteger);
qry.next;
end;
result := arrObjects;
end;
end;
class function TModel.get(fields: array of string; values: array of variant): TObject;
var
arrObjects: Tarray<TObject>;
begin
result := nil;
arrObjects := Self.find(fields, values);
if length(arrObjects) > 0 then
result := arrObjects[0];
end;
class function TModel.getContext: TRttiContext;
begin
result := TRttiContext.Create;
end;
class function TModel.getTableName(className: string): string;
procedure raiseError;
begin
raise Exception.Create('Class Name(\' + className + '\) convention doesnt follow the pattern to model inherit \T[ClassName]\');
end;
var
I: integer;
begin
result := '';
if className[1] <> 'T' then
raiseError;
if className[2] <> Uppercase(className[2]) then
raiseError;
result := LowerCase(className[2]);
for I := 3 to length(className) do
begin
if className[I] = LowerCase(className[I]) then
result := result + className[I]
else
result := result + '_' + LowerCase(className[I]);
end;
end;
class function TModel.hasAny(fields: array of string; values: array of variant): boolean;
begin
result := Self.get(fields, values) <> nil;
end;
procedure TModel.save;
function hasValidPrefix(const Field: TRttiField): boolean;
begin
result := copy(Field.Name, 1, 2) = FIELD_PREFIX;
end;
function isForeignKey(const Field: TRttiField): boolean;
begin
result := copy(Field.Name, length(Field.Name) - 2, length(Field.Name)) = FOREIGN_KEY_POSTFIX;
end;
function isDate(const aValue: TValue): boolean;
begin
result := (aValue.TypeInfo = System.TypeInfo(tDate)) or (aValue.TypeInfo = System.TypeInfo(tdatetime));
end;
function getFieldName(const Field: TRttiField): string;
begin
result := copy(Field.Name, 3, length(Field.Name));
end;
function getFieldSetter(const Field: TRttiField): string;
begin
result := 'set' + getFieldName(Field);
end;
var
sql, updateFields: string;
Field: TRttiField;
setterMethod: trttimethod;
classFields: Tarray<TRttiField>;
classMethods: Tarray<trttimethod>;
fieldValues: TList<variant>;
fieldNames: TList<string>;
idValue: integer;
aValue: TValue;
begin
fieldValues := TList<variant>.Create;
fieldNames := TList<string>.Create;
fieldValues.Clear;
fieldNames.Clear;
Self.aClassTypeInfo := TModel.getContext.GetType(Self.ClassType);
classFields := Self.aClassTypeInfo.GetFields();
classMethods := Self.aClassTypeInfo.GetMethods();
idValue := Self.aClassTypeInfo.GetField(ID_FIELD).GetValue(Self).asInteger;
// SAVE
if idValue = 0 then
begin
for Field in classFields do
begin
if Field.Name <> ID_FIELD then
if hasValidPrefix(Field) then
begin
if isForeignKey(Field) then
begin
if Field.GetValue(Self).AsVariant <> 0 then
begin
fieldValues.Add(Field.GetValue(Self).asInteger);
fieldNames.Add(getFieldName(Field));
end;
end
else
begin
aValue := Field.GetValue(Self);
for setterMethod in classMethods do
if LowerCase(setterMethod.Name) = LowerCase(getFieldSetter(Field)) then
begin
setterMethod.Invoke(Self, [aValue]);
Break;
end;
if isDate(aValue) then
fieldValues.Add(aValue.AsType<tdatetime>)
else
fieldValues.Add(aValue.AsVariant);
fieldNames.Add(getFieldName(Field));
end;
end;
end;
sql := 'insert into ' + TModel.getTableName(Self.className) + '(id,' + Thelper.arrToStr(fieldNames.ToArray) + ') values(default ' +
Thelper.genData(',?', length(fieldValues.ToArray)) + ')';
TDB.execute(sql, fieldValues.ToArray);
Self.aClassTypeInfo.GetField(ID_FIELD)
.SetValue(Self, TDB.execute('select id from ' + TModel.getTableName(Self.className) + ' order by id desc limit 1')
.fields[0].asInteger);
end
// UPDATE
else
begin
updateFields := '';
for Field in classFields do
if Field.Name <> ID_FIELD then
if hasValidPrefix(Field) then
if isForeignKey(Field) then
begin
if Field.GetValue(Self).AsVariant <> 0 then
begin
updateFields := updateFields + (getFieldName(Field) + ' = ?,');
fieldValues.Add(Field.GetValue(Self).asInteger);
end
else
updateFields := updateFields + (getFieldName(Field) + ' = null,');
end
else
begin
updateFields := updateFields + (getFieldName(Field) + ' = ?,');
aValue := Field.GetValue(Self);
for setterMethod in classMethods do
if setterMethod.Name = getFieldSetter(Field) then
begin
setterMethod.Invoke(Self, [aValue]);
Break;
end;
if isDate(aValue) then
fieldValues.Add(aValue.AsType<tdatetime>)
else
fieldValues.Add(aValue.AsVariant);
end;
fieldValues.Add(idValue);
updateFields := copy(updateFields, 0, length(updateFields) - 1);
sql := 'update ' + TModel.getTableName(Self.className) + ' set ' + updateFields + ' where id = ?';
TDB.execute(sql, fieldValues.ToArray);
end;
end;
end.
|
unit Form.Main;
interface
uses
System.SysUtils,
System.Variants,
System.Classes,
System.Actions,
Winapi.Windows, Winapi.Messages,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
Vcl.ActnList, Vcl.ExtCtrls, Vcl.PlatformDefaultStyleActnCtrls,
Vcl.ActnMan, Vcl.ComCtrls, Vcl.Menus,
Pattern.Command,
Pattern.CommandAction,
Command.Button1,
Command.Button2;
type
TForm1 = class(TForm)
Memo1: TMemo;
GroupBoxSimpleDemo: TGroupBox;
btnAdhocExecute: TButton;
Button1: TButton;
Button2: TButton;
Edit1: TEdit;
procedure FormCreate(Sender: TObject);
procedure btnAdhocExecuteClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
public
private
actCommandButon1: TCommandAction;
actCommandButon2: TCommandAction;
procedure BuildCommandsOnStart;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.BuildCommandsOnStart;
begin
// ---------------------------------------------------------
// ---------------------------------------------------------
actCommandButon1 := TCommandAction.Create(Self)
.WithCommand(TButon1Command.Create(Self))
.WithShortCut(TextToShortCut('Ctrl+1'))
.WithCaption('Run command: Button1') //--+
.WithInjections([Memo1]);
// ---------------------------------------------------------
// ---------------------------------------------------------
actCommandButon2 := TCommandAction.Create(Self)
.WithCommand(TButon2Command.Create(Self))
.WithShortCut(TextToShortCut('Ctrl+2'))
.WithCaption('Run command: Button2') //--+
.WithInjections([Memo1, Edit1]);
// ---------------------------------------------------------
// ---------------------------------------------------------
Button1.Action := actCommandButon1;
Button2.Action := actCommandButon2;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
BuildCommandsOnStart;
Memo1.Clear;
ReportMemoryLeaksOnShutdown := True;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
// this event is not called. Action actCommandButon1 is triggered
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
// this event is not called. Action actCommandButon2 is triggered
end;
procedure TForm1.btnAdhocExecuteClick(Sender: TObject);
begin
TCommand.AdhocExecute<TButon1Command>([Memo1]);
end;
end.
|
unit monitorHandler;
interface
uses
Messages, Classes, Windows;
type
TMonitorSettings = class(TObject)
private
FMsgHandlerHWND: HWND;
procedure WndMethod(var AMsg: TMessage);
public
constructor Create;
destructor Destroy; override;
end;
function GetMonitorBrightness (
hMonitor: THandle; var pdwMinimumBrightness : DWORD;
var pdwCurrentBrightness : DWORD; var pdwMaximumBrightness : DWORD): BOOL; stdcall;
external 'Dxva2.dll' name 'GetMonitorBrightness';
function SetMonitorBrightness (
hMonitor: THandle; dwNewBrightness: DWORD): BOOL; stdcall;
external 'Dxva2.dll' name 'SetMonitorBrightness';
function GetMonitorContrast (
hMonitor: THandle; var pdwMinimumBrightness : DWORD;
var pdwCurrentBrightness : DWORD; var pdwMaximumBrightness : DWORD): BOOL; stdcall;
external 'Dxva2.dll' name 'GetMonitorContrast';
function SetMonitorContrast (
hMonitor: THandle; dwNewBrightness: DWORD): BOOL; stdcall;
external 'Dxva2.dll' name 'SetMonitorContrast';
function GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor: THandle;
pdwNumberOfPhysicalMonitors: PDWORD): Boolean; stdcall;
external 'Dxva2.dll' name 'GetNumberOfPhysicalMonitorsFromHMONITOR';
function GetPhysicalMonitorsFromHMONITOR(hMonitor: THandle;
dwPhysicalMonitorArraySizwe: DWORD; pPhysicalMonitorArray: Pointer): Boolean; stdcall;
external 'Dxva2.dll' name 'GetPhysicalMonitorsFromHMONITOR';
function DestroyPhysicalMonitors(dwPhysicalMonitorArraySize: DWORD;
pPhysicalMonitorArray: Pointer): Boolean; stdcall;
external 'Dxva2.dll' name 'DestroyPhysicalMonitors';
implementation
{ TMonitorSettings }
constructor TMonitorSettings.Create;
begin
inherited Create;
FMsgHandlerHWND := AllocateHWnd(WndMethod);
end;
destructor TMonitorSettings.Destroy;
begin
DeallocateHWnd(FMsgHandlerHWND);
inherited;
end;
procedure TMonitorSettings.WndMethod(var AMsg: TMessage);
begin
// if AMsg.msg = WM_
//else
AMsg.Result := DefWindowProc(FMsgHandlerHWND, AMsg.Msg, AMsg.WParam, AMsg.LParam);
end;
end.
|
unit oCoverSheetParam_WidgetClock;
{
================================================================================
*
* Application: CPRS - CoverSheet
* Developer: doma.user@domain.ext
* Site: Salt Lake City ISC
* Date: 2015-12-04
*
* Description: Proof of concept for multiple types of panels.
*
* Notes:
*
================================================================================
}
interface
uses
System.Classes,
System.SysUtils,
Vcl.Controls,
oCoverSheetParam,
iCoverSheetIntf;
type
TCoverSheetParam_WidgetClock = class(TCoverSheetParam, ICoverSheetParam)
protected
function NewCoverSheetControl(aOwner: TComponent): TControl; override;
public
constructor Create(aInitStr: string = '');
end;
implementation
uses
oDelimitedString,
mCoverSheetDisplayPanel_WidgetClock;
{ TCoverSheetParam_WidgetClock }
constructor TCoverSheetParam_WidgetClock.Create(aInitStr: string = '');
begin
inherited Create;
with NewDelimitedString(aInitStr) do
try
setTitle(GetPieceAsString(2, 'Clock'));
finally
Free;
end;
end;
function TCoverSheetParam_WidgetClock.NewCoverSheetControl(aOwner: TComponent): TControl;
begin
Result := TfraCoverSheetDisplayPanel_WidgetClock.Create(aOwner);
end;
end.
|
unit BaseFDQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, NotifyEvents,
System.Contnrs;
type
TQryBase = class(TFrame)
FDQuery: TFDQuery;
private
FDataSource: TDataSource;
FSQL: string;
function GetAutoTransactionEventList: TObjectList;
function GetDataSource: TDataSource;
{ Private declarations }
protected
FAutoTransactionEventList: TObjectList;
procedure ApplyDelete(ASender: TDataSet; ARequest: TFDUpdateRequest; var
AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); virtual;
procedure ApplyInsert(ASender: TDataSet; ARequest: TFDUpdateRequest; var
AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); virtual;
procedure ApplyUpdate(ASender: TDataSet; ARequest: TFDUpdateRequest; var
AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); virtual;
// TODO: DoOnNeedPost
// procedure DoOnNeedPost(var Message: TMessage); message WM_NEED_POST;
procedure DoOnQueryUpdateRecord(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions);
procedure FDQueryUpdateRecordOnClient(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
property AutoTransactionEventList: TObjectList read GetAutoTransactionEventList;
property SQL: string read FSQL write FSQL;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AfterConstruction; override;
procedure CascadeDelete(const AIDMaster: Variant;
const ADetailKeyFieldName: String;
const AFromClientOnly: Boolean = False);
procedure DeleteFromClient;
procedure SetParamType(AParameterName: string;
ADataType: TFieldType = ftInteger; AParamType: TParamType = ptInput);
property DataSource: TDataSource read GetDataSource;
{ Public declarations }
end;
implementation
{$R *.dfm}
uses RepositoryDataModule;
constructor TQryBase.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TQryBase.Destroy;
begin
inherited;
if FAutoTransactionEventList <> nil then
FreeAndNil(FAutoTransactionEventList);
end;
procedure TQryBase.AfterConstruction;
begin
inherited;
// Сохраняем первоначальный SQL
FSQL := FDQuery.SQL.Text
end;
procedure TQryBase.ApplyDelete(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions);
begin
end;
procedure TQryBase.ApplyInsert(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions);
begin
end;
procedure TQryBase.ApplyUpdate(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions);
begin
end;
procedure TQryBase.CascadeDelete(const AIDMaster: Variant;
const ADetailKeyFieldName: String; const AFromClientOnly: Boolean = False);
var
E: TFDUpdateRecordEvent;
begin
Assert(AIDMaster > 0);
E := FDQuery.OnUpdateRecord;
try
// Если каскадное удаление уже реализовано на стороне сервера
// Просто удалим эти записи с клиента ничего не сохраняя на стороне сервера
if AFromClientOnly then
FDQuery.OnUpdateRecord := FDQueryUpdateRecordOnClient;
// Пока есть записи подчинённые мастеру
while FDQuery.LocateEx(ADetailKeyFieldName, AIDMaster, []) do
begin
FDQuery.Delete;
end;
finally
if AFromClientOnly then
FDQuery.OnUpdateRecord := E;
end;
end;
procedure TQryBase.DeleteFromClient;
var
E: TFDUpdateRecordEvent;
begin
Assert(FDQuery.RecordCount > 0);
E := FDQuery.OnUpdateRecord;
try
FDQuery.OnUpdateRecord := FDQueryUpdateRecordOnClient;
FDQuery.Delete;
finally
FDQuery.OnUpdateRecord := E;
end;
end;
procedure TQryBase.DoOnQueryUpdateRecord(ASender: TDataSet; ARequest:
TFDUpdateRequest; var AAction: TFDErrorAction; AOptions:
TFDUpdateRowOptions);
begin
if ARequest in [arDelete, arInsert, arUpdate] then
begin
// try
AAction := eaApplied;
// Если произошло удаление
if ARequest = arDelete then
begin
ApplyDelete(ASender, ARequest, AAction, AOptions);
end;
// Операция добавления записи на клиенте
if ARequest = arInsert then
begin
ApplyInsert(ASender, ARequest, AAction, AOptions);
end;
// Операция обновления записи на клиенте
if ARequest = arUpdate then
begin
ApplyUpdate(ASender, ARequest, AAction, AOptions);
end;
{
except
on E: Exception do
begin
AAction := eaFail;
DoOnUpdateRecordException(E);
end;
end;
}
end
else
AAction := eaSkip;
end;
procedure TQryBase.FDQueryUpdateRecordOnClient(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
begin
inherited;
AAction := eaApplied;
end;
function TQryBase.GetAutoTransactionEventList: TObjectList;
begin
if FAutoTransactionEventList = nil then
FAutoTransactionEventList := TObjectList.Create;
Result := FAutoTransactionEventList;
end;
function TQryBase.GetDataSource: TDataSource;
begin
if FDataSource = nil then
begin
FDataSource := TDataSource.Create(Self);
FDataSource.DataSet := FDQuery;
end;
Result := FDataSource;
end;
procedure TQryBase.SetParamType(AParameterName: string;
ADataType: TFieldType = ftInteger; AParamType: TParamType = ptInput);
var
P: TFDParam;
begin
Assert(not AParameterName.IsEmpty);
P := FDQuery.ParamByName(AParameterName);
P.DataType := ADataType;
P.ParamType := AParamType;
end;
end.
|
{**************************************}
{ TeeChart Pro Charting Library }
{ Custom Series Example: TImageBar }
{ Copyright (c) 1998-2004 by David Berneda.}
{**************************************}
unit ImageBar;
{$I TeeDefs.inc}
interface
Uses {$IFNDEF LINUX}
Windows,
{$ENDIF}
Classes,
{$IFDEF CLX}
QGraphics, Types,
{$ELSE}
Graphics,
{$ENDIF}
Series, Chart, TeCanvas;
// This unit implements a custom TeeChart Series.
// The TImageBarSeries is a normal BarSeries with an optional Image to
// be displayed on each Bar point, stretched or tiled.
// Only rectangular Bar style is allowed.
type
TImageBarSeries=class(TBarSeries)
private
FImage:TPicture;
FImageTiled:Boolean;
Procedure SetImage(Value:TPicture);
Procedure SetImageTiled(Value:Boolean);
Procedure DrawTiledImage(AImage:TPicture; Const R:TRect; StartFromTop:Boolean);
protected
class Function GetEditorClass:String; override;
Procedure PrepareForGallery(IsEnabled:Boolean); override;
public
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
Procedure DrawBar(BarIndex,StartPos,EndPos:Integer); override;
published
property Image:TPicture read FImage write SetImage;
property ImageTiled:Boolean read FImageTiled write SetImageTiled default False;
end;
// Used also at ImaPoint.pas unit
Procedure LoadBitmapFromResourceName(ABitmap:TBitmap; const ResName: string);
implementation
Uses
SysUtils, TeeProcs, TeeProCo;
// This resource file contains the default bitmap image
{$IFDEF CLR}
{$R 'TeeMoney.bmp'}
{$R 'TImageBarSeries.bmp'}
{$ELSE}
{$R TeeImaBa.res}
{$ENDIF}
{ This function loads a bitmap from a resource linked to the executable }
Procedure LoadBitmapFromResourceName(ABitmap:TBitmap; const ResName: string);
begin
{$IFDEF CLR}
TeeLoadBitmap(ABitmap,ResName,'');
{$ELSE}
ABitmap.LoadFromResourceName(HInstance,ResName);
{$ENDIF}
end;
{ overrided constructor to create the Image property }
Constructor TImageBarSeries.Create(AOwner:TComponent);
begin
inherited;
FImage:=TPicture.Create;
FImage.OnChange:=CanvasChanged;
LoadBitmapFromResourceName(FImage.Bitmap,'TeeMoney'); { <-- load default }
end;
Destructor TImageBarSeries.Destroy;
begin
FImage.Free;
inherited;
end;
Procedure TImageBarSeries.SetImage(Value:TPicture);
begin
FImage.Assign(Value);
end;
Procedure TImageBarSeries.SetImageTiled(Value:Boolean);
begin
SetBooleanProperty(FImageTiled,Value);
end;
{ Add two bars only to the gallery }
Procedure TImageBarSeries.PrepareForGallery(IsEnabled:Boolean);
begin
inherited;
FillSampleValues(2);
ParentChart.View3DOptions.Orthogonal:=True;
end;
{ This method draws an image in tiled mode }
Procedure TImageBarSeries.DrawTiledImage( AImage:TPicture;
Const R:TRect;
StartFromTop:Boolean );
Var tmpX : Integer;
tmpY : Integer;
tmpWidth : Integer;
tmpHeight : Integer;
RectH : Integer;
RectW : Integer;
tmpRect : TRect;
begin
tmpWidth :=AImage.Width;
tmpHeight:=AImage.Height;
if (tmpWidth>0) and (tmpHeight>0) then
Begin
ParentChart.Canvas.ClipRectangle(R);
RectSize(R,RectW,RectH);
tmpY:=0;
while tmpY<RectH do
begin
tmpX:=0;
while tmpX<RectW do
begin
if StartFromTop then
tmpRect:=TeeRect(R.Left,R.Top+tmpY,R.Right,R.Top+tmpY+tmpHeight)
else
tmpRect:=TeeRect(R.Left,R.Bottom-tmpY-tmpHeight,R.Right,R.Bottom-tmpY);
ParentChart.Canvas.StretchDraw(tmpRect,AImage.Graphic);
Inc(tmpX,tmpWidth);
end;
Inc(tmpY,tmpHeight);
end;
ParentChart.Canvas.UnClipRectangle;
end;
end;
Procedure TImageBarSeries.DrawBar(BarIndex,StartPos,EndPos:Integer);
Var R : TRect;
tmp : Integer;
tmp3D : Boolean;
begin
{ first thing to do is to call the inherited DrawBar method of TBarSeries }
inherited;
if Assigned(FImage.Graphic) and (FImage.Graphic.Width>0) then { <-- if non empty image... }
Begin
{ Calculate the exact rectangle, removing borders }
R:=BarBounds;
if R.Bottom<R.Top then SwapInteger(R.Top,R.Bottom);
if BarPen.Visible then
begin
tmp:=BarPen.Width;
if (tmp>1) and ((tmp mod 2)=0) then Dec(tmp);
Inc(R.Left,tmp);
Inc(R.Top,tmp);
if not ParentChart.View3D then
begin
Dec(R.Right);
Dec(R.Bottom);
end;
end;
tmp3D:=ParentChart.View3D and (not ParentChart.View3DOptions.Orthogonal);
if not tmp3D then
R:=ParentChart.Canvas.CalcRect3D(R,StartZ)
else
if not TeeCull(ParentChart.Canvas.FourPointsFromRect(R,StartZ)) then
exit;
{ Draw the image }
if FImageTiled then { tiled }
DrawTiledImage(FImage,R,BarBounds.Bottom<BarBounds.Top)
else { stretched }
if tmp3D then
ParentChart.Canvas.StretchDraw(R,FImage.Graphic,StartZ)
else
ParentChart.Canvas.StretchDraw(R,FImage.Graphic);
end;
end;
class Function TImageBarSeries.GetEditorClass:String;
begin
result:='TImageBarSeriesEditor';
end;
initialization
RegisterTeeSeries( TImageBarSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_ImageBarSeries,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GallerySamples, 1 );
finalization
UnRegisterTeeSeries([ TImageBarSeries ]);
end.
|
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is HashMap.pas. }
{ }
{ The Initial Developer of the Original Code is Jean-Philippe BEMPEL aka RDM. Portions created by }
{ Jean-Philippe BEMPEL are Copyright (C) Jean-Philippe BEMPEL (rdm_30 att yahoo dott com) }
{ All rights reserved. }
{ }
{ Contributors: }
{ Florent Ouchet (outchy) }
{ }
{**************************************************************************************************}
{ }
{ The Delphi Container Library }
{ }
{**************************************************************************************************}
{ }
{ Last modified: $Date:: 2008-06-05 15:35:37 +0200 (jeu., 05 juin 2008) $ }
{ Revision: $Rev:: 2376 $ }
{ Author: $Author:: obones $ }
{ }
{**************************************************************************************************}
unit JclHashMaps;
{$I jcl.inc}
interface
uses
Classes,
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
{$IFDEF SUPPORTS_GENERICS}
{$IFDEF CLR}
System.Collections.Generic,
{$ENDIF CLR}
JclAlgorithms,
{$ENDIF SUPPORTS_GENERICS}
JclBase, JclAbstractContainers, JclContainerIntf, JclSynch;
{$I containers\JclContainerCommon.imp}
{$I containers\JclHashMaps.imp}
{$I containers\JclHashMaps.int}
type
// Hash Function
// Result must be in 0..Range-1
TJclHashFunction = function(Key, Range: Integer): Integer;
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclIntfIntfHashEntry,TJclIntfIntfHashEntryArray,TJclIntfIntfBucket,TJclIntfIntfBucketArray,TJclIntfIntfHashMap,TJclIntfAbstractContainer,IJclIntfIntfMap,IJclIntfSet,IJclIntfCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: IInterface): IInterface;
function KeysEqual(const A\, B: IInterface): Boolean;
function ValuesEqual(const A\, B: IInterface): Boolean;,,,,const ,IInterface,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclAnsiStrIntfHashEntry,TJclAnsiStrIntfHashEntryArray,TJclAnsiStrIntfBucket,TJclAnsiStrIntfBucketArray,TJclAnsiStrIntfHashMap,TJclAnsiStrAbstractContainer,IJclAnsiStrIntfMap,IJclAnsiStrSet,IJclIntfCollection, IJclStrContainer\, IJclAnsiStrContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: AnsiString): AnsiString;
function FreeValue(var Value: IInterface): IInterface;
function KeysEqual(const A\, B: AnsiString): Boolean;
function ValuesEqual(const A\, B: IInterface): Boolean;,,,,const ,AnsiString,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclIntfAnsiStrHashEntry,TJclIntfAnsiStrHashEntryArray,TJclIntfAnsiStrBucket,TJclIntfAnsiStrBucketArray,TJclIntfAnsiStrHashMap,TJclAnsiStrAbstractContainer,IJclIntfAnsiStrMap,IJclIntfSet,IJclAnsiStrCollection, IJclStrContainer\, IJclAnsiStrContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: AnsiString): AnsiString;
function Hash(const AInterface: IInterface): Integer; reintroduce;
function KeysEqual(const A\, B: IInterface): Boolean;
function ValuesEqual(const A\, B: AnsiString): Boolean;,,,,const ,IInterface,const ,AnsiString)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclAnsiStrAnsiStrHashEntry,TJclAnsiStrAnsiStrHashEntryArray,TJclAnsiStrAnsiStrBucket,TJclAnsiStrAnsiStrBucketArray,TJclAnsiStrAnsiStrHashMap,TJclAnsiStrAbstractContainer,IJclAnsiStrAnsiStrMap,IJclAnsiStrSet,IJclAnsiStrCollection, IJclStrContainer\, IJclAnsiStrContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: AnsiString): AnsiString;
function FreeValue(var Value: AnsiString): AnsiString;
function KeysEqual(const A\, B: AnsiString): Boolean;
function ValuesEqual(const A\, B: AnsiString): Boolean;,,,,const ,AnsiString,const ,AnsiString)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclWideStrIntfHashEntry,TJclWideStrIntfHashEntryArray,TJclWideStrIntfBucket,TJclWideStrIntfBucketArray,TJclWideStrIntfHashMap,TJclWideStrAbstractContainer,IJclWideStrIntfMap,IJclWideStrSet,IJclIntfCollection, IJclStrContainer\, IJclWideStrContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: WideString): WideString;
function FreeValue(var Value: IInterface): IInterface;
function KeysEqual(const A\, B: WideString): Boolean;
function ValuesEqual(const A\, B: IInterface): Boolean;,,,,const ,WideString,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclIntfWideStrHashEntry,TJclIntfWideStrHashEntryArray,TJclIntfWideStrBucket,TJclIntfWideStrBucketArray,TJclIntfWideStrHashMap,TJclWideStrAbstractContainer,IJclIntfWideStrMap,IJclIntfSet,IJclWideStrCollection, IJclStrContainer\, IJclWideStrContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: WideString): WideString;
function Hash(const AInterface: IInterface): Integer; reintroduce;
function KeysEqual(const A\, B: IInterface): Boolean;
function ValuesEqual(const A\, B: WideString): Boolean;,,,,const ,IInterface,const ,WideString)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclWideStrWideStrHashEntry,TJclWideStrWideStrHashEntryArray,TJclWideStrWideStrBucket,TJclWideStrWideStrBucketArray,TJclWideStrWideStrHashMap,TJclWideStrAbstractContainer,IJclWideStrWideStrMap,IJclWideStrSet,IJclWideStrCollection, IJclStrContainer\, IJclWideStrContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: WideString): WideString;
function FreeValue(var Value: WideString): WideString;
function KeysEqual(const A\, B: WideString): Boolean;
function ValuesEqual(const A\, B: WideString): Boolean;,,,,const ,WideString,const ,WideString)*)
{$IFDEF CONTAINER_ANSISTR}
TJclStrIntfHashMap = TJclAnsiStrIntfHashMap;
TJclIntfStrHashMap = TJclIntfAnsiStrHashMap;
TJclStrStrHashMap = TJclAnsiStrAnsiStrHashMap;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
TJclStrIntfHashMap = TJclWideStrIntfHashMap;
TJclIntfStrHashMap = TJclIntfWideStrHashMap;
TJclStrStrHashMap = TJclWideStrWideStrHashMap;
{$ENDIF CONTAINER_WIDESTR}
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclSingleIntfHashEntry,TJclSingleIntfHashEntryArray,TJclSingleIntfBucket,TJclSingleIntfBucketArray,TJclSingleIntfHashMap,TJclSingleAbstractContainer,IJclSingleIntfMap,IJclSingleSet,IJclIntfCollection, IJclSingleContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Single): Single;
function FreeValue(var Value: IInterface): IInterface;
function KeysEqual(const A\, B: Single): Boolean;
function ValuesEqual(const A\, B: IInterface): Boolean;,,,,const ,Single,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclIntfSingleHashEntry,TJclIntfSingleHashEntryArray,TJclIntfSingleBucket,TJclIntfSingleBucketArray,TJclIntfSingleHashMap,TJclSingleAbstractContainer,IJclIntfSingleMap,IJclIntfSet,IJclSingleCollection, IJclSingleContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: Single): Single;
function Hash(const AInterface: IInterface): Integer; reintroduce;
function KeysEqual(const A\, B: IInterface): Boolean;
function ValuesEqual(const A\, B: Single): Boolean;,,,,const ,IInterface,const ,Single)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclSingleSingleHashEntry,TJclSingleSingleHashEntryArray,TJclSingleSingleBucket,TJclSingleSingleBucketArray,TJclSingleSingleHashMap,TJclSingleAbstractContainer,IJclSingleSingleMap,IJclSingleSet,IJclSingleCollection, IJclSingleContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Single): Single;
function FreeValue(var Value: Single): Single;
function KeysEqual(const A\, B: Single): Boolean;
function ValuesEqual(const A\, B: Single): Boolean;,,,,const ,Single,const ,Single)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclDoubleIntfHashEntry,TJclDoubleIntfHashEntryArray,TJclDoubleIntfBucket,TJclDoubleIntfBucketArray,TJclDoubleIntfHashMap,TJclDoubleAbstractContainer,IJclDoubleIntfMap,IJclDoubleSet,IJclIntfCollection, IJclDoubleContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Double): Double;
function FreeValue(var Value: IInterface): IInterface;
function KeysEqual(const A\, B: Double): Boolean;
function ValuesEqual(const A\, B: IInterface): Boolean;,,,,const ,Double,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclIntfDoubleHashEntry,TJclIntfDoubleHashEntryArray,TJclIntfDoubleBucket,TJclIntfDoubleBucketArray,TJclIntfDoubleHashMap,TJclDoubleAbstractContainer,IJclIntfDoubleMap,IJclIntfSet,IJclDoubleCollection, IJclDoubleContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: Double): Double;
function Hash(const AInterface: IInterface): Integer; reintroduce;
function KeysEqual(const A\, B: IInterface): Boolean;
function ValuesEqual(const A\, B: Double): Boolean;,,,,const ,IInterface,const ,Double)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclDoubleDoubleHashEntry,TJclDoubleDoubleHashEntryArray,TJclDoubleDoubleBucket,TJclDoubleDoubleBucketArray,TJclDoubleDoubleHashMap,TJclDoubleAbstractContainer,IJclDoubleDoubleMap,IJclDoubleSet,IJclDoubleCollection, IJclDoubleContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Double): Double;
function FreeValue(var Value: Double): Double;
function KeysEqual(const A\, B: Double): Boolean;
function ValuesEqual(const A\, B: Double): Boolean;,,,,const ,Double,const ,Double)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclExtendedIntfHashEntry,TJclExtendedIntfHashEntryArray,TJclExtendedIntfBucket,TJclExtendedIntfBucketArray,TJclExtendedIntfHashMap,TJclExtendedAbstractContainer,IJclExtendedIntfMap,IJclExtendedSet,IJclIntfCollection, IJclExtendedContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Extended): Extended;
function FreeValue(var Value: IInterface): IInterface;
function KeysEqual(const A\, B: Extended): Boolean;
function ValuesEqual(const A\, B: IInterface): Boolean;,,,,const ,Extended,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclIntfExtendedHashEntry,TJclIntfExtendedHashEntryArray,TJclIntfExtendedBucket,TJclIntfExtendedBucketArray,TJclIntfExtendedHashMap,TJclExtendedAbstractContainer,IJclIntfExtendedMap,IJclIntfSet,IJclExtendedCollection, IJclExtendedContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: Extended): Extended;
function Hash(const AInterface: IInterface): Integer; reintroduce;
function KeysEqual(const A\, B: IInterface): Boolean;
function ValuesEqual(const A\, B: Extended): Boolean;,,,,const ,IInterface,const ,Extended)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclExtendedExtendedHashEntry,TJclExtendedExtendedHashEntryArray,TJclExtendedExtendedBucket,TJclExtendedExtendedBucketArray,TJclExtendedExtendedHashMap,TJclExtendedAbstractContainer,IJclExtendedExtendedMap,IJclExtendedSet,IJclExtendedCollection, IJclExtendedContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Extended): Extended;
function FreeValue(var Value: Extended): Extended;
function KeysEqual(const A\, B: Extended): Boolean;
function ValuesEqual(const A\, B: Extended): Boolean;,,,,const ,Extended,const ,Extended)*)
{$IFDEF MATH_EXTENDED_PRECISION}
TJclFloatIntfHashMap = TJclExtendedIntfHashMap;
TJclIntfFloatHashMap = TJclIntfExtendedHashMap;
TJclFloatFloatHashMap = TJclExtendedExtendedHashMap;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
TJclFloatIntfHashMap = TJclDoubleIntfHashMap;
TJclIntfFloatHashMap = TJclIntfDoubleHashMap;
TJclFloatFloatHashMap = TJclDoubleDoubleHashMap;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
TJclFloatIntfHashMap = TJclSingleIntfHashMap;
TJclIntfFloatHashMap = TJclIntfSingleHashMap;
TJclFloatFloatHashMap = TJclSingleSingleHashMap;
{$ENDIF MATH_SINGLE_PRECISION}
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclIntegerIntfHashEntry,TJclIntegerIntfHashEntryArray,TJclIntegerIntfBucket,TJclIntegerIntfBucketArray,TJclIntegerIntfHashMap,TJclIntegerAbstractContainer,IJclIntegerIntfMap,IJclIntegerSet,IJclIntfCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Integer): Integer;
function FreeValue(var Value: IInterface): IInterface;
function KeysEqual(A\, B: Integer): Boolean;
function ValuesEqual(const A\, B: IInterface): Boolean;,,,,,Integer,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclIntfIntegerHashEntry,TJclIntfIntegerHashEntryArray,TJclIntfIntegerBucket,TJclIntfIntegerBucketArray,TJclIntfIntegerHashMap,TJclIntegerAbstractContainer,IJclIntfIntegerMap,IJclIntfSet,IJclIntegerCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: Integer): Integer;
function Hash(const AInterface: IInterface): Integer; reintroduce;
function KeysEqual(const A\, B: IInterface): Boolean;
function ValuesEqual(A\, B: Integer): Boolean;,,,,const ,IInterface,,Integer)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclIntegerIntegerHashEntry,TJclIntegerIntegerHashEntryArray,TJclIntegerIntegerBucket,TJclIntegerIntegerBucketArray,TJclIntegerIntegerHashMap,TJclIntegerAbstractContainer,IJclIntegerIntegerMap,IJclIntegerSet,IJclIntegerCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Integer): Integer;
function FreeValue(var Value: Integer): Integer;
function KeysEqual(A\, B: Integer): Boolean;
function ValuesEqual(A\, B: Integer): Boolean;,,,,,Integer,,Integer)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclCardinalIntfHashEntry,TJclCardinalIntfHashEntryArray,TJclCardinalIntfBucket,TJclCardinalIntfBucketArray,TJclCardinalIntfHashMap,TJclCardinalAbstractContainer,IJclCardinalIntfMap,IJclCardinalSet,IJclIntfCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Cardinal): Cardinal;
function FreeValue(var Value: IInterface): IInterface;
function KeysEqual(A\, B: Cardinal): Boolean;
function ValuesEqual(const A\, B: IInterface): Boolean;,,,,,Cardinal,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclIntfCardinalHashEntry,TJclIntfCardinalHashEntryArray,TJclIntfCardinalBucket,TJclIntfCardinalBucketArray,TJclIntfCardinalHashMap,TJclCardinalAbstractContainer,IJclIntfCardinalMap,IJclIntfSet,IJclCardinalCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: Cardinal): Cardinal;
function Hash(const AInterface: IInterface): Integer; reintroduce;
function KeysEqual(const A\, B: IInterface): Boolean;
function ValuesEqual(A\, B: Cardinal): Boolean;,,,,const ,IInterface,,Cardinal)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclCardinalCardinalHashEntry,TJclCardinalCardinalHashEntryArray,TJclCardinalCardinalBucket,TJclCardinalCardinalBucketArray,TJclCardinalCardinalHashMap,TJclCardinalAbstractContainer,IJclCardinalCardinalMap,IJclCardinalSet,IJclCardinalCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Cardinal): Cardinal;
function FreeValue(var Value: Cardinal): Cardinal;
function KeysEqual(A\, B: Cardinal): Boolean;
function ValuesEqual(A\, B: Cardinal): Boolean;,,,,,Cardinal,,Cardinal)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclInt64IntfHashEntry,TJclInt64IntfHashEntryArray,TJclInt64IntfBucket,TJclInt64IntfBucketArray,TJclInt64IntfHashMap,TJclInt64AbstractContainer,IJclInt64IntfMap,IJclInt64Set,IJclIntfCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Int64): Int64;
function FreeValue(var Value: IInterface): IInterface;
function KeysEqual(const A\, B: Int64): Boolean;
function ValuesEqual(const A\, B: IInterface): Boolean;,,,,const ,Int64,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclIntfInt64HashEntry,TJclIntfInt64HashEntryArray,TJclIntfInt64Bucket,TJclIntfInt64BucketArray,TJclIntfInt64HashMap,TJclInt64AbstractContainer,IJclIntfInt64Map,IJclIntfSet,IJclInt64Collection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: Int64): Int64;
function Hash(const AInterface: IInterface): Integer; reintroduce;
function KeysEqual(const A\, B: IInterface): Boolean;
function ValuesEqual(const A\, B: Int64): Boolean;,,,,const ,IInterface,const ,Int64)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclInt64Int64HashEntry,TJclInt64Int64HashEntryArray,TJclInt64Int64Bucket,TJclInt64Int64BucketArray,TJclInt64Int64HashMap,TJclInt64AbstractContainer,IJclInt64Int64Map,IJclInt64Set,IJclInt64Collection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Int64): Int64;
function FreeValue(var Value: Int64): Int64;
function KeysEqual(const A\, B: Int64): Boolean;
function ValuesEqual(const A\, B: Int64): Boolean;,,,,const ,Int64,const ,Int64)*)
{$IFNDEF CLR}
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclPtrIntfHashEntry,TJclPtrIntfHashEntryArray,TJclPtrIntfBucket,TJclPtrIntfBucketArray,TJclPtrIntfHashMap,TJclPtrAbstractContainer,IJclPtrIntfMap,IJclPtrSet,IJclIntfCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Pointer): Pointer;
function FreeValue(var Value: IInterface): IInterface;
function KeysEqual(A\, B: Pointer): Boolean;
function ValuesEqual(const A\, B: IInterface): Boolean;,,,,,Pointer,const ,IInterface)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclIntfPtrHashEntry,TJclIntfPtrHashEntryArray,TJclIntfPtrBucket,TJclIntfPtrBucketArray,TJclIntfPtrHashMap,TJclPtrAbstractContainer,IJclIntfPtrMap,IJclIntfSet,IJclPtrCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function FreeValue(var Value: Pointer): Pointer;
function Hash(const AInterface: IInterface): Integer; reintroduce;
function KeysEqual(const A\, B: IInterface): Boolean;
function ValuesEqual(A\, B: Pointer): Boolean;,,,,const ,IInterface,,Pointer)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclPtrPtrHashEntry,TJclPtrPtrHashEntryArray,TJclPtrPtrBucket,TJclPtrPtrBucketArray,TJclPtrPtrHashMap,TJclPtrAbstractContainer,IJclPtrPtrMap,IJclPtrSet,IJclPtrCollection,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Pointer): Pointer;
function FreeValue(var Value: Pointer): Pointer;
function KeysEqual(A\, B: Pointer): Boolean;
function ValuesEqual(A\, B: Pointer): Boolean;,,,,,Pointer,,Pointer)*)
{$ENDIF ~CLR}
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclIntfHashEntry,TJclIntfHashEntryArray,TJclIntfBucket,TJclIntfBucketArray,TJclIntfHashMap,TJclAbstractContainerBase,IJclIntfMap,IJclIntfSet,IJclCollection, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: IInterface): IInterface;
function Hash(const AInterface: IInterface): Integer; reintroduce;
function KeysEqual(const A\, B: IInterface): Boolean;
function ValuesEqual(A\, B: TObject): Boolean;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,const ,IInterface,,TObject)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclAnsiStrHashEntry,TJclAnsiStrHashEntryArray,TJclAnsiStrBucket,TJclAnsiStrBucketArray,TJclAnsiStrHashMap,TJclAnsiStrAbstractContainer,IJclAnsiStrMap,IJclAnsiStrSet,IJclCollection, IJclStrContainer\, IJclAnsiStrContainer\, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: AnsiString): AnsiString;
function KeysEqual(const A\, B: AnsiString): Boolean;
function ValuesEqual(A\, B: TObject): Boolean;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,const ,AnsiString,,TObject)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclWideStrHashEntry,TJclWideStrHashEntryArray,TJclWideStrBucket,TJclWideStrBucketArray,TJclWideStrHashMap,TJclwideStrAbstractContainer,IJclWideStrMap,IJclWideStrSet,IJclCollection, IJclStrContainer\, IJclWideStrContainer\, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: WideString): WideString;
function KeysEqual(const A\, B: WideString): Boolean;
function ValuesEqual(A\, B: TObject): Boolean;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,const ,WideString,,TObject)*)
{$IFDEF CONTAINER_ANSISTR}
TJclStrHashMap = TJclAnsiStrHashMap;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
TJclStrHashMap = TJclWideStrHashMap;
{$ENDIF CONTAINER_WIDESTR}
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclSingleHashEntry,TJclSingleHashEntryArray,TJclSingleBucket,TJclSingleBucketArray,TJclSingleHashMap,TJclSingleAbstractContainer,IJclSingleMap,IJclSingleSet,IJclCollection, IJclSingleContainer\, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Single): Single;
function KeysEqual(const A\, B: Single): Boolean;
function ValuesEqual(A\, B: TObject): Boolean;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,const ,Single,,TObject)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclDoubleHashEntry,TJclDoubleHashEntryArray,TJclDoubleBucket,TJclDoubleBucketArray,TJclDoubleHashMap,TJclDoubleAbstractContainer,IJclDoubleMap,IJclDoubleSet,IJclCollection, IJclDoubleContainer\, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Double): Double;
function KeysEqual(const A\, B: Double): Boolean;
function ValuesEqual(A\, B: TObject): Boolean;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,const ,Double,,TObject)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclExtendedHashEntry,TJclExtendedHashEntryArray,TJclExtendedBucket,TJclExtendedBucketArray,TJclExtendedHashMap,TJclExtendedAbstractContainer,IJclExtendedMap,IJclExtendedSet,IJclCollection, IJclExtendedContainer\, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Extended): Extended;
function KeysEqual(const A\, B: Extended): Boolean;
function ValuesEqual(A\, B: TObject): Boolean;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,const ,Extended,,TObject)*)
{$IFDEF MATH_EXTENDED_PRECISION}
TJclFloatHashMap = TJclExtendedHashMap;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
TJclFloatHashMap = TJclDoubleHashMap;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
TJclFloatHashMap = TJclSingleHashMap;
{$ENDIF MATH_SINGLE_PRECISION}
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclIntegerHashEntry,TJclIntegerHashEntryArray,TJclIntegerBucket,TJclIntegerBucketArray,TJclIntegerHashMap,TJclIntegerAbstractContainer,IJclIntegerMap,IJclIntegerSet,IJclCollection, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Integer): Integer;
function KeysEqual(A\, B: Integer): Boolean;
function ValuesEqual(A\, B: TObject): Boolean;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,,Integer,,TObject)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclCardinalHashEntry,TJclCardinalHashEntryArray,TJclCardinalBucket,TJclCardinalBucketArray,TJclCardinalHashMap,TJclCardinalAbstractContainer,IJclCardinalMap,IJclCardinalSet,IJclCollection, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Cardinal): Cardinal;
function KeysEqual(A\, B: Cardinal): Boolean;
function ValuesEqual(A\, B: TObject): Boolean;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,,Cardinal,,TObject)*)
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclInt64HashEntry,TJclInt64HashEntryArray,TJclInt64Bucket,TJclInt64BucketArray,TJclInt64HashMap,TJclInt64AbstractContainer,IJclInt64Map,IJclInt64Set,IJclCollection, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Int64): Int64;
function KeysEqual(const A\, B: Int64): Boolean;
function ValuesEqual(A\, B: TObject): Boolean;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,const ,Int64,,TObject)*)
{$IFNDEF CLR}
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclPtrHashEntry,TJclPtrHashEntryArray,TJclPtrBucket,TJclPtrBucketArray,TJclPtrHashMap,TJclPtrAbstractContainer,IJclPtrMap,IJclPtrSet,IJclCollection, IJclValueOwner\,,
FOwnsValues: Boolean;,
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function FreeKey(var Key: Pointer): Pointer;
function KeysEqual(A\, B: Pointer): Boolean;
function ValuesEqual(A\, B: TObject): Boolean;,
property OwnsValues: Boolean read FOwnsValues;,,; AOwnsValues: Boolean,,Pointer,,TObject)*)
{$ENDIF ~CLR}
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclHashEntry,TJclHashEntryArray,TJclBucket,TJclBucketArray,TJclHashMap,TJclAbstractContainerBase,IJclMap,IJclSet,IJclCollection, IJclKeyOwner\, IJclValueOwner\,,
FOwnsKeys: Boolean;
FOwnsValues: Boolean;,
{ IJclKeyOwner }
function FreeKey(var Key: TObject): TObject;
function GetOwnsKeys: Boolean;
{ IJclValueOwner }
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function Hash(AObject: TObject): Integer;
function KeysEqual(A\, B: TObject): Boolean;
function ValuesEqual(A\, B: TObject): Boolean;,
property OwnsKeys: Boolean read FOwnsKeys;
property OwnsValues: Boolean read FOwnsValues;,; AOwnsKeys: Boolean,; AOwnsValues: Boolean,,TObject,,TObject)*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO JCLHASHMAPINT(TJclHashEntry<TKey\,TValue>,TJclHashEntryArray<TKey\,TValue>,TJclBucket<TKey\,TValue>,TJclBucketArray<TKey\,TValue>,TJclHashMap<TKey\,TValue>,TJclAbstractContainerBase,IJclMap<TKey\,TValue>,IJclSet<TKey>,IJclCollection<TValue>, IJclPairOwner<TKey\, TValue>\,,
FOwnsKeys: Boolean;
FOwnsValues: Boolean;,
{ IJclPairOwner }
function FreeKey(var Key: TKey): TKey;
function FreeValue(var Value: TValue): TValue;
function GetOwnsKeys: Boolean;
function GetOwnsValues: Boolean;
function Hash(const AKey: TKey): Integer; virtual; abstract;
function KeysEqual(const A\, B: TKey): Boolean; virtual; abstract;
function ValuesEqual(const A\, B: TValue): Boolean; virtual; abstract;
function CreateEmptyArrayList(ACapacity: Integer; AOwnsObjects: Boolean): IJclCollection<TValue>; virtual; abstract;
function CreateEmptyArraySet(ACapacity: Integer; AOwnsObjects: Boolean): IJclSet<TKey>; virtual; abstract;,
property OwnsKeys: Boolean read FOwnsKeys;
property OwnsValues: Boolean read FOwnsValues;,; AOwnsKeys: Boolean,; AOwnsValues: Boolean,const ,TKey,const ,TValue)*)
// E = external helper to compare and hash items
// KeyComparer is used only when getting KeySet
// GetHashCode and Equals methods of KeyEqualityComparer are used
// GetHashCode of ValueEqualityComparer is not used
TJclHashMapE<TKey, TValue> = class(TJclHashMap<TKey, TValue>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclPackable, IJclContainer, IJclMap<TKey,TValue>, IJclPairOwner<TKey, TValue>)
private
FKeyEqualityComparer: IEqualityComparer<TKey>;
FKeyComparer: IComparer<TKey>;
FValueEqualityComparer: IEqualityComparer<TValue>;
protected
procedure AssignPropertiesTo(Dest: TJclAbstractContainerBase); override;
function Hash(const AKey: TKey): Integer; override;
function KeysEqual(const A, B: TKey): Boolean; override;
function ValuesEqual(const A, B: TValue): Boolean; override;
function CreateEmptyArrayList(ACapacity: Integer; AOwnsObjects: Boolean): IJclCollection<TValue>; override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function CreateEmptyArraySet(ACapacity: Integer; AOwnsObjects: Boolean): IJclSet<TKey>; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
public
constructor Create(const AKeyEqualityComparer: IEqualityComparer<TKey>;
const AValueEqualityComparer: IEqualityComparer<TValue>;
const AKeyComparer: IComparer<TKey>; ACapacity: Integer; AOwnsValues: Boolean; AOwnsKeys: Boolean);
property KeyEqualityComparer: IEqualityComparer<TKey> read FKeyEqualityComparer write FKeyEqualityComparer;
property KeyComparer: IComparer<TKey> read FKeyComparer write FKeyComparer;
property ValueEqualityComparer: IEqualityComparer<TValue> read FValueEqualityComparer write FValueEqualityComparer;
end;
// F = Functions to compare and hash items
// KeyComparer is used only when getting KeySet
TJclHashMapF<TKey, TValue> = class(TJclHashMap<TKey, TValue>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclPackable, IJclContainer, IJclMap<TKey,TValue>, IJclPairOwner<TKey, TValue>)
private
FKeyEqualityCompare: TEqualityCompare<TKey>;
FKeyHash: THashConvert<TKey>;
FKeyCompare: TCompare<TKey>;
FValueEqualityCompare: TEqualityCompare<TValue>;
protected
procedure AssignPropertiesTo(Dest: TJclAbstractContainerBase); override;
function Hash(const AKey: TKey): Integer; override;
function KeysEqual(const A, B: TKey): Boolean; override;
function ValuesEqual(const A, B: TValue): Boolean; override;
function CreateEmptyArrayList(ACapacity: Integer; AOwnsObjects: Boolean): IJclCollection<TValue>; override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function CreateEmptyArraySet(ACapacity: Integer; AOwnsObjects: Boolean): IJclSet<TKey>; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
public
constructor Create(AKeyEqualityCompare: TEqualityCompare<TKey>; AKeyHash: THashConvert<TKey>;
AValueEqualityCompare: TEqualityCompare<TValue>; AKeyCompare: TCompare<TKey>;
ACapacity: Integer; AOwnsValues: Boolean; AOwnsKeys: Boolean);
property KeyEqualityCompare: TEqualityCompare<TKey> read FKeyEqualityCompare write FKeyEqualityCompare;
property KeyCompare: TCompare<TKey> read FKeyCompare write FKeyCompare;
property KeyHash: THashConvert<TKey> read FKeyHash write FKeyHash;
property ValueEqualityCompare: TEqualityCompare<TValue> read FValueEqualityCompare write FValueEqualityCompare;
end;
// I = items can compare themselves to an other, items can create hash value from themselves
TJclHashMapI<TKey: IComparable<TKey>, IEquatable<TKey>, IHashable; TValue: IEquatable<TValue>> = class(TJclHashMap<TKey, TValue>,
{$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE} IJclIntfCloneable, IJclCloneable, IJclPackable, IJclContainer,
IJclMap<TKey,TValue>, IJclPairOwner<TKey, TValue>)
protected
function Hash(const AKey: TKey): Integer; override;
function KeysEqual(const A, B: TKey): Boolean; override;
function ValuesEqual(const A, B: TValue): Boolean; override;
function CreateEmptyArrayList(ACapacity: Integer; AOwnsObjects: Boolean): IJclCollection<TValue>; override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function CreateEmptyArraySet(ACapacity: Integer; AOwnsObjects: Boolean): IJclSet<TKey>; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
end;
{$ENDIF SUPPORTS_GENERICS}
function HashMul(Key, Range: Integer): Integer;
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL: https://jcl.svn.sourceforge.net:443/svnroot/jcl/tags/JCL-1.102-Build3072/jcl/source/prototypes/JclHashMaps.pas $';
Revision: '$Revision: 2376 $';
Date: '$Date: 2008-06-05 15:35:37 +0200 (jeu., 05 juin 2008) $';
LogPath: 'JCL\source\common'
);
{$ENDIF UNITVERSIONING}
implementation
uses
SysUtils,
JclArrayLists, JclArraySets, JclResources;
function HashMul(Key, Range: Integer): Integer;
const
A = 0.6180339887; // (sqrt(5) - 1) / 2
begin
Result := Trunc(Range * (Frac(Key * A)));
end;
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfIntfHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfIntfHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfIntfHashMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfIntfHashMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclIntfIntfHashMap.KeysEqual(const A, B: IInterface): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclIntfIntfHashMap.ValuesEqual(const A, B: IInterface): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclIntfIntfHashMap,TJclIntfIntfHashEntryArray,TJclIntfIntfBucket,IJclIntfIntfMap,IJclIntfSet,IJclIntfIterator,IJclIntfCollection,,,,const ,IInterface,nil,const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclAnsiStrIntfHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclAnsiStrIntfHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclAnsiStrArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclAnsiStrIntfHashMap.FreeKey(var Key: AnsiString): AnsiString;
begin
Result := Key;
Key := '';
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclAnsiStrIntfHashMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclAnsiStrIntfHashMap.KeysEqual(const A, B: AnsiString): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclAnsiStrIntfHashMap.ValuesEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclAnsiStrIntfHashMap,TJclAnsiStrIntfHashEntryArray,TJclAnsiStrIntfBucket,IJclAnsiStrIntfMap,IJclAnsiStrSet,IJclAnsiStrIterator,IJclIntfCollection,,,,const ,AnsiString,'',const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfAnsiStrHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfAnsiStrHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclAnsiStrArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfAnsiStrHashMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfAnsiStrHashMap.FreeValue(var Value: AnsiString): AnsiString;
begin
Result := Value;
Value := '';
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH
function TJclIntfAnsiStrHashMap.Hash(const AInterface: IInterface): Integer;
begin
Result := Integer(AInterface);
end;
}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclIntfAnsiStrHashMap.KeysEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclIntfAnsiStrHashMap.ValuesEqual(const A, B: AnsiString): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclIntfAnsiStrHashMap,TJclIntfAnsiStrHashEntryArray,TJclIntfAnsiStrBucket,IJclIntfAnsiStrMap,IJclIntfSet,IJclIntfIterator,IJclAnsiStrCollection,,,,const ,IInterface,nil,const ,AnsiString,'')}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclAnsiStrAnsiStrHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclAnsiStrAnsiStrHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclAnsiStrArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclAnsiStrArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclAnsiStrAnsiStrHashMap.FreeKey(var Key: AnsiString): AnsiString;
begin
Result := Key;
Key := '';
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclAnsiStrAnsiStrHashMap.FreeValue(var Value: AnsiString): AnsiString;
begin
Result := Value;
Value := '';
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclAnsiStrAnsiStrHashMap.KeysEqual(const A, B: AnsiString): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclAnsiStrAnsiStrHashMap.ValuesEqual(const A, B: AnsiString): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclAnsiStrAnsiStrHashMap,TJclAnsiStrAnsiStrHashEntryArray,TJclAnsiStrAnsiStrBucket,IJclAnsiStrAnsiStrMap,IJclAnsiStrSet,IJclAnsiStrIterator,IJclAnsiStrCollection,,,,const ,AnsiString,'',const ,AnsiString,'')}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclWideStrIntfHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclWideStrIntfHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclWideStrArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclWideStrIntfHashMap.FreeKey(var Key: WideString): WideString;
begin
Result := Key;
Key := '';
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclWideStrIntfHashMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclWideStrIntfHashMap.KeysEqual(const A, B: WideString): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclWideStrIntfHashMap.ValuesEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclWideStrIntfHashMap,TJclWideStrIntfHashEntryArray,TJclWideStrIntfBucket,IJclWideStrIntfMap,IJclWideStrSet,IJclWideStrIterator,IJclIntfCollection,,,,const ,WideString,'',const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfWideStrHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfWideStrHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclWideStrArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfWideStrHashMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfWideStrHashMap.FreeValue(var Value: WideString): WideString;
begin
Result := Value;
Value := '';
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH
function TJclIntfWideStrHashMap.Hash(const AInterface: IInterface): Integer;
begin
Result := Integer(AInterface);
end;
}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclIntfWideStrHashMap.KeysEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclIntfWideStrHashMap.ValuesEqual(const A, B: WideString): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclIntfWideStrHashMap,TJclIntfWideStrHashEntryArray,TJclIntfWideStrBucket,IJclIntfWideStrMap,IJclIntfSet,IJclIntfIterator,IJclWideStrCollection,,,,const ,IInterface,nil,const ,WideString,'')}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclWideStrWideStrHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclWideStrWideStrHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclWideStrArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclWideStrArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclWideStrWideStrHashMap.FreeKey(var Key: WideString): WideString;
begin
Result := Key;
Key := '';
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclWideStrWideStrHashMap.FreeValue(var Value: WideString): WideString;
begin
Result := Value;
Value := '';
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclWideStrWideStrHashMap.KeysEqual(const A, B: WideString): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclWideStrWideStrHashMap.ValuesEqual(const A, B: Widestring): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclWideStrWideStrHashMap,TJclWideStrWideStrHashEntryArray,TJclWideStrWideStrBucket,IJclWideStrWideStrMap,IJclWideStrSet,IJclWideStrIterator,IJclWideStrCollection,,,,const ,WideString,'',const ,WideString,'')}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclSingleIntfHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclSingleIntfHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclSingleArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclSingleIntfHashMap.FreeKey(var Key: Single): Single;
begin
Result := Key;
Key := 0.0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclSingleIntfHashMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclSingleIntfHashMap.KeysEqual(const A, B: Single): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclSingleIntfHashMap.ValuesEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclSingleIntfHashMap,TJclSingleIntfHashEntryArray,TJclSingleIntfBucket,IJclSingleIntfMap,IJclSingleSet,IJclSingleIterator,IJclIntfCollection,,,,const ,Single,0.0,const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfSingleHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfSingleHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclSingleArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfSingleHashMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfSingleHashMap.FreeValue(var Value: Single): Single;
begin
Result := Value;
Value := 0.0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH
function TJclIntfSingleHashMap.Hash(const AInterface: IInterface): Integer;
begin
Result := Integer(AInterface);
end;
}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclIntfSingleHashMap.KeysEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclIntfSingleHashMap.ValuesEqual(const A, B: Single): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclIntfSingleHashMap,TJclIntfSingleHashEntryArray,TJclIntfSingleBucket,IJclIntfSingleMap,IJclIntfSet,IJclIntfIterator,IJclSingleCollection,,,,const ,IInterface,nil,const ,Single,0.0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclSingleSingleHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclSingleSingleHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclSingleArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclSingleArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclSingleSingleHashMap.FreeKey(var Key: Single): Single;
begin
Result := Key;
Key := 0.0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclSingleSingleHashMap.FreeValue(var Value: Single): Single;
begin
Result := Value;
Value := 0.0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclSingleSingleHashMap.KeysEqual(const A, B: Single): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclSingleSingleHashMap.ValuesEqual(const A, B: Single): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclSingleSingleHashMap,TJclSingleSingleHashEntryArray,TJclSingleSingleBucket,IJclSingleSingleMap,IJclSingleSet,IJclSingleIterator,IJclSingleCollection,,,,const ,Single,0.0,const ,Single,0.0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclDoubleIntfHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclDoubleIntfHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclDoubleArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclDoubleIntfHashMap.FreeKey(var Key: Double): Double;
begin
Result := Key;
Key := 0.0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclDoubleIntfHashMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclDoubleIntfHashMap.KeysEqual(const A, B: Double): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclDoubleIntfHashMap.ValuesEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclDoubleIntfHashMap,TJclDoubleIntfHashEntryArray,TJclDoubleIntfBucket,IJclDoubleIntfMap,IJclDoubleSet,IJclDoubleIterator,IJclIntfCollection,,,,const ,Double,0.0,const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfDoubleHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfDoubleHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclDoubleArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfDoubleHashMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfDoubleHashMap.FreeValue(var Value: Double): Double;
begin
Result := Value;
Value := 0.0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH
function TJclIntfDoubleHashMap.Hash(const AInterface: IInterface): Integer;
begin
Result := Integer(AInterface);
end;
}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclIntfDoubleHashMap.KeysEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclIntfDoubleHashMap.ValuesEqual(const A, B: Double): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclIntfDoubleHashMap,TJclIntfDoubleHashEntryArray,TJclIntfDoubleBucket,IJclIntfDoubleMap,IJclIntfSet,IJclIntfIterator,IJclDoubleCollection,,,,const ,IInterface,nil,const ,Double,0.0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclDoubleDoubleHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclDoubleDoubleHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclDoubleArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclDoubleArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclDoubleDoubleHashMap.FreeKey(var Key: Double): Double;
begin
Result := Key;
Key := 0.0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclDoubleDoubleHashMap.FreeValue(var Value: Double): Double;
begin
Result := Value;
Value := 0.0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclDoubleDoubleHashMap.KeysEqual(const A, B: Double): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclDoubleDoubleHashMap.ValuesEqual(const A, B: Double): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclDoubleDoubleHashMap,TJclDoubleDoubleHashEntryArray,TJclDoubleDoubleBucket,IJclDoubleDoubleMap,IJclDoubleSet,IJclDoubleIterator,IJclDoubleCollection,,,,const ,Double,0.0,const ,Double,0.0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclExtendedIntfHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclExtendedIntfHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclExtendedArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclExtendedIntfHashMap.FreeKey(var Key: Extended): Extended;
begin
Result := Key;
Key := 0.0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclExtendedIntfHashMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclExtendedIntfHashMap.KeysEqual(const A, B: Extended): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclExtendedIntfHashMap.ValuesEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclExtendedIntfHashMap,TJclExtendedIntfHashEntryArray,TJclExtendedIntfBucket,IJclExtendedIntfMap,IJclExtendedSet,IJclExtendedIterator,IJclIntfCollection,,,,const ,Extended,0.0,const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfExtendedHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfExtendedHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclExtendedArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfExtendedHashMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfExtendedHashMap.FreeValue(var Value: Extended): Extended;
begin
Result := Value;
Value := 0.0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH
function TJclIntfExtendedHashMap.Hash(const AInterface: IInterface): Integer;
begin
Result := Integer(AInterface);
end;
}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclIntfExtendedHashMap.KeysEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclIntfExtendedHashMap.ValuesEqual(const A, B: Extended): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclIntfExtendedHashMap,TJclIntfExtendedHashEntryArray,TJclIntfExtendedBucket,IJclIntfExtendedMap,IJclIntfSet,IJclIntfIterator,IJclExtendedCollection,,,,const ,IInterface,nil,const ,Extended,0.0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclExtendedExtendedHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclExtendedExtendedHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclExtendedArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclExtendedArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclExtendedExtendedHashMap.FreeKey(var Key: Extended): Extended;
begin
Result := Key;
Key := 0.0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclExtendedExtendedHashMap.FreeValue(var Value: Extended): Extended;
begin
Result := Value;
Value := 0.0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclExtendedExtendedHashMap.KeysEqual(const A, B: Extended): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclExtendedExtendedHashMap.ValuesEqual(const A, B: Extended): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclExtendedExtendedHashMap,TJclExtendedExtendedHashEntryArray,TJclExtendedExtendedBucket,IJclExtendedExtendedMap,IJclExtendedSet,IJclExtendedIterator,IJclExtendedCollection,,,,const ,Extended,0.0,const ,Extended,0.0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntegerIntfHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntegerIntfHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntegerArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntegerIntfHashMap.FreeKey(var Key: Integer): Integer;
begin
Result := Key;
Key := 0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntegerIntfHashMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclIntegerIntfHashMap.KeysEqual(A, B: Integer): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclIntegerIntfHashMap.ValuesEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclIntegerIntfHashMap,TJclIntegerIntfHashEntryArray,TJclIntegerIntfBucket,IJclIntegerIntfMap,IJclIntegerSet,IJclIntegerIterator,IJclIntfCollection,,,,,Integer,0,const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfIntegerHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfIntegerHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntegerArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfIntegerHashMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfIntegerHashMap.FreeValue(var Value: Integer): Integer;
begin
Result := Value;
Value := 0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH
function TJclIntfIntegerHashMap.Hash(const AInterface: IInterface): Integer;
begin
Result := Integer(AInterface);
end;
}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclIntfIntegerHashMap.KeysEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclIntfIntegerHashMap.ValuesEqual(A, B: Integer): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclIntfIntegerHashMap,TJclIntfIntegerHashEntryArray,TJclIntfIntegerBucket,IJclIntfIntegerMap,IJclIntfSet,IJclIntfIterator,IJclIntegerCollection,,,,const ,IInterface,nil,,Integer,0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntegerIntegerHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntegerIntegerHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntegerArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntegerArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntegerIntegerHashMap.FreeKey(var Key: Integer): Integer;
begin
Result := Key;
Key := 0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntegerIntegerHashMap.FreeValue(var Value: Integer): Integer;
begin
Result := Value;
Value := 0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclIntegerIntegerHashMap.KeysEqual(A, B: Integer): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclIntegerIntegerHashMap.ValuesEqual(A, B: Integer): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclIntegerIntegerHashMap,TJclIntegerIntegerHashEntryArray,TJclIntegerIntegerBucket,IJclIntegerIntegerMap,IJclIntegerSet,IJclIntegerIterator,IJclIntegerCollection,,,,,Integer,0,,Integer,0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclCardinalIntfHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclCardinalIntfHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclCardinalArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclCardinalIntfHashMap.FreeKey(var Key: Cardinal): Cardinal;
begin
Result := Key;
Key := 0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclCardinalIntfHashMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclCardinalIntfHashMap.KeysEqual(A, B: Cardinal): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclCardinalIntfHashMap.ValuesEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclCardinalIntfHashMap,TJclCardinalIntfHashEntryArray,TJclCardinalIntfBucket,IJclCardinalIntfMap,IJclCardinalSet,IJclCardinalIterator,IJclIntfCollection,,,,,Cardinal,0,const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfCardinalHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfCardinalHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclCardinalArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfCardinalHashMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfCardinalHashMap.FreeValue(var Value: Cardinal): Cardinal;
begin
Result := Value;
Value := 0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH
function TJclIntfCardinalHashMap.Hash(const AInterface: IInterface): Integer;
begin
Result := Integer(AInterface);
end;
}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclIntfCardinalHashMap.KeysEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclIntfCardinalHashMap.ValuesEqual(A, B: Cardinal): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclIntfCardinalHashMap,TJclIntfCardinalHashEntryArray,TJclIntfCardinalBucket,IJclIntfCardinalMap,IJclIntfSet,IJclIntfIterator,IJclCardinalCollection,,,,const ,IInterface,nil,,Cardinal,0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclCardinalCardinalHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclCardinalCardinalHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclCardinalArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclCardinalArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclCardinalCardinalHashMap.FreeKey(var Key: Cardinal): Cardinal;
begin
Result := Key;
Key := 0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclCardinalCardinalHashMap.FreeValue(var Value: Cardinal): Cardinal;
begin
Result := Value;
Value := 0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclCardinalCardinalHashMap.KeysEqual(A, B: Cardinal): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclCardinalCardinalHashMap.ValuesEqual(A, B: Cardinal): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclCardinalCardinalHashMap,TJclCardinalCardinalHashEntryArray,TJclCardinalCardinalBucket,IJclCardinalCardinalMap,IJclCardinalSet,IJclCardinalIterator,IJclCardinalCollection,,,,,Cardinal,0,,Cardinal,0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclInt64IntfHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclInt64IntfHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclInt64ArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclInt64IntfHashMap.FreeKey(var Key: Int64): Int64;
begin
Result := Key;
Key := 0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclInt64IntfHashMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclInt64IntfHashMap.KeysEqual(const A, B: Int64): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclInt64IntfHashMap.ValuesEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclInt64IntfHashMap,TJclInt64IntfHashEntryArray,TJclInt64IntfBucket,IJclInt64IntfMap,IJclInt64Set,IJclInt64Iterator,IJclIntfCollection,,,,const ,Int64,0,const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfInt64HashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfInt64HashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclInt64ArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfInt64HashMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfInt64HashMap.FreeValue(var Value: Int64): Int64;
begin
Result := Value;
Value := 0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH
function TJclIntfInt64HashMap.Hash(const AInterface: IInterface): Integer;
begin
Result := Integer(AInterface);
end;
}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclIntfInt64HashMap.KeysEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclIntfInt64HashMap.ValuesEqual(const A, B: Int64): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclIntfInt64HashMap,TJclIntfInt64HashEntryArray,TJclIntfInt64Bucket,IJclIntfInt64Map,IJclIntfSet,IJclIntfIterator,IJclInt64Collection,,,,const ,IInterface,nil,const ,Int64,0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclInt64Int64HashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclInt64Int64HashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclInt64ArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclInt64ArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclInt64Int64HashMap.FreeKey(var Key: Int64): Int64;
begin
Result := Key;
Key := 0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclInt64Int64HashMap.FreeValue(var Value: Int64): Int64;
begin
Result := Value;
Value := 0;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclInt64Int64HashMap.KeysEqual(const A, B: Int64): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclInt64Int64HashMap.ValuesEqual(const A, B: Int64): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclInt64Int64HashMap,TJclInt64Int64HashEntryArray,TJclInt64Int64Bucket,IJclInt64Int64Map,IJclInt64Set,IJclInt64Iterator,IJclInt64Collection,,,,const ,Int64,0,const ,Int64,0)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$IFNDEF CLR}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclPtrIntfHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclPtrIntfHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclPtrArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclIntfArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclPtrIntfHashMap.FreeKey(var Key: Pointer): Pointer;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclPtrIntfHashMap.FreeValue(var Value: IInterface): IInterface;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclPtrIntfHashMap.KeysEqual(A, B: Pointer): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclPtrIntfHashMap.ValuesEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclPtrIntfHashMap,TJclPtrIntfHashEntryArray,TJclPtrIntfBucket,IJclPtrIntfMap,IJclPtrSet,IJclPtrIterator,IJclIntfCollection,,,,,Pointer,nil,const ,IInterface,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfPtrHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfPtrHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclPtrArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfPtrHashMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfPtrHashMap.FreeValue(var Value: Pointer): Pointer;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH
function TJclIntfPtrHashMap.Hash(const AInterface: IInterface): Integer;
begin
Result := Integer(AInterface);
end;
}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclIntfPtrHashMap.KeysEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclIntfPtrHashMap.ValuesEqual(A, B: Pointer): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclIntfPtrHashMap,TJclIntfPtrHashEntryArray,TJclIntfPtrBucket,IJclIntfPtrMap,IJclIntfSet,IJclIntfIterator,IJclPtrCollection,,,,const ,IInterface,nil,,Pointer,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclPtrPtrHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclPtrPtrHashMap.Create(FCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclPtrArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclPtrArrayList.Create(Param)}
{$JPPDEFINEMACRO FREEKEY
function TJclPtrPtrHashMap.FreeKey(var Key: Pointer): Pointer;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclPtrPtrHashMap.FreeValue(var Value: Pointer): Pointer;
begin
Result := Value;
Value := nil;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclPtrPtrHashMap.KeysEqual(A, B: Pointer): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclPtrPtrHashMap.ValuesEqual(A, B: Pointer): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclPtrPtrHashMap,TJclPtrPtrHashEntryArray,TJclPtrPtrBucket,IJclPtrPtrMap,IJclPtrSet,IJclPtrIterator,IJclPtrCollection,,,,,Pointer,nil,,Pointer,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$ENDIF ~CLR}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfHashMap.Create(FCapacity, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntfArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntfHashMap.FreeKey(var Key: IInterface): IInterface;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntfHashMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclIntfHashMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO HASH
function TJclIntfHashMap.Hash(const AInterface: IInterface): Integer;
begin
Result := Integer(AInterface);
end;
}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclIntfHashMap.KeysEqual(const A, B: IInterface): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclIntfHashMap.ValuesEqual(A, B: TObject): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclIntfHashMap,TJclIntfHashEntryArray,TJclIntfBucket,IJclIntfMap,IJclIntfSet,IJclIntfIterator,IJclCollection,; AOwnsValues: Boolean,,
FOwnsValues := AOwnsValues;,const ,IInterface,nil,,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclAnsiStrHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclAnsiStrHashMap.Create(FCapacity, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclAnsiStrArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclAnsiStrHashMap.FreeKey(var Key: AnsiString): AnsiString;
begin
Result := Key;
Key := '';
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclAnsiStrHashMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclAnsiStrHashMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclAnsiStrHashMap.KeysEqual(const A, B: AnsiString): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclAnsiStrHashMap.ValuesEqual(A, B: TObject): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclAnsiStrHashMap,TJclAnsiStrHashEntryArray,TJclAnsiStrBucket,IJclAnsiStrMap,IJclAnsiStrSet,IJclAnsiStrIterator,IJclCollection,; AOwnsValues: Boolean,,
FOwnsValues := AOwnsValues;,const ,AnsiString,'',,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclWideStrHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclWideStrHashMap.Create(FCapacity, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclWideStrArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclWideStrHashMap.FreeKey(var Key: WideString): WideString;
begin
Result := Key;
Key := '';
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclWideStrHashMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclWideStrHashMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclWideStrHashMap.KeysEqual(const A, B: WideString): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclWideStrHashMap.ValuesEqual(A, B: TObject): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclWideStrHashMap,TJclWideStrHashEntryArray,TJclWideStrBucket,IJclWideStrMap,IJclWideStrSet,IJclWideStrIterator,IJclCollection,; AOwnsValues: Boolean,,
FOwnsValues := AOwnsValues;,const ,WideString,'',,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclSingleHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclSingleHashMap.Create(FCapacity, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclSingleArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclSingleHashMap.FreeKey(var Key: Single): Single;
begin
Result := Key;
Key := 0.0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclSingleHashMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclSingleHashMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclSingleHashMap.KeysEqual(const A, B: Single): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclSingleHashMap.ValuesEqual(A, B: TObject): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclSingleHashMap,TJclSingleHashEntryArray,TJclSingleBucket,IJclSingleMap,IJclSingleSet,IJclSingleIterator,IJclCollection,; AOwnsValues: Boolean,,
FOwnsValues := AOwnsValues;,const ,Single,0.0,,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclDoubleHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclDoubleHashMap.Create(FCapacity, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclDoubleArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclDoubleHashMap.FreeKey(var Key: Double): Double;
begin
Result := Key;
Key := 0.0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclDoubleHashMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclDoubleHashMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclDoubleHashMap.KeysEqual(const A, B: Double): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclDoubleHashMap.ValuesEqual(A, B: TObject): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclDoubleHashMap,TJclDoubleHashEntryArray,TJclDoubleBucket,IJclDoubleMap,IJclDoubleSet,IJclDoubleIterator,IJclCollection,; AOwnsValues: Boolean,,
FOwnsValues := AOwnsValues;,const ,Double,0.0,,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclExtendedHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclExtendedHashMap.Create(FCapacity, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclExtendedArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclExtendedHashMap.FreeKey(var Key: Extended): Extended;
begin
Result := Key;
Key := 0.0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclExtendedHashMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclExtendedHashMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclExtendedHashMap.KeysEqual(const A, B: Extended): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclExtendedHashMap.ValuesEqual(A, B: TObject): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclExtendedHashMap,TJclExtendedHashEntryArray,TJclExtendedBucket,IJclExtendedMap,IJclExtendedSet,IJclExtendedIterator,IJclCollection,; AOwnsValues: Boolean,,
FOwnsValues := AOwnsValues;,const ,Extended,0.0,,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntegerHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntegerHashMap.Create(FCapacity, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclIntegerArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclIntegerHashMap.FreeKey(var Key: Integer): Integer;
begin
Result := Key;
Key := 0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclIntegerHashMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclIntegerHashMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclIntegerHashMap.KeysEqual(A, B: Integer): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclIntegerHashMap.ValuesEqual(A, B: TObject): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclIntegerHashMap,TJclIntegerHashEntryArray,TJclIntegerBucket,IJclIntegerMap,IJclIntegerSet,IJclIntegerIterator,IJclCollection,; AOwnsValues: Boolean,,
FOwnsValues := AOwnsValues;,,Integer,0,,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclCardinalHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclCardinalHashMap.Create(FCapacity, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclCardinalArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclCardinalHashMap.FreeKey(var Key: Cardinal): Cardinal;
begin
Result := Key;
Key := 0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclCardinalHashMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclCardinalHashMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclCardinalHashMap.KeysEqual(A, B: Cardinal): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclCardinalHashMap.ValuesEqual(A, B: TObject): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclCardinalHashMap,TJclCardinalHashEntryArray,TJclCardinalBucket,IJclCardinalMap,IJclCardinalSet,IJclCardinalIterator,IJclCollection,; AOwnsValues: Boolean,,
FOwnsValues := AOwnsValues;,,Cardinal,0,,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclInt64HashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclInt64HashMap.Create(FCapacity, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclInt64ArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclInt64HashMap.FreeKey(var Key: Int64): Int64;
begin
Result := Key;
Key := 0;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclInt64HashMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclInt64HashMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclInt64HashMap.KeysEqual(const A, B: Int64): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclInt64HashMap.ValuesEqual(A, B: TObject): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclInt64HashMap,TJclInt64HashEntryArray,TJclInt64Bucket,IJclInt64Map,IJclInt64Set,IJclInt64Iterator,IJclCollection,; AOwnsValues: Boolean,,
FOwnsValues := AOwnsValues;,const ,Int64,0,,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$IFNDEF CLR}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclPtrHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclPtrHashMap.Create(FCapacity, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclPtrArraySet.Create(Param)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclPtrHashMap.FreeKey(var Key: Pointer): Pointer;
begin
Result := Key;
Key := nil;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclPtrHashMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclPtrHashMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclPtrHashMap.KeysEqual(A, B: Pointer): Boolean;
begin
Result := ItemsEqual(A, B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclPtrHashMap.ValuesEqual(A, B: TObject): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclPtrHashMap,TJclPtrHashEntryArray,TJclPtrBucket,IJclPtrMap,IJclPtrSet,IJclPtrIterator,IJclCollection,; AOwnsValues: Boolean,,
FOwnsValues := AOwnsValues;,,Pointer,nil,,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$ENDIF ~CLR}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclHashMap.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclHashMap.Create(FCapacity, False, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)TJclArraySet.Create(Param, False)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)TJclArrayList.Create(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclHashMap.FreeKey(var Key: TObject): TObject;
begin
if FOwnsKeys then
begin
Result := nil;
FreeAndNil(Key);
end
else
begin
Result := Key;
Key := nil;
end;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclHashMap.FreeValue(var Value: TObject): TObject;
begin
if FOwnsValues then
begin
Result := nil;
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := nil;
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS
function TJclHashMap.GetOwnsKeys: Boolean;
begin
Result := FOwnsKeys;
end;
}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclHashMap.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO HASH
function TJclHashMap.Hash(AObject: TObject): Integer;
begin
Result := Integer(AObject);
end;
}
{$JPPDEFINEMACRO KEYSEQUAL
function TJclHashMap.KeysEqual(A, B: TObject): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPDEFINEMACRO VALUESEQUAL
function TJclHashMap.ValuesEqual(A, B: TObject): Boolean;
begin
Result := Integer(A) = Integer(B);
end;
}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclHashMap,TJclHashEntryArray,TJclBucket,IJclMap,IJclSet,IJclIterator,IJclCollection,; AOwnsKeys: Boolean,; AOwnsValues: Boolean,
FOwnsKeys := AOwnsKeys;
FOwnsValues := AOwnsValues;,,TObject,nil,,TObject,nil)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
{$IFDEF SUPPORTS_GENERICS}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYARRAYSET(Param)CreateEmptyArraySet(Param, False)}
{$JPPDEFINEMACRO CREATEEMPTYARRAYLIST(Param)CreateEmptyArrayList(Param, False)}
{$JPPDEFINEMACRO FREEKEY
function TJclHashMap<TKey, TValue>.FreeKey(var Key: TKey): TKey;
begin
if FOwnsKeys then
begin
Result := Default(TKey);
FreeAndNil(Key);
end
else
begin
Result := Key;
Key := Default(TKey);
end;
end;
}
{$JPPDEFINEMACRO FREEVALUE
function TJclHashMap<TKey, TValue>.FreeValue(var Value: TValue): TValue;
begin
if FOwnsValues then
begin
Result := Default(TValue);
FreeAndNil(Value);
end
else
begin
Result := Value;
Value := Default(TValue);
end;
end;
}
{$JPPDEFINEMACRO GETOWNSKEYS
function TJclHashMap<TKey, TValue>.GetOwnsKeys: Boolean;
begin
Result := FOwnsKeys;
end;
}
{$JPPDEFINEMACRO GETOWNSVALUES
function TJclHashMap<TKey, TValue>.GetOwnsValues: Boolean;
begin
Result := FOwnsValues;
end;
}
{$JPPDEFINEMACRO HASH}
{$JPPDEFINEMACRO KEYSEQUAL}
{$JPPDEFINEMACRO VALUESEQUAL}
{$JPPEXPANDMACRO JCLHASHMAPIMP(TJclHashMap<TKey\, TValue>,TJclHashEntryArray<TKey\, TValue>,TJclBucket<TKey\, TValue>,IJclMap<TKey\, TValue>,IJclSet<TKey>,IJclIterator<TKey>,IJclCollection<TValue>,; AOwnsKeys: Boolean,; AOwnsValues: Boolean,
FOwnsKeys := AOwnsKeys;
FOwnsValues := AOwnsValues;,const ,TKey,Default(TKey),const ,TValue,Default(TValue))}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO CREATEEMPTYARRAYSET(Param)}
{$JPPUNDEFMACRO CREATEEMPTYARRAYLIST(Param)}
{$JPPUNDEFMACRO FREEKEY}
{$JPPUNDEFMACRO FREEVALUE}
{$JPPUNDEFMACRO GETOWNSKEYS}
{$JPPUNDEFMACRO GETOWNSVALUES}
{$JPPUNDEFMACRO HASH}
{$JPPUNDEFMACRO KEYSEQUAL}
{$JPPUNDEFMACRO VALUESEQUAL}
//=== { TJclHashMapE<TKey, TValue> } =========================================
constructor TJclHashMapE<TKey, TValue>.Create(const AKeyEqualityComparer: IEqualityComparer<TKey>;
const AValueEqualityComparer: IEqualityComparer<TValue>; const AKeyComparer: IComparer<TKey>; ACapacity: Integer;
AOwnsValues: Boolean; AOwnsKeys: Boolean);
begin
inherited Create(ACapacity, AOwnsKeys, AOwnsValues);
FKeyEqualityComparer := AKeyEqualityComparer;
FValueEqualityComparer := AValueEqualityComparer;
FKeyComparer := AKeyComparer;
end;
procedure TJclHashMapE<TKey, TValue>.AssignPropertiesTo(Dest: TJclAbstractContainerBase);
var
ADest: TJclHashMapE<TKey, TValue>;
begin
inherited AssignPropertiesTo(Dest);
if Dest is TJclHashMapE<TKey, TValue> then
begin
ADest := TJclHashMapE<TKey, TValue>(Dest);
ADest.FKeyEqualityComparer := FKeyEqualityComparer;
ADest.FValueEqualityComparer := FValueEqualityComparer;
ADest.FKeyComparer := FKeyComparer;
end;
end;
function TJclHashMapE<TKey, TValue>.CreateEmptyArrayList(ACapacity: Integer; AOwnsObjects: Boolean): IJclCollection<TValue>;
begin
Result := TJclArrayListE<TValue>.Create(ValueEqualityComparer, ACapacity, AOwnsObjects);
end;
function TJclHashMapE<TKey, TValue>.CreateEmptyArraySet(ACapacity: Integer; AOwnsObjects: Boolean): IJclSet<TKey>;
begin
Result := TJclArraySetE<TKey>.Create(KeyComparer, ACapacity, AOwnsObjects);
end;
function TJclHashMapE<TKey, TValue>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclHashMapE<TKey, TValue>.Create(KeyEqualityComparer, ValueEqualityComparer,
KeyComparer, FCapacity, False, False);
AssignPropertiesTo(Result);
end;
function TJclHashMapE<TKey, TValue>.Hash(const AKey: TKey): Integer;
begin
if KeyEqualityComparer = nil then
raise EJclNoHashConverterError.Create;
Result := KeyEqualityComparer.GetHashCode(AKey);
end;
function TJclHashMapE<TKey, TValue>.KeysEqual(const A, B: TKey): Boolean;
begin
if KeyEqualityComparer = nil then
raise EJclNoEqualityComparerError.Create;
Result := KeyEqualityComparer.Equals(A, B);
end;
function TJclHashMapE<TKey, TValue>.ValuesEqual(const A, B: TValue): Boolean;
begin
if ValueEqualityComparer = nil then
raise EJclNoEqualityComparerError.Create;
Result := ValueEqualityComparer.Equals(A, B);
end;
//=== { TJclHashMapF<TKey, TValue> } =========================================
constructor TJclHashMapF<TKey, TValue>.Create(AKeyEqualityCompare: TEqualityCompare<TKey>;
AKeyHash: THashConvert<TKey>; AValueEqualityCompare: TEqualityCompare<TValue>; AKeyCompare: TCompare<TKey>;
ACapacity: Integer; AOwnsValues: Boolean; AOwnsKeys: Boolean);
begin
inherited Create(ACapacity, AOwnsKeys, AOwnsValues);
FKeyEqualityCompare := AKeyEqualityCompare;
FKeyHash := AKeyHash;
FValueEqualityCompare := AValueEqualityCompare;
FKeyCompare := AKeyCompare;
end;
procedure TJclHashMapF<TKey, TValue>.AssignPropertiesTo(Dest: TJclAbstractContainerBase);
var
ADest: TJclHashMapF<TKey, TValue>;
begin
inherited AssignPropertiesTo(Dest);
if Dest is TJclHashMapF<TKey, TValue> then
begin
ADest := TJclHashMapF<TKey, TValue>(Dest);
ADest.FKeyEqualityCompare := FKeyEqualityCompare;
ADest.FKeyHash := FKeyHash;
ADest.FValueEqualityCompare := FValueEqualityCompare;
ADest.FKeyCompare := FKeyCompare;
end;
end;
function TJclHashMapF<TKey, TValue>.CreateEmptyArrayList(ACapacity: Integer; AOwnsObjects: Boolean): IJclCollection<TValue>;
begin
Result := TJclArrayListF<TValue>.Create(ValueEqualityCompare, ACapacity, AOwnsObjects);
end;
function TJclHashMapF<TKey, TValue>.CreateEmptyArraySet(ACapacity: Integer; AOwnsObjects: Boolean): IJclSet<TKey>;
begin
Result := TJclArraySetF<TKey>.Create(KeyCompare, ACapacity, AOwnsObjects);
end;
function TJclHashMapF<TKey, TValue>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclHashMapF<TKey, TValue>.Create(KeyEqualityCompare, KeyHash, ValueEqualityCompare, KeyCompare, FCapacity,
False, False);
AssignPropertiesTo(Result);
end;
function TJclHashMapF<TKey, TValue>.Hash(const AKey: TKey): Integer;
begin
if not Assigned(KeyHash) then
raise EJclNoHashConverterError.Create;
Result := KeyHash(AKey);
end;
function TJclHashMapF<TKey, TValue>.KeysEqual(const A, B: TKey): Boolean;
begin
if not Assigned(KeyEqualityCompare) then
raise EJclNoEqualityComparerError.Create;
Result := KeyEqualityCompare(A, B);
end;
function TJclHashMapF<TKey, TValue>.ValuesEqual(const A, B: TValue): Boolean;
begin
if not Assigned(ValueEqualityCompare) then
raise EJclNoEqualityComparerError.Create;
Result := ValueEqualityCompare(A, B);
end;
//=== { TJclHashMapI<TKey, TValue> } =========================================
function TJclHashMapI<TKey, TValue>.CreateEmptyArrayList(ACapacity: Integer; AOwnsObjects: Boolean): IJclCollection<TValue>;
begin
Result := TJclArrayListI<TValue>.Create(ACapacity, AOwnsObjects);
end;
function TJclHashMapI<TKey, TValue>.CreateEmptyArraySet(ACapacity: Integer; AOwnsObjects: Boolean): IJclSet<TKey>;
begin
Result := TJclArraySetI<TKey>.Create(ACapacity, AOwnsObjects);
end;
function TJclHashMapI<TKey, TValue>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclHashMapI<TKey, TValue>.Create(FCapacity, False, False);
AssignPropertiesTo(Result);
end;
function TJclHashMapI<TKey, TValue>.Hash(const AKey: TKey): Integer;
begin
Result := AKey.GetHashCode;
end;
function TJclHashMapI<TKey, TValue>.KeysEqual(const A, B: TKey): Boolean;
begin
Result := A.Equals(B);
end;
function TJclHashMapI<TKey, TValue>.ValuesEqual(const A, B: TValue): Boolean;
begin
Result := A.Equals(B);
end;
{$ENDIF SUPPORTS_GENERICS}
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
|
unit Devices.Tecon.Common;
interface
uses Windows, GMGlobals;
procedure Tecon_CRC(var buf: array of Byte; Len: int);
function Tecon_CheckCRC(const buf: array of Byte; Len: int): bool;
procedure Tecon_ReplyAuthorization(var bufs: TTwoBuffers);
function Tecon_CheckK105Authorization(buf: array of Byte; Len: int): bool;
function Tecon_CheckCommonPrmReply(buf: array of Byte; Len: int): bool;
function Tecon_CheckCurrentsPrmReply(buf: array of Byte; Len: int): bool;
function Tecon_CheckArchPrmReply(buf: array of Byte; Len: int): bool;
function Tecon_CheckCurrentsPrmReplyCOM(buf: array of Byte; Len: int): bool;
function Tecon_CheckPrmReply(buf: array of Byte; Len: int): bool;
function DecToHexDigits(n: Byte): byte;
implementation
// функция для переделки времени нормального во время ТЭКОН
// специфика в том, что компоненты времени передаются в шестнадцатиричном виде, но такие же как в десятичном
// Например dec25 -> 0x25
function DecToHexDigits(n: Byte): byte;
var n1, n2: byte;
begin
Result := 0;
if n >= 100 then Exit;
n1 := n div 10;
n2 := n mod 10;
Result := n1 * 16 + n2;
end;
// ТЭКОН может использовать ту же самую CRC с полиномом $A001, что и УБЗ
// А может ограничиться тупой суммой по модулю 256
// EN по модулю 256
function Tecon_CalcCRC(const buf: array of Byte; Len: int): Byte;
var i, n, CRC: int;
begin
CRC := 0;
if buf[0] = $68 then
n := 4
else
n := 1;
for i := n to Len - 1 do
CRC := (CRC + buf[i]) and $FFFF;
Result := CRC and $FF;
end;
procedure Tecon_CRC(var buf: array of Byte; Len: int);
begin
buf[Len] := Tecon_CalcCRC(buf, Len);
buf[Len + 1] := $16;
end;
function Tecon_ValidateMsg(const buf: array of Byte; Len: int): bool;
begin
Result := false;
if (Len < 2) or (Len > Length(buf)) then Exit;
if not buf[0] in [$10, $68] then Exit;
if buf[Len - 1] <> $16 then Exit;
if buf[0] = $68 then
begin
// 68 LL+2 LL+2 68 0Р Адрес ХХо..ХХn КС 16
if Len < 9 then Exit;
if buf[3] <> $68 then Exit;
// if (buf[4] and $F0) > 0 then Exit;
if buf[1] <> buf[2] then Exit;
if Len <> 6 + buf[1] then Exit;
Result := true;
end
else
if buf[0] = $10 then
begin
// 10 0Р Адрес ХХ0 ХХ1 ХХ2 ХХ3 КС 16
if Len < 6 then Exit;
if (buf[1] and $F0) > 0 then Exit;
Result := true;
end;
end;
function Tecon_CheckCRC(const buf: array of Byte; Len: int): bool;
begin
Result := false;
// предполагается, что мы проверяем прием
// у приема подписывается все, включая номер пакета, не подписывется только заголовок "10" или "68 LL+2 LL+2 68"
// Особый случай, квитанция Ok - $A2 и квитанция Error - $E5
if (Len = 1) and (buf[0] in [$A2, $E5]) then
begin
Result := true;
Exit;
end;
// предварительно имеет смысл провести валидацию, корректна ли посылка
if not Tecon_ValidateMsg(buf, Len) then Exit;
Result := Tecon_CalcCRC(buf, Len - 2) = buf[Len - 2];
end;
procedure Tecon_ReplyAuthorization(var bufs: TTwoBuffers);
begin
bufs.BufSend[0] := $10;
bufs.BufSend[1] := $40;
bufs.BufSend[2] := bufs.BufRec[7];
bufs.BufSend[3] := $1B;
bufs.BufSend[4] := 0;
bufs.BufSend[5] := 0;
bufs.BufSend[6] := 0;
Tecon_CRC(bufs.BufSend, 7);
bufs.LengthSend := 9;
end;
function Tecon_CheckK105Authorization(buf: array of Byte; Len: int): bool;
begin
Result := (Len = 14) and Tecon_CheckCRC(buf, Len) and
(buf[0] = $68) and (buf[1] = $08) // заголовок
and (buf[6] = $1B); // 1В - функция авторизации
end;
function Tecon_CheckReplyLength(buf: array of Byte; len: int; lens: SetOfInt): bool;
begin
Result := (buf[1] = buf[2])
and (buf[1] > 2)
and ( (lens = []) or (buf[1] in lens) )
and (len = buf[1] + 6); // buf[1] - номер преобразователя + длина данных + CRC. 6 - это заголовок, номер посылки и 0x16 в конце
end;
function Tecon_CheckCommonPrmReply(buf: array of Byte; Len: int): bool;
begin
Result := Tecon_CheckCRC(buf, Len) and
(buf[0] = $68) and (buf[3] = $68) // заголовок
and (buf[4] and $F0 = 0); // номер запроса в формате $0P
end;
function Tecon_CheckCurrentsPrmReply(buf: array of Byte; Len: int): bool;
begin
Result := Tecon_CheckCommonPrmReply(buf, len)
and Tecon_CheckReplyLength(buf, len, [$03, $04, $06]);
end;
function Tecon_CheckArchPrmReply(buf: array of Byte; Len: int): bool;
begin
Result := Tecon_CheckCommonPrmReply(buf, len)
and Tecon_CheckReplyLength(buf, len, [])
and (buf[1] mod 4 = 2);
end;
function Tecon_CheckCurrentsPrmReplyCOM(buf: array of Byte; Len: int): bool;
begin
Result := Tecon_CheckCRC(buf, Len)
and (Len = 9)
and (buf[0] = $10) and (buf[1] = 0);
end;
function Tecon_CheckPrmReply(buf: array of Byte; Len: int): bool;
begin
Result := Tecon_CheckCurrentsPrmReplyCOM(buf, len)
or Tecon_CheckCurrentsPrmReply(buf, len)
or Tecon_CheckArchPrmReply(buf, len);
end;
end.
|
{ ***************************************************************************
Copyright (c) 2013-2018 Kike Pérez
Unit : Quick.ImageFX.GR32
Description : Image manipulation with GR32
Author : Kike Pérez
Version : 3.0
Created : 10/04/2013
Modified : 26/02/2018
This file is part of QuickImageFX: https://github.com/exilon/QuickImageFX
Third-party libraries used:
Graphics32 (https://github.com/graphics32/graphics32)
CCR-Exif from Chris Rolliston (https://code.google.com/archive/p/ccr-exif)
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.ImageFX.GR32;
interface
uses
Windows,
Classes,
Controls,
Vcl.ImgList,
System.SysUtils,
Vcl.Graphics,
Winapi.ShellAPI,
System.Math,
GR32,
GR32_Resamplers,
GR32_Image,
GR32_Filters,
GR32_Transforms,
GR32_Math,
System.Net.HttpClient,
GDIPAPI,
GDIPOBJ,
GDIPUTIL,
Vcl.Imaging.pngimage,
Vcl.Imaging.jpeg,
Vcl.Imaging.GIFImg,
Quick.Base64,
Quick.ImageFX.Base,
Quick.ImageFX.Types;
const
MaxPixelCountA = MaxInt Div SizeOf (TRGBQuad);
type
TImageFormat = (ifBMP, ifJPG, ifPNG, ifGIF);
TScanlineMode = (smHorizontal, smVertical);
PRGBAArray = ^TRGBAArray;
TRGBAArray = Array [0..MaxPixelCountA -1] Of TRGBQuad;
PGPColorArr = ^TGPColorArr;
TGPColorArr = array[0..500] of TGPColor;
pRGBQuadArray = ^TRGBQuadArray;
TRGBQuadArray = ARRAY [0 .. $EFFFFFF] OF TRGBQuad;
TRGBArray = ARRAY[0..32767] OF TRGBTriple;
pRGBArray = ^TRGBArray;
TImageFX = class(TImageFXBase)
private
fBitmap : TBitmap32;
procedure InitBitmap(var bmp : TBitmap);
procedure CleanTransparentPng(var png: TPngImage; NewWidth, NewHeight: Integer);
procedure DoScanlines(ScanlineMode : TScanlineMode);
function ResizeImage(w, h : Integer; ResizeOptions : TResizeOptions) : TImageFX;
procedure GPBitmapToBitmap(gpbmp : TGPBitmap; bmp : TBitmap32);
function GetFileInfo(AExt : string; var AInfo : TSHFileInfo; ALargeIcon : Boolean = false) : boolean;
procedure SetPixelImage(const x, y: Integer; const P: TPixelInfo; bmp32 : TBitmap32);
function GetPixelImage(const x, y: Integer; bmp32 : TBitmap32): TPixelInfo;
protected
function GetPixel(const x, y: Integer): TPixelInfo;
procedure SetPixel(const x, y: Integer; const P: TPixelInfo);
public
property AsBitmap32 : TBitmap32 read fBitmap write fBitmap;
constructor Create; overload; override;
constructor Create(fromfile : string); overload;
destructor Destroy; override;
function NewBitmap(w, h : Integer) : TImageFx;
property Pixel[const x, y: Integer]: TPixelInfo read GetPixel write SetPixel;
function LoadFromFile(fromfile : string; CheckIfFileExists : Boolean = False) : TImageFX;
function LoadFromStream(stream : TStream) : TImageFX;
function LoadFromString(str : string) : TImageFX;
function LoadFromImageList(imgList : TImageList; ImageIndex : Integer) : TImageFX;
function LoadFromIcon(Icon : TIcon) : TImageFX;
function LoadFromFileIcon(FileName : string; IconIndex : Word) : TImageFX;
function LoadFromFileExtension(aFilename : string; LargeIcon : Boolean) : TImageFX;
function LoadFromResource(ResourceName : string) : TImageFX;
function LoadFromHTTP(urlImage : string; out HTTPReturnCode : Integer; RaiseExceptions : Boolean = False) : TImageFX;
procedure GetResolution(var x,y : Integer); overload;
function GetResolution : string; overload;
function AspectRatio : Double;
function AspectRatioStr : string;
class function GetAspectRatio(cWidth, cHeight : Integer) : string;
function Clear : TImageFX;
function Resize(w, h : Integer) : TImageFX; overload;
function Resize(w, h : Integer; ResizeMode : TResizeMode; ResizeFlags : TResizeFlags = []; ResampleMode : TResamplerMode = rsLinear) : TImageFX; overload;
function Draw(png : TPngImage; alpha : Double = 1) : TImageFX; overload;
function Draw(png : TPngImage; x, y : Integer; alpha : Double = 1) : TImageFX; overload;
function Draw(stream: TStream; x: Integer; y: Integer; alpha: Double = 1) : TImageFX; overload;
function DrawCentered(png : TPngImage; alpha : Double = 1) : TImageFX; overload;
function DrawCentered(stream: TStream; alpha : Double = 1) : TImageFX; overload;
function Rotate90 : TImageFX;
function Rotate180 : TImageFX;
function Rotate270 : TImageFX;
function RotateAngle(RotAngle : Single) : TImageFX;
function FlipX : TImageFX;
function FlipY : TImageFX;
function GrayScale : TImageFX;
function ScanlineH : TImageFX;
function ScanlineV : TImageFX;
function Lighten(StrenghtPercent : Integer = 30) : TImageFX;
function Darken(StrenghtPercent : Integer = 30) : TImageFX;
function Tint(mColor : TColor) : TImageFX;
function TintAdd(R, G , B : Integer) : TImageFX;
function TintBlue : TImageFX;
function TintRed : TImageFX;
function TintGreen : TImageFX;
function Solarize : TImageFX;
function Rounded(RoundLevel : Integer = 27) : TImageFX;
function AntiAliasing : TImageFX;
function SetAlpha(Alpha : Byte) : TImageFX;
procedure SaveToPNG(outfile : string);
procedure SaveToJPG(outfile : string);
procedure SaveToBMP(outfile : string);
procedure SaveToGIF(outfile : string);
function AsBitmap : TBitmap;
function AsPNG : TPngImage;
function AsJPG : TJpegImage;
function AsGIF : TGifImage;
function AsString(imgFormat : TImageFormat = ifJPG) : string;
procedure SaveToStream(stream : TStream; imgFormat : TImageFormat = ifJPG);
end;
implementation
constructor TImageFX.Create;
begin
inherited Create;
fBitmap := TBitmap32.Create;
end;
procedure TImageFX.InitBitmap(var bmp : TBitmap);
begin
bmp.PixelFormat := pf32bit;
bmp.HandleType := bmDIB;
bmp.AlphaFormat := afDefined;
end;
constructor TImageFX.Create(fromfile: string);
begin
Create;
LoadFromFile(fromfile);
end;
destructor TImageFX.Destroy;
begin
if Assigned(fBitmap) then fBitmap.Free;
inherited;
end;
{function TImageFX.LoadFromFile(fromfile: string) : TImageFX;
var
fs: TFileStream;
FirstBytes: AnsiString;
Graphic: TGraphic;
bmp : TBitmap;
begin
Result := Self;
if not FileExists(fromfile) then
begin
fLastResult := arFileNotExist;
Exit;
end;
Graphic := nil;
fs := TFileStream.Create(fromfile, fmOpenRead);
try
SetLength(FirstBytes, 8);
fs.Read(FirstBytes[1], 8);
if Copy(FirstBytes, 1, 2) = 'BM' then
begin
Graphic := TBitmap.Create;
end else
if FirstBytes = #137'PNG'#13#10#26#10 then
begin
Graphic := TPngImage.Create;
end else
if Copy(FirstBytes, 1, 3) = 'GIF' then
begin
Graphic := TGIFImage.Create;
end else
if Copy(FirstBytes, 1, 2) = #$FF#$D8 then
begin
Graphic := TJPEGImage.Create;
end;
if Assigned(Graphic) then
begin
try
fs.Seek(0, soFromBeginning);
Graphic.LoadFromStream(fs);
bmp := TBitmap.Create;
try
InitBitmap(bmp);
bmp.Assign(Graphic);
fBitmap.Assign(bmp);
fLastResult := arOk;
finally
bmp.Free;
end;
except
end;
Graphic.Free;
end;
finally
fs.Free;
end;
end;}
function TImageFX.LoadFromFile(fromfile: string; CheckIfFileExists : Boolean = False) : TImageFX;
var
GPBitmap : TGPBitmap;
Status : TStatus;
PropItem : PPropertyItem;
PropSize: UINT;
Orientation : PWORD;
begin
Result := Self;
if (CheckIfFileExists) and (not FileExists(fromfile)) then
begin
LastResult := arFileNotExist;
Exit;
end;
GPBitmap := TGPBitmap.Create(fromfile);
try
//read EXIF orientation to rotate if needed
PropSize := GPBitmap.GetPropertyItemSize(PropertyTagOrientation);
GetMem(PropItem,PropSize);
try
Status := GPBitmap.GetPropertyItem(PropertyTagOrientation,PropSize,PropItem);
if Status = TStatus.Ok then
begin
Orientation := PWORD(PropItem^.Value);
case Orientation^ of
6 : GPBitmap.RotateFlip(Rotate90FlipNone);
8 : GPBitmap.RotateFlip(Rotate270FlipNone);
3 : GPBitmap.RotateFlip(Rotate180FlipNone);
end;
end;
finally
FreeMem(PropItem);
end;
GPBitmapToBitmap(GPBitmap,fBitmap);
LastResult := arOk;
finally
GPBitmap.Free;
end;
end;
function TImageFX.LoadFromStream(stream: TStream) : TImageFX;
var
Graphic : TGraphic;
GraphicClass : TGraphicClass;
begin
Result := Self;
if (not Assigned(stream)) or (stream.Size < 1024) then
begin
LastResult := arZeroBytes;
Exit;
end;
stream.Seek(0,soBeginning);
if not FindGraphicClass(Stream, GraphicClass) then raise EInvalidGraphic.Create('Unknow Graphic format');
Graphic := GraphicClass.Create;
try
stream.Seek(0,soBeginning);
Graphic.LoadFromStream(stream);
fBitmap.Assign(Graphic);
//GetEXIFInfo(stream);
LastResult := arOk;
finally
Graphic.Free;
end;
end;
function TImageFX.LoadFromString(str: string) : TImageFX;
var
stream : TStringStream;
begin
Result := Self;
if str = '' then
begin
LastResult := arZeroBytes;
Exit;
end;
str := Base64Decode(str);
stream := TStringStream.Create(str);
try
fBitmap.LoadFromStream(stream);
LastResult := arOk;
finally
stream.Free;
end;
end;
function TImageFX.LoadFromFileIcon(FileName : string; IconIndex : Word) : TImageFX;
var
Icon : TIcon;
begin
Result := Self;
Icon := TIcon.Create;
try
Icon.Handle := ExtractAssociatedIcon(hInstance,pChar(FileName),IconIndex);
Icon.Transparent := True;
fBitmap.Assign(Icon);
finally
Icon.Free;
end;
end;
function TImageFX.LoadFromResource(ResourceName : string) : TImageFX;
var
icon : TIcon;
GPBitmap : TGPBitmap;
begin
Result := Self;
icon:=TIcon.Create;
try
icon.LoadFromResourceName(HInstance,ResourceName);
icon.Transparent:=True;
GPBitmap := TGPBitmap.Create(Icon.Handle);
try
GPBitmapToBitmap(GPBitmap,fBitmap);
finally
if Assigned(GPBitmap) then GPBitmap.Free;
end;
finally
icon.Free;
end;
//png:=TPngImage.CreateBlank(COLOR_RGBALPHA,16,Icon.Width,Icon.Height);
//png.Canvas.Draw(0,0,Icon);
//DrawIcon(png.Canvas.Handle, 0, 0, Icon.Handle);
end;
function TImageFX.LoadFromImageList(imgList : TImageList; ImageIndex : Integer) : TImageFX;
var
icon : TIcon;
begin
Result := Self;
//imgList.ColorDepth := cd32bit;
//imgList.DrawingStyle := dsTransparent;
icon := TIcon.Create;
try
imgList.GetIcon(ImageIndex,icon);
fBitmap.Assign(Icon);
finally
icon.Free;
end;
end;
function TImageFX.LoadFromIcon(Icon : TIcon) : TImageFX;
begin
Result := Self;
fBitmap.Assign(Icon);
end;
function TImageFX.LoadFromFileExtension(aFilename : string; LargeIcon : Boolean) : TImageFX;
var
icon : TIcon;
aInfo : TSHFileInfo;
begin
Result := Self;
LastResult := arUnknowFmtType;
if GetFileInfo(ExtractFileExt(aFilename),aInfo,LargeIcon) then
begin
icon := TIcon.Create;
try
Icon.Handle := AInfo.hIcon;
Icon.Transparent := True;
fBitmap.Assign(Icon);
LastResult := arOk;
finally
icon.Free;
DestroyIcon(aInfo.hIcon);
end;
end;
end;
function TImageFX.LoadFromHTTP(urlImage : string; out HTTPReturnCode : Integer; RaiseExceptions : Boolean = False) : TImageFX;
var
http : THTTPClient;
ms : TMemoryStream;
pic : TGraphic;
begin
Result := Self;
HTTPReturnCode := 500;
LastResult := arUnknowFmtType;
ms := GetHTTPStream(urlImage,HTTPReturnCode);
try
if urlImage.EndsWith('.jpg',True) then pic := TJPEGImage.Create
else if urlImage.EndsWith('.png',True) then pic := TPngImage.Create
else if urlImage.EndsWith('.bmp',True) then pic := TBitmap.Create
else if urlImage.EndsWith('.gif',True) then pic := TGIFImage.Create
else raise Exception.Create('Unknow Format');
try
pic.LoadFromStream(ms);
fBitmap.Assign(pic);
LastResult := arOk;
finally
pic.Free;
end;
finally
ms.Free;
end;
end;
function TImageFX.AspectRatio : Double;
begin
if Assigned(fBitmap) then Result := fBitmap.width / fBitmap.Height
else Result := 0;
end;
function TImageFX.AspectRatioStr : string;
begin
if Assigned(fBitmap) then
begin
Result := GetAspectRatio(fBitmap.Width,fBitmap.Height);
end
else Result := 'N/A';
end;
class function TImageFX.GetAspectRatio(cWidth, cHeight : Integer) : string;
var
ar : Integer;
begin
if cHeight = 0 then Exit;
ar := GCD(cWidth,cHeight);
Result := Format('%d:%d',[cWidth div ar, cHeight div ar]);
end;
function Lerp(a, b: Byte; t: Double): Byte;
var
tmp: Double;
begin
tmp := t*a + (1-t)*b;
if tmp<0 then result := 0 else
if tmp>255 then result := 255 else
result := Round(tmp);
end;
procedure TImageFX.GetResolution(var x,y : Integer);
begin
if Assigned(fBitmap) then
begin
x := fBitmap.Width;
y := fBitmap.Height;
LastResult := arOk;
end
else
begin
x := -1;
y := -1;
LastResult := arCorruptedData;
end;
end;
function TImageFX.GetResolution : string;
begin
if Assigned(fBitmap) then
begin
Result := Format('%d x %d',[fBitmap.Width,fBitmap.Height]);
LastResult := arOk;
end
else
begin
Result := 'N/A';
LastResult := arCorruptedData;
end;
end;
function TImageFX.Clear : TImageFX;
begin
Result := Self;
fBitmap.Clear;
fBitmap.FillRect(0,0,fBitmap.Width,fBitmap.Height,Color32(clNone));
LastResult := arOk;
end;
function TImageFX.ResizeImage(w, h : Integer; ResizeOptions : TResizeOptions) : TImageFX;
var
bmp32 : TBitmap32;
Resam : TCustomResampler;
srcRect,
tgtRect : TRect;
crop : Integer;
srcRatio : Double;
nw, nh : Integer;
begin
Result := Self;
LastResult := arResizeError;
if (not Assigned(fBitmap)) or ((fBitmap.Width * fBitmap.Height) = 0) then
begin
LastResult := arZeroBytes;
Exit;
end;
//if any value is 0, calculates proportionaly
if (w * h) = 0 then
begin
//scales max w or h
if ResizeOptions.ResizeMode = rmScale then
begin
if (h = 0) and (fBitmap.Height > fBitmap.Width) then
begin
h := w;
w := 0;
end;
end
else ResizeOptions.ResizeMode := rmFitToBounds;
begin
if w > h then
begin
nh := (w * fBitmap.Height) div fBitmap.Width;
h := nh;
nw := w;
end
else
begin
nw := (h * fBitmap.Width) div fBitmap.Height;
w := nw;
nh := h;
end;
end;
end;
case ResizeOptions.ResizeMode of
rmScale: //recalculate width or height target size to preserve original aspect ratio
begin
if fBitmap.Width > fBitmap.Height then
begin
nh := (w * fBitmap.Height) div fBitmap.Width;
h := nh;
nw := w;
end
else
begin
nw := (h * fBitmap.Width) div fBitmap.Height;
w := nw;
nh := h;
end;
srcRect := Rect(0,0,fBitmap.Width,fBitmap.Height);
end;
rmCropToFill: //preserve target aspect ratio cropping original image to fill whole size
begin
nw := w;
nh := h;
crop := Round(h / w * fBitmap.Width);
if crop < fBitmap.Height then
begin
//target image is wider, so crop top and bottom
srcRect.Left := 0;
srcRect.Top := (fBitmap.Height - crop) div 2;
srcRect.Width := fBitmap.Width;
srcRect.Height := crop;
end
else
begin
//target image is narrower, so crop left and right
crop := Round(w / h * fBitmap.Height);
srcRect.Left := (fBitmap.Width - crop) div 2;
srcRect.Top := 0;
srcRect.Width := crop;
srcRect.Height := fBitmap.Height;
end;
end;
rmFitToBounds: //resize image to fit max bounds of target size
begin
srcRatio := fBitmap.Width / fBitmap.Height;
if fBitmap.Width > fBitmap.Height then
begin
nw := w;
nh := Round(w / srcRatio);
if nh > h then //too big
begin
nh := h;
nw := Round(h * srcRatio);
end;
end
else
begin
nh := h;
nw := Round(h * srcRatio);
if nw > w then //too big
begin
nw := w;
nh := Round(w / srcRatio);
end;
end;
srcRect := Rect(0,0,fBitmap.Width,fBitmap.Height);
end;
else
begin
nw := w;
nh := h;
srcRect := Rect(0,0,fBitmap.Width,fBitmap.Height);
end;
end;
//if image is smaller no upsizes
if ResizeOptions.NoMagnify then
begin
if (fBitmap.Width < nw) or (fBitmap.Height < nh) then
begin
//if FitToBounds then preserve original size
if ResizeOptions.ResizeMode = rmFitToBounds then
begin
nw := fBitmap.Width;
nh := fBitmap.Height;
end
else
begin
//all cases no resizes, but CropToFill needs to grow to fill target size
if ResizeOptions.ResizeMode <> rmCropToFill then
begin
if ResizeOptions.SkipSmaller then
begin
LastResult := arAlreadyOptim;
nw := srcRect.Width;
nh := srcRect.Height;
w := nw;
h := nh;
end
else Exit;
end;
end;
end;
end;
if ResizeOptions.Center then
begin
tgtRect.Top := (h - nh) div 2;
tgtRect.Left := (w - nw) div 2;
tgtRect.Width := nw;
tgtRect.Height := nh;
end
else tgtRect := Rect(0,0,nw,nh);
//selects resampler algorithm
case ResizeOptions.ResamplerMode of
rsAuto :
begin
if (w < fBitmap.Width ) or (h < fBitmap.Height) then Resam := TDraftResampler.Create
else Resam := TLinearResampler.Create;
end;
rsNearest : Resam := TNearestResampler.Create;
rsGR32Draft : Resam := TDraftResampler.Create;
rsGR32Kernel : Resam := TKernelResampler.Create;
rsLinear : Resam := TLinearResampler.Create;
else Resam := TKernelResampler.Create;
end;
try
bmp32 := TBitmap32.Create;
try
bmp32.Width := w;
bmp32.Height := h;
if ResizeOptions.FillBorders then bmp32.FillRect(0,0,w,h,Color32(ResizeOptions.BorderColor));
StretchTransfer(bmp32,tgtRect,tgtRect,fBitmap,srcRect,Resam,dmOpaque,nil);
try
fBitmap.Assign(bmp32);
LastResult := arOk;
except
LastResult := arCorruptedData;
end;
finally
bmp32.Free;
end;
finally
Resam.Free;
end;
end;
function TImageFX.Resize(w, h : Integer) : TImageFX;
begin
Result := ResizeImage(w,h,ResizeOptions);
end;
function TImageFX.Resize(w, h : Integer; ResizeMode : TResizeMode; ResizeFlags : TResizeFlags = []; ResampleMode : TResamplerMode = rsLinear) : TImageFX;
var
ResizeOptions : TResizeOptions;
begin
ResizeOptions := TResizeOptions.Create;
try
if (rfNoMagnify in ResizeFlags) then ResizeOptions.NoMagnify := True else ResizeOptions.NoMagnify := False;
if (rfCenter in ResizeFlags) then ResizeOptions.Center := True else ResizeOptions.Center := False;
if (rfFillBorders in ResizeFlags) then ResizeOptions.FillBorders := True else ResizeOptions.FillBorders := False;
Result := ResizeImage(w,h,ResizeOptions);
finally
ResizeOptions.Free;
end;
end;
function TImageFX.Draw(png : TPngImage; alpha : Double = 1) : TImageFX;
begin
Result := Self;
Draw(png, (fBitmap.Width - png.Width) div 2, (fBitmap.Height - png.Height) div 2);
end;
function TImageFX.Draw(png : TPngImage; x, y : Integer; alpha : Double = 1) : TImageFX;
begin
Result := Self;
fBitmap.DrawMode := TDrawMode.dmTransparent;
fBitmap.Canvas.Draw(x,y,png);
end;
function TImageFX.Draw(stream: TStream; x: Integer; y: Integer; alpha: Double = 1) : TImageFX;
var
overlay : TPngImage;
Buffer : TBytes;
Size : Int64;
begin
//get overlay image
overlay.LoadFromStream(stream);
//needs x or y center image
if x = -1 then x := (fBitmap.Width - overlay.Width) div 2;
if y = -1 then y := (fBitmap.Height - overlay.Height) div 2;
Result := Draw(overlay,x,y,alpha);
end;
function TImageFX.DrawCentered(png : TPngImage; alpha : Double = 1) : TImageFX;
begin
Result := Draw(png,(fBitmap.Width - png.Width) div 2, (fBitmap.Height - png.Height) div 2,alpha);
end;
function TImageFX.DrawCentered(stream: TStream; alpha : Double = 1) : TImageFX;
begin
Result := Draw(stream,-1,-1,alpha);
end;
function TImageFX.NewBitmap(w, h: Integer): TImageFx;
begin
if Assigned(Self.fBitmap) then
begin
Self.fBitmap.Clear;
Self.fBitmap.SetSize(w, h);
end
else Result := Self;
end;
function TImageFX.Rotate90 : TImageFX;
var
bmp32 : TBitmap32;
begin
Result := Self;
LastResult := arRotateError;
bmp32 := TBitmap32.Create;
try
bmp32.Assign(fBitmap);
bmp32.Rotate90(fBitmap);
LastResult := arOk;
finally
bmp32.Free;
end;
end;
function TImageFX.Rotate180 : TImageFX;
var
bmp32 : TBitmap32;
begin
Result := Self;
LastResult := arRotateError;
bmp32 := TBitmap32.Create;
try
bmp32.Assign(fBitmap);
bmp32.Rotate180(fBitmap);
LastResult := arOk;
finally
bmp32.Free;
end;
end;
function TImageFX.RotateAngle(RotAngle: Single) : TImageFX;
var
SrcR: Integer;
SrcB: Integer;
T: TAffineTransformation;
Sn, Cn: TFloat;
Sx, Sy, Scale: Single;
bmp32 : TBitmap32;
begin
Result := Self;
LastResult := arRotateError;
//SetBorderTransparent(fBitmap, fBitmap.BoundsRect);
SrcR := fBitmap.Width - 1;
SrcB := fBitmap.Height - 1;
T := TAffineTransformation.Create;
T.SrcRect := FloatRect(0, 0, SrcR + 1, SrcB + 1);
try
// shift the origin
T.Clear;
// move the origin to a center for scaling and rotation
T.Translate(-SrcR * 0.5, -SrcB * 0.5);
T.Rotate(0, 0, RotAngle);
RotAngle := RotAngle * PI / 180;
// get the width and height of rotated image (without scaling)
GR32_Math.SinCos(RotAngle, Sn, Cn);
Sx := Abs(SrcR * Cn) + Abs(SrcB * Sn);
Sy := Abs(SrcR * Sn) + Abs(SrcB * Cn);
// calculate a new scale so that the image fits in original boundaries
Sx := fBitmap.Width / Sx;
Sy := fBitmap.Height / Sy;
Scale := Min(Sx, Sy);
T.Scale(Scale);
// move the origin back
T.Translate(SrcR * 0.5, SrcB * 0.5);
// transform the bitmap
bmp32 := TBitmap32.Create;
bmp32.SetSize(fBitmap.Width,fBitmap.Height);
try
//bmp32.Clear(clBlack32);
Transform(bmp32, fBitmap, T);
fBitmap.Assign(bmp32);
LastResult := arOk;
finally
bmp32.Free;
end;
finally
T.Free;
end;
end;
function TImageFX.Rotate270 : TImageFX;
var
bmp32 : TBitmap32;
begin
Result := Self;
LastResult := arRotateError;
bmp32 := TBitmap32.Create;
try
bmp32.Assign(fBitmap);
bmp32.Rotate270(fBitmap);
LastResult := arOk;
finally
bmp32.Free;
end;
end;
function TImageFX.FlipX : TImageFX;
var
bmp32 : TBitmap32;
begin
Result := Self;
LastResult := arRotateError;
bmp32 := TBitmap32.Create;
try
bmp32.Assign(fBitmap);
bmp32.FlipHorz(fBitmap);
LastResult := arOk;
finally
bmp32.Free;
end;
end;
function TImageFX.FlipY : TImageFX;
var
bmp32 : TBitmap32;
begin
Result := Self;
LastResult := arRotateError;
bmp32 := TBitmap32.Create;
try
bmp32.Assign(fBitmap);
bmp32.FlipVert(fBitmap);
LastResult := arOk;
finally
bmp32.Free;
end;
end;
function TImageFX.GrayScale : TImageFX;
begin
Result := Self;
LastResult := arColorizeError;
ColorToGrayScale(fBitmap,fBitmap,True);
LastResult := arOk;
end;
function TImageFX.Lighten(StrenghtPercent : Integer = 30) : TImageFX;
var
Bits: PColor32Entry;
I, J: Integer;
begin
Result := Self;
LastResult := arColorizeError;
Bits := @fBitmap.Bits[0];
fBitmap.BeginUpdate;
try
for I := 0 to fBitmap.Height - 1 do
begin
for J := 0 to fBitmap.Width - 1 do
begin
if Bits.R + 5 < 255 then Bits.R := Bits.R + 5;
if Bits.G + 5 < 255 then Bits.G := Bits.G + 5;
if Bits.B + 5 < 255 then Bits.B := Bits.B + 5;
Inc(Bits);
end;
end;
LastResult := arOk;
finally
fBitmap.EndUpdate;
fBitmap.Changed;
end;
end;
function TImageFX.Darken(StrenghtPercent : Integer = 30) : TImageFX;
var
Bits: PColor32Entry;
I, J: Integer;
Percent: Single;
Brightness: Integer;
begin
Result := Self;
LastResult := arColorizeError;
Percent := (100 - StrenghtPercent) / 100;
Bits := @fBitmap.Bits[0];
fBitmap.BeginUpdate;
try
for I := 0 to fBitmap.Height - 1 do
begin
for J := 0 to fBitmap.Width - 1 do
begin
Brightness := Round((Bits.R+Bits.G+Bits.B)/765);
Bits.R := Lerp(Bits.R, Brightness, Percent);
Bits.G := Lerp(Bits.G, Brightness, Percent);
Bits.B := Lerp(Bits.B, Brightness, Percent);
Inc(Bits);
end;
end;
LastResult := arOk;
finally
fBitmap.EndUpdate;
fBitmap.Changed;
end;
end;
function TImageFX.Tint(mColor : TColor) : TImageFX;
var
Bits: PColor32Entry;
Color: TColor32Entry;
I, J: Integer;
Percent: Single;
Brightness: Single;
begin
Result := Self;
LastResult := arColorizeError;
Color.ARGB := Color32(mColor);
Percent := 10 / 100;
Bits := @fBitmap.Bits[0];
fBitmap.BeginUpdate;
try
for I := 0 to fBitmap.Height - 1 do
begin
for J := 0 to fBitmap.Width - 1 do
begin
Brightness := (Bits.R+Bits.G+Bits.B)/765;
Bits.R := Lerp(Bits.R, Round(Brightness * Color.R), Percent);
Bits.G := Lerp(Bits.G, Round(Brightness * Color.G), Percent);
Bits.B := Lerp(Bits.B, Round(Brightness * Color.B), Percent);
Inc(Bits);
end;
end;
LastResult := arOk;
finally
fBitmap.EndUpdate;
fBitmap.Changed;
end;
end;
function TImageFX.TintAdd(R, G , B : Integer) : TImageFX;
var
Bits: PColor32Entry;
I, J: Integer;
begin
Result := Self;
LastResult := arColorizeError;
Bits := @fBitmap.Bits[0];
fBitmap.BeginUpdate;
try
for I := 0 to fBitmap.Height - 1 do
begin
for J := 0 to fBitmap.Width - 1 do
begin
//Brightness := (Bits.R+Bits.G+Bits.B)/765;
if R > -1 then Bits.R := Bits.R + R;
if G > -1 then Bits.G := Bits.G + G;
if B > -1 then Bits.B := Bits.B + B;
Inc(Bits);
end;
end;
LastResult := arOk;
finally
fBitmap.EndUpdate;
fBitmap.Changed;
end;
end;
function TImageFX.TintBlue : TImageFX;
begin
Result := Tint(clBlue);
end;
function TImageFX.TintRed : TImageFX;
begin
Result := Tint(clRed);
end;
function TImageFX.TintGreen : TImageFX;
begin
Result := Tint(clGreen);
end;
function TImageFX.Solarize : TImageFX;
begin
Result := TintAdd(255,-1,-1);
end;
function TImageFX.ScanlineH;
begin
Result := Self;
DoScanLines(smHorizontal);
end;
function TImageFX.ScanlineV;
begin
Result := Self;
DoScanLines(smVertical);
end;
procedure TImageFX.DoScanLines(ScanLineMode : TScanlineMode);
var
Bits: PColor32Entry;
Color: TColor32Entry;
I, J: Integer;
DoLine : Boolean;
begin
LastResult := arColorizeError;
Color.ARGB := Color32(clBlack);
Bits := @fBitmap.Bits[0];
fBitmap.BeginUpdate;
try
for I := 0 to fBitmap.Height - 1 do
begin
for J := 0 to fBitmap.Width - 1 do
begin
DoLine := False;
if ScanLineMode = smHorizontal then
begin
if Odd(I) then DoLine := True;
end
else
begin
if Odd(J) then DoLine := True;
end;
if DoLine then
begin
Bits.R := Round(Bits.R-((Bits.R/255)*100));;// Lerp(Bits.R, Round(Brightness * Color.R), Percent);
Bits.G := Round(Bits.G-((Bits.G/255)*100));;//Lerp(Bits.G, Round(Brightness * Color.G), Percent);
Bits.B := Round(Bits.B-((Bits.B/255)*100));;//Lerp(Bits.B, Round(Brightness * Color.B), Percent);
end;
Inc(Bits);
end;
end;
LastResult := arOk;
finally
fBitmap.EndUpdate;
fBitmap.Changed;
end;
end;
procedure TImageFX.SaveToPNG(outfile : string);
var
png : TPngImage;
begin
LastResult := arConversionError;
png := AsPNG;
try
png.SaveToFile(outfile);
finally
png.Free;
end;
LastResult := arOk;
end;
procedure TImageFX.SaveToJPG(outfile : string);
var
jpg : TJPEGImage;
begin
LastResult := arConversionError;
jpg := AsJPG;
try
jpg.SaveToFile(outfile);
finally
jpg.Free;
end;
LastResult := arOk;
end;
procedure TImageFX.SaveToBMP(outfile : string);
var
bmp : TBitmap;
begin
LastResult := arConversionError;
bmp := AsBitmap;
try
bmp.SaveToFile(outfile);
finally
bmp.Free;
end;
LastResult := arOk;
end;
procedure TImageFX.SaveToGIF(outfile : string);
var
gif : TGIFImage;
begin
LastResult := arConversionError;
gif := AsGIF;
try
gif.SaveToFile(outfile);
finally
gif.Free;
end;
LastResult := arOk;
end;
procedure TImageFX.SaveToStream(stream : TStream; imgFormat : TImageFormat = ifJPG);
var
graf : TGraphic;
begin
case imgFormat of
ifBMP:
begin
graf := TBitmap.Create;
try
graf := Self.AsBitmap;
graf.SaveToStream(stream);
finally
graf.Free;
end;
end;
ifJPG:
begin
graf := TJPEGImage.Create;
try
graf := Self.AsJPG;
graf.SaveToStream(stream);
finally
graf.Free;
end;
end;
ifPNG:
begin
graf := TPngImage.Create;
try
graf := Self.AsPNG;
graf.SaveToStream(stream);
finally
graf.Free;
end;
end;
ifGIF:
begin
graf := TGIFImage.Create;
try
graf := Self.AsGIF;
graf.SaveToStream(stream);
finally
graf.Free;
end;
end;
end;
end;
procedure TImageFX.GPBitmapToBitmap(gpbmp : TGPBitmap; bmp : TBitmap32);
var
Graphics : TGPGraphics;
begin
//bmp.PixelFormat := pf32bit;
//bmp.HandleType := bmDIB;
//bmp.AlphaFormat := afDefined;
bmp.Width := gpbmp.GetWidth;
bmp.Height := gpbmp.GetHeight;
Graphics := TGPGraphics.Create(bmp.Canvas.Handle);
try
Graphics.Clear(ColorRefToARGB(ColorToRGB(clNone)));
// set the composition mode to copy
Graphics.SetCompositingMode(CompositingModeSourceCopy);
// set high quality rendering modes
Graphics.SetInterpolationMode(InterpolationModeHighQualityBicubic);
Graphics.SetPixelOffsetMode(PixelOffsetModeHighQuality);
Graphics.SetSmoothingMode(SmoothingModeHighQuality);
// draw the input image on the output in modified size
Graphics.DrawImage(gpbmp,0,0,gpbmp.GetWidth,gpbmp.GetHeight);
finally
Graphics.Free;
end;
end;
function TImageFX.GetFileInfo(AExt : string; var AInfo : TSHFileInfo; ALargeIcon : Boolean = False) : Boolean;
var uFlags : integer;
begin
FillMemory(@AInfo,SizeOf(TSHFileInfo),0);
uFlags := SHGFI_ICON+SHGFI_TYPENAME+SHGFI_USEFILEATTRIBUTES;
if ALargeIcon then uFlags := uFlags + SHGFI_LARGEICON
else uFlags := uFlags + SHGFI_SMALLICON;
if SHGetFileInfo(PChar(AExt),FILE_ATTRIBUTE_NORMAL,AInfo,SizeOf(TSHFileInfo),uFlags) = 0 then Result := False
else Result := True;
end;
function TImageFX.AsBitmap : TBitmap;
begin
LastResult := arConversionError;
Result := TBitmap.Create;
InitBitmap(Result);
Result.Assign(fBitmap);
LastResult := arOk;
end;
function TImageFX.AsPNG: TPngImage;
var
n, a: Integer;
PNB: TPngImage;
FFF: PRGBAArray;
AAA: pByteArray;
bmp : TBitmap;
begin
LastResult := arConversionError;
Result := TPngImage.CreateBlank(COLOR_RGBALPHA,16,fBitmap.Width,fBitmap.Height);
PNB := TPngImage.Create;
try
PNB.CompressionLevel := PNGCompressionLevel;
Result.CompressionLevel := PNGCompressionLevel;
bmp := AsBitmap;
try
PNB.Assign(bmp);
PNB.CreateAlpha;
for a := 0 to bmp.Height - 1 do
begin
FFF := bmp.ScanLine[a];
AAA := PNB.AlphaScanline[a];
for n := 0 to bmp.Width - 1 do
begin
AAA[n] := FFF[n].rgbReserved;
end;
end;
finally
bmp.Free;
end;
Result.Assign(PNB);
LastResult := arOk;
finally
PNB.Free;
end;
end;
function TImageFX.AsJPG : TJPEGImage;
var
jpg : TJPEGImage;
bmp : TBitmap;
begin
LastResult := arConversionError;
jpg := TJPEGImage.Create;
jpg.ProgressiveEncoding := ProgressiveJPG;
jpg.CompressionQuality := JPGQualityPercent;
bmp := AsBitmap;
try
jpg.Assign(bmp);
finally
bmp.Free;
end;
Result := jpg;
LastResult := arOk;
end;
function TImageFX.AsGIF : TGifImage;
var
gif : TGIFImage;
bmp : TBitmap;
begin
LastResult := arConversionError;
gif := TGIFImage.Create;
bmp := AsBitmap;
try
gif.Assign(bmp);
finally
bmp.Free;
end;
Result := gif;
LastResult := arOk;
end;
function TImageFX.AsString(imgFormat : TImageFormat = ifJPG) : string;
var
ss : TStringStream;
begin
LastResult := arConversionError;
ss := TStringStream.Create;
try
case imgFormat of
ifBMP : fBitmap.SaveToStream(ss);
ifJPG : Self.AsJPG.SaveToStream(ss);
ifPNG : Self.AsPNG.SaveToStream(ss);
ifGIF : Self.AsGIF.SaveToStream(ss);
else raise Exception.Create('Format unknow!');
end;
Result := Base64Encode(ss.DataString);
LastResult := arOk;
finally
ss.Free;
end;
end;
function TImageFX.GetPixel(const x, y: Integer): TPixelInfo;
begin
Result := GetPixelImage(x,y,fBitmap);
end;
procedure TImageFX.CleanTransparentPng(var png: TPngImage; NewWidth, NewHeight: Integer);
var
BasePtr: Pointer;
begin
png := TPngImage.CreateBlank(COLOR_RGBALPHA, 16, NewWidth, NewHeight);
BasePtr := png.AlphaScanline[0];
ZeroMemory(BasePtr, png.Header.Width * png.Header.Height);
end;
function TImageFX.Rounded(RoundLevel : Integer = 27) : TImageFX;
var
rgn : HRGN;
auxbmp : TBitmap;
begin
Result := Self;
auxbmp := TBitmap.Create;
try
auxbmp.Assign(fBitmap);
fBitmap.Clear($00FFFFFF);
with fBitmap.Canvas do
begin
Brush.Style:=bsClear;
//Brush.Color:=clTransp;
Brush.Color:=clNone;
FillRect(Rect(0,0,auxbmp.Width,auxbmp.Height));
rgn := CreateRoundRectRgn(0,0,auxbmp.width + 1,auxbmp.height + 1,RoundLevel,RoundLevel);
SelectClipRgn(Handle,rgn);
Draw(0,0,auxbmp);
DeleteObject(Rgn);
end;
//bmp32.Assign(auxbmp);
finally
FreeAndNil(auxbmp);
end;
end;
function TImageFX.AntiAliasing : TImageFX;
var
bmp : TBitmap;
begin
Result := Self;
bmp := TBitmap.Create;
try
//DoAntialias(fBitmap,bmp);
fBitmap.Assign(bmp);
finally
bmp.Free;
end;
end;
function TImageFX.SetAlpha(Alpha : Byte) : TImageFX;
begin
Result := Self;
//DoAlpha(fBitmap,Alpha);
end;
procedure TImageFX.SetPixel(const x, y: Integer; const P: TPixelInfo);
begin
SetPixelImage(x,y,P,fBitmap);
end;
procedure TImageFX.SetPixelImage(const x, y: Integer; const P: TPixelInfo; bmp32 : TBitmap32);
begin
bmp32.Pixel[x,y] := RGB(P.R,P.G,P.B);
end;
function TImageFX.GetPixelImage(const x, y: Integer; bmp32 : TBitmap32) : TPixelInfo;
var
lRGB : TRGB;
begin
lRGB := ColorToRGBValues(bmp32.Pixel[x,y]);
Result.R := lRGB.R;
Result.G := lRGB.G;
Result.B := lRGB.B;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLMirror<p>
Implements a basic, stencil-based mirror (as in Mark Kilgard's demo).<p>
It is strongly recommended to read and understand the explanations in the
materials/mirror demo before using this component.<p>
<b>History : </b><font size=-1><ul>
<li>23/08/10 - Yar - Added OpenGLTokens to uses, replaced OpenGL1x functions to OpenGLAdapter
<li>22/04/10 - Yar - Fixes after GLState revision
<li>05/03/10 - DanB - More state added to TGLStateCache
<li>15/12/08- Paul Robello - corrected call to FOnEndRenderingMirrors
<li>06/06/07 - DaStr - Added GLColor to uses (BugtrackerID = 1732211)
<li>30/03/07 - DaStr - Added $I GLScene.inc
<li>28/03/07 - DaStr - Renamed parameters in some methods
(thanks Burkhard Carstens) (Bugtracker ID = 1678658)
<li>18/07/04 - Orlando - added custom shapes
<li>13/02/03 - DanB - added TGLMirror.AxisAlignedDimensionsUnscaled
<li>13/11/02 - EG - Fixed TGLMirror.DoRender transform
<li>06/11/02 - EG - Fixed Stencil setup
<li>30/10/02 - EG - Added OnBegin/EndRenderingMirrors
<li>25/10/02 - EG - Fixed Stencil cleanup
<li>22/02/01 - EG - Fixed change notification,
Fixed special effects support (PFX, etc.)
<li>07/12/01 - EG - Creation
</ul></font>
}
unit GLMirror;
interface
{$I GLScene.inc}
uses
Classes,
GLScene, GLVectorGeometry, OpenGLAdapter, OpenGLTokens, GLContext,
GLMaterial, GLColor, GLRenderContextInfo,
GLState
, GLVectorTypes;
type
// TMirrorOptions
//
TMirrorOption = (moUseStencil, moOpaque, moMirrorPlaneClip, moClearZBuffer);
TMirrorOptions = set of TMirrorOption;
const
cDefaultMirrorOptions = [moUseStencil];
type
// TMirrorShapes ORL
TMirrorShapes = (msRect, msDisk);
// TGLMirror
//
{: A simple plane mirror.<p>
This mirror requires a stencil buffer for optimal rendering!<p>
The object is a mix between a plane and a proxy object, in that the plane
defines the mirror's surface, while the proxy part is used to reference
the objects that should be mirrored (it is legal to self-mirror, but no
self-mirror visuals will be rendered).<p>
It is strongly recommended to read and understand the explanations in the
materials/mirror demo before using this component. }
TGLMirror = class(TGLSceneObject)
private
{ Private Declarations }
FRendering: Boolean;
FMirrorObject: TGLBaseSceneObject;
FWidth, FHeight: TGLFloat;
FMirrorOptions: TMirrorOptions;
FOnBeginRenderingMirrors, FOnEndRenderingMirrors: TNotifyEvent;
FShape: TMirrorShapes; //ORL
FRadius: TGLFloat; //ORL
FSlices: TGLInt; //ORL
protected
{ Protected Declarations }
procedure Notification(AComponent: TComponent; Operation: TOperation);
override;
procedure SetMirrorObject(const val: TGLBaseSceneObject);
procedure SetMirrorOptions(const val: TMirrorOptions);
procedure ClearZBufferArea(aBuffer: TGLSceneBuffer);
procedure SetHeight(AValue: TGLFloat);
procedure SetWidth(AValue: TGLFloat);
procedure SetRadius(const aValue: Single); //ORL
procedure SetSlices(const aValue: TGLInt); //ORL
procedure SetShape(aValue: TMirrorShapes); //ORL
function GetRadius: single; //ORL
function GetSlices: TGLInt; //ORL
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
procedure DoRender(var ARci: TRenderContextInfo;
ARenderSelf, ARenderChildren: Boolean); override;
procedure BuildList(var ARci: TRenderContextInfo); override;
procedure Assign(Source: TPersistent); override;
function AxisAlignedDimensionsUnscaled: TVector; override;
published
{ Public Declarations }
{: Selects the object to mirror.<p>
If nil, the whole scene is mirrored. }
property MirrorObject: TGLBaseSceneObject read FMirrorObject write
SetMirrorObject;
{: Controls rendering options.<p>
<ul>
<li>moUseStencil: mirror area is stenciled, prevents reflected
objects to be visible on the sides of the mirror (stencil buffer
must be active in the viewer)
<li>moOpaque: mirror is opaque (ie. painted with background color)
<li>moMirrorPlaneClip: a ClipPlane is defined to prevent reflections
from popping out of the mirror (for objects behind or halfway through)
<li>moClearZBuffer: mirror area's ZBuffer is cleared so that background
objects don't interfere with reflected objects (reflected objects
must be rendered AFTER the mirror in the hierarchy). Works only
along with stenciling.
</ul>
}
property MirrorOptions: TMirrorOptions read FMirrorOptions write
SetMirrorOptions default cDefaultMirrorOptions;
property Height: TGLFloat read FHeight write SetHeight;
property Width: TGLFloat read FWidth write SetWidth;
{: Fired before the object's mirror images are rendered. }
property OnBeginRenderingMirrors: TNotifyEvent read FOnBeginRenderingMirrors
write FOnBeginRenderingMirrors;
{: Fired after the object's mirror images are rendered. }
property OnEndRenderingMirrors: TNotifyEvent read FOnEndRenderingMirrors
write FOnEndRenderingMirrors;
property Radius: TGLFloat read FRadius write SetRadius; //ORL
property Slices: TGLInt read FSlices write SetSlices default 16; //ORL
property Shape: TMirrorShapes read FShape write SetShape default msRect;
//ORL
end;
//-------------------------------------------------------------
//-------------------------------------------------------------
//-------------------------------------------------------------
implementation
//-------------------------------------------------------------
//-------------------------------------------------------------
//-------------------------------------------------------------
// ------------------
// ------------------ TGLMirror ------------------
// ------------------
// Create
//
constructor TGLMirror.Create(AOwner: Tcomponent);
begin
inherited Create(AOwner);
FWidth := 1;
FHeight := 1;
FMirrorOptions := cDefaultMirrorOptions;
ObjectStyle := ObjectStyle + [osDirectDraw];
Material.FrontProperties.Diffuse.Initialize(VectorMake(1, 1, 1, 0.1));
Material.BlendingMode := bmTransparency;
FRadius := 1; //ORL
FSlices := 16; //ORL
Shape := msRect; //ORL
end;
// DoRender
//
procedure TGLMirror.DoRender(var ARci: TRenderContextInfo;
ARenderSelf, ARenderChildren: Boolean);
var
oldProxySubObject: Boolean;
refMat, curMat, ModelMat: TMatrix;
clipPlane: TDoubleHmgPlane;
bgColor: TColorVector;
cameraPosBackup, cameraDirectionBackup: TVector;
CurrentBuffer: TGLSceneBuffer;
begin
if FRendering then
Exit;
FRendering := True;
try
oldProxySubObject := ARci.proxySubObject;
ARci.proxySubObject := True;
CurrentBuffer := TGLSceneBuffer(ARci.buffer);
if VectorDotProduct(VectorSubtract(ARci.cameraPosition, AbsolutePosition),
AbsoluteDirection) > 0 then
with ARci.GLStates do
begin
// "Render" stencil mask
if MirrorOptions <> [] then
begin
if (moUseStencil in MirrorOptions) then
begin
Enable(stStencilTest);
ARci.GLStates.StencilClearValue := 0;
GL.Clear(GL_STENCIL_BUFFER_BIT);
SetStencilFunc(cfAlways, 1, 1);
SetStencilOp(soReplace, soZero, soReplace);
end;
if (moOpaque in MirrorOptions) then
begin
bgColor := ConvertWinColor(CurrentBuffer.BackgroundColor);
ARci.GLStates.SetGLMaterialColors(cmFront, bgColor, clrBlack,
clrBlack, clrBlack, 0);
end
else
SetGLColorWriting(False);
Enable(stDepthTest);
DepthWriteMask := False;
BuildList(ARci);
DepthWriteMask := True;
if (moUseStencil in MirrorOptions) then
begin
SetStencilFunc(cfEqual, 1, 1);
SetStencilOp(soKeep, soKeep, soKeep);
end;
if (moClearZBuffer in MirrorOptions) then
ClearZBufferArea(CurrentBuffer);
if not (moOpaque in MirrorOptions) then
SetGLColorWriting(True);
end;
ARci.PipelineTransformation.Push;
ARci.PipelineTransformation.ModelMatrix := IdentityHmgMatrix;
Disable(stCullFace);
Enable(stNormalize);
if moMirrorPlaneClip in MirrorOptions then
begin
GL.Enable(GL_CLIP_PLANE0);
SetPlane(clipPlane, PlaneMake(AffineVectorMake(AbsolutePosition),
VectorNegate(AffineVectorMake(AbsoluteDirection))));
GL.ClipPlane(GL_CLIP_PLANE0, @clipPlane);
end;
// Mirror lights
refMat := MakeReflectionMatrix(
AffineVectorMake(AbsolutePosition),
AffineVectorMake(AbsoluteDirection));
curMat := MatrixMultiply(refMat, ARci.PipelineTransformation.ViewMatrix);
ARci.PipelineTransformation.ViewMatrix := curMat;
Scene.SetupLights(CurrentBuffer.LimitOf[limLights]);
// mirror geometry and render master
cameraPosBackup := ARci.cameraPosition;
cameraDirectionBackup := ARci.cameraDirection;
ARci.cameraPosition := VectorTransform(ARci.cameraPosition, refMat);
ARci.cameraDirection := VectorTransform(ARci.cameraDirection, refMat);
// temporary fix? (some objects don't respect culling options, or ?)
CullFaceMode := cmFront;
if Assigned(FOnBeginRenderingMirrors) then
FOnBeginRenderingMirrors(Self);
if Assigned(FMirrorObject) then
begin
ModelMat := IdentityHmgMatrix;
if FMirrorObject.Parent <> nil then
MatrixMultiply(ModelMat, FMirrorObject.Parent.AbsoluteMatrix, ModelMat);
MatrixMultiply(ModelMat, FMirrorObject.LocalMatrix^, ModelMat);
ARci.PipelineTransformation.ModelMatrix := ModelMat;
FMirrorObject.DoRender(ARci, ARenderSelf, FMirrorObject.Count > 0);
end
else
begin
Scene.Objects.DoRender(ARci, ARenderSelf, True);
end;
if Assigned(FOnEndRenderingMirrors) then
FOnEndRenderingMirrors(Self);
// Restore to "normal"
ARci.cameraPosition := cameraPosBackup;
ARci.cameraDirection := cameraDirectionBackup;
ARci.GLStates.CullFaceMode := cmBack;
ARci.PipelineTransformation.ReplaceFromStack;
Scene.SetupLights(CurrentBuffer.LimitOf[limLights]);
ARci.PipelineTransformation.Pop;
if moMirrorPlaneClip in MirrorOptions then
GL.Disable(GL_CLIP_PLANE0);
ARci.GLStates.Disable(stStencilTest);
ARci.proxySubObject := oldProxySubObject;
// start rendering self
if ARenderSelf then
begin
Material.Apply(ARci);
repeat
BuildList(ARci);
until not Material.UnApply(ARci);
end;
end;
if ARenderChildren then
Self.RenderChildren(0, Count - 1, ARci);
if Assigned(FMirrorObject) then
FMirrorObject.Effects.RenderPostEffects(ARci);
finally
FRendering := False;
end;
end;
// BuildList
//
procedure TGLMirror.BuildList(var ARci: TRenderContextInfo);
var
hw, hh: TGLFloat;
quadric: PGLUquadricObj;
begin
if msRect = FShape then
begin
hw := FWidth * 0.5;
hh := FHeight * 0.5;
GL.Normal3fv(@ZVector);
GL.Begin_(GL_QUADS);
GL.Vertex3f(hw, hh, 0);
GL.Vertex3f(-hw, hh, 0);
GL.Vertex3f(-hw, -hh, 0);
GL.Vertex3f(hw, -hh, 0);
GL.End_;
end
else
begin
quadric := gluNewQuadric;
gluDisk(Quadric, 0, FRadius, FSlices, 1); //radius. slices, loops
end;
end;
// BuildList
//
procedure TGLMirror.ClearZBufferArea(aBuffer: TGLSceneBuffer);
var
worldMat: TMatrix;
p: TAffineVector;
begin
with aBuffer do
begin
GL.PushMatrix;
worldMat := Self.AbsoluteMatrix;
GL.MatrixMode(GL_PROJECTION);
GL.PushMatrix;
GL.LoadIdentity;
GL.Ortho(0, Width, 0, Height, 1, -1);
GL.MatrixMode(GL_MODELVIEW);
GL.LoadIdentity;
with aBuffer.RenderingContext.GLStates do
begin
DepthFunc := cfAlways;
SetGLColorWriting(False);
end;
GL.Begin_(GL_QUADS);
p := WorldToScreen(VectorTransform(AffineVectorMake(Self.Width * 0.5,
Self.Height * 0.5, 0), worldMat));
GL.Vertex3f(p.V[0], p.V[1], 0.999);
p := WorldToScreen(VectorTransform(AffineVectorMake(-Self.Width * 0.5,
Self.Height * 0.5, 0), worldMat));
GL.Vertex3f(p.V[0], p.V[1], 0.999);
p := WorldToScreen(VectorTransform(AffineVectorMake(-Self.Width * 0.5,
-Self.Height * 0.5, 0), worldMat));
GL.Vertex3f(p.V[0], p.V[1], 0.999);
p := WorldToScreen(VectorTransform(AffineVectorMake(Self.Width * 0.5,
-Self.Height * 0.5, 0), worldMat));
GL.Vertex3f(p.V[0], p.V[1], 0.999);
GL.End_;
with aBuffer.RenderingContext.GLStates do
begin
DepthFunc := cfLess;
SetGLColorWriting(True);
end;
GL.MatrixMode(GL_PROJECTION);
GL.PopMatrix;
GL.MatrixMode(GL_MODELVIEW);
GL.PopMatrix;
end;
end;
// Notification
//
procedure TGLMirror.Notification(AComponent: TComponent; Operation: TOperation);
begin
if (Operation = opRemove) and (AComponent = FMirrorObject) then
MirrorObject := nil;
inherited;
end;
// SetMirrorObject
//
procedure TGLMirror.SetMirrorObject(const val: TGLBaseSceneObject);
begin
if FMirrorObject <> val then
begin
if Assigned(FMirrorObject) then
FMirrorObject.RemoveFreeNotification(Self);
FMirrorObject := val;
if Assigned(FMirrorObject) then
FMirrorObject.FreeNotification(Self);
NotifyChange(Self);
end;
end;
// SetWidth
//
procedure TGLMirror.SetWidth(AValue: TGLFloat);
begin
if AValue <> FWidth then
begin
FWidth := AValue;
NotifyChange(Self);
end;
end;
// SetHeight
//
procedure TGLMirror.SetHeight(AValue: TGLFloat);
begin
if AValue <> FHeight then
begin
FHeight := AValue;
NotifyChange(Self);
end;
end;
// Assign
//
procedure TGLMirror.Assign(Source: TPersistent);
begin
if Assigned(Source) and (Source is TGLMirror) then
begin
FWidth := TGLMirror(Source).FWidth;
FHeight := TGLMirror(Source).FHeight;
FMirrorOptions := TGLMirror(Source).FMirrorOptions;
MirrorObject := TGLMirror(Source).MirrorObject;
end;
inherited Assign(Source);
end;
// AxisAlignedDimensions
//
function TGLMirror.AxisAlignedDimensionsUnscaled: TVector;
begin
Result := VectorMake(0.5 * Abs(FWidth),
0.5 * Abs(FHeight), 0);
end;
// SetMirrorOptions
//
procedure TGLMirror.SetMirrorOptions(const val: TMirrorOptions);
begin
if FMirrorOptions <> val then
begin
FMirrorOptions := val;
NotifyChange(Self);
end;
end;
//ORL add-ons
// SetRadius
//
procedure TGLMirror.SetRadius(const aValue: Single);
begin
if aValue <> FRadius then
begin
FRadius := aValue;
StructureChanged;
end;
end;
// GetRadius
//
function TGLMirror.GetRadius: single;
begin
result := FRadius;
end;
// SetSlices
//
procedure TGLMirror.SetSlices(const aValue: TGLInt);
begin
if aValue <> FSlices then
begin
if aValue > 2 then
FSlices := aValue;
StructureChanged;
end
else
begin
end;
end;
// GetSlices
//
function TGLMirror.GetSlices: TGLInt;
begin
result := FSlices;
end;
// SetShape
//
procedure TGLMirror.SetShape(aValue: TMirrorShapes);
begin
if aValue <> FShape then
begin
FShape := aValue;
StructureChanged;
end;
end;
//-------------------------------------------------------------
//-------------------------------------------------------------
//-------------------------------------------------------------
initialization
//-------------------------------------------------------------
//-------------------------------------------------------------
//-------------------------------------------------------------
RegisterClasses([TGLMirror]);
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.