text stringlengths 14 6.51M |
|---|
{$undef ITEM_REF_IS_PTR}
{$undef ITEM_FREE_FUNC}
{$undef CMP_FUNC}
{$undef VECTOR_ENABLE_MOVE}
unit StrVec;
interface
uses
Classes;
type
TItem = String;
{$include Vector.inc}
IStrVector = interface(IVector)
procedure Assign(Src: TStrings); overload;
function Clone: IStrVector;
procedure ToStrings(Dst: TStrings);
end;
TStrVector = class(TVector, IStrVector)
procedure Assign(Src: TStrings); overload;
function Clone: IStrVector;
procedure ToStrings(Dst: TStrings);
end;
function Join(Vec: IStrVector; const Separator: String): String;
function Split(const Str: String; const Delim: String): IStrVector;
procedure Cat(Vec: IStrVector; const Str: String); overload;
procedure Cat(const Str: String; Vec: IStrVector); overload;
procedure Cat(V1, V2: IStrVector); overload;
procedure Fmt(Vec: IStrVector; const FmtStr: String);
function StrToken2(var Str: string; const Separators: string): string;
implementation
{$define IMPL}
uses
SysUtils, GUtils;
{$include Vector.inc}
procedure TStrVector.Assign(Src: TStrings);
var
i: Integer;
begin
Clear;
Capacity := Src.Count;
for i := 0 to Src.Count - 1 do
Add(Src[i]);
end;
procedure TStrVector.ToStrings(Dst: TStrings);
var
i: Integer;
begin
Dst.Clear;
for i := 0 to Count - 1 do
Dst.Add(Items[i]);
end;
function TStrVector.Clone: IStrVector;
var
V: TStrVector;
begin
V := TStrVector.Create;
V.Assign(Self);
Result := V;
end;
function Join(Vec: IStrVector; const Separator: String): String;
var
i: Integer;
begin
if Vec.Count = 0 then
Result := ''
else begin
Result := Vec[0];
for i := 1 to Vec.Count - 1 do
Result := Result + Separator + Vec[i];
end;
end;
function Split(const Str: String; const Delim: String): IStrVector;
var
DelimTable: packed array [Char] of Boolean;
i, s, f, l: Integer;
begin
Result := TStrVector.Create;
if Str = '' then
Exit;
FillChar(DelimTable, SizeOf(DelimTable), 0);
for i := 1 to Length(Delim) do
DelimTable[Delim[i]] := True;
s := 1;
l := Length(Str);
while True do begin
while DelimTable[Str[s]] and (s <= l) do
Inc(s);
if s > l then
Break;
f := s + 1;
while not DelimTable[Str[f]] and (f <= l) do
Inc(f);
Result.Add(Copy(Str, s, f - s));
if f > l then
Break;
s := f + 1;
end;
end;
procedure Cat(Vec: IStrVector; const Str: String);
var
i: Integer;
begin
for i := 0 to Vec.Count - 1 do
Vec[i] := Vec[i] + Str;
end;
procedure Cat(const Str: String; Vec: IStrVector);
var
i: Integer;
begin
for i := 0 to Vec.Count - 1 do
Vec[i] := Str + Vec[i];
end;
procedure Cat(V1, V2: IStrVector);
var
i: Integer;
begin
Assert(V1.Count = V2.Count);
for i := 0 to V1.Count - 1 do
V1[i] := V1[i] + V2[i];
end;
procedure Fmt(Vec: IStrVector; const FmtStr: String);
var
i: Integer;
begin
for i := 0 to Vec.Count - 1 do
Vec[i] := Format(FmtStr, [Vec[i]]);
end;
function StrToken2(var Str: string; const Separators: string): string;
var
L, I, J: Integer;
begin
L := Length(Str);
I := 1;
while (I <= L) and (Pos(Str[I], Separators) > 0) do
Inc(I);
if I > L then
begin
Str := '';
Result := '';
end
else
begin
J := I + 1;
while (J <= L) and (Pos(Str[J], Separators) = 0) do
Inc(J);
Result := Copy(Str, I, J - I);
Str := Copy(Str, J, L);
end;
end;
end.
|
{ -------------------------------------------------------------------------------
Unit Name: gridimportfn
Author: Aaron Hochwimmer (hochwimmera@pbworld.com)
Latest Version Available: http://software.pbpower.net/download.html
Purpose: parsing data grids into an array of z(x,y) points.
Information on surfer can be found at
http://www.goldensoftware.com/products/surfer/surfer.shtml
Updates:
23-Jul-2002: Version 1.01
Replaces "blanked" values with BlankSub (default = 0)
15-Jun-2003: Version 1.1
Added ArcInfo Support
(thx Phil Scadden - p.scadden@gns.cri.nz)
18-Jun-2003: Version 1.2
Fixed bug - surfer specs have xlo,xhi etc as doubles
Hiding array variable away as private variables
Remove commasplit dependency
21-Jun-2003: Version 1.3
Remove dialogs dependency, added LoadGrid method, bug fix to
GSASCII detection
29-Jun-2003: Version 1.31
Identify grid type (via GridType property)
14-Jul-2003: Version 1.32
Added GlobalStrToFloat (thx Philipp Pammler -pilli_willi@gmx.de)
23-Jul-2003: Version 1.33
Updated for GlobalStrToFloat (GSASCII)
24-Jul-2004: Version 1.34
Removed XScale,YScale,ConstructArrays - obsolete
------------------------------------------------------------------------------- }
unit cGridimportfn;
interface
uses
System.Classes, System.SysUtils;
type
TDouble1d = array of double;
TSingle2d = array of array of Single;
TGridType = (gtSurfer7, gtSurferGSBin, gtSurferGSASCII, gtArcInfoASCII, gtGMS,
gtUnknown);
TContourGridData = class(TObject)
private
FNodes: TSingle2d; // stores nodes: z=f(x,y)
FBlankVal: double; // blankvalue used in surfer (z values > are "blank")
FBlankSub: double; // used to substitute for viewing
FnBlanks: Integer; // number of blank nodes
FGlobalFloat: Boolean;
FGridType: TGridType;
FNx: SmallInt; // number of columns in the grid
FNy: SmallInt; // number of rows in the grid
FDx: Single; // spacing between adjacent x nodes
FDy: Single; // spacing between adjacent y nodes
FXlo: Single; // min x value of the grid
FXhi: Single; // max x value of the grid
FXRange: Single; // (xhi-xlo) - the x range
FYlo: Single; // min y value of the grid
FYhi: Single; // max y value of the grid
FYRange: Single; // (yhi-ylo) - the y range
FZlo: Single; // min z value of the grid
FZhi: Single; // max z value of the grid
FZRange: Single; // (zhi-zlo) - the z range
StrLine, StrVal: string; // string current line and value
procedure CalcDerived;
procedure CalcDerivedNative;
function ExtractWord(N: Integer; const S: string;
const WordDelims: TSysCharSet): string;
function WordPosition(const N: Integer; const S: string;
const WordDelims: TSysCharSet): Integer;
{ ** attempts to open a surfer grid (.grd) in GS ASCII format.
Integer return code: 0 = file processed ok
1 = not a GS ASCII file }
function LoadSurferGSASCII(FileName: TFileName): Integer;
{ ** attempts to open a surfer grid (.grd) in GS Binary format.
Integer return code: 0 = file processed ok
1 = not a GS Binary file }
function LoadSurferGSBinary(FileName: TFileName): Integer;
{ ** attempts to open a surfer grid (.grd) in native binary format. This format
is used by default by both Surfer 7 and Surfer 8.
Integer return code: 0 = file processed ok
1 = not a Surfer Grid file }
function LoadSurferGridNative(FileName: TFileName): Integer;
protected
function GetNode(I, J: Integer): Single;
function GlobalStrToFloat(const S: string): double;
public
constructor Create;
destructor Destroy; override;
{ ** attempts to load an ArcInfo ASCII File Format.
Integer return code: 0 = file processed ok
1 = not a ArcInfo ASCII File Format }
function LoadARCINFOASCII(FileName: TFileName): Integer;
{ ** attempts to open a surfer grid (.grd) in either GS ASCII, GS Binary, or
Surfer 7 GRD format.
Integer return code: 0 = file processed ok
1 = not a surfer grid of any format }
function LoadSurferGrid(FileName: TFileName): Integer;
{ ** attempts to open any grid (.grd) either a surfer grid or an ArcInfo one
this is a easiest method for using the class }
function LoadGrid(FileName: TFileName): Integer;
property Nodes[I, J: Integer]: Single read GetNode;
property BlankVal: double read FBlankVal write FBlankVal;
property BlankSub: double read FBlankSub write FBlankSub;
property GlobalFloat: Boolean read FGlobalFloat write FGlobalFloat;
property GridType: TGridType read FGridType write FGridType;
property Nblanks: Integer read FnBlanks write FnBlanks;
property Nx: SmallInt read FNx write FNx;
property Ny: SmallInt read FNy write FNy;
property Xlo: Single read FXlo write FXlo;
property Xhi: Single read FXhi write FXhi;
property Xrange: Single read FXRange write FXRange;
property Ylo: Single read FYlo write FYlo;
property Yhi: Single read FYhi write FYhi;
property Yrange: Single read FYRange write FYRange;
property Dx: Single read FDx write FDx;
property Dy: Single read FDy write FDy;
property Zlo: Single read FZlo write FZlo;
property Zhi: Single read FZhi write FZhi;
property Zrange: Single read FZRange write FZRange;
end;
const
dSURFBLANKVAL = 1.70141E38; // used in Surfer ASCII and Binary for blanking
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
implementation
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// ------ TContourGridData.CalcDerived -----------------------------------------
// calculates derived quantities such as step sizes and ranges.
// Also sets up the points array
//
procedure TContourGridData.CalcDerived;
begin
Xrange := Xhi - Xlo;
Dx := Xrange / (Nx - 1);
Yrange := Yhi - Ylo;
Dy := Yrange / (Ny - 1);
Zrange := Zhi - Zlo;
SetLength(FNodes, Ny, Nx);
end;
// ------ TContourGridData.CalcDerivedNative -----------------------------------
{ calculates derived quantities such as ranges. Different to CalcDerived
as the native Surfer Grid/Surfer 7 format has different parameters }
procedure TContourGridData.CalcDerivedNative;
begin
Xrange := (Nx - 1) * Dx;
Xhi := Xlo + Xrange;
Yrange := (Ny - 1) * Dy;
Yhi := Ylo + Yrange;
Zrange := Zhi - Zlo;
SetLength(FNodes, Ny, Nx);
end;
// ----- TContourGridData.ExtractWord ------------------------------------------
{ this function was obtained from RxLib }
function TContourGridData.ExtractWord(N: Integer; const S: string;
const WordDelims: TSysCharSet): string;
var
I, Len: Integer;
begin
Len := 0;
I := WordPosition(N, S, WordDelims);
if (I <> 0) then
// find the end of the current word
while (I <= Length(S)) and not(S[I] in WordDelims) do
begin
// add the I'th character to result
Inc(Len);
SetLength(Result, Len);
Result[Len] := S[I];
Inc(I);
end;
SetLength(Result, Len);
end;
// ----- TContourGridData.GlobalStrToFloat -------------------------------------
{ code to attempt to convert a string to a float for either '.' or ','
separators. This is used to attempt to read in grids that have been generated
in different parts of the world - code from Philipp Pammler }
function TContourGridData.GlobalStrToFloat(const S: string): double;
var
I: Integer;
Separators: set of Char;
Str: string;
begin
Str := S;
Separators := ['.', ','];
for I := 0 to Length(Str) do
begin
if Str[I] in Separators then
Str[I] := FormatSettings.DecimalSeparator;
// local separator
end;
Result := StrToFloat(Str);
end;
// ----- TContourGridData.WordPosition -----------------------------------------
// this function was obtained from RxLib
function TContourGridData.WordPosition(const N: Integer; const S: string;
const WordDelims: TSysCharSet): Integer;
var
Count, I: Integer;
begin
Count := 0;
I := 1;
Result := 0;
while ((I <= Length(S)) and (Count <> N)) do
begin
// skip over delimiters
while (I <= Length(S)) and (S[I] in WordDelims) do
Inc(I);
// if we're not beyond end of S, we're at the start of a word
if I <= Length(S) then
Inc(Count);
// if not finished, find the end of the current word
if Count <> N then
while (I <= Length(S)) and not(S[I] in WordDelims) do
Inc(I)
else
Result := I;
end;
end;
// ----- TContourGridData.LoadARCINFOASCII -------------------------------------
{ ARC/INFO ASCIIGRID file format
ARC ASCIIGRID refers to a specific interchange format developed for ARC/INFO
rasters. The format consists of a header that specifies the geographic domain
and resolution, followed by the actual grid cell values.
General Format:
---------------
Lines 1-6 Geographic Header: Coordinates may be in decimal or integer format.
DD:MM:SS format for geodatic coordinates is not supported.
Line 1: ncols xxxxx
ncols refers to the number of columns in the grid and xxxxx is the numerical
value
Line 2: nrows xxxxx
nrows refers to the number of rows in the grid and xxxxx is the numerical
value
Line 3: xllcorner xxxxx
xllcorner refers to the western edge of the grid and xxxxx is the numerical
value
Line 4: yllcorner xxxxx
yllcorder refers to the southern edge of the grid and xxxxx is the numerical
value
Line 5: cellsize xxxxx
cellsize refers to the resolution of the grid and xxxxx is the numerical value
Line 6: nodata_value
nodata_value refers to the value that represents missing data and xxxxx is the
numerical value
Record 7 --> End Of File:
-------------------------
xxx xxx xxx
val(nox,noy)(f) = individual grid values, column varying fastest in integer
format. Grid values are stored as integers but can be read as floating point
values.
xllcorner and yllcorner are given as the EDGES of the grid, NOT the centers of
the edge cells.
ARC/INFO supports other header strings that allow the centers of the edge cells
to be given, but they are not supported here. The origin of the grid is the
upper left and the terminus is the lower right.
ARC format grids are single-band files.
}
function TContourGridData.LoadARCINFOASCII(FileName: TFileName): Integer;
var
sl, tl: TStringList;
iRow, iCol: Integer;
I, J, N: Integer;
begin
tl := TStringList.Create;
sl := TStringList.Create;
try
sl.LoadFromFile(FileName);
tl.DelimitedText := sl[0];
if (tl[0] <> 'ncols') then // not ARC/INFO file
begin
sl.Free;
tl.Free;
Result := 1;
Exit;
end;
Nx := StrToInt(tl[1]); // ncols
tl.DelimitedText := sl[1];
Ny := StrToInt(tl[1]); // nrows
tl.DelimitedText := sl[2];
Xlo := StrToInt(tl[1]); // xllcorner
tl.DelimitedText := sl[3];
Ylo := StrToInt(tl[1]); // yllcorner
tl.DelimitedText := sl[4];
Dx := StrToInt(tl[1]); // cellsize
Dy := Dx;
tl.DelimitedText := sl[5];
BlankVal := StrToFloat(tl[1]); // blank value
// temp as we don't know zlo and zhi yet...}
Zlo := 0.0;
Zhi := 0.0;
{ ** calculate the derived quantites - ranges and stuff etc }
CalcDerivedNative;
Zhi := -3 * 10E38; // set artificial bounds
Zlo := 3 * 10E38;
Nblanks := 0;
{
for iRow := Ny - 1 downto 0 do
begin
tl.DelimitedText := sl[iRow + 6]; // Read Rows
for iCol := 0 to Nx - 1 do
begin
fPoints[iRow,iCol] := StrToFloat(tl[iCol]); // Read Col
if (fPoints[iRow,iCol] = BlankVal) then
nblanks := nblanks + 1
else
begin
if (fPoints[iRow,iCol] > zhi) then
zhi := fPoints[iRow,iCol];
if (fPoints[iRow,iCol] < zlo) then
zlo := fPoints[iRow,iCol];
end;
end;
end;
{ }
iRow := Ny - 1;
iCol := 0;
N := 5;
while (N < sl.Count) and (iRow >= 0) do
begin
Inc(N);
tl.DelimitedText := sl[N]; // Read Line
I := 1;
StrVal := tl[I];
while (StrVal <> '') do
begin
Inc(I);
FNodes[iRow, iCol] := StrToFloat(StrVal);
if (FNodes[iRow, iCol] = BlankVal) then
Nblanks := Nblanks + 1
else
begin
if (FNodes[iRow, iCol] > Zhi) then
Zhi := FNodes[iRow, iCol];
if (FNodes[iRow, iCol] < Zlo) then
Zlo := FNodes[iRow, iCol];
end;
Inc(iCol);
if (iCol = Nx) then
begin
Dec(iRow);
iCol := 0;
end;
StrVal := ExtractWord(I, sl[N], [' ']);
end;
end;
finally
sl.Free;
tl.Free;
Zrange := Zhi - Zlo;
Result := 0;
GridType := gtArcInfoASCII;
end;
end;
// ------ TContourGridData.LoadSurferGSASCII -----------------------------------
{ GS ASCII Grid File Format:
GS ASCII GRid files [.grd] contain 5 header lines that provide information about
the size limits of the grid, followed by a list of z values. The fields within
a GS ASCII grid _must_ be space delimited.
The listing of z values follows the header information in the file. The z values
are stored in row-major order starting with the minimum Y coordinate. The first
z value of the grid corresponds to the lower left corner of the map (min X,Y).
When the maximum X value is reached in the row the list of z values continues
with the next highest row, until all the rows have been included.
General Format:
id = a four char id string "DSAA" which idicates GS ASCII grid file
nx ny = nx is the number of grid lines along the x axis (columns)
ny is the number of grid lines along the y axis (rows)
xlo xhi = xlo is the floating point minimum X value of the grid
xhi is the floating point maximum X value of the grid
ylo yhi = ylo is the floating point minimum Y value of the grid
yhi is the floating point maximum Y value of the grid
zlo zhi = zlo is the floating point minimum Z value of the grid
= xhi is the floating point maximum Z value of the grid
grid row 1
grid row 2
etc
NB: each grid row has a constant Y coordinate. Grid row 1 corresponds to ylo
and the last grid row corresponds to yhi. Within each row the Z values are
arranged from xlo to xhi. When an ASCII grid file is created in surfer the
program generates 10 z values per line for readability. This function will read
files with any number of values per line.
}
function TContourGridData.LoadSurferGSASCII(FileName: TFileName): Integer;
var
FileStrings: TStringList;
tl: TStringList;
I, // I = row counter
J, // J = column counter
K, // K = counter used with extractWord
N: Integer; // N = counter to increment through file
bNOTGSASCII: Boolean;
LineNum: Integer;
{ sub } function ReadLine: string;
begin
Result := FileStrings[N];
Inc(N);
end;
begin
FileStrings := TStringList.Create;
tl := TStringList.Create;
FileStrings.LoadFromFile(FileName);
N := 0;
try
// check for valid GS ASCII header
if (Copy(ReadLine, 1, 4) <> 'DSAA') then
bNOTGSASCII := true
else
begin
bNOTGSASCII := false;
// read nx,ny
StrLine := ReadLine;
Nx := StrToInt(ExtractWord(1, StrLine, [' ']));
Ny := StrToInt(ExtractWord(2, StrLine, [' ']));
// read xlo,xhi
StrLine := ReadLine;
if GlobalFloat then
begin
Xlo := GlobalStrToFloat(ExtractWord(1, StrLine, [' ']));
Xhi := GlobalStrToFloat(ExtractWord(2, StrLine, [' ']));
end
else
begin
Xlo := StrToFloat(ExtractWord(1, StrLine, [' ']));
Xhi := StrToFloat(ExtractWord(2, StrLine, [' ']));
end;
// read ylo,yhi
StrLine := ReadLine;
if GlobalFloat then
begin
Ylo := GlobalStrToFloat(ExtractWord(1, StrLine, [' ']));
Yhi := GlobalStrToFloat(ExtractWord(2, StrLine, [' ']));
end
else
begin
Ylo := StrToFloat(ExtractWord(1, StrLine, [' ']));
Yhi := StrToFloat(ExtractWord(2, StrLine, [' ']));
end;
// read zlo,zhi
StrLine := ReadLine;
if GlobalFloat then
begin
Zlo := GlobalStrToFloat(ExtractWord(1, StrLine, [' ']));
Zhi := GlobalStrToFloat(ExtractWord(2, StrLine, [' ']));
end
else
begin
Zlo := StrToFloat(ExtractWord(1, StrLine, [' ']));
Zhi := StrToFloat(ExtractWord(2, StrLine, [' ']));
end;
CalcDerived; // calculates the derived quantites - step sizes etc
Nblanks := 0;
BlankVal := dSURFBLANKVAL;
// loop over the Ny-1 Rows
for I := 0 to Ny - 1 do
begin
J := 0;
// reading lines until Nx-1 Cols entries have been obtained
while J <= Nx - 1 do
begin
StrLine := ReadLine;
K := 1;
StrVal := ExtractWord(K, StrLine, [' ']);
while (StrVal <> '') do
begin
if (J <= Nx - 1) then
if GlobalFloat then
FNodes[I, J] := GlobalStrToFloat(StrVal)
else
FNodes[I, J] := StrToFloat(StrVal);
if (FNodes[I, J] >= BlankVal) then
Nblanks := Nblanks + 1;
Inc(J);
Inc(K);
StrVal := ExtractWord(K, StrLine, [' ']);
end;
if (J > Nx - 1) then
Break;
end;
end;
end;
finally
if bNOTGSASCII then
Result := 1
else
begin
Result := 0;
GridType := gtSurferGSASCII;
end;
FileStrings.Free;
tl.Free;
end;
end;
// ------ TContourGridData.LoadSurferGSBinary ----------------------------------
{ GS Binary Grid File Format:
GS Binary grid files [.grd] use a similar layout to the GS ASCII described
above. The difference is in the ID string and that the files are binary :)
Data types used:
AnsiChar - single byte
smallint - 16 byte signed integer
single - 32 bit single precision floating point value
double - 64 bit double precision floating point value
General Format:
Element Type Description
id char 4 byte id string "DSBB" indicates GS Binary grid file
nx smallint number of grid lines along the x axis (columns)
ny smallint number of grid lines along the y axis (columns)
xlo double minimum X value of the grid
xhi double maximum X value of the grid
ylo double minimum Y value of the grid
yhi double maximum Y value of the grid
zlo double minimum Z value of the grid
zhi double maximum Z value of the grid
z11,z12,... single first row of the grid. Each row has constant Y coordinate
first row corresponds to ylo, and last corresponds to yhi
Within each row, the Z values are ordered from xlo -> xhi.
z21,z22,... single second row of the grid
z31,z32,... single third row of the grid
... single all other rows of the grid up to yhi
}
function TContourGridData.LoadSurferGSBinary(FileName: TFileName): Integer;
var
BinFile: file;
I, J: Integer;
D: double;
ZVal: Single;
NDouble, NSingle, NSmallInt, col: Integer; // sizeof vars
sType: array [1 .. 4] of AnsiChar; // Used instead of old Char type
NRead: Integer; // number of bytes read - unused
begin
AssignFile(BinFile, FileName);
Reset(BinFile, 1); // record size of 1 byte
// check to see if this is a GS Binary file
BlockRead(BinFile, sType, 4, NRead);
if (sType <> 'DSBB') then
begin
Result := 1;
CloseFile(BinFile);
end
else
begin
NDouble := sizeof(D);
NSingle := sizeof(ZVal);
NSmallInt := sizeof(I);
// read nx,ny
BlockRead(BinFile, I, NSmallInt, NRead);
Nx := I;
BlockRead(BinFile, I, NSmallInt, NRead);
Ny := I;
// read xlo,xhi
BlockRead(BinFile, D, NDouble, NRead);
Xlo := D;
BlockRead(BinFile, D, NDouble, NRead);
Xhi := D;
// read ylo,yhi
BlockRead(BinFile, D, NDouble, NRead);
Ylo := D;
BlockRead(BinFile, D, NDouble, NRead);
Yhi := D;
// read zlo,zhi
BlockRead(BinFile, D, NDouble, NRead);
Zlo := D;
BlockRead(BinFile, D, NDouble, NRead);
Zhi := D;
// calculate the derived quantities - step sizes etc
CalcDerived;
Nblanks := 0;
BlankVal := dSURFBLANKVAL;
// now read in the points
for I := 0 to Ny - 1 do
for J := 0 to Nx - 1 do
begin
BlockRead(BinFile, ZVal, NSingle, NRead);
FNodes[I, J] := ZVal;
if (ZVal >= BlankVal) then
Nblanks := Nblanks + 1;
end;
Result := 0;
GridType := gtSurferGSBin;
CloseFile(BinFile);
end;
end;
// ------ TContourGridData.LoadSurferGridNative --------------------------------
{ Surfer Grid and Surfer 7 Grid files [.GRD] use the same file format.
Uses tag-based binary file format (allow for future enhancements)
Each section is preceded by a tag structure - which indicates the type and size
of the following data.
If a program does not understand or want a type of data, it can read the tag
and skip to the next section. Sections can appear in any order than the first
(which must be the header section)
Data types used:
integer - 32 bit signed integer
double - 64 bit double precision floating point value
Each section is preceded by a tag structure with the following format:
Element Type Description
id integer The type of data in the following section.
size integer The number of bytes in the section (not including this
tag). Skipping this many bytes after reading this tag
aligns the file pointer on the next tag.
Tag Id values. The 0x prefix indicates a hexadecimal value:
id Description
0x42525344 Header section:
must be the first section within the file
0x44495247 Grid section:
describes a 2d matrix of Z values
0x41544144 Data section:
contains a variable amount of data.
0x49544c46 Fault Info section:
describes the fault traces used when creating a grid
** Header Section **
The header section must be the first section in the file and has the following
format.
Element Type Description
version integer Version number of the file format. Currently set to 1.
** Grid Section **
The grid section consists of a header that describes a 2D matrix of values,
followed by the matrix itself. This section encapsulates all of the data that
was traditionally referred to as a grid:
Element Type Description
ny integer number of rows in the grid (Y direction)
nx integer number of columns in the grid (X direction)
xlo double X coordinate of the lower left corner of the grid
ylo double Y coordinate of the lower right corner of the grid
xstep double spacing between adjacent nodes in the X direction
ystep double spacing between adjacent nodes in the Y direction
zlo double minimum Z value within the grid
zhi double maximum Z value within the grid
rotation double not currently used
blankval double nodes are blanked if >= this value
A Data section containing the 2d matrix of values (doubles) must immediately
follow a grid section. Within a data section the grid is stored in row-major
order, with the lowest row (min Y) first.
** Fault Info Section ** (NOT USED IN THIS CLASS)
Element Type Description
nTraces integer number of fault traces (polylines)
nVertices integer total number of vertices in all the traces
A Data section containing an array of Trace structures and an array of Vertex
structures must immediately follow a Fault Info section. The number of trace
structures in the array is nTraces and the number of vertex structures is
nVertices.
Trace Structure
Element Type Description
iFirst integer 0-based index into the vertex array for the first vertex
of this trace
nPts integer number of vertices in this trace
Vertex Structure
Element Type Description
x double X coordinate of the vertex
y double Y coordinate of the vertex
}
function TContourGridData.LoadSurferGridNative(FileName: TFileName): Integer;
const
sHEADER = '42525344'; // Id for Header section
sFAULTINFO = '49544c46'; // Id Fault info section
sGRIDSECT = '44495247'; // Id indicating a grid section
sDATASECT = '41544144'; // Id indicating a data section
iSECTSIZE = 8;
var
BinFile: file;
buf: array of byte;
dval: double;
col, I, J, iHeaderID, iSize, iVal, iVersion, NDouble, nInteger,
NRead: Integer;
sSectionID, sSectionID2: AnsiString;
begin
AssignFile(BinFile, FileName);
Reset(BinFile, 1); // set the default record size to 1 byte
nInteger := sizeof(iHeaderID); // just size of integer variable
// read in the header
BlockRead(BinFile, iHeaderID, nInteger, NRead);
sSectionID := IntToHex(iHeaderID, iSECTSIZE);
// check the header tag
if (sSectionID <> sHEADER) then
begin
Result := 1;
CloseFile(BinFile);
end
else
begin
NDouble := sizeof(dval); // just size of double variable
BlockRead(BinFile, iSize, nInteger, NRead); // size of header section
BlockRead(BinFile, iVersion, nInteger, NRead); // file version
// the sections are in any order...
while (not eof(BinFile)) do
begin
// what section is this?
BlockRead(BinFile, iHeaderID, nInteger, NRead);
sSectionID := IntToHex(iHeaderID, iSECTSIZE);
// FAULT INFO SECTION
if (sSectionID = sFAULTINFO) then
begin
BlockRead(BinFile, iSize, nInteger, NRead);
// size of fault info section
SetLength(buf, iSize); // set up the temp buffer
BlockRead(BinFile, buf, iSize, NRead); // skip the section
// from the specs a data section will follow - skip this one as well
BlockRead(BinFile, iHeaderID, nInteger, NRead);
sSectionID2 := IntToHex(iHeaderID, iSECTSIZE);
if (sSectionID2 = sDATASECT) then
begin
BlockRead(BinFile, iSize, nInteger, NRead);
SetLength(buf, iSize); // set up the temp buffer
BlockRead(BinFile, buf, iSize, NRead); // skip the section}
end;
// GRID SECTION}
end
else if (sSectionID = sGRIDSECT) then
begin
BlockRead(BinFile, iSize, nInteger, NRead); // size of grid section
BlockRead(BinFile, iVal, nInteger, NRead);
Ny := iVal;
BlockRead(BinFile, iVal, nInteger, NRead);
Nx := iVal;
BlockRead(BinFile, dval, NDouble, NRead);
Xlo := dval;
BlockRead(BinFile, dval, NDouble, NRead);
Ylo := dval;
BlockRead(BinFile, dval, NDouble, NRead);
Dx := dval;
BlockRead(BinFile, dval, NDouble, NRead);
Dy := dval;
BlockRead(BinFile, dval, NDouble, NRead);
Zlo := dval;
BlockRead(BinFile, dval, NDouble, NRead);
Zhi := dval;
BlockRead(BinFile, dval, NDouble, NRead); // rotation - not used here
// blank value
BlockRead(BinFile, dval, NDouble, NRead);
BlankVal := dval;
Nblanks := 0;
CalcDerivedNative;
// from the specs a data section will follow - skip this one as well
BlockRead(BinFile, iHeaderID, nInteger, NRead);
sSectionID2 := IntToHex(iHeaderID, iSECTSIZE);
if (sSectionID2 = sDATASECT) then
begin
col := Nx - 1;
BlockRead(BinFile, iSize, nInteger, NRead);
// now read in the points
for I := 0 to Ny - 1 do
begin
for J := 0 to col do
begin
BlockRead(BinFile, dval, NDouble, NRead);
FNodes[I, J] := dval;
if (dval >= BlankVal) then
Nblanks := Nblanks + 1;
end;
end;
end;
end; // while not eof
end;
Result := 0;
GridType := gtSurfer7;
CloseFile(BinFile);
end;
end;
// ------ TContourGridData.LoadSurferGrid --------------------------------------
function TContourGridData.LoadSurferGrid(FileName: TFileName): Integer;
begin
// the native GRD format first - Surfer 7 or 8
if (LoadSurferGridNative(FileName) = 0) then
Result := 0
// check if the GRD file is GS Binary
else if (LoadSurferGSBinary(FileName) = 0) then
Result := 0
// check if the GRD file is GS ASCII
else if (LoadSurferGSASCII(FileName) = 0) then
Result := 0
else // not a surfer grid file
begin
Result := 1;
GridType := gtUnknown;
end;
end;
// ----- TContourGridData.LoadGrid ---------------------------------------------
function TContourGridData.LoadGrid(FileName: TFileName): Integer;
begin
if (LoadSurferGrid(FileName) = 0) then
Result := 0
else if (LoadARCINFOASCII(FileName) = 0) then
Result := 0
else
begin
Result := 1;
GridType := gtUnknown;
end;
end;
// TContourGridData.GetNode --------------------------------------
// a case when i,j are out of range should never happen
function TContourGridData.GetNode(I, J: Integer): Single;
begin
try
Result := FNodes[I, J];
except
Result := 0; // to avoid compilation warning
end;
end;
// ------ TContourGridData.Create ----------------------------------------------
constructor TContourGridData.Create;
begin
inherited Create;
BlankSub := 0.0; // default for blanked values;
FGlobalFloat := true;
end;
// ------ TContourGridData.destroy ---------------------------------------------
destructor TContourGridData.Destroy;
begin
FNodes := nil;
inherited Destroy;
end;
// =============================================================================
end.
|
(* User Interface - Unit responsible for displaying messages and stats *)
unit ui;
{$mode objfpc}{$H+}
{$RANGECHECKS OFF}
interface
uses
SysUtils, Graphics, globalutils;
const
(* side bar X position *)
sbx = 687;
(* side bar Y position *)
sby = 10;
(* side bar Width *)
sbw = 145;
(* side bar Height *)
sbh = 210; // + 60
(* equipment bar Y position *)
eqy = 242;
(* equipment bar Height *)
eqh = 70;
(* Look box Y position *)
infoy = 324;
(* Look box Height *)
infoh = 55;
var
messageArray: array[1..7] of string = (' ', ' ', ' ', ' ', ' ', ' ', ' ');
buffer: string;
logo: TBitmap;
(* Status effects *)
poisonStatusSet: boolean;
(* Title screen *)
procedure titleScreen(yn: byte);
(* Draws the panel on side of screen *)
procedure drawSidepanel;
(* Update player level *)
procedure updateLevel;
(* Update Experience points display *)
procedure updateXP;
(* Update player health display *)
procedure updateHealth;
(* Update player attack value *)
procedure updateAttack;
(* Update player defence value *)
procedure updateDefence;
(* Display equipped weapon *)
procedure updateWeapon(weaponName: shortstring);
(* Display equipped armour *)
procedure updateArmour(armourName: shortstring);
(* Display status effects *)
procedure displayStatusEffect(onoff: byte; effectType: shortstring);
(* Info window results from LOOK command *)
procedure displayLook(displayType: byte; entityName, itemDescription: shortstring;
currentHP, maxHP: smallint);
(* Write text to the message log *)
procedure displayMessage(message: string);
(* Store all messages from players turn *)
procedure bufferMessage(message: string);
(* Write buffered message to the message log *)
procedure writeBufferedMessages;
(* Display Quit Game confirmation *)
procedure exitPrompt;
(* Rewrite message at top of log *)
procedure rewriteTopMessage;
(* Clear message log *)
procedure clearLog;
implementation
uses
main, entities, items;
procedure titleScreen(yn: byte);
begin
logo := TBitmap.Create;
logo.LoadFromResourceName(HINSTANCE, 'TITLESCREEN');
(* Clear the screen *)
main.tempScreen.Canvas.Brush.Color := globalutils.BACKGROUNDCOLOUR;
main.tempScreen.Canvas.FillRect(0, 0, tempScreen.Width, tempScreen.Height);
(* Draw logo *)
drawToBuffer(145, 57, logo);
(* Check if a save file exists and display menu *)
if (yn = 0) then
begin
writeToBuffer(200, 250, UITEXTCOLOUR, 'N - New Game');
writeToBuffer(200, 270, UITEXTCOLOUR, 'Q - Quit');
end
else
begin
writeToBuffer(200, 250, UITEXTCOLOUR, 'L - Load Last Game');
writeToBuffer(200, 270, UITEXTCOLOUR, 'N - New Game');
writeToBuffer(200, 290, UITEXTCOLOUR, 'Q - Quit');
end;
logo.Free;
end;
procedure drawSidepanel;
begin
main.tempScreen.Canvas.Pen.Color := globalutils.UICOLOUR;
(* Stats window *)
main.tempScreen.Canvas.Rectangle(sbx, sby, sbx + sbw, sby + sbh);
(* Equipment window *)
main.tempScreen.Canvas.Rectangle(sbx, eqy, sbx + sbw, eqy + eqh);
(* Info window *)
main.tempScreen.Canvas.Rectangle(sbx, infoy, sbx + sbw, infoy + infoh);
main.tempScreen.Canvas.Font.Size := 10;
(* Write stats *)
writeToBuffer(sbx + 8, sby + 5, UITEXTCOLOUR, entities.entityList[0].race);
updateLevel;
updateXP;
updateHealth;
updateAttack;
updateDefence;
(* Write Equipment window *)
writeToBuffer(sbx + 8, eqy - 8, MESSAGEFADE1, 'Equipment'); // originally eqy + 5
updateWeapon('none');
updateArmour('none');
(* Write Info window *)
writeToBuffer(sbx + 8, infoy - 8, MESSAGEFADE1, 'Info');
(* Set status effect flags *)
poisonStatusSet := False;
end;
procedure updateLevel;
begin
(* Select players title *)
if (entities.entityList[0].xpReward <= 10) then
entities.entityList[0].description := 'the Worthless'
else if (entities.entityList[0].xpReward > 10) then
entities.entityList[0].description := 'the Brawler';
(* Paint over previous title *)
main.tempScreen.Canvas.Brush.Color := BACKGROUNDCOLOUR;
main.tempScreen.Canvas.FillRect(sbx + 8, sby + 25, sbx + 135, sby + 45);
(* Write title to screen *)
main.tempScreen.Canvas.Font.Size := 10;
writeToBuffer(sbx + 8, sby + 25, UITEXTCOLOUR, entities.entityList[0].description);
end;
procedure updateXP;
begin
(* Paint over previous stats *)
main.tempScreen.Canvas.Brush.Color := BACKGROUNDCOLOUR;
main.tempScreen.Canvas.FillRect(sbx + 80, sby + 55, sbx + 135, sby + 75);
main.tempScreen.Canvas.Pen.Color := UICOLOUR;
(* Write Experience points *)
main.tempScreen.Canvas.Font.Size := 10;
writeToBuffer(sbx + 8, sby + 55, UITEXTCOLOUR, 'Experience: ' +
IntToStr(entities.entityList[0].xpReward));
end;
procedure updateHealth;
var
healthPercentage: smallint;
begin
(* Paint over previous stats *)
main.tempScreen.Canvas.Brush.Color := BACKGROUNDCOLOUR;
main.tempScreen.Canvas.FillRect(sbx + 33, sby + 75, sbx + 135, sby + 95);
(* Draw Health amount *)
main.tempScreen.Canvas.Font.Size := 10;
writeToBuffer(sbx + 8, sby + 75, UITEXTCOLOUR, 'Health: ' +
IntToStr(entities.entityList[0].currentHP) + ' / ' +
IntToStr(entities.entityList[0].maxHP));
(* Draw health bar *)
main.tempScreen.Canvas.Brush.Color := $2E2E00; // Background colour
main.tempScreen.Canvas.FillRect(sbx + 8, sby + 95, sbx + 108, sby + 100);
(* Calculate percentage of total health *)
healthPercentage := (entities.entityList[0].currentHP * 100) div
entities.entityList[0].maxHP;
main.tempScreen.Canvas.Brush.Color := $0B9117; // Green colour
main.tempScreen.Canvas.FillRect(sbx + 8, sby + 95, sbx +
(healthPercentage + 8), sby + 100);
end;
procedure updateAttack;
begin
(* Paint over previous stats *)
main.tempScreen.Canvas.Brush.Color := BACKGROUNDCOLOUR;
main.tempScreen.Canvas.FillRect(sbx + 50, sby + 105, sbx + 135, sby + 125);
main.tempScreen.Canvas.Pen.Color := UICOLOUR;
(* Draw Attack amount *)
main.tempScreen.Canvas.Font.Size := 10;
writeToBuffer(sbx + 8, sby + 105, UITEXTCOLOUR, 'Attack: ' +
IntToStr(entities.entityList[0].attack));
end;
procedure updateDefence;
begin
(* Paint over previous stats *)
main.tempScreen.Canvas.Brush.Color := BACKGROUNDCOLOUR;
main.tempScreen.Canvas.FillRect(sbx + 60, sby + 125, sbx + 135, sby + 145);
main.tempScreen.Canvas.Pen.Color := UICOLOUR;
(* Draw Defence amount *)
main.tempScreen.Canvas.Font.Size := 10;
writeToBuffer(sbx + 8, sby + 125, UITEXTCOLOUR, 'Defence: ' +
IntToStr(entities.entityList[0].defense));
end;
procedure updateWeapon(weaponName: shortstring);
begin
main.tempScreen.Canvas.Font.Size := 10;
(* Paint over previous text *)
main.tempScreen.Canvas.Brush.Color := BACKGROUNDCOLOUR;
main.tempScreen.Canvas.FillRect(sbx + 8, eqy + 13, sbx + 135, eqy + 30);
if (weaponName = 'none') then
begin
writeToBuffer(sbx + 8, eqy + 13, MESSAGEFADE2, 'No weapon equipped');
end
else
begin
writeToBuffer(sbx + 8, eqy + 13, UITEXTCOLOUR, weaponName);
end;
end;
procedure updateArmour(armourName: shortstring);
begin
main.tempScreen.Canvas.Font.Size := 10;
(* Paint over previous text *)
main.tempScreen.Canvas.Brush.Color := BACKGROUNDCOLOUR;
main.tempScreen.Canvas.FillRect(sbx + 8, eqy + 33, sbx + 135, eqy + 51);
if (armourName = 'none') then
begin
writeToBuffer(sbx + 8, eqy + 33, MESSAGEFADE2, 'No armour equipped');
end
else
begin
writeToBuffer(sbx + 8, eqy + 33, UITEXTCOLOUR, armourName);
end;
end;
procedure displayStatusEffect(onoff: byte; effectType: shortstring);
begin
(* Paint over previous stats *)
main.tempScreen.Canvas.Brush.Color := BACKGROUNDCOLOUR;
main.tempScreen.Canvas.FillRect(sbx + 3, sby + 150, sbx + 140, sby + 170);
main.tempScreen.Canvas.Pen.Color := UICOLOUR;
(* POISON *)
if (effectType = 'poison') then
begin
if (onoff = 1) then
writeToBuffer(sbx + 8, sby + 151, STSPOISON, 'Poisoned');
end;
end;
(* displayType: 1 = Entity, 2 = Item *)
procedure displayLook(displayType: byte; entityName, itemDescription: shortstring;
currentHP, maxHP: smallint);
begin
(* Paint over previous text *)
main.tempScreen.Canvas.Brush.Color := BACKGROUNDCOLOUR;
main.tempScreen.Canvas.FillRect(sbx + 3, infoy + 10, sbx + 135, infoy + 50);
main.tempScreen.Canvas.Font.Size := 10;
if (displayType = 1) then
begin
if (entityName <> 'none') then
begin
(* Display entity name *)
writeToBuffer(sbx + 5, infoy + 10, UITEXTCOLOUR, entityName);
(* Display health *)
writeToBuffer(sbx + 5, infoy + 30, UITEXTCOLOUR, 'Health: ' +
IntToStr(currentHP) + ' / ' + IntToStr(maxHP));
end;
end
else if (displayType = 2) then
begin
begin
(* Display item name *)
writeToBuffer(sbx + 5, infoy + 10, UITEXTCOLOUR, entityName);
(* Display item description *)
writeToBuffer(sbx + 5, infoy + 30, MESSAGEFADE1, itemDescription);
end;
end;
end;
procedure displayMessage(message: string);
begin
(* Catch duplicate messages *)
if (message = messageArray[1]) then
begin
main.tempScreen.Canvas.Brush.Color := BACKGROUNDCOLOUR;
messageArray[1] := messageArray[1] + ' x2';
main.tempScreen.Canvas.Font.Size := 9;
writeToBuffer(10, 410, UITEXTCOLOUR, messageArray[1]);
end
else
begin
(* Clear the message log *)
main.tempScreen.Canvas.Brush.Color := globalutils.BACKGROUNDCOLOUR;
main.tempScreen.Canvas.FillRect(5, 410, 833, 550);
(* Shift all messages down one line *)
messageArray[7] := messageArray[6];
messageArray[6] := messageArray[5];
messageArray[5] := messageArray[4];
messageArray[4] := messageArray[3];
messageArray[3] := messageArray[2];
messageArray[2] := messageArray[1];
messageArray[1] := message;
(* Display each line, gradually getting darker *)
main.tempScreen.Canvas.Font.Size := 9;
writeToBuffer(10, 410, UITEXTCOLOUR, messageArray[1]);
writeToBuffer(10, 430, MESSAGEFADE1, messageArray[2]);
writeToBuffer(10, 450, MESSAGEFADE2, messageArray[3]);
writeToBuffer(10, 470, MESSAGEFADE3, messageArray[4]);
writeToBuffer(10, 490, MESSAGEFADE4, messageArray[5]);
writeToBuffer(10, 510, MESSAGEFADE5, messageArray[6]);
writeToBuffer(10, 530, MESSAGEFADE6, messageArray[7]);
end;
end;
{ TODO : If buffered message is longer than a certain length, flush the buffer with writeBuffer procedure }
procedure bufferMessage(message: string);
begin
buffer := buffer + message + '. ';
end;
procedure writeBufferedMessages;
begin
if (buffer <> '') then
displayMessage(buffer);
buffer := '';
end;
procedure exitPrompt;
begin
main.tempScreen.Canvas.Brush.Color := globalutils.BACKGROUNDCOLOUR;
main.tempScreen.Canvas.Font.Size := 9;
writeToBuffer(10, 410, clWhite,
'Exit game? [Q] - Quit game | [X] - Exit to main menu | [ESC] - Return to game');
end;
procedure rewriteTopMessage;
begin
// rewrite message at top of log *)
main.tempScreen.Canvas.Brush.Color := globalutils.BACKGROUNDCOLOUR;
main.tempScreen.Canvas.FillRect(5, 410, 833, 429);
main.tempScreen.Canvas.Font.Size := 9;
writeToBuffer(10, 410, UITEXTCOLOUR, messageArray[1]);
end;
procedure clearLog;
begin
messageArray[7] := ' ';
messageArray[6] := ' ';
messageArray[5] := ' ';
messageArray[4] := ' ';
messageArray[3] := ' ';
messageArray[2] := ' ';
messageArray[1] := ' ';
end;
end.
|
unit VConstSoporte;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ExtCtrls;
type
TConstSoporteForm = class(TForm)
Label1: TLabel;
FechaSoporteEdit: TEdit;
disponiblesListView: TListView;
Panel1: TPanel;
documentalRadioButton: TRadioButton;
NoDocumentalRadioButton: TRadioButton;
Panel2: TPanel;
vinculadosListView: TListView;
addButton: TButton;
addAllButton: TButton;
delButton: TButton;
delAllButton: TButton;
CancelarButton: TButton;
aceptarButton: TButton;
IncluirPendientesCheckBox: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure documentalRadioButtonClick(Sender: TObject);
procedure disponiblesListViewSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
procedure vinculadosListViewSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
private
FOnChangeNat: TNotifyEvent;
public
property OnChangeNat: TNotifyEvent read FOnChangeNat write FOnChangeNat;
end;
var
ConstSoporteForm: TConstSoporteForm;
implementation
{$R *.dfm}
procedure TConstSoporteForm.FormCreate(Sender: TObject);
begin
FOnChangeNat := nil;
end;
procedure TConstSoporteForm.documentalRadioButtonClick(Sender: TObject);
begin
if assigned( FOnChangeNat ) then FOnChangeNat( Self );
end;
procedure TConstSoporteForm.disponiblesListViewSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
begin
addButton.Enabled := Selected;
end;
procedure TConstSoporteForm.vinculadosListViewSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
begin
delButton.Enabled := Selected;
end;
end.
|
unit UpCommandMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, Ibase, uFControl, uLabeledFControl,
uSpravControl, FIBDatabase, pFIBDatabase, cxControls, cxContainer,
cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, cxPropertiesStore,
frxClass, frxDBSet, DB, FIBDataSet, pFIBDataSet, cxCheckBox,
pFibStoredProc, cxMemo, uCharControl, uIntControl, cxLabel,Registry,
ActnList, NagScreenUnit, cxDropDownEdit, accmgmt, UpKernelUnit;
type
TfrmCommandPrint = class(TForm)
OkButton: TBitBtn;
CancelButton: TBitBtn;
CertDBSet: TfrxDBDataset;
OrderDBSet: TfrxDBDataset;
Label2: TLabel;
SizeFont: TcxTextEdit;
ActionList1: TActionList;
Pereform: TAction;
lblFont: TLabel;
RectorSpr: TcxButtonEdit;
lblRector: TcxLabel;
lblProrector: TcxLabel;
ProrectorSpr: TcxButtonEdit;
ReadTrans: TpFIBTransaction;
CommandDB: TpFIBDatabase;
OrderDSet: TpFIBDataSet;
CertDSet: TpFIBDataSet;
NamePost: TcxTextEdit;
ReportPrint: TfrxReport;
procedure CancelButtonClick(Sender: TObject);
procedure SizeFontKeyPress(Sender: TObject; var Key: Char);
procedure OkButtonClick(Sender: TObject);
procedure ProrectorSprPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure RectorSprPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
{ Private declarations }
id_order_in:Int64;
NagScreen : TNagScreen;
public
{ Public declarations }
constructor Create(AOwner:TComponent;DbHandle:TISC_DB_HANDLE;id_order:Int64);reintroduce;
end;
procedure GetExtReport(DBHandle:TISC_DB_HANDLE;id_order:Int64);stdcall;
exports GetExtReport;
implementation
uses uUnivSprav, RxMemDS, BaseTypes;
{$R *.dfm}
procedure GetExtReport(DBHandle:TISC_DB_HANDLE;id_order:Int64);
begin
with TfrmCommandPrint.Create(Application.MainForm,DBHandle,id_order) do
begin
ShowModal;
Free;
end;
end;
procedure TfrmCommandPrint.CancelButtonClick(Sender: TObject);
begin
Close;
end;
constructor TfrmCommandPrint.Create(AOwner: TComponent; DbHandle: TISC_DB_HANDLE;id_order:Int64);
begin
try
inherited Create(AOwner);
CommandDB.handle:=DbHandle;
ReadTrans.StartTransaction;
self.id_order_in:=id_order;
RectorSpr.Text:=KYVLoadFromRegistry('CommandRector',GetUserId);
ProrectorSpr.Text:=KYVLoadFromRegistry('CommandProrector',GetUserId);
NamePost.Text:=KYVLoadFromRegistry('CommandRectorPost', GetUserId);
except on E:Exception do
begin
agMessageDlg(Application.Title, E.Message, mtInformation, [mbOK]);
end;
end;
end;
procedure TfrmCommandPrint.SizeFontKeyPress(Sender: TObject;
var Key: Char);
begin
if ((key<>#8) and ((key > '9') or (key < '0'))) then
key := Chr(0);
end;
procedure TfrmCommandPrint.OkButtonClick(Sender: TObject);
begin
if CertDSet.Active then CertDSet.Close;
CertDSet.SQLs.SelectSQL.Text:='Select Distinct * From Up_Command_Certificate_Print(:Id_Order)';
CertDSet.ParamByName('Id_Order').AsInt64:=id_order_in;
CertDSet.Open;
if OrderDSet.Active then OrderDSet.Close;
OrderDSet.SQLs.SelectSQL.Text:='Select Distinct * From Up_Command_Order_Print(:Id_Order)';
OrderDSet.ParamByName('Id_Order').AsInt64:=id_order_in;
OrderDSet.Open;
if ((not CertDSet.IsEmpty) and (not OrderDSet.IsEmpty)) then
begin
ReportPrint.Clear;
ReportPrint.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Up\UpCommandPrint.fr3', True);
ReportPrint.Variables['Rector'] :=''''+RectorSpr.Text+'''';
ReportPrint.Variables['Prorector'] :=''''+ProrectorSpr.Text+'''';
ReportPrint.Variables['RectorPost'] := ''''+NamePost.Text+'''';
ReportPrint.ShowReport;
end;
end;
procedure TfrmCommandPrint.ProrectorSprPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Params:TUnivParams;
OutPut : TRxMemoryData;
begin
Params.FormCaption:=' ';
Params.ShowMode:=fsmSelect;
Params.ShowButtons:=[fbExit];
Params.TableName:='up_get_text_shablon(6)';
Params.Fields:='text1,text2,id_shablon';
Params.FieldsName:='ПІБ,Посада';
Params.KeyField:='ID_shablon';
Params.ReturnFields:='text1,text2';
Params.DBHandle:=Integer(CommandDB.Handle);
OutPut:=TRxMemoryData.Create(self);
if GetUnivSprav(Params,OutPut) then
begin
ProrectorSpr.Text:=VarToStr(output['text1']);
KYVSaveIntoRegistry('CommandProrector',ProrectorSpr.Text,GetUserId);
end;
end;
procedure TfrmCommandPrint.RectorSprPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
Params:TUnivParams;
OutPut : TRxMemoryData;
begin
Params.FormCaption:=' ';
Params.ShowMode:=fsmSelect;
Params.ShowButtons:=[fbExit];
Params.TableName:='up_get_text_shablon(6)';
Params.Fields:='text1,text2,id_shablon';
Params.FieldsName:='ПІБ,Посада';
Params.KeyField:='ID_shablon';
Params.ReturnFields:='text1,text2';
Params.DBHandle:=Integer(CommandDB.Handle);
OutPut:=TRxMemoryData.Create(self);
if GetUnivSprav(Params,OutPut) then
begin
RectorSpr.Text:=VarToStr(output['text1']);
NamePost.Text:=VarToStr(output['text2']);
KYVSaveIntoRegistry('CommandRector',RectorSpr.Text,GetUserId);
KYVSaveIntoRegistry('CommandRectorPost', NamePost.Text, GetUserId);
end;
end;
procedure TfrmCommandPrint.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
var i:Byte;
begin
for i:=0 to CommandDB.TransactionCount-1 do
begin
if CommandDB.Transactions[i].Active then CommandDB.Transactions[i].RollBack;
end;
CommandDB.Close;
CanClose:=True;
end;
end.
|
unit uInterfaces;
interface
type
IViewModel = interface
['{68989DD0-5306-42CE-B90D-852B8BA6CC07}']
end;
TViewModel = class(TInterfacedObject, IViewModel)
public
constructor Create; overload;
destructor Destroy; override;
end;
TViewModelClass = class of TViewModel;
IVM_User<I: IViewModel; K: TViewModel> = interface
['{E70146E0-464C-4604-8602-66B1702C3341}']
function GetVM_AsInterface: I;
function GetVM_AsObject: K;
property VM_AsInterface: I read GetVM_AsInterface;
property VM_AsObject: K read GetVM_AsObject;
end;
IView = interface
['{AFCC9C0D-321F-4197-8FC0-6343B43FCF62}']
end;
implementation
{ TViewModel }
constructor TViewModel.Create;
begin
inherited;
end;
destructor TViewModel.Destroy;
begin
inherited;
end;
end.
|
unit MetaData;
interface
uses
System.Classes, FireDAC.Comp.Client, Data.DB;
type
TReference = class
Table: String;
TableTag: Integer;
Field: String;
Name: String;
Caption: String;
Width: Integer;
end;
type
TSort = (None, Up, Down);
type
TField = class
FieldName: String;
FieldCaption: String;
FieldWidth: Integer;
References: TReference;
FieldVisible: Boolean;
Sorted: TSort;
procedure AddReferense(ARefTable: String = ''; ARefField: String = '';
ARefName: String = ''; ARefCaption: String = ''; ARefWidth: Integer = 0;
ARefTableTag: Integer = -1);
end;
type
TTable = class
TableName: String;
TableCaption: String;
TableFields: array of TField;
function GetFieldsCount(ATag: Integer): Integer;
function AddField(AFieldName, AFieldCaption: String; AFieldWidth: Integer;
AFieldVisible: Boolean; ASorted: TSort = None): TField;
function GetDataList(Index: Integer): TStringList;
end;
type
TMData = class
public
Tables: array of TTable;
function GetTablesCount: Integer;
property TablesCount: Integer read GetTablesCount;
function AddTable(ATableName, ATableCaption: string): TTable;
end;
var
TablesMetaData: TMData;
implementation
{ TMData }
uses SQLGenerator, ConnectionForm;
function TTable.AddField(AFieldName, AFieldCaption: String;
AFieldWidth: Integer; AFieldVisible: Boolean; ASorted: TSort = None): TField;
begin
SetLength(TableFields, Length(TableFields) + 1);
TableFields[high(TableFields)] := TField.Create;
with TableFields[High(TableFields)] do
begin
FieldName := AFieldName;
FieldCaption := AFieldCaption;
FieldWidth := AFieldWidth;
FieldVisible := AFieldVisible;
Sorted := ASorted;
end;
Result := TableFields[high(TableFields)];
end;
function TMData.AddTable(ATableName, ATableCaption: string): TTable;
begin
SetLength(Tables, Length(Tables) + 1);
Tables[High(Tables)] := TTable.Create;
with Tables[High(Tables)] do
begin
TableName := ATableName;
TableCaption := ATableCaption;
end;
Result := Tables[High(Tables)];
end;
function TMData.GetTablesCount: Integer;
begin
Result := Length(TablesMetaData.Tables);
end;
{ TTable }
function TTable.GetDataList(Index: Integer): TStringList;
var
Query: TFDQuery;
DataSource: TDataSource;
begin
Result := TStringList.Create;
Query := TFDQuery.Create(Nil);
Query.Connection := ConnectionFormWindow.MainConnection;
DataSource := TDataSource.Create(Nil);
DataSource.DataSet := Query;
Query.Active := false;
if Self.TableFields[Index].References = Nil then
Query.SQL.Text := 'SELECT ' + Self.TableFields[Index].FieldName + ' FROM ' +
Self.TableName
else
Query.SQL.Text := 'SELECT ' + Self.TableFields[Index].References.Name +
' FROM ' + Self.TableFields[Index].References.Table;
Query.Active := true;
while not Query.Eof do
begin
Result.Append(String(Query.Fields.Fields[0].Value));
Query.Next;
end;
end;
function TTable.GetFieldsCount(ATag: Integer): Integer;
begin
Result := Length(TablesMetaData.Tables[ATag].TableFields)
end;
{ TField }
procedure TField.AddReferense(ARefTable: String = ''; ARefField: String = '';
ARefName: String = ''; ARefCaption: String = ''; ARefWidth: Integer = 0;
ARefTableTag: Integer = -1);
begin
References := TReference.Create;
References.Table := ARefTable;
References.Field := ARefField;
References.Name := ARefName;
References.Caption := ARefCaption;
References.Width := ARefWidth;
References.TableTag := ARefTableTag;
end;
initialization
TablesMetaData := TMData.Create;
with TablesMetaData do
begin
with AddTable('AUDITORIES', 'Аудитории') do
begin
AddField('ID', 'ID', 50, false);
AddField('AUD_CAPTION', 'Номер', 100, true);
end;
with AddTable('DISCIPLINES', 'Дисциплины') do
begin
AddField('ID', 'ID', 50, false);
AddField('DIS_CAPTION', 'Дисциплина', 200, true);
end;
with AddTable('DISCIPLINE_PROFESSOR', 'Преподаватели - Дисциплины') do
begin
AddField('ID', 'ID', 50, false);
AddField('PROF_ID', 'ID Преподавателя', 100, false)
.AddReferense('PROFESSORS', 'ID', 'PROF_NAME',
'ФИО Перподавателя', 200, 5);
AddField('DIS_ID', 'ID Дисциплины', 100, false).AddReferense('DISCIPLINES',
'ID', 'DIS_CAPTION', 'Дисциплина', 200, 1);
end;
with AddTable('GROUP_DISCIPLINE', 'Группы - Дисциплины') do
begin
AddField('ID', 'ID', 50, false);
AddField('GROUP_ID', 'ID Группы', 100, false).AddReferense('GROUPS', 'ID',
'GROUP_NUMBER', 'Группа', 100, 9);
AddField('DISCIPLINE_ID', 'ID Дисциплины', 100, false)
.AddReferense('DISCIPLINES', 'ID', 'DIS_CAPTION', 'Дисциплина', 200, 1);
end;
with AddTable('LESSON_TYPES', 'Типы Занятий') do
begin
AddField('ID', 'ID', 50, false);
AddField('LES_TYPE_CAPTION', 'Тип занятия', 200, true);
end;
with AddTable('PROFESSORS', 'Преподаватели') do
begin
AddField('ID', 'ID', 50, false);
AddField('PROF_NAME', 'ФИО', 200, true);
end;
with AddTable('SCHEDULE', 'Расписание') do
begin
AddField('ID', 'ID', 50, false);
AddField('GROUP_ID', 'ID Группы', 100, false).AddReferense('GROUPS', 'ID',
'GROUP_NUMBER', 'Группа', 100, 9);
AddField('LES_TYPE_ID', 'ID Типа Занятия', 100, false)
.AddReferense('LESSON_TYPES', 'ID', 'LES_TYPE_CAPTION',
'Тип Занятия', 200, 4);
AddField('DIS_ID', 'ID Дисциплины', 100, false).AddReferense('DISCIPLINES',
'ID', 'DIS_CAPTION', 'Дисциплина', 200, 1);
AddField('TIME_ID', 'ID Пары', 100, false).AddReferense('TIMES', 'ID',
'TIME_CAPTION', 'Время', 100, 7);
AddField('AUD_ID', 'ID Аудитории', 100, false).AddReferense('AUDITORIES',
'ID', 'AUD_CAPTION', 'Аудитория', 100, 0);
AddField('PROF_ID', 'ID Преподавателя', 100, false)
.AddReferense('PROFESSORS', 'ID', 'PROF_NAME', 'ФИО Преподавателя', 200, 5);
AddField('WEEKDAY_ID', 'ID Дня', 100, false).AddReferense('WEEKDAYS', 'ID',
'WEEKDAY_CAPTION', 'День Недели', 100, 8);
end;
with AddTable('TIMES', 'Время') do
begin
AddField('ID', 'ID', 50, false);
AddField('TIME_CAPTION', 'Пара', 100, true);
AddField('TIME_START_TIME', 'Начало Пары', 100, true);
AddField('TIME_END_TIME', 'Конец Пары', 100, true);
end;
with AddTable('WEEKDAYS', 'Дни Недели') do
begin
AddField('ID', 'ID', 50, false);
AddField('WEEKDAY_CAPTION', 'День', 100, true);
AddField('WEEKDAY_NUMBER', 'Номер', 50, true);
end;
with AddTable('GROUPS', 'Группы') do
begin
AddField('ID', 'ID', 50, false);
AddField('GROUP_NUMBER', 'Номер', 100, true);
//AddField('GROUP_NAME', 'Название', 200, true);
end;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [NFE_DETALHE_IMPOSTO_PIS]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit NfeDetalheImpostoPisVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL;
type
TNfeDetalheImpostoPisVO = class(TVO)
private
FID: Integer;
FID_NFE_DETALHE: Integer;
FCST_PIS: String;
FQUANTIDADE_VENDIDA: Extended;
FVALOR_BASE_CALCULO_PIS: Extended;
FALIQUOTA_PIS_PERCENTUAL: Extended;
FALIQUOTA_PIS_REAIS: Extended;
FVALOR_PIS: Extended;
published
property Id: Integer read FID write FID;
property IdNfeDetalhe: Integer read FID_NFE_DETALHE write FID_NFE_DETALHE;
property CstPis: String read FCST_PIS write FCST_PIS;
property QuantidadeVendida: Extended read FQUANTIDADE_VENDIDA write FQUANTIDADE_VENDIDA;
property ValorBaseCalculoPis: Extended read FVALOR_BASE_CALCULO_PIS write FVALOR_BASE_CALCULO_PIS;
property AliquotaPisPercentual: Extended read FALIQUOTA_PIS_PERCENTUAL write FALIQUOTA_PIS_PERCENTUAL;
property AliquotaPisReais: Extended read FALIQUOTA_PIS_REAIS write FALIQUOTA_PIS_REAIS;
property ValorPis: Extended read FVALOR_PIS write FVALOR_PIS;
end;
TListaNfeDetalheImpostoPisVO = specialize TFPGObjectList<TNfeDetalheImpostoPisVO>;
implementation
initialization
Classes.RegisterClass(TNfeDetalheImpostoPisVO);
finalization
Classes.UnRegisterClass(TNfeDetalheImpostoPisVO);
end.
|
unit AutoPilot;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, sButton, sLabel, ExtCtrls;
type
TAutoPilotForm = class(TForm)
StopAutoPilot: TsButton;
sLabel1: TsLabel;
LabelTime: TsLabel;
Counter: TTimer;
sLabel2: TsLabel;
sLabel3: TsLabel;
sLabel4: TsLabel;
sLabel5: TsLabel;
LabelMap: TsLabel;
sLabel7: TsLabel;
sLabel8: TsLabel;
sLabel9: TsLabel;
procedure StopAutoPilotClick(Sender: TObject);
procedure FormHide(Sender: TObject);
procedure CounterTimer(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
AutoPilotForm: TAutoPilotForm;
s, m , h: Integer;
implementation
uses BlockUnit, Unit1;
{$R *.dfm}
procedure TAutoPilotForm.CounterTimer(Sender: TObject);
begin
//Update labels
LabelMap.Caption := Unit1.currentMap;
//Count
s := s + 1;
if s = 60 then begin
s := 0;
m := m + 1;
if m = 60 then begin
m := 0;
h := h + 1;
end;
end;
LabelTime.Caption := IntToStr(h) + ' hours ' + IntToStr(m) + ' minutes ' + IntToStr(s) + ' seconds';
end;
procedure TAutoPilotForm.FormHide(Sender: TObject);
begin
Block.Hide;
Counter.Enabled := false;
s := 0;
m := 0;
h := 0;
LabelTime.Caption := '0 hours 0 minutes 0 seconds';
end;
procedure TAutoPilotForm.FormShow(Sender: TObject);
begin
Counter.Enabled := true;
end;
procedure TAutoPilotForm.StopAutoPilotClick(Sender: TObject);
begin
AutoPilotForm.Hide;
end;
end.
|
unit MT5.Utils;
interface
uses
System.SysUtils, System.SyncObjs, System.Classes, System.Math, System.StrUtils, System.Hash;
type
TMTUtils = class
private
{ private declarations }
protected
{ protected declarations }
public
{ public declarations }
class procedure AsynAwait(AProc: TProc);
class function BytesToStr(ABytes: TArray<Byte>): string;
class function StrToHex(AString: string): string;
class function HexToInt(AHexadecimal: string): Integer;
class function GetHex(AHash: TArray<Byte>): string;
class function GetMD5(AInput: TArray<Byte>): TArray<Byte>;
class function Quotes(AString: string): string;
class function GetString(ABytes: TArray<Byte>): string;
class function GetFromHex(AHexString: string): TArray<Byte>;
class function GetRandomHex(ALength: Integer): TArray<Byte>;
class function GetHashFromPassword(APassword: string; ARandCode: TArray<Byte>): TArray<Byte>;
class function CompareBytes(ABytesLeft: TArray<Byte>; ABytesRight: TArray<Byte>): Boolean;
class function ToOldVolume(ANewVolume: Int64): Int64;
class function ToNewVolume(AOldVolume: Int64): Int64;
class function GetEndPosHeaderData(AHeaderData: TArray<Byte>): Int64;
end;
implementation
{ TMTUtils }
uses
MT5.Protocol;
class procedure TMTUtils.AsynAwait(AProc: TProc);
var
LEvent: TEvent;
begin
LEvent := TEvent.Create;
try
TThread.CreateAnonymousThread(
procedure
begin
try
AProc;
finally
LEvent.SetEvent;
end;
end
).Start;
LEvent.WaitFor;
finally
LEvent.Free;
end;
end;
class function TMTUtils.BytesToStr(ABytes: TArray<Byte>): string;
var
I: Integer;
begin
Result := EmptyStr;
for I := Low(ABytes) to High(ABytes) do
Result := Result + Chr(ABytes[I]);
end;
class function TMTUtils.CompareBytes(ABytesLeft, ABytesRight: TArray<Byte>): Boolean;
var
I: Integer;
begin
if Length(ABytesLeft) = 0 then
Exit(Length(ABytesRight) = 0);
if Length(ABytesRight) = 0 then
Exit(False);
if Length(ABytesLeft) <> Length(ABytesRight) then
Exit(False);
for I := Low(ABytesLeft) to High(ABytesLeft) do
begin
if ABytesLeft[I] <> ABytesRight[I] then
Exit(False)
end;
Exit(True);
end;
class function TMTUtils.GetEndPosHeaderData(AHeaderData: TArray<Byte>): Int64;
var
LPos: Int64;
I: Integer;
begin
LPos := 0;
try
for I := Low(AHeaderData) to High(AHeaderData) div 9 do
begin
if AHeaderData[(I + 1) * 9 + 1] = $0 then
begin
LPos := (I + 1) * 9;
Break;
end;
end;
finally
Result := LPos;
end;
end;
class function TMTUtils.GetFromHex(AHexString: string): TArray<Byte>;
var
I: Integer;
begin
if AHexString.IsEmpty then
Exit();
if Length(AHexString) mod 2 <> 0 then
Exit();
SetLength(Result, Length(AHexString) div 2);
I := 0;
while I < Length(AHexString) do
begin
Result[I div 2] := Byte(HexToInt(AHexString.Substring(I, 2)));
Inc(I, 2);
end;
end;
class function TMTUtils.GetHashFromPassword(APassword: string; ARandCode: TArray<Byte>): TArray<Byte>;
var
LHash: TArray<Byte>;
LApiWord: TArray<Byte>;
LHashContains: TArray<Byte>;
begin
if Length(ARandCode) = 0 then
Exit();
try
LHash := GetMD5(TEncoding.Unicode.GetBytes(APassword));
if Length(LHash) = 0 then
Exit();
LApiWord := TEncoding.UTF8.GetBytes(TMTProtocolConsts.WEB_API_WORD);
LHashContains := LHash + LApiWord;
if Length(LHashContains) = 0 then
Exit();
LHash := GetMD5(LHashContains);
if Length(LHash) = 0 then
Exit();
LHashContains := LHash + ARandCode;
if Length(LHashContains) = 0 then
Exit();
Exit(GetMD5(LHashContains));
except
Exit();
end;
end;
class function TMTUtils.GetHex(AHash: TArray<Byte>): string;
var
I: Integer;
begin
Result := '';
if Length(AHash) = 0 then
Exit;
for I := Low(AHash) to High(AHash) do
Result := Result + IntToHex(AHash[I], 2);
end;
class function TMTUtils.GetMD5(AInput: TArray<Byte>): TArray<Byte>;
var
LMemoryStream: TMemoryStream;
begin
LMemoryStream := TMemoryStream.Create;
try
LMemoryStream.Position := 0;
LMemoryStream.WriteBuffer(AInput, Length(AInput));
LMemoryStream.Position := 0;
Result := THashMD5.GetHashBytes(LMemoryStream);
finally
LMemoryStream.Free;
end;
end;
class function TMTUtils.GetRandomHex(ALength: Integer): TArray<Byte>;
var
I: Integer;
begin
SetLength(Result, 16);
for I := Low(Result) to High(Result) do
Result[I] := Byte(Random(256) - 1);
end;
class function TMTUtils.GetString(ABytes: TArray<Byte>): string;
begin
try
Result := TEncoding.Unicode.GetString(ABytes);
except
Result := EmptyStr;
end;
end;
class function TMTUtils.HexToInt(AHexadecimal: String): Integer;
begin
Result := StrToInt('$' + AHexadecimal);
end;
class function TMTUtils.Quotes(AString: string): string;
begin
Result := AString.Replace('\\', '\\\\');
Result := Result.Replace('=', '\=');
Result := Result.Replace('|', '\|');
Result := Result.Replace('\n', '\\\n');
end;
class function TMTUtils.StrToHex(AString: string): string;
var
I: Integer;
begin
Result := '';
for I := 1 to Length(AString) do
Result := Result + IntToHex(Ord(AString[I]), 2);
end;
class function TMTUtils.ToNewVolume(AOldVolume: Int64): Int64;
begin
Result := AOldVolume * 10000;
end;
class function TMTUtils.ToOldVolume(ANewVolume: Int64): Int64;
begin
Result := ANewVolume div 10000;
end;
end.
|
unit FormMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,Voxel_Engine, Menus, ExtCtrls, StdCtrls, Voxel, ComCtrls, ToolWin,
ImgList, Math, palette, Spin, Buttons, ogl3dview_engine,OpenGL15,FTGifAnimate,
undo_engine,ShellAPI,Constants,cls_Config,pause,FormNewVxlUnit,mouse,Registry,
Form3dpreview,Debug, FormAutoNormals, XPMan;
{$INCLUDE Global_Conditionals.inc}
Const
APPLICATION_TITLE = 'Voxel Section Editor III';
APPLICATION_VER = '1.38';
type
TFrmMain = class(TForm)
MainMenu1: TMainMenu;
File1: TMenuItem;
Open1: TMenuItem;
OpenVXLDialog: TOpenDialog;
Panel1: TPanel;
LeftPanel: TPanel;
RightPanel: TPanel;
MainPaintPanel: TPanel;
CnvView2: TPaintBox;
CnvView1: TPaintBox;
lblView1: TLabel;
lblView2: TLabel;
lblView0: TLabel;
View1: TMenuItem;
lblSection: TLabel;
ViewMode1: TMenuItem;
Full1: TMenuItem;
CrossSection1: TMenuItem;
EmphasiseDepth1: TMenuItem;
Panel2: TPanel;
ToolBar1: TToolBar;
BarOpen: TToolButton;
BarSaveAs: TToolButton;
BarReopen: TToolButton;
ToolButton4: TToolButton;
mnuBarUndo: TToolButton;
mnuBarRedo: TToolButton;
ToolButton10: TToolButton;
ToolButton7: TToolButton;
ToolButton3: TToolButton;
ToolButton6: TToolButton;
ToolButton13: TToolButton;
ToolButton11: TToolButton;
ToolButton1: TToolButton;
ToolButton8: TToolButton;
ToolButton9: TToolButton;
ImageList1: TImageList;
Spectrum1: TMenuItem;
Colours1: TMenuItem;
Normals1: TMenuItem;
Panel3: TPanel;
SectionCombo: TComboBox;
lblTools: TLabel;
Panel4: TPanel;
lblpalette: TLabel;
cnvPalette: TPaintBox;
pnlPalette: TPanel;
lblActiveColour: TLabel;
pnlActiveColour: TPanel;
ScrollBar2: TScrollBar;
Panel5: TPanel;
ScrollBar1: TScrollBar;
Panel6: TPanel;
N2: TMenuItem;
ShowUsedColoursNormals1: TMenuItem;
lbl3dview: TLabel;
OGL3DPreview: TPanel;
Panel7: TPanel;
SpeedButton2: TSpeedButton;
btn3DRotateX2: TSpeedButton;
btn3DRotateY2: TSpeedButton;
btn3DRotateY: TSpeedButton;
Bevel1: TBevel;
SpeedButton1: TSpeedButton;
btn3DRotateX: TSpeedButton;
spin3Djmp: TSpinEdit;
ColorDialog: TColorDialog;
Popup3d: TPopupMenu;
Views1: TMenuItem;
Front1: TMenuItem;
Back1: TMenuItem;
MenuItem1: TMenuItem;
LEft1: TMenuItem;
Right1: TMenuItem;
MenuItem2: TMenuItem;
Bottom1: TMenuItem;
op1: TMenuItem;
N3: TMenuItem;
Cameo1: TMenuItem;
Cameo21: TMenuItem;
Cameo31: TMenuItem;
Cameo41: TMenuItem;
Options2: TMenuItem;
DebugMode1: TMenuItem;
RemapColour1: TMenuItem;
Gold1: TMenuItem;
Red1: TMenuItem;
Orange1: TMenuItem;
Magenta1: TMenuItem;
Purple1: TMenuItem;
Blue1: TMenuItem;
Green1: TMenuItem;
DarkSky1: TMenuItem;
White1: TMenuItem;
N4: TMenuItem;
BackgroundColour1: TMenuItem;
extColour1: TMenuItem;
N5: TMenuItem;
lblLayer: TLabel;
pnlLayer: TPanel;
XCursorBar: TTrackBar;
Label2: TLabel;
Label3: TLabel;
YCursorBar: TTrackBar;
Label4: TLabel;
ZCursorBar: TTrackBar;
StatusBar1: TStatusBar;
mnuDirectionPopup: TPopupMenu;
mnuEdit: TMenuItem;
mnuDirTowards: TMenuItem;
mnuDirAway: TMenuItem;
mnuCancel1: TMenuItem;
lblBrush: TLabel;
Panel8: TPanel;
Brush_5: TSpeedButton;
Brush_4: TSpeedButton;
Brush_3: TSpeedButton;
Brush_2: TSpeedButton;
Brush_1: TSpeedButton;
SpeedButton3: TSpeedButton;
SpeedButton4: TSpeedButton;
SpeedButton5: TSpeedButton;
SpeedButton6: TSpeedButton;
SpeedButton9: TSpeedButton;
SpeedButton7: TSpeedButton;
SpeedButton8: TSpeedButton;
SpeedButton10: TSpeedButton;
SpeedButton11: TSpeedButton;
NewProject1: TMenuItem;
ReOpen1: TMenuItem;
N1: TMenuItem;
Save1: TMenuItem;
SaveAs1: TMenuItem;
N6: TMenuItem;
N7: TMenuItem;
N8: TMenuItem;
Exit1: TMenuItem;
EmptyVoxel1: TMenuItem;
EmptyVoxel2: TMenuItem;
Section1: TMenuItem;
VoxelHeader1: TMenuItem;
SaveVXLDialog: TSaveDialog;
New1: TMenuItem;
N9: TMenuItem;
Resize1: TMenuItem;
FullResize1: TMenuItem;
Delete1: TMenuItem;
ClearLayer1: TMenuItem;
ClearEntireSection1: TMenuItem;
normalsaphere1: TMenuItem;
ools2: TMenuItem;
N10: TMenuItem;
Edit1: TMenuItem;
Undo1: TMenuItem;
Redo1: TMenuItem;
N11: TMenuItem;
RemoveRedundentVoxels1: TMenuItem;
CnvView0: TPaintBox;
Sites1: TMenuItem;
CnCSource1: TMenuItem;
PPMForUpdates1: TMenuItem;
N13: TMenuItem;
Editing1: TMenuItem;
General1: TMenuItem;
ResourceSites1: TMenuItem;
ools3: TMenuItem;
CGen1: TMenuItem;
Dezire1: TMenuItem;
PlanetCNC1: TMenuItem;
PixelOps1: TMenuItem;
ESource1: TMenuItem;
MadHQGraphicsDump1: TMenuItem;
YRArgentina1: TMenuItem;
ibEd1: TMenuItem;
XCC1: TMenuItem;
Help1: TMenuItem;
VXLSEHelp1: TMenuItem;
N14: TMenuItem;
About1: TMenuItem;
Options1: TMenuItem;
Preferences1: TMenuItem;
Display3dView1: TMenuItem;
Section2: TMenuItem;
Copyofthissection1: TMenuItem;
Importfrommodel1: TMenuItem;
Flip1: TMenuItem;
N15: TMenuItem;
Mirror1: TMenuItem;
Nudge1: TMenuItem;
FlipXswitchFrontBack1: TMenuItem;
FlipYswitchRightLeft1: TMenuItem;
FlipZswitchTopBottom1: TMenuItem;
MirrorBottomToTop1: TMenuItem;
MirrorTopToBottom1: TMenuItem;
N16: TMenuItem;
MirrorLeftToRight1: TMenuItem;
MirrorRightToLeft1: TMenuItem;
N17: TMenuItem;
MirrorBackToFront1: TMenuItem;
Nudge1Left1: TMenuItem;
Nudge1Right1: TMenuItem;
Nudge1up1: TMenuItem;
Nudge1Down1: TMenuItem;
RedUtils1: TMenuItem;
Palette1: TMenuItem;
iberianSunPalette1: TMenuItem;
RedAlert2Palette1: TMenuItem;
Custom1: TMenuItem;
N18: TMenuItem;
blank1: TMenuItem;
SpeedButton12: TSpeedButton;
N19: TMenuItem;
DarkenLightenValue1: TMenuItem;
N110: TMenuItem;
N21: TMenuItem;
N31: TMenuItem;
N41: TMenuItem;
N51: TMenuItem;
ClearVoxelColour1: TMenuItem;
Copy1: TMenuItem;
Cut1: TMenuItem;
ClearUndoSystem1: TMenuItem;
IconList: TImageList;
PasteFull1: TMenuItem;
Paste1: TMenuItem;
ColourScheme1: TMenuItem;
N22: TMenuItem;
iberianSun2: TMenuItem;
RedAlert22: TMenuItem;
YurisRevenge1: TMenuItem;
blank2: TMenuItem;
blank3: TMenuItem;
blank4: TMenuItem;
PalPack1: TMenuItem;
N23: TMenuItem;
About2: TMenuItem;
N24: TMenuItem;
Allied1: TMenuItem;
Soviet1: TMenuItem;
Yuri1: TMenuItem;
Blue2: TMenuItem;
Brick1: TMenuItem;
Brown11: TMenuItem;
Brown21: TMenuItem;
Grayscale1: TMenuItem;
Green2: TMenuItem;
NoUnlit1: TMenuItem;
Remap1: TMenuItem;
Red2: TMenuItem;
Yellow1: TMenuItem;
blank5: TMenuItem;
blank6: TMenuItem;
blank7: TMenuItem;
blank8: TMenuItem;
blank9: TMenuItem;
blank10: TMenuItem;
blank11: TMenuItem;
blank12: TMenuItem;
blank13: TMenuItem;
blank14: TMenuItem;
blank15: TMenuItem;
blank16: TMenuItem;
blank17: TMenuItem;
ToolButton2: TToolButton;
ToolButton14: TToolButton;
OpenDialog1: TOpenDialog;
DisableDrawPreview1: TMenuItem;
SmoothNormals1: TMenuItem;
Disable3dView1: TMenuItem;
ReplaceColours1: TMenuItem;
Normals3: TMenuItem;
Colours2: TMenuItem;
VoxelTexture1: TMenuItem;
N12: TMenuItem;
test1: TMenuItem;
AcidVat1: TMenuItem;
RA2GraphicsHeaven1: TMenuItem;
CnCGuild1: TMenuItem;
iberiumSunCom1: TMenuItem;
Scripts1: TMenuItem;
SpinButton3: TSpinButton;
SpinButton1: TSpinButton;
SpinButton2: TSpinButton;
TopBarImageHolder: TImage;
MainViewPopup: TPopupMenu;
Magnification1: TMenuItem;
N1x1: TMenuItem;
N3x1: TMenuItem;
N5x1: TMenuItem;
N7x1: TMenuItem;
N9x1: TMenuItem;
N10x1: TMenuItem;
N131: TMenuItem;
N15x1: TMenuItem;
N17x1: TMenuItem;
N19x1: TMenuItem;
N21x1: TMenuItem;
N23x1: TMenuItem;
N25x1: TMenuItem;
ToolButton5: TToolButton;
ToolButton12: TToolButton;
CubedAutoNormals1: TMenuItem;
SpeedButton13: TSpeedButton;
Others1: TMenuItem;
blank18: TMenuItem;
MirrorFrontToBack2: TMenuItem;
RockTheBattlefield1: TMenuItem;
RenegadeProjects1: TMenuItem;
RevoraCCForums1: TMenuItem;
Display3DWindow1: TMenuItem;
PPMModdingForums1: TMenuItem;
VKHomepage1: TMenuItem;
ProjectSVN1: TMenuItem;
XPManifest1: TXPManifest;
CNCNZcom1: TMenuItem;
CCFilefront1: TMenuItem;
procedure CCFilefront1Click(Sender: TObject);
procedure CNCNZcom1Click(Sender: TObject);
procedure ProjectSVN1Click(Sender: TObject);
procedure VKHomepage1Click(Sender: TObject);
procedure PPMModdingForums1Click(Sender: TObject);
procedure FormDeactivate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure NewAutoNormals1Click(Sender: TObject);
procedure Display3DWindow1Click(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure RevoraCCForums1Click(Sender: TObject);
procedure RenegadeProjects1Click(Sender: TObject);
procedure RockTheBattlefield1Click(Sender: TObject);
procedure Open1Click(Sender: TObject);
procedure CnvView0Paint(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure changecaption(Filename : boolean; FName : string);
procedure CnvView1Paint(Sender: TObject);
procedure CnvView2Paint(Sender: TObject);
Procedure SetIsEditable(Value : boolean);
Procedure RefreshAll;
Procedure SetupSections;
procedure SectionComboChange(Sender: TObject);
procedure Full1Click(Sender: TObject);
procedure CrossSection1Click(Sender: TObject);
procedure EmphasiseDepth1Click(Sender: TObject);
Procedure SetViewMode(VM : EViewMode);
Procedure SetSpectrum(SP : ESpectrumMode);
procedure Colours1Click(Sender: TObject);
procedure Normals1Click(Sender: TObject);
procedure cnvPalettePaint(Sender: TObject);
procedure SetActiveColor(Value : integer; CN : boolean);
procedure SetActiveNormal(Value : integer; CN : boolean);
Procedure SetActiveCN(Value : integer);
procedure ScrollBar1Change(Sender: TObject);
procedure setupscrollbars;
procedure FormShow(Sender: TObject);
procedure cnvPaletteMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ShowUsedColoursNormals1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure OGL3DPreviewMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure OGL3DPreviewMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure OGL3DPreviewMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure SpeedButton1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure DebugMode1Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure btn3DRotateXClick(Sender: TObject);
Procedure SetRotationAdders;
procedure btn3DRotateX2Click(Sender: TObject);
procedure btn3DRotateY2Click(Sender: TObject);
procedure btn3DRotateYClick(Sender: TObject);
procedure spin3DjmpChange(Sender: TObject);
procedure BackgroundColour1Click(Sender: TObject);
procedure extColour1Click(Sender: TObject);
procedure ClearRemapClicks;
procedure Gold1Click(Sender: TObject);
procedure Red1Click(Sender: TObject);
procedure Orange1Click(Sender: TObject);
procedure Magenta1Click(Sender: TObject);
procedure Purple1Click(Sender: TObject);
procedure Blue1Click(Sender: TObject);
procedure Green1Click(Sender: TObject);
procedure DarkSky1Click(Sender: TObject);
procedure White1Click(Sender: TObject);
procedure Front1Click(Sender: TObject);
procedure Back1Click(Sender: TObject);
procedure LEft1Click(Sender: TObject);
procedure Right1Click(Sender: TObject);
procedure Bottom1Click(Sender: TObject);
procedure op1Click(Sender: TObject);
procedure Cameo1Click(Sender: TObject);
procedure Cameo21Click(Sender: TObject);
procedure Cameo31Click(Sender: TObject);
procedure Cameo41Click(Sender: TObject);
procedure CnvView2MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure CnvView1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure CnvView1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure CnvView1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure CnvView2MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure CnvView2MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure CnvView0MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
Procedure UpdateCursor(P : TVector3i; Repaint : Boolean);
procedure XCursorBarChange(Sender: TObject);
Procedure CursorReset;
Procedure CursorResetNoMAX;
Procedure SetupStatusBar;
procedure CnvView0MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure lblView1Click(Sender: TObject);
procedure lblView2Click(Sender: TObject);
procedure mnuDirectionPopupPopup(Sender: TObject);
procedure mnuEditClick(Sender: TObject);
procedure mnuDirTowardsClick(Sender: TObject);
procedure mnuDirAwayClick(Sender: TObject);
procedure DoAfterLoadingThings;
procedure Brush_1Click(Sender: TObject);
procedure Brush_2Click(Sender: TObject);
procedure Brush_3Click(Sender: TObject);
procedure Brush_4Click(Sender: TObject);
procedure Brush_5Click(Sender: TObject);
procedure SpeedButton3Click(Sender: TObject);
Procedure SetVXLTool(VXLTool_ : Integer);
procedure CnvView0MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure SpeedButton5Click(Sender: TObject);
procedure SpeedButton4Click(Sender: TObject);
procedure SpeedButton10Click(Sender: TObject);
procedure SpeedButton11Click(Sender: TObject);
procedure SpeedButton6Click(Sender: TObject);
procedure SpeedButton8Click(Sender: TObject);
procedure Save1Click(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure SaveAs1Click(Sender: TObject);
procedure VoxelHeader1Click(Sender: TObject);
procedure N6Click(Sender: TObject);
Procedure UpdateUndo_RedoState;
procedure mnuBarUndoClick(Sender: TObject);
procedure mnuBarRedoClick(Sender: TObject);
procedure updatenormals1Click(Sender: TObject);
procedure Delete1Click(Sender: TObject);
procedure normalsaphere1Click(Sender: TObject);
procedure RemoveRedundentVoxels1Click(Sender: TObject);
procedure ClearEntireSection1Click(Sender: TObject);
procedure CnCSource1Click(Sender: TObject);
procedure PPMForUpdates1Click(Sender: TObject);
procedure CGen1Click(Sender: TObject);
procedure Dezire1Click(Sender: TObject);
procedure PlanetCNC1Click(Sender: TObject);
procedure PixelOps1Click(Sender: TObject);
procedure ESource1Click(Sender: TObject);
procedure SavageWarTS1Click(Sender: TObject);
procedure MadHQGraphicsDump1Click(Sender: TObject);
procedure YRArgentina1Click(Sender: TObject);
procedure ibEd1Click(Sender: TObject);
procedure XCC1Click(Sender: TObject);
procedure OpenHyperlink(HyperLink: PChar);
procedure VXLSEHelp1Click(Sender: TObject);
procedure Display3dView1Click(Sender: TObject);
procedure About1Click(Sender: TObject);
procedure FlipXswitchFrontBack1Click(Sender: TObject);
procedure FlipYswitchRightLeft1Click(Sender: TObject);
procedure FlipZswitchTopBottom1Click(Sender: TObject);
procedure MirrorBottomToTop1Click(Sender: TObject);
procedure MirrorLeftToRight1Click(Sender: TObject);
procedure MirrorBackToFront1Click(Sender: TObject);
procedure MirrorFrontToBack1Click(Sender: TObject);
procedure Nudge1Left1Click(Sender: TObject);
procedure Section2Click(Sender: TObject);
procedure Copyofthissection1Click(Sender: TObject);
procedure RedUtils1Click(Sender: TObject);
procedure RA2FAQ1Click(Sender: TObject);
procedure BuildReopenMenu;
procedure mnuHistoryClick(Sender: TObject);
procedure BarReopenClick(Sender: TObject);
procedure iberianSunPalette1Click(Sender: TObject);
procedure RedAlert2Palette1Click(Sender: TObject);
Procedure LoadPalettes;
procedure blank1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
Procedure CheckVXLChanged;
procedure SpeedButton7Click(Sender: TObject);
procedure SpeedButton12Click(Sender: TObject);
Procedure SetDarkenLighten(Value : integer);
procedure N110Click(Sender: TObject);
procedure N21Click(Sender: TObject);
procedure N31Click(Sender: TObject);
procedure N41Click(Sender: TObject);
procedure N51Click(Sender: TObject);
procedure ToolButton11Click(Sender: TObject);
procedure ClearLayer1Click(Sender: TObject);
procedure Copy1Click(Sender: TObject);
procedure Cut1Click(Sender: TObject);
procedure ClearUndoSystem1Click(Sender: TObject);
procedure PasteFull1Click(Sender: TObject);
procedure Paste1Click(Sender: TObject);
function LoadCScheme : integer;
procedure blank2Click(Sender: TObject);
procedure About2Click(Sender: TObject);
function LoadCSchemes(Dir : string; c : integer) : Integer;
procedure EmptyVoxel1Click(Sender: TObject);
procedure EmptyVoxel2Click(Sender: TObject);
Procedure NewVFile(Game : integer);
Procedure SetCursor;
procedure DisableDrawPreview1Click(Sender: TObject);
procedure SmoothNormals1Click(Sender: TObject);
procedure VoxelTexture1Click(Sender: TObject);
procedure test1Click(Sender: TObject);
procedure AcidVat1Click(Sender: TObject);
procedure RA2GraphicsHeaven1Click(Sender: TObject);
procedure CnCGuild1Click(Sender: TObject);
procedure iberiumSunCom1Click(Sender: TObject);
procedure Importfrommodel1Click(Sender: TObject);
procedure Resize1Click(Sender: TObject);
procedure SpinButton3UpClick(Sender: TObject);
procedure SpinButton3DownClick(Sender: TObject);
procedure SpinButton1DownClick(Sender: TObject);
procedure SpinButton1UpClick(Sender: TObject);
procedure SpinButton2DownClick(Sender: TObject);
procedure SpinButton2UpClick(Sender: TObject);
procedure FullResize1Click(Sender: TObject);
procedure ToolButton9Click(Sender: TObject);
procedure SpeedButton9Click(Sender: TObject);
Procedure SelectCorrectPalette;
Procedure SelectCorrectPalette2(Palette : String);
procedure ToolButton13Click(Sender: TObject);
Procedure CreateVxlError(v,n : Boolean);
procedure N1x1Click(Sender: TObject);
procedure CubedAutoNormals1Click(Sender: TObject);
procedure SpeedButton13Click(Sender: TObject);
procedure UpdatePositionStatus(x,y,z : integer);
private
{ Private declarations }
procedure Idle(Sender: TObject; var Done: Boolean);
public
{ Public declarations }
{IsEditable,}IsVXLLoading : boolean;
ShiftPressed : boolean;
AltPressed : boolean;
p_Frm3DPreview : PFrm3DPReview;
{$ifdef DEBUG_FILE}
DebugFile : TDebugFile;
{$endif}
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
uses FormHeaderUnit,LoadForm,FormNewSectionSizeUnit,FormPalettePackAbout,HVA,FormReplaceColour,FormVoxelTexture,
FormHVA,FormBoundsManager, FormImportSection,FormFullResize,FormPreferences,FormVxlError;
procedure RunAProgram (const theProgram, itsParameters, defaultDirectory : string);
var rslt : integer;
msg : string;
begin
rslt := ShellExecute (0, 'open',
pChar (theProgram),
pChar (itsParameters),
pChar (defaultDirectory),
sw_ShowNormal);
if rslt <= 32
then begin
case rslt of
0,
se_err_OOM : msg := 'Out of memory/resources';
error_File_Not_Found : msg := 'File "' + theProgram + '" not found';
error_Path_Not_Found : msg := 'Path not found';
error_Bad_Format : msg := 'Damaged or invalid exe';
se_err_AccessDenied : msg := 'Access denied';
se_err_NoAssoc,
se_err_AssocIncomplete : msg := 'Filename association invalid';
se_err_DDEBusy,
se_err_DDEFail,
se_err_DDETimeOut : msg := 'DDE error';
se_err_Share : msg := 'Sharing violation';
else msg := 'no text';
end; // of case
raise Exception.Create ('ShellExecute error #' + IntToStr (rslt) + ': ' + msg);
end;
end;
procedure TFrmMain.Open1Click(Sender: TObject);
var
HVAName : string;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Open1Click');
{$endif}
IsVXLLoading := true;
Application.OnIdle := nil; //Idle;
CheckVXLChanged;
if OpenVXLDialog.Execute then
SetIsEditable(LoadVoxel(OpenVXLDialog.FileName));
if IsEditable then
begin
if p_Frm3DPreview <> nil then
begin
p_Frm3DPreview^.SpFrame.MaxValue := 1;
p_Frm3DPreview^.SpStopClick(nil);
end;
HVAName := copy(OpenVXLDialog.Filename,1,Length(OpenVXLDialog.FileName) - 3) + 'hva';
if FileExists(HVAName) then
begin
try
if not LoadHVA(HVAName) then
ClearHVA;
except
end;
end
else
ClearHVA;
DoAfterLoadingThings;
end;
IsVXLLoading := false;
end;
procedure TFrmMain.CnvView0Paint(Sender: TObject);
begin
PaintView2(0,true,CnvView[0],ActiveSection.View[0]);
end;
procedure TFrmMain.FormCreate(Sender: TObject);
var
i : integer;
pfd : TPIXELFORMATDESCRIPTOR;
pf : Integer;
begin
// 1.32: Debug adition
{$ifdef DEBUG_FILE}
DebugFile := TDebugFile.Create('debugdev.txt');
DebugFile.Add('FrmMain: FormCreate');
{$endif}
// 1.32: Shortcut aditions
ShiftPressed := false;
AltPressed := false;
CnvView[0] := @CnvView0;
CnvView[1] := @CnvView1;
CnvView[2] := @CnvView2;
lblView[0] := @lblView0;
lblView[1] := @lblView1;
lblView[2] := @lblView2;
mnuReopen := @ReOpen1;
BuildReopenMenu;
Height := 768;
for i := 0 to 2 do
begin
cnvView[i].ControlStyle := cnvView[i].ControlStyle + [csOpaque];
lblView[i].ControlStyle := lblView[i].ControlStyle + [csOpaque];
end;
SetIsEditable(False);
//FrmMain.DoubleBuffered := true;
//MainPaintPanel.DoubleBuffered := true;
LeftPanel.DoubleBuffered := true;
RightPanel.DoubleBuffered := true;
SetActiveColor(16,true);
SetActiveNormal(0,false);
changecaption(false,'');
// Resets the 3 views on the right sidebar if the res is too low for 203 high ones.
if RightPanel.Height < lblView1.Height+CnvView1.Height+lblView2.Height+CnvView2.Height+lbl3dview.Height+Panel7.Height+OGL3DPreview.Height then
begin
i := RightPanel.Height - (lblView1.Height+lblView2.Height+lbl3dview.Height+Panel7.Height);
i := trunc(i / 3);
CnvView1.Height := i;
CnvView2.Height := i;
OGL3DPreview.Height := i;
end;
// 1.2 Enable Idle only on certain situations.
Application.OnIdle := nil;
// OpenGL initialisieren
InitOpenGL;
dc:=GetDC(FrmMain.OGL3DPreview.Handle);
BGColor := CleanVCCol(GetVXLPaletteColor(-1));
FontColor := SetVector(1,1,1);
Size := 0.2;
RemapColour.X := RemapColourMap[0].R /255;
RemapColour.Y := RemapColourMap[0].G /255;
RemapColour.Z := RemapColourMap[0].B /255;
// PixelFormat
pfd.nSize:=sizeof(pfd);
pfd.nVersion:=1;
pfd.dwFlags:=PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER or 0;
pfd.iPixelType:=PFD_TYPE_RGBA; // PFD_TYPE_RGBA or PFD_TYPEINDEX
pfd.cColorBits:=32;
pf :=ChoosePixelFormat(dc, @pfd); // Returns format that most closely matches above pixel format
SetPixelFormat(dc, pf, @pfd);
rc :=wglCreateContext(dc); // Rendering Context = window-glCreateContext
wglMakeCurrent(dc,rc); // Make the DC (Form1) the rendering Context
ActivateRenderingContext(DC, RC);
glEnable(GL_TEXTURE_2D); // Enable Texture Mapping
glClearColor(BGColor.X, BGColor.Y, BGColor.Z, 1.0);
glShadeModel(GL_SMOOTH); // Enables Smooth Color Shading
glClearDepth(1.0); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enable Depth Buffer
glDepthFunc(GL_LESS); // The Type Of Depth Test To Do
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); //Realy Nice perspective calculations
BuildFont;
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
xRot :=-90;
yRot :=-85;
Depth :=-30;
DemoStart :=GetTickCount();
QueryPerformanceFrequency(FFrequency); // get high-resolution Frequency
QueryPerformanceCounter(FoldTime);
glViewport(0, 0, OGL3DPreview.Width, OGL3DPreview.Height); // Set the viewport for the OpenGL window
glMatrixMode(GL_PROJECTION); // Change Matrix Mode to Projection
glLoadIdentity(); // Reset View
gluPerspective(45.0, OGL3DPreview.Width/OGL3DPreview.Height, 1.0, 500.0); // Do the perspective calculations. Last value = max clipping depth
glMatrixMode(GL_MODELVIEW); // Return to the modelview matrix }
oglloaded := true;
p_Frm3DPreview := nil;
Application.OnDeactivate := OnDeactivate;
Application.OnActivate := OnActivate;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: FormCreate Loaded');
{$endif}
end;
{------------------------------------------------------------------}
{------------------------------------------------------------------}
procedure TFrmMain.Idle(Sender: TObject; var Done: Boolean);
var
tmp : int64;
t2 : double;
Form3D : PFrm3DPreview;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Idle');
{$endif}
Done := FALSE;
if (not iseditable) or (not oglloaded) then
begin
Done := true;
exit;
end;
if not Display3dView1.checked then
begin
LastTime :=ElapsedTime;
ElapsedTime := GetTickCount() - DemoStart; // Calculate Elapsed Time
ElapsedTime :=(LastTime + ElapsedTime) DIV 2; // Average it out for smoother movement
QueryPerformanceCounter(tmp);
t2 := tmp-FoldTime;
FPS := t2/FFrequency;
FoldTime := TMP;
FPS := 1/FPS;
wglMakeCurrent(dc,rc); // Make the DC (Form1) the rendering Context
glDraw(); // Draw the scene
SwapBuffers(DC); // Display the scene
end;
// For those wondering why do I need a variable... to avoid problems
// when closing the form.
Form3D := p_Frm3DPreview;
if Form3D <> nil then
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('Preview3D: Idle');
{$endif}
Form3D^.Idle(sender,done);
// Once the window is rendered, the FormMain OGL returns as default.
end;
end;
procedure TFrmMain.FormResize(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: FormResize');
{$endif}
CentreViews;
setupscrollbars;
end;
procedure TFrmMain.changecaption(Filename : boolean; FName : string);
begin
Caption := APPLICATION_TITLE + ' v' + APPLICATION_VER;
if Filename then
Caption := Caption + ' [' + extractfilename(FName) + ']';
end;
procedure TFrmMain.CnvView1Paint(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView1Paint');
{$endif}
PaintView2(1,false,CnvView[1],ActiveSection.View[1]);
end;
procedure TFrmMain.CnvView2Paint(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView2Paint');
{$endif}
PaintView2(2,false,CnvView[2],ActiveSection.View[2]);
end;
Procedure TFrmMain.SetIsEditable(Value : boolean);
var
i : integer;
begin
IsEditable := value;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetIsEditable');
{$endif}
for i := 0 to 2 do
begin
cnvView[i].Enabled := isEditable;
//lblView[i].Enabled := isEditable;
end;
if iseditable then
begin
for i := 0 to 2 do
begin
lblView[i].Color := clNavy;
lblView[i].Font.Color := clYellow;
lblView[i].Refresh;
end;
lblSection.Color := clNavy;
lblSection.Font.Color := clYellow;
lblTools.Color := clNavy;
lblTools.Font.Color := clYellow;
lblPalette.Color := clNavy;
lblPalette.Font.Color := clYellow;
lbl3dview.Color := clNavy;
lbl3dview.Font.Color := clYellow;
lblLayer.Color := clNavy;
lblLayer.Font.Color := clYellow;
lblBrush.Color := clNavy;
lblBrush.Font.Color := clYellow;
lblBrush.refresh;
lblLayer.refresh;
lbl3dview.refresh;
lblSection.refresh;
lblTools.refresh;
lblPalette.refresh;
If SpectrumMode = ModeColours then
SetActiveColor(ActiveColour,true);
cnvPalette.refresh;
// 1.32 Aditions:
cnvView0.OnMouseDown := cnvView0MouseDown;
cnvView0.OnMouseUp := cnvView0MouseUp;
cnvView0.OnMouseMove := cnvView0MouseMove;
cnvView0.OnPaint := cnvView0Paint;
cnvView1.OnMouseDown := cnvView1MouseDown;
cnvView1.OnMouseUp := cnvView1MouseUp;
cnvView1.OnMouseMove := cnvView1MouseMove;
cnvView1.OnPaint := cnvView1Paint;
cnvView2.OnMouseDown := cnvView2MouseDown;
cnvView2.OnMouseUp := cnvView2MouseUp;
cnvView2.OnMouseMove := cnvView2MouseMove;
cnvView2.OnPaint := cnvView2Paint;
oGL3DPreview.OnMouseDown := ogl3DPreviewMouseDown;
oGL3DPreview.OnMouseUp := ogl3DPreviewMouseUp;
oGL3DPreview.OnMouseMove := ogl3DPreviewMouseMove;
end
else
begin
// We'll force a closure of the 3D Preview window.
if p_Frm3DPreview <> nil then
begin
p_Frm3DPreview^.Release;
p_Frm3DPreview := nil;
end;
// 1.32 Aditions:
cnvView0.OnMouseDown := nil;
cnvView0.OnMouseUp := nil;
cnvView0.OnMouseMove := nil;
cnvView0.OnPaint := nil;
cnvView1.OnMouseDown := nil;
cnvView1.OnMouseUp := nil;
cnvView1.OnMouseMove := nil;
cnvView1.OnPaint := nil;
cnvView2.OnMouseDown := nil;
cnvView2.OnMouseUp := nil;
cnvView2.OnMouseMove := nil;
cnvView2.OnPaint := nil;
oGL3DPreview.OnMouseDown := nil;
oGL3DPreview.OnMouseUp := nil;
oGL3DPreview.OnMouseMove := nil;
end;
View1.Visible := IsEditable;
Section1.Visible := IsEditable;
ools2.Visible := IsEditable;
Edit1.Visible := IsEditable;
Scripts1.Visible := IsEditable;
SectionCombo.Enabled := IsEditable;
BarSaveAs.Enabled := IsEditable;
ToolButton5.Enabled := IsEditable;
ToolButton7.Enabled := IsEditable;
ToolButton3.Enabled := IsEditable;
ToolButton13.Enabled := IsEditable;
ToolButton11.Enabled := IsEditable;
ToolButton1.Enabled := IsEditable;
ToolButton2.Enabled := IsEditable;
btn3DRotateY.Enabled := IsEditable;
btn3DRotateY2.Enabled := IsEditable;
btn3DRotateX.Enabled := IsEditable;
btn3DRotateX2.Enabled := IsEditable;
spin3Djmp.Enabled := IsEditable;
SpeedButton1.Enabled := IsEditable;
SpeedButton2.Enabled := IsEditable;
SpeedButton3.Enabled := IsEditable;
SpeedButton4.Enabled := IsEditable;
SpeedButton5.Enabled := IsEditable;
SpeedButton6.Enabled := IsEditable;
SpeedButton7.Enabled := IsEditable;
SpeedButton8.Enabled := IsEditable;
SpeedButton9.Enabled := IsEditable;
SpeedButton10.Enabled := IsEditable;
SpeedButton11.Enabled := IsEditable;
SpeedButton12.Enabled := IsEditable;
SpeedButton13.Enabled := IsEditable;
Brush_1.Enabled := IsEditable;
Brush_2.Enabled := IsEditable;
Brush_3.Enabled := IsEditable;
Brush_4.Enabled := IsEditable;
Brush_5.Enabled := IsEditable;
pnlLayer.Enabled := IsEditable;
mnuDirectionPopup.AutoPopup := IsEditable;
Magnification1.Enabled := IsEditable;
N6.Enabled := IsEditable;
SaveAs1.Enabled := IsEditable;
Save1.Enabled := IsEditable;
if not iseditable then
OGL3DPreview.Refresh;
end;
Procedure TFrmMain.RefreshAll;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Refresh All');
{$endif}
RefreshViews;
RepaintViews;
Update3dView(ActiveSection);
if p_Frm3DPreview <> nil then
begin
p_Frm3DPreview^.Update3dView(ActiveSection);
end;
end;
Procedure TFrmMain.SetupSections;
var
i : integer;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Setup Sections');
{$endif}
SectionCombo.Clear;
for i := 0 to (VoxelFile.Header.NumSections - 1) do
SectionCombo.Items.Add(VoxelFile.Section[i].Name);
SectionCombo.ItemIndex := CurrentSection;
end;
procedure TFrmMain.SectionComboChange(Sender: TObject);
begin
if IsVXLLoading then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SectionComboChange');
{$endif}
CurrentSection := SectionCombo.ItemIndex;
ChangeSection;
ResetUndoRedo;
UpdateUndo_RedoState;
RefreshAll;
end;
procedure TFrmMain.Full1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Full1Click');
{$endif}
SetViewMode(ModeFull);
RepaintViews;
end;
procedure TFrmMain.CrossSection1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CrossSection1Click');
{$endif}
SetViewMode(ModeCrossSection);
RepaintViews;
end;
procedure TFrmMain.EmphasiseDepth1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: EmphasiseDepth1Click');
{$endif}
SetViewMode(ModeEmphasiseDepth);
RepaintViews;
end;
Procedure TFrmMain.SetViewMode(VM : EViewMode);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetViewMode');
{$endif}
Full1.checked := false;
CrossSection1.checked := false;
EmphasiseDepth1.checked := false;
if VM = ModeFull then
Full1.checked := true;
if VM = ModeCrossSection then
CrossSection1.checked := true;
if VM = ModeEmphasiseDepth then
EmphasiseDepth1.checked := true;
ViewMode := VM;
end;
Procedure TFrmMain.SetSpectrum(SP : ESpectrumMode);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetSpectrum');
{$endif}
Normals1.checked := false;
Colours1.checked := false;
if SP = ModeNormals then
Normals1.checked := true
else
Colours1.checked := true;
SpectrumMode := SP;
SetSpectrumMode;
ActiveSection.View[0].Refresh;
ActiveSection.View[1].Refresh;
ActiveSection.View[2].Refresh;
PaintPalette(cnvPalette,True);
RebuildLists := true;
if p_Frm3DPreview <> nil then
begin
p_Frm3DPreview^.RebuildLists := true;
end;
if not IsVXLLoading then
RepaintViews;
end;
procedure TFrmMain.Colours1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Colours1Click');
{$endif}
SetSpectrum(ModeColours);
SetActiveColor(ActiveColour,true);
end;
procedure TFrmMain.Normals1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Normals1Click');
{$endif}
SetSpectrum(ModeNormals);
SetActiveNormal(ActiveNormal,true);
end;
procedure TFrmMain.cnvPalettePaint(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: cnvPalettePaint');
{$endif}
PaintPalette(cnvPalette,true);
end;
procedure TFrmMain.SetActiveColor(Value : integer; CN : boolean);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetActiveColour');
{$endif}
ActiveColour := Value;
if CN then
if SpectrumMode = ModeColours then
SetActiveCN(Value);
end;
procedure TFrmMain.SetActiveNormal(Value : integer; CN : boolean);
var
v : integer;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetActiveNormal');
{$endif}
v := Value;
if ActiveNormalsCount > 0 then
if v > ActiveNormalsCount-1 then
v := ActiveNormalsCount-1; // normal too high
ActiveNormal := v;
if CN then
if SpectrumMode = ModeNormals then
SetActiveCN(V);
end;
Procedure TFrmMain.SetActiveCN(Value : integer);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetActiveCN');
{$endif}
if isEditable then
pnlActiveColour.Color := GetVXLPaletteColor(Value)
else
pnlActiveColour.Color := colourtogray(GetVXLPaletteColor(Value));
lblActiveColour.Caption := IntToStr(Value) + ' (0x' + IntToHex(Value,3) + ')';
cnvPalette.Repaint;
end;
procedure TFrmMain.ScrollBar1Change(Sender: TObject);
var
x , y, width, height : integer;
begin
if not isEditable then Exit;
if not scrollbar_editable then Exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: ScrollBar1Change');
{$endif}
Width := cnvView[0].Width;
Height := cnvView[0].Height;
with ActiveSection.Viewport[0] do
begin
x := ActiveSection.View[0].Width * Zoom;
if ScrollBar1.enabled then
if x > Width then
Left := 0 - ((x - Width) div 2) -(ScrollBar1.Position - (ScrollBar1.Max div 2))
else
Left := ((Width - x) div 2) -(ScrollBar1.Position - (ScrollBar1.Max div 2));
y := ActiveSection.View[0].Height * Zoom;
if ScrollBar2.enabled then
if y > Height then
Top := 0 - ((y - Height) div 2) -(ScrollBar2.Position - (ScrollBar2.Max div 2))
else
Top := (Height - y) div 2 -(ScrollBar2.Position - (ScrollBar2.Max div 2));
end;
PaintView2(0,true,CnvView[0],ActiveSection.View[0]);
end;
procedure TFrmMain.setupscrollbars;
begin
ScrollBar1.Enabled := false;
ScrollBar2.Enabled := false;
if not isEditable then Exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetupScrollBars');
{$endif}
If (ActiveSection.View[0].Width * ActiveSection.Viewport[0].zoom) > cnvView[0].Width then
begin
scrollbar_editable := false;
// showmessage(inttostr(ActiveSection.View[0].Width * ActiveSection.Viewport[0].zoom - cnvView[0].Width));
ScrollBar2.Position := 0;
ScrollBar1.max := ActiveSection.View[0].Width * ActiveSection.Viewport[0].zoom - cnvView[0].Width;
ScrollBar1.Position := ScrollBar1.max div 2;
ScrollBar1.Enabled := true;
scrollbar_editable := true;
end
else
ScrollBar1.Enabled := false;
If (ActiveSection.View[0].Height * ActiveSection.Viewport[0].zoom) > cnvView[0].Height then
begin
scrollbar_editable := false;
//showmessage(inttostr(ActiveSection.View[0].Height * ActiveSection.Viewport[0].zoom - cnvView[0].Height));
ScrollBar2.Position := 0;
ScrollBar2.max := ActiveSection.View[0].Height * ActiveSection.Viewport[0].zoom - cnvView[0].Height;
ScrollBar2.Position := ScrollBar2.max div 2;
ScrollBar2.Enabled := true;
scrollbar_editable := true;
end
else
ScrollBar2.Enabled := false;
end;
Function GetParamStr : String;
var
x : integer;
begin
Result := '';
for x := 1 to ParamCount do
if Result <> '' then
Result := Result + ' ' +ParamStr(x)
else
Result := ParamStr(x);
end;
procedure TFrmMain.FormShow(Sender: TObject);
var
frm: TLoadFrm;
l: Integer;
Reg: TRegistry;
LatestVersion: string;
VoxelName,HVAName: string;
begin
frm:=TLoadFrm.Create(Self);
if testbuild then
frm.Label4.Caption := APPLICATION_VER + ' TB '+testbuildversion
else
frm.Label4.Caption := APPLICATION_VER;
// 1.2:For future compatibility with other OS tools, we are
// using the registry keys to confirm its existance.
Reg :=TRegistry.Create;
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKey('Software\CnC Tools\VXLSEIII\',true) then
begin
LatestVersion := Reg.ReadString('Version');
if APPLICATION_VER > LatestVersion then
begin
Reg.WriteString('Path',ParamStr(0));
Reg.WriteString('Version',APPLICATION_VER);
end;
Reg.CloseKey;
end;
Reg.Free;
frm.Show;
l := 0;
while l < 25 do
begin
if l = 0 then begin frm.Loading.Caption := 'Loading: 3rd Party Palettes';frm.Loading.Refresh; LoadPalettes; end;
if l = 10 then begin frm.Loading.Caption := 'Loading: Colour Schemes'; frm.Loading.Refresh; LoadCScheme; end;
if l = 23 then begin frm.Loading.Caption := 'Finished Loading'; delay(50); end;
l := l + 1;
delay(2);
end;
frm.Close;
frm.Free;
WindowState := wsMaximized;
// refresh;
setupscrollbars;
UpdateUndo_RedoState;
VXLTool := 4;
if ParamCount > 0 then
begin
VoxelName := GetParamStr;
If FileExists(VoxelName) then
Begin
IsVXLLoading := true;
SetIsEditable(LoadVoxel(VoxelName));
if IsEditable then
begin
HVAName := copy(VoxelName,1,Length(VoxelName) - 3) + 'hva';
if FileExists(HVAName) then
begin
try
if not LoadHVA(HVAName) then
ClearHVA;
except
end;
end;
DoAfterLoadingThings;
end;
IsVXLLoading := false;
End;
end;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: FormShow Loaded');
{$endif}
end;
procedure TFrmMain.cnvPaletteMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var colwidth, rowheight: Real;
i, j, idx: Integer;
begin
If not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: cnvPaletteMouseUp');
{$endif}
colwidth := cnvPalette.Width / 8;
rowheight := cnvPalette.Height / 32;
i := Trunc(X / colwidth);
j := Trunc(Y / rowheight);
idx := (i * 32) + j;
if SpectrumMode = ModeColours then
SetActiveColor(idx,true)
else if not (idx > ActiveNormalsCount-1) then
SetActiveNormal(idx,true);
end;
// 1.2b: Build the Show Used Colours/Normals array
// Ripped from VXLSE II 2.2 SE OpenGL (never released version)
// Original function apparently made by Stucuk
procedure BuildUsedColoursArray;
var
x,y,z : integer;
v : TVoxelUnpacked;
begin
// This part is modified by Banshee. It's stupid to see it checking if x < 244 everytime
for x := 0 to 244 do
begin
UsedColours[x] := false;
UsedNormals[x] := false;
end;
for x := 245 to 255 do
UsedColours[x] := false;
for x := 0 to ActiveSection.Tailer.XSize -1 do
for y := 0 to ActiveSection.Tailer.YSize -1 do
for z := 0 to ActiveSection.Tailer.ZSize -1 do
begin
ActiveSection.GetVoxel(x,y,z,v);
if v.Used then
begin
UsedColours[v.Colour] := true;
UsedNormals[v.normal] := true;
end;
end;
end;
procedure TFrmMain.ShowUsedColoursNormals1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: ShowUsedColoursNormals1');
{$endif}
ShowUsedColoursNormals1.Checked := not UsedColoursOption;
UsedColoursOption := ShowUsedColoursNormals1.Checked;
// 1.2b: Refresh Show Use Colours
if UsedColoursOption then
BuildUsedColoursArray;
PaintPalette(cnvPalette,True);
end;
procedure TFrmMain.FormDestroy(Sender: TObject);
begin
wglMakeCurrent(0,0);
wglDeleteContext(rc);
UpdateHistoryMenu;
Config.SaveSettings;
end;
procedure TFrmMain.OGL3DPreviewMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
If not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: OGL3DPreviewMouseMove');
{$endif}
if MouseButton = 1 then
begin
xRot := xRot + (Y - Ycoord)/2; // moving up and down = rot around X-axis
yRot := yRot + (X - Xcoord)/2;
Xcoord := X;
Ycoord := Y;
end;
if MouseButton = 2 then
begin
Depth :=Depth - (Y-ZCoord)/3;
Zcoord := Y;
end;
end;
procedure TFrmMain.OGL3DPreviewMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
If not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: OGL3DPreviewMouseDown');
{$endif}
if Button = mbLeft then
begin
MouseButton :=1;
Xcoord := X;
Ycoord := Y;
end;
if Button = mbRight then
begin
MouseButton :=2;
Zcoord := Y;
end;
end;
procedure TFrmMain.OGL3DPreviewMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: OGL3DPreviewMouseUp');
{$endif}
MouseButton :=0;
end;
procedure TFrmMain.SpeedButton1MouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SpeedButton1MouseUp');
{$endif}
Popup3d.Popup(Left+SpeedButton1.Left+ RightPanel.Left +5,Top+ 90+ Panel7.Top + SpeedButton1.Top);
end;
procedure TFrmMain.DebugMode1Click(Sender: TObject);
begin
DebugMode1.Checked := not DebugMode1.Checked;
end;
Procedure TFrmMain.SetRotationAdders;
var
V : single;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetRotationAdders');
{$endif}
try
V := spin3Djmp.Value / 10;
except
exit; // Not a value
end;
if btn3DRotateX2.Down then
XRot2 := -V
else if btn3DRotateX.Down then
XRot2 := V;
if btn3DRotateY2.Down then
YRot2 := -V
else if btn3DRotateY.Down then
YRot2 := V;
end;
procedure TFrmMain.SpeedButton2Click(Sender: TObject);
begin
Depth := -30;
end;
procedure TFrmMain.btn3DRotateXClick(Sender: TObject);
begin
if btn3DRotateX.Down then
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Btn3DRotateXClick');
{$endif}
SetRotationAdders;
XRotB := True;
end
else
XRotB := false;
end;
procedure TFrmMain.btn3DRotateX2Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Bnt3DRotateX2Click');
{$endif}
if btn3DRotateX2.Down then
begin
SetRotationAdders;
XRotB := True;
end
else
XRotB := false;
end;
procedure TFrmMain.btn3DRotateY2Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Btn3DRotateY2Click');
{$endif}
if btn3DRotateY2.Down then
begin
SetRotationAdders;
YRotB := True;
end
else
YRotB := false;
end;
procedure TFrmMain.btn3DRotateYClick(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: btn3DRotateYClick');
{$endif}
if btn3DRotateY.Down then
begin
SetRotationAdders;
YRotB := True;
end
else
YRotB := false;
end;
procedure TFrmMain.spin3DjmpChange(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Spin3DJmpChange');
{$endif}
SetRotationAdders;
end;
procedure TFrmMain.BackgroundColour1Click(Sender: TObject);
begin
ColorDialog.Color := TVector3fToTColor(BGColor);
if ColorDialog.Execute then
BGColor := TColorToTVector3f(ColorDialog.Color);
end;
procedure TFrmMain.extColour1Click(Sender: TObject);
begin
ColorDialog.Color := TVector3fToTColor(FontColor);
if ColorDialog.Execute then
FontColor := TColorToTVector3f(ColorDialog.Color);
end;
procedure TFrmMain.ClearRemapClicks;
begin
Red1.Checked := false;
Blue1.Checked := false;
Green1.Checked := false;
White1.Checked := false;
Orange1.Checked := false;
Magenta1.Checked := false;
Purple1.Checked := false;
Gold1.Checked := false;
DarkSky1.Checked := false;
end;
procedure TFrmMain.Red1Click(Sender: TObject);
begin
ClearRemapClicks;
Red1.Checked := true;
RemapColour.X := RemapColourMap[0].R /255;
RemapColour.Y := RemapColourMap[0].G /255;
RemapColour.Z := RemapColourMap[0].B /255;
RebuildLists := true;
end;
procedure TFrmMain.Blue1Click(Sender: TObject);
begin
ClearRemapClicks;
Blue1.Checked := true;
RemapColour.X := RemapColourMap[1].R /255;
RemapColour.Y := RemapColourMap[1].G /255;
RemapColour.Z := RemapColourMap[1].B /255;
RebuildLists := true;
end;
procedure TFrmMain.Green1Click(Sender: TObject);
begin
ClearRemapClicks;
Green1.Checked := true;
RemapColour.X := RemapColourMap[2].R /255;
RemapColour.Y := RemapColourMap[2].G /255;
RemapColour.Z := RemapColourMap[2].B /255;
RebuildLists := true;
end;
procedure TFrmMain.White1Click(Sender: TObject);
begin
ClearRemapClicks;
White1.Checked := true;
RemapColour.X := RemapColourMap[3].R /255;
RemapColour.Y := RemapColourMap[3].G /255;
RemapColour.Z := RemapColourMap[3].B /255;
RebuildLists := true;
end;
procedure TFrmMain.Orange1Click(Sender: TObject);
begin
ClearRemapClicks;
Orange1.Checked := true;
RemapColour.X := RemapColourMap[4].R /255;
RemapColour.Y := RemapColourMap[4].G /255;
RemapColour.Z := RemapColourMap[4].B /255;
RebuildLists := true;
end;
procedure TFrmMain.Magenta1Click(Sender: TObject);
begin
ClearRemapClicks;
Magenta1.Checked := true;
RemapColour.X := RemapColourMap[5].R /255;
RemapColour.Y := RemapColourMap[5].G /255;
RemapColour.Z := RemapColourMap[5].B /255;
RebuildLists := true;
end;
procedure TFrmMain.Purple1Click(Sender: TObject);
begin
ClearRemapClicks;
Purple1.Checked := true;
RemapColour.X := RemapColourMap[6].R /255;
RemapColour.Y := RemapColourMap[6].G /255;
RemapColour.Z := RemapColourMap[6].B /255;
RebuildLists := true;
end;
procedure TFrmMain.Gold1Click(Sender: TObject);
begin
ClearRemapClicks;
Gold1.Checked := true;
RemapColour.X := RemapColourMap[7].R /255;
RemapColour.Y := RemapColourMap[7].G /255;
RemapColour.Z := RemapColourMap[7].B /255;
RebuildLists := true;
end;
procedure TFrmMain.DarkSky1Click(Sender: TObject);
begin
ClearRemapClicks;
DarkSky1.Checked := true;
RemapColour.X := RemapColourMap[8].R /255;
RemapColour.Y := RemapColourMap[8].G /255;
RemapColour.Z := RemapColourMap[8].B /255;
RebuildLists := true;
end;
procedure TFrmMain.Front1Click(Sender: TObject);
begin
XRot := -90;
YRot := -90;
//Depth := -30;
end;
procedure TFrmMain.Back1Click(Sender: TObject);
begin
XRot := -90;
YRot := 90;
//Depth := -30;
end;
procedure TFrmMain.LEft1Click(Sender: TObject);
begin
XRot := -90;
YRot := -180;
//Depth := -30;
end;
procedure TFrmMain.Right1Click(Sender: TObject);
begin
XRot := -90;
YRot := 0;
//Depth := -30;
end;
procedure TFrmMain.Bottom1Click(Sender: TObject);
begin
XRot := 180;
YRot := 180;
//Depth := -30;
end;
procedure TFrmMain.op1Click(Sender: TObject);
begin
XRot := 0;
YRot := 180;
//Depth := -30;
end;
procedure TFrmMain.Cameo1Click(Sender: TObject);
begin
XRot := 287;//-72.5;
YRot := 225;//237;
//Depth := -30;
end;
procedure TFrmMain.Cameo21Click(Sender: TObject);
begin
XRot := 287;//-72.5;
YRot := 315;//302;
//Depth := -30;
end;
procedure TFrmMain.Cameo31Click(Sender: TObject);
begin
XRot := 287;//-72.5;
YRot := 255;//302;
//Depth := -30;
end;
procedure TFrmMain.Cameo41Click(Sender: TObject);
begin
XRot := 287;//-72.5;
YRot := 285;//302;
//Depth := -30;
end;
procedure TFrmMain.CnvView2MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView2MouseUp');
{$endif}
isLeftMB := false;
end;
procedure TFrmMain.CnvView1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView1MouseUp');
{$endif}
isLeftMB := false;
end;
procedure TFrmMain.CnvView1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView1MouseDown');
{$endif}
if Button = mbLeft then
isLeftMB := true;
if isLeftMB then
begin
TranslateClick(1,X,Y,LastClick[1].X,LastClick[1].Y,LastClick[1].Z);
MoveCursor(LastClick[1].X,LastClick[1].Y,LastClick[1].Z,true);
CursorResetNoMAX;
end;
end;
procedure TFrmMain.CnvView1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
if not IsEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView1MouseMove');
{$endif}
if isLeftMB then
begin
TranslateClick(1,X,Y,LastClick[1].X,LastClick[1].Y,LastClick[1].Z);
MoveCursor(LastClick[1].X,LastClick[1].Y,LastClick[1].Z,true);
CursorResetNoMAX;
end;
end;
procedure TFrmMain.CnvView2MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
if not IsEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView2MouseMove');
{$endif}
if isLeftMB then
begin
TranslateClick(2,X,Y,LastClick[2].X,LastClick[2].Y,LastClick[2].Z);
MoveCursor(LastClick[2].X,LastClick[2].Y,LastClick[2].Z,true);
CursorResetNoMAX;
end;
end;
procedure TFrmMain.CnvView2MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView2MouseDown');
{$endif}
if Button = mbLeft then
isLeftMB := true;
if isLeftMB then
begin
TranslateClick(2,X,Y,LastClick[2].X,LastClick[2].Y,LastClick[2].Z);
MoveCursor(LastClick[2].X,LastClick[2].Y,LastClick[2].Z,true);
CursorResetNoMAX;
end;
end;
procedure TFrmMain.CnvView0MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
TempI : integer;
V : TVoxelUnpacked;
begin
if not iseditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView0MouseUp');
{$endif}
if ((ssAlt in shift) and (Button = mbLeft)) or ((Button = mbLeft) and (VXLTool = VXLTool_Dropper)) then
begin
TempI := GetPaletteColourFromVoxel(X,Y,0);
if TempI > -1 then
if SpectrumMode = ModeColours then
SetActiveColor(TempI,True)
else
SetActiveNormal(TempI,True);
end;
if (ssCtrl in shift) and (Button = mbLeft) then
begin
TranslateClick(0,x,y,LastClick[0].x,LastClick[0].y,LastClick[0].z);
MoveCursor(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,false);
end;
if VXLTool = VXLTool_FloodFill then
begin
TranslateClick(0,x,y,LastClick[0].x,LastClick[0].y,LastClick[0].z);
ActiveSection.GetVoxel(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v);
if (SpectrumMode = ModeColours) or (v.Used=False) then
v.Colour := ActiveColour;
if (SpectrumMode = ModeNormals) or (v.Used=False) then
v.Normal := ActiveNormal;
v.Used := True;
VXLFloodFillTool(ActiveSection,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v,ActiveSection.View[0].GetOrient);
end;
if VXLTool = VXLTool_FloodFillErase then
begin
TranslateClick(0,x,y,LastClick[0].x,LastClick[0].y,LastClick[0].z);
ActiveSection.GetVoxel(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v);
if (SpectrumMode = ModeColours) or (v.Used=False) then
v.Colour := 0;
if (SpectrumMode = ModeNormals) or (v.Used=False) then
v.Normal := 0;
v.Used := False;
VXLFloodFillTool(ActiveSection,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v,ActiveSection.View[0].GetOrient);
end;
if VXLTool = VXLTool_Darken then
begin
TranslateClick(0,x,y,LastClick[0].x,LastClick[0].y,LastClick[0].z);
ActiveSection.GetVoxel(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v);
if (SpectrumMode = ModeColours) or (v.Used=False) then
v.Colour := ActiveColour;
if (SpectrumMode = ModeNormals) or (v.Used=False) then
v.Normal := ActiveNormal;
v.Used := True;
VXLBrushToolDarkenLighten(ActiveSection,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,VXLBrush,ActiveSection.View[0].GetOrient,True);
end;
if VXLTool = VXLTool_Lighten then
begin
TranslateClick(0,x,y,LastClick[0].x,LastClick[0].y,LastClick[0].z);
ActiveSection.GetVoxel(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v);
if (SpectrumMode = ModeColours) or (v.Used=False) then
v.Colour := ActiveColour;
if (SpectrumMode = ModeNormals) or (v.Used=False) then
v.Normal := ActiveNormal;
v.Used := True;
VXLBrushToolDarkenLighten(ActiveSection,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,VXLBrush,ActiveSection.View[0].GetOrient,false);
end;
if ApplyTempView(ActiveSection) then
UpdateUndo_RedoState;
if isLeftMouseDown then
begin
isLeftMouseDown := False;
RefreshAll;
end;
end;
Procedure TFrmMain.UpdateCursor(P : TVector3i; Repaint : Boolean);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: UpdateCursor');
{$endif}
XCursorBar.Position := P.X;
YCursorBar.Position := P.Y;
ZCursorBar.Position := P.Z;
UpdatePositionStatus(P.X,P.Y,P.Z);
StatusBar1.Refresh;
MoveCursor(P.X,P.Y,P.Z,Repaint);
end;
procedure TFrmMain.XCursorBarChange(Sender: TObject);
begin
if IsVXLLoading then exit;
if isCursorReset then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: XCursorBarChange');
{$endif}
UpdateCursor(SetVectorI(XCursorBar.Position,YCursorBar.Position,ZCursorBar.Position),true);
end;
Procedure TFrmMain.CursorReset;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CursorReset');
{$endif}
isCursorReset := true;
XCursorBar.Position := 0;
YCursorBar.Position := 0;
ZCursorBar.Position := 0;
XCursorBar.Max := ActiveSection.Tailer.XSize-1;
YCursorBar.Max := ActiveSection.Tailer.YSize-1;
ZCursorBar.Max := ActiveSection.Tailer.ZSize-1;
XCursorBar.Position := ActiveSection.X;
YCursorBar.Position := ActiveSection.Y;
ZCursorBar.Position := ActiveSection.Z;
UpdatePositionStatus(ActiveSection.X,ActiveSection.Y,ActiveSection.Z);
StatusBar1.Refresh;
isCursorReset := false;
end;
Procedure TFrmMain.CursorResetNoMAX;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CursorResetNoMAX');
{$endif}
isCursorReset := true;
XCursorBar.Position := ActiveSection.X;
YCursorBar.Position := ActiveSection.Y;
ZCursorBar.Position := ActiveSection.Z;
UpdatePositionStatus(ActiveSection.X,ActiveSection.Y,ActiveSection.Z);
StatusBar1.Refresh;
isCursorReset := false;
end;
Procedure TFrmMain.SetupStatusBar;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetupStatusBar');
{$endif}
if ActiveSection.Tailer.Unknown = 2 then
StatusBar1.Panels[0].Text := 'Type: Tiberian Sun'
else if ActiveSection.Tailer.Unknown = 4 then
StatusBar1.Panels[0].Text := 'Type: RedAlert 2'
else
StatusBar1.Panels[0].Text := 'Type: Unknown ' + inttostr(ActiveSection.Tailer.Unknown);
StatusBar1.Panels[1].Text := 'X Size: ' + inttostr(ActiveSection.Tailer.YSize) + ', Y Size: ' + inttostr(ActiveSection.Tailer.ZSize) + ', Z Size: ' + inttostr(ActiveSection.Tailer.XSize);
StatusBar1.Panels[2].Text := '';
StatusBar1.Refresh;
end;
procedure TFrmMain.CnvView0MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
var
V : TVoxelUnpacked;
TempI : integer;
begin
if VoxelOpen and isEditable then //exit;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView0MouseMove');
{$endif}
TranslateClick(0,x,y,LastClick[0].x,LastClick[0].y,LastClick[0].z);
StatusBar1.Panels[2].Text := 'X: ' + inttostr(LastClick[0].Y) + ', Y: ' + inttostr(LastClick[0].Z) + ', Z: ' + inttostr(LastClick[0].X);
StatusBar1.Refresh;
if not isLeftMouseDown then
begin
TranslateClick2(0,X,Y,LastClick[0].X,LastClick[0].Y,LastClick[0].Z);
with ActiveSection.Tailer do
if (LastClick[0].X < 0) or (LastClick[0].Y < 0) or (LastClick[0].Z < 0) or (LastClick[0].X > XSize-1) or (LastClick[0].Y > YSize-1) or (LastClick[0].Z > ZSize-1) then
begin
if TempView.Data_no > 0 then
begin
TempView.Data_no := 0;
Setlength(TempView.Data,0);
CnvView[0].Repaint;
end;
Mouse_Current := crDefault;
CnvView[0].Cursor := Mouse_Current;
Exit;
end;
SetCursor;
CnvView[0].Cursor := Mouse_Current;
if TempView.Data_no > 0 then
begin
TempView.Data_no := 0;
Setlength(TempView.Data,0);
//CnvView[0].Repaint;
end;
if not DisableDrawPreview1.Checked then
begin
if VXLTool = VXLTool_Brush then
if VXLBrush <> 4 then
begin
ActiveSection.GetVoxel(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v);
if (SpectrumMode = ModeColours) or (v.Used=False) then
v.Colour := ActiveColour;
if (SpectrumMode = ModeNormals) or (v.Used=False) then
v.Normal := ActiveNormal;
v.Used := True;
VXLBrushTool(ActiveSection,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v,VXLBrush,ActiveSection.View[0].GetOrient);
// ActiveSection.BrushTool(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v,VXLBrush,ActiveSection.View[0].GetOrient);
CnvView[0].Repaint;
exit;
end;
if VXLTool = VXLTool_SmoothNormal then
if VXLBrush <> 4 then
begin
ActiveSection.GetVoxel(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v);
VXLSmoothBrushTool(ActiveSection,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v,VXLBrush,ActiveSection.View[0].GetOrient);
CnvView[0].Repaint;
exit;
end;
end;
exit;
end;
if ((ssAlt in shift) and (isLeftMouseDown)) or ((isLeftMouseDown) and (VXLTool = VXLTool_Dropper)) then
begin
TempI := GetPaletteColourFromVoxel(X,Y,0);
if TempI > -1 then
if SpectrumMode = ModeColours then
SetActiveColor(TempI,True)
else
SetActiveNormal(TempI,True);
end;
if (ssCtrl in shift) and (isLeftMouseDown) then
begin
isLeftMouseDown := false;
MoveCursor(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,true);
isLeftMouseDown := true;
end;
if (ssCtrl in Shift) or (ssAlt in shift) then Exit;
if VXLTool = VXLTool_Brush then
begin
ActiveSection.GetVoxel(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v);
if (SpectrumMode = ModeColours) or (v.Used=False) then
v.Colour := ActiveColour;
if (SpectrumMode = ModeNormals) or (v.Used=False) then
v.Normal := ActiveNormal;
v.Used := True;
VXLBrushTool(ActiveSection,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v,VXLBrush,ActiveSection.View[0].GetOrient);
RepaintViews;
exit;
end;
if VXLTool = VXLTool_SmoothNormal then
begin
ActiveSection.GetVoxel(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v);
VXLSmoothBrushTool(ActiveSection,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v,VXLBrush,ActiveSection.View[0].GetOrient);
RepaintViews;
exit;
end;
if VXLTool = VXLTool_Erase then
begin
v.Used := false;
v.Colour := 0;
v.Normal := 0;
VXLBrushTool(ActiveSection,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v,VXLBrush,ActiveSection.View[0].GetOrient);
RepaintViews;
exit;
end;
if VXLTool = VXLTool_Line then
begin
V.Used := true;
V.Colour := ActiveColour;
V.Normal := ActiveNormal;
drawstraightline(ActiveSection,TempView,LastClick[0],LastClick[1],V);
RepaintViews;
exit;
end;
if VXLTool = VXLTool_Rectangle then
begin
V.Used := true;
V.Colour := ActiveColour;
V.Normal := ActiveNormal;
VXLRectangle(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,LastClick[1].X,LastClick[1].Y,LastClick[1].Z,false,v);
RepaintViews;
exit;
end;
if VXLTool = VXLTool_FilledRectangle then
begin
V.Used := true;
V.Colour := ActiveColour;
V.Normal := ActiveNormal;
VXLRectangle(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,LastClick[1].X,LastClick[1].Y,LastClick[1].Z,true,v);
RepaintViews;
exit;
end;
end;
end;
procedure TFrmMain.lblView1Click(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: lblView1Click');
{$endif}
ActivateView(1);
setupscrollbars;
end;
procedure TFrmMain.lblView2Click(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: lblView2Click');
{$endif}
ActivateView(2);
setupscrollbars;
end;
procedure TFrmMain.mnuDirectionPopupPopup(Sender: TObject);
var
comp: TComponent;
idx: Integer;
View: TVoxelView;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: MenuDirectionPopupPopup');
{$endif}
comp := mnuDirectionPopup.PopupComponent;
mnuEdit.Visible := (comp <> lblView0); // can't edit as already editing it!
if comp = lblView0 then
View := ActiveSection.View[0]
else if comp = lblView1 then
View := ActiveSection.View[1]
else
View := ActiveSection.View[2];
idx := (View.getViewNameIdx div 2) * 2;
with mnuDirTowards do
begin
Caption := ViewName[idx];
Enabled := not (View.getDir = dirTowards);
end;
with mnuDirAway do
begin
Caption := ViewName[idx+1];
Enabled := not (View.getDir = dirAway);
end;
end;
procedure TFrmMain.mnuEditClick(Sender: TObject);
var comp: TComponent;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: MenuEditClick');
{$endif}
comp := mnuDirectionPopup.PopupComponent;
if comp = lblView1 then
ActivateView(1)
else
ActivateView(2);
end;
procedure TFrmMain.mnuDirTowardsClick(Sender: TObject);
procedure SetDir(WndIndex: Integer);
// var idx: Integer;
begin
with ActiveSection.View[WndIndex] do
begin
setDir(dirTowards);
// idx := getViewNameIdx;
//lblView[WndIndex].Caption := ViewName[idx];
SyncViews;
Refresh;
RepaintViews;
cnvView[WndIndex].Repaint;
end;
end;
var
i: Integer;
// KnownComponent: Boolean;
comp: TComponent;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: MenuDirTowardsClick');
{$endif}
comp := mnuDirectionPopup.PopupComponent;
//KnownComponent := False;
for i := 0 to 2 do
begin
if comp.Name = lblView[i].Name then
begin
SetDir(i);
Break;
end;
end;
end;
procedure TFrmMain.mnuDirAwayClick(Sender: TObject);
procedure SetDir(WndIndex: Integer);
begin
with ActiveSection.View[WndIndex] do
begin
setDir(dirAway);
SyncViews;
Refresh;
RepaintViews;
cnvView[WndIndex].Repaint;
end;
end;
var
i: Integer;
comp: TComponent;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: MenuDirAwayClick');
{$endif}
comp := mnuDirectionPopup.PopupComponent;
// KnownComponent := False;
for i := 0 to 2 do
begin
if comp.Name = lblView[i].Name then
begin
SetDir(i);
// KnownComponent := True;
Break;
end;
end;
end;
Procedure TFrmMain.SelectCorrectPalette2(Palette : String);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SelectCorrectPalette2');
{$endif}
if Palette = 'TS' then
iberianSunPalette1Click(nil)
else if Palette = 'RA2' then
RedAlert2Palette1Click(nil)
else if fileexists(ExtractFileDir(ParamStr(0)) + '\palettes\USER\' + Palette) then
begin
LoadPaletteFromFile(ExtractFileDir(ParamStr(0)) + '\palettes\USER\' + Palette);
cnvPalette.Repaint;
end;
end;
Procedure TFrmMain.SelectCorrectPalette;
begin
if not Config.Palette then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SelectCorrectPalette');
{$endif}
if VoxelFile.Section[0].Tailer.Unknown = 2 then
SelectCorrectPalette2(Config.TS)
else
SelectCorrectPalette2(Config.RA2);
end;
Procedure TFrmMain.CreateVxlError(v,n : Boolean);
var
frm : tFrmVxlError;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CreateVxlError');
{$endif}
frm:=TFrmVxlError.Create(Self);
frm.Visible:=False;
frm.Image1.Picture := TopBarImageHolder.Picture;
frm.TabSheet1.TabVisible := v;
frm.TabSheet2.TabVisible := n;
frm.ShowModal;
frm.Close;
frm.Free;
end;
procedure TFrmMain.DoAfterLoadingThings;
var
v,n : boolean;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: DoAfterLoadingThings');
{$endif}
if VXLFilename = '' then
changecaption(true,'Untitled')
else
changecaption(true,VXLFilename);
v := not IsVoxelValid;
n := HasNormalsBug;
if v or n then
CreateVxlError(v,n);
SetupSections;
SetViewMode(ModeEmphasiseDepth);
SetSpectrum(SpectrumMode);
SetActiveNormal(ActiveNormal,true);
// 1.2b: Refresh Show Use Colours
if UsedColoursOption then
BuildUsedColoursArray;
// End of 1.2b adition
setupscrollbars;
SetupStatusBar;
CursorReset;
ResetUndoRedo;
UpdateUndo_RedoState;
SelectCorrectPalette;
PaintPalette(cnvPalette,True);
if p_Frm3DPreview <> nil then
begin
p_Frm3DPreview^.SpFrame.MaxValue := HVAFile.Header.N_Frames;
p_Frm3DPreview^.SpFrame.Value := 1;
end;
if not Display3dView1.Checked then
if @Application.OnIdle = nil then
Application.OnIdle := Idle
else
Application.OnIdle := nil;
RefreshAll;
end;
procedure TFrmMain.Brush_1Click(Sender: TObject);
begin
VXLBrush := 0;
end;
procedure TFrmMain.Brush_2Click(Sender: TObject);
begin
VXLBrush := 1;
end;
procedure TFrmMain.Brush_3Click(Sender: TObject);
begin
VXLBrush := 2;
end;
procedure TFrmMain.Brush_4Click(Sender: TObject);
begin
VXLBrush := 3;
end;
procedure TFrmMain.Brush_5Click(Sender: TObject);
begin
VXLBrush := 4;
end;
procedure TFrmMain.SpeedButton3Click(Sender: TObject);
begin
SetVXLTool(VXLTool_Brush);
end;
Procedure TFrmMain.SetVXLTool(VXLTool_ : Integer);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetVXLTool');
{$endif}
SpeedButton3.Down := false;
SpeedButton4.Down := false;
SpeedButton5.Down := false;
SpeedButton6.Down := false;
SpeedButton7.Down := false;
SpeedButton8.Down := false;
SpeedButton9.Down := false;
SpeedButton10.Down := false;
SpeedButton11.Down := false;
SpeedButton12.Down := false;
if VXLTool_ = VXLTool_Brush then
SpeedButton3.Down := true
else if VXLTool_ = VXLTool_Line then
SpeedButton4.Down := true
else if VXLTool_ = VXLTool_Erase then
SpeedButton5.Down := true
else if VXLTool_ = VXLTool_FloodFill then
SpeedButton10.Down := true
else if VXLTool_ = VXLTool_FloodFillErase then
SpeedButton13.Down := true
else if VXLTool_ = VXLTool_Dropper then
SpeedButton11.Down := true
else if VXLTool_ = VXLTool_Rectangle then
SpeedButton6.Down := true
else if VXLTool_ = VXLTool_FilledRectangle then
SpeedButton8.Down := true
else if VXLTool_ = VXLTool_Darken then
SpeedButton7.Down := true
else if VXLTool_ = VXLTool_Lighten then
SpeedButton12.Down := true
else if VXLTool_ = VXLTool_SmoothNormal then
SpeedButton9.Down := true;
VXLTool := VXLTool_;
end;
procedure TFrmMain.CnvView0MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
TranslateClick2(0,X,Y,LastClick[0].X,LastClick[0].Y,LastClick[0].Z);
if (LastClick[0].X < 0) or (LastClick[0].Y < 0) or (LastClick[0].Z < 0) then Exit;
with ActiveSection.Tailer do
if (LastClick[0].X > XSize-1) or (LastClick[0].Y > YSize-1) or (LastClick[0].Z > ZSize-1) then Exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView0MouseDown');
{$endif}
if (VXLTool = VXLTool_Line) or (VXLTool = VXLTool_FilledRectangle) or (VXLTool = VXLTool_Rectangle) then
begin
LastClick[1].X := LastClick[0].X;
LastClick[1].Y := LastClick[0].Y;
LastClick[1].Z := LastClick[0].Z;
end;
if button = mbleft then
begin
if TempView.Data_no > 0 then
begin
TempView.Data_no := 0;
Setlength(TempView.Data,0);
end;
isLeftMouseDown := true;
CnvView0MouseMove(sender,shift,x,y);
end;
end;
procedure TFrmMain.SpeedButton5Click(Sender: TObject);
begin
SetVXLTool(VXLTool_Erase);
end;
procedure TFrmMain.SpeedButton4Click(Sender: TObject);
begin
SetVXLTool(VXLTool_Line);
end;
procedure TFrmMain.SpeedButton10Click(Sender: TObject);
begin
SetVXLTool(VXLTool_FloodFill);
end;
procedure TFrmMain.SpeedButton11Click(Sender: TObject);
begin
SetVXLTool(VXLTool_Dropper);
end;
procedure TFrmMain.SpeedButton6Click(Sender: TObject);
begin
SetVXLTool(VXLTool_Rectangle);
end;
procedure TFrmMain.SpeedButton8Click(Sender: TObject);
begin
SetVXLTool(VXLTool_FilledRectangle);
end;
procedure TFrmMain.Save1Click(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Save1Click');
{$endif}
if VXLFilename <> '' then
begin
if FileExists(VXLFilename) then
begin
// ShowBusyMessage('Saving...');
VoxelFile.SaveToFile(VXLFilename);
VXLChanged := false;
changecaption(true,VXLFilename);
// HideBusyMessage;
end
else
SaveAs1Click(Sender);
end;
end;
procedure TFrmMain.Exit1Click(Sender: TObject);
begin
Close;
end;
procedure TFrmMain.SaveAs1Click(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SaveAs1Click');
{$endif}
if SaveVXLDialog.Execute then
begin
VoxelFile.SaveToFile(SaveVXLDialog.Filename);
VXLFilename := SaveVXLDialog.Filename;
VXLChanged := false;
changecaption(true,VXLFilename);
Config.AddFileToHistory(VXLFilename);
UpdateHistoryMenu;
end;
end;
procedure TFrmMain.VoxelHeader1Click(Sender: TObject);
var
FrmHeader: TFrmHeader;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: VoxelHeader1Click');
{$endif}
FrmHeader:=TFrmHeader.Create(Self);
with FrmHeader do
begin
SetValues(@VoxelFile);
PageControl1.ActivePage := PageControl1.Pages[1];
Image2.Picture := TopBarImageHolder.Picture;
ShowModal;
Free;
end;
end;
procedure TFrmMain.N6Click(Sender: TObject);
var
FrmHeader: TFrmHeader;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: N6Click');
{$endif}
FrmHeader:=TFrmHeader.Create(Self);
with FrmHeader do
begin
SetValues(@VoxelFile);
PageControl1.ActivePage := PageControl1.Pages[0];
Image2.Picture := TopBarImageHolder.Picture;
ShowModal;
Free;
end;
end;
Procedure TFrmMain.UpdateUndo_RedoState;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: UpdateUndo_RedoState');
{$endif}
mnuBarUndo.Enabled := IsUndoRedoUsed(Undo);
mnuBarRedo.Enabled := IsUndoRedoUsed(Redo);
Undo1.Enabled := mnuBarUndo.Enabled;
Redo1.Enabled := mnuBarRedo.Enabled;
end;
procedure TFrmMain.mnuBarUndoClick(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: MenuBarUndoClick');
{$endif}
UndoRestorePoint(Undo,Redo);
UpdateUndo_RedoState;
RefreshAll;
VXLChanged := true;
end;
procedure TFrmMain.mnuBarRedoClick(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: MenuBarRedoClick');
{$endif}
RedoRestorePoint(Undo,Redo);
UpdateUndo_RedoState;
RefreshAll;
VXLChanged := true;
end;
procedure TFrmMain.updatenormals1Click(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: UpdateNormals1Click');
{$endif}
// ask the user to confirm
if MessageDlg('Autonormals v1.1' +#13#13+
'This process will modify the voxel''s normals.' +#13+
'If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then
Exit;
//ResetUndoRedo;
CreateVXLRestorePoint(ActiveSection,Undo);
UpdateUndo_RedoState;
if ApplyNormalsToVXL(ActiveSection) > 0 then
if MessageDlg('Some were Confused, This may mean there are redundant voxels.'+#13#13+'Run Remove Redundant Voxels?',mtConfirmation,[mbYes,mbNo],0) = mrYes then
RemoveRedundentVoxels1Click(Sender);
Refreshall;
VXLChanged := true;
end;
procedure TFrmMain.CubedAutoNormals1Click(Sender: TObject);
var
FrmAutoNormals : TFrmAutoNormals;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CubedAutoNormals1Click');
{$endif}
// One AutoNormals to rule them all!
FrmAutoNormals := TFrmAutoNormals.Create(self);
FrmAutoNormals.MyVoxel := ActiveSection;
FrmAutoNormals.ShowModal;
FrmAutoNormals.Release;
// Old code
{
// ask the user to confirm
if MessageDlg('Autonormals v5.2' +#13#13+
'This process will modify the voxel''s normals.' +#13+
'If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then
Exit;
//ResetUndoRedo;
CreateVXLRestorePoint(ActiveSection,Undo);
UpdateUndo_RedoState;
ApplyCubedNormalsToVXL(ActiveSection);
Refreshall;
VXLChanged := true;
}
end;
procedure TFrmMain.Delete1Click(Sender: TObject);
var
SectionIndex,i: Integer;
begin
if not isEditable then exit;
if VoxelFile.Header.NumSections<2 then
begin
MessageDlg('Can''t delete if there''s only 1 section!',mtWarning,[mbOK],0);
Exit;
end;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Delete1Click');
{$endif}
// ask the user to confirm
if MessageDlg('Delete Section' +#13#13+
'This process will delete the current section.' +#13+
'This cannot be undone. If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then
Exit;
//we can't undo these actions!!!
ResetUndoRedo;
UpdateUndo_RedoState;
SetisEditable(False);
SectionIndex:=ActiveSection.Header.Number;
VoxelFile.RemoveSection(SectionIndex);
SectionCombo.Items.Clear;
for i:=0 to VoxelFile.Header.NumSections-1 do
begin
SectionCombo.Items.Add(VoxelFile.Section[i].Name);
end;
SectionCombo.ItemIndex:=0;
SectionComboChange(Self);
SetisEditable(True);
VXLChanged := true;
Refreshall;
end;
procedure TFrmMain.normalsaphere1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: NormalSphere1Click');
{$endif}
Update3dViewWithNormals(ActiveSection);
end;
procedure TFrmMain.RemoveRedundentVoxels1Click(Sender: TObject);
var no{, i}: integer;
label Done;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: RemoveRedundantVoxels1Click');
{$endif}
// ensure the user wants to do this!
if MessageDlg('Remove Redundent Voxels v1.0' +#13#13+
'This process will remove voxels that are hidden from view.' +#13+
'If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then exit;
// stop undo's
// ResetUndoRedo;
CreateVXLRestorePoint(ActiveSection,Undo);
UpdateUndo_RedoState;
// ok, do it
no := RemoveRedundantVoxelsFromVXL(ActiveSection);
if no = 0 then
ShowMessage('Remove Redundent Voxels v1.0' +#13#13+ 'Removed: 0')
else
begin
ShowMessage('Remove Redundent Voxels v1.0' +#13#13+ 'Removed: ' + IntToStr(no));
RefreshAll;
VXLChanged := true;
end;
end;
procedure TFrmMain.ClearEntireSection1Click(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: ClearEntireSection1Click');
{$endif}
if MessageDlg('Clear Section' +#13#13+
'This process will remove all voxels from the current section.' +#13+
'If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then exit;
CreateVXLRestorePoint(ActiveSection,Undo);
UpdateUndo_RedoState;
ActiveSection.Clear;
VXLChanged := true;
RefreshAll;
end;
procedure TFrmMain.VXLSEHelp1Click(Sender: TObject);
begin
if not fileexists(extractfiledir(paramstr(0))+'/help.chm') then
begin
messagebox(0,'VXLSE Help' + #13#13 + 'help.chm not found','VXLSE Help',0);
exit;
end;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: VXLSEHelp1Click');
{$endif}
RunAProgram('help.chm','',extractfiledir(paramstr(0)));
end;
procedure TFrmMain.Display3dView1Click(Sender: TObject);
begin
Display3dView1.Checked := not Display3dView1.Checked;
Disable3dView1.Checked := Display3dView1.Checked;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Display3DView1Click');
{$endif}
if Display3dView1.Checked then
begin
if p_Frm3DPreview = nil then
Application.OnIdle := nil
else
begin
if @Application.OnIdle = nil then
Application.OnIdle := Idle;
end;
OGL3DPreview.Refresh;
end
else
if @Application.OnIdle = nil then
Application.OnIdle := Idle;
end;
procedure TFrmMain.About1Click(Sender: TObject);
var
frm: TLoadFrm;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: About1Click');
{$endif}
frm:=TLoadFrm.Create(Self);
frm.Visible:=False;
if testbuild then
frm.Label4.Caption := APPLICATION_VER + ' TB '+testbuildversion
else
frm.Label4.Caption := APPLICATION_VER;
frm.Image2.Visible := false;
frm.LblWill.Left := 117;
frm.butOK.Visible:=True;
frm.Loading.Caption:='';
frm.ShowModal;
frm.Close;
frm.Free;
end;
procedure TFrmMain.FlipXswitchFrontBack1Click(Sender: TObject);
begin
//Create a transformation matrix...
CreateVXLRestorePoint(ActiveSection,Undo);
UpdateUndo_RedoState;
ActiveSection.FlipMatrix([-1,1,1],[1,0,0]);
RefreshAll;
VXLChanged := true;
end;
procedure TFrmMain.FlipYswitchRightLeft1Click(Sender: TObject);
begin
//Create a transformation matrix...
CreateVXLRestorePoint(ActiveSection,Undo);
UpdateUndo_RedoState;
ActiveSection.FlipMatrix([1,-1,1],[0,1,0]);
RefreshAll;
VXLChanged := true;
end;
procedure TFrmMain.FlipZswitchTopBottom1Click(Sender: TObject);
begin
//Create a transformation matrix...
CreateVXLRestorePoint(ActiveSection,Undo);
UpdateUndo_RedoState;
ActiveSection.FlipMatrix([1,1,-1],[0,0,1]);
RefreshAll;
VXLChanged := true;
end;
procedure TFrmMain.MirrorBottomToTop1Click(Sender: TObject);
var
FlipFirst: Boolean;
begin
FlipFirst:=False;
if (Sender.ClassNameIs('TMenuItem')) then
begin
if CompareStr((Sender as TMenuItem).Name,'MirrorTopToBottom1')=0 then
begin
//flip first!
FlipFirst:=True;
end;
end;
CreateVXLRestorePoint(ActiveSection,Undo);
UpdateUndo_RedoState;
//Based on the current view...
case ActiveSection.View[0].GetViewNameIdx of
0:
begin
if not FlipFirst then ActiveSection.FlipMatrix([1,1,-1],[0,0,1]);
ActiveSection.Mirror(oriZ);
end;
1:
begin
if not FlipFirst then ActiveSection.FlipMatrix([1,1,-1],[0,0,1]);
ActiveSection.Mirror(oriZ);
end;
2:
begin
if not FlipFirst then ActiveSection.FlipMatrix([1,1,-1],[0,0,1]);
ActiveSection.Mirror(oriZ);
end;
3:
begin
if not FlipFirst then ActiveSection.FlipMatrix([1,1,-1],[0,0,1]);
ActiveSection.Mirror(oriZ);
end;
4:
begin
if not FlipFirst then ActiveSection.FlipMatrix([1,-1,1],[0,1,0]);
ActiveSection.Mirror(oriY);
end;
5:
begin
if not FlipFirst then ActiveSection.FlipMatrix([1,-1,1],[0,1,0]);
ActiveSection.Mirror(oriY);
end;
end;
RefreshAll;
VXLChanged := true;
end;
procedure TFrmMain.MirrorLeftToRight1Click(Sender: TObject);
var
FlipFirst: Boolean;
begin
FlipFirst:=False;
if (Sender.ClassNameIs('TMenuItem')) then begin
if CompareStr((Sender as TMenuItem).Name,'MirrorLeftToRight1')=0 then begin
//flip first!
FlipFirst:=True;
// ActiveSection.FlipMatrix([1,-1,1],[0,1,0]);
end;
end;
CreateVXLRestorePoint(ActiveSection,Undo);
UpdateUndo_RedoState;
//Based on the current view...
case ActiveSection.View[0].GetViewNameIdx of
0:
begin
if FlipFirst then ActiveSection.FlipMatrix([1,-1,1],[0,1,0]);
ActiveSection.Mirror(oriY);
end;
1:
begin
//reverse here :) (reversed view, that's why!)
if not FlipFirst then ActiveSection.FlipMatrix([1,-1,1],[0,1,0]);
ActiveSection.Mirror(oriY);
end;
2:
begin
if FlipFirst then ActiveSection.FlipMatrix([-1,1,1],[1,0,0]);
ActiveSection.Mirror(oriX);
end;
3:
begin
if not FlipFirst then ActiveSection.FlipMatrix([-1,1,1],[1,0,0]);
ActiveSection.Mirror(oriX);
end;
4:
begin
if FlipFirst then ActiveSection.FlipMatrix([-1,1,1],[1,0,0]);
ActiveSection.Mirror(oriX);
end;
5:
begin
if not FlipFirst then ActiveSection.FlipMatrix([-1,1,1],[1,0,0]);
ActiveSection.Mirror(oriX);
end;
end;
RefreshAll;
VXLChanged := true;
end;
procedure TFrmMain.MirrorBackToFront1Click(Sender: TObject);
begin
CreateVXLRestorePoint(ActiveSection,Undo);
UpdateUndo_RedoState;
FlipXswitchFrontBack1Click(Sender);
ActiveSection.Mirror(oriX);
RefreshAll;
VXLChanged := true;
end;
procedure TFrmMain.MirrorFrontToBack1Click(Sender: TObject);
begin
CreateVXLRestorePoint(ActiveSection,Undo);
UpdateUndo_RedoState;
ActiveSection.Mirror(oriX);
RefreshAll;
VXLChanged := true;
end;
procedure TFrmMain.Nudge1Left1Click(Sender: TObject);
var
i: Integer;
NR: Array[0..2] of Single;
begin
NR[0]:=0; NR[1]:=0; NR[2]:=0;
if (Sender.ClassNameIs('TMenuItem')) then begin
if (CompareStr((Sender as TMenuItem).Name,'Nudge1Left1')=0) or (CompareStr((Sender as TMenuItem).Name,'Nudge1Right1')=0) then begin
//left and right
case ActiveSection.View[0].GetViewNameIdx of
0: NR[1]:=-1;
1: NR[1]:=1;
2: NR[0]:=-1;
3: NR[0]:=1;
4: NR[0]:=-1;
5: NR[0]:=1;
end;
if CompareStr((Sender as TMenuItem).Name,'Nudge1Right1')=0 then begin
for i:=0 to 2 do begin
NR[i]:=-NR[i];
end;
end;
end else begin
//up and down
case ActiveSection.View[0].GetViewNameIdx of
0: NR[2]:=-1;
1: NR[2]:=-1;
2: NR[2]:=-1;
3: NR[2]:=-1;
4: NR[1]:=-1;
5: NR[1]:=-1;
end;
if CompareStr((Sender as TMenuItem).Name,'Nudge1up1')=0 then begin
for i:=0 to 2 do begin
NR[i]:=-NR[i];
end;
end;
end;
end;
CreateVXLRestorePoint(ActiveSection,Undo);
UpdateUndo_RedoState;
ActiveSection.FlipMatrix([1,1,1],NR,False);
RefreshAll;
VXLChanged := true;
end;
procedure TFrmMain.Section2Click(Sender: TObject);
var
i, SectionIndex: Integer;
FrmNewSectionSize: TFrmNewSectionSize;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Section2Click');
{$endif}
FrmNewSectionSize:=TFrmNewSectionSize.Create(Self);
with FrmNewSectionSize do
begin
ShowModal;
if aborted then Exit;
if MessageDlg('Create Section' + #13#13+ 'Are you sure you want to create a section: ' + #13#13 +
'Name: ' + AsciizToStr(Name,16) + Chr(10) +
'Size: ' + IntToStr(X) + 'x' + IntToStr(Y) + 'x' + IntToStr(Z),
mtConfirmation,[mbYes,mbNo],0) = mrNo then
exit;
SetisEditable(False);
SectionIndex:=ActiveSection.Header.Number;
if not before then //after
Inc(SectionIndex);
VoxelFile.InsertSection(SectionIndex,Name,X,Y,Z);
SectionCombo.Items.Clear;
for i:=0 to VoxelFile.Header.NumSections-1 do
begin
SectionCombo.Items.Add(VoxelFile.Section[i].Name);
end;
VoxelFile.Section[SectionIndex].Tailer.Unknown := VoxelFile.Section[0].Tailer.Unknown;
//MajorRepaint;
SectionCombo.ItemIndex:=SectionIndex;
SectionComboChange(Self);
ResetUndoRedo;
SetisEditable(True);
VXLChanged := true;
end;
FrmNewSectionSize.Free;
end;
procedure TFrmMain.Copyofthissection1Click(Sender: TObject);
var
i, SectionIndex,x,y,z : Integer;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CopyOfThisSection1Click');
{$endif}
if MessageDlg('Copy Section' + #13#13+ 'Are you sure you want to make a copy of the current section?',
mtConfirmation,[mbYes,mbNo],0) = mrNo then
exit;
SectionIndex:=ActiveSection.Header.Number;
Inc(SectionIndex);
ResetUndoRedo;
UpdateUndo_RedoState;
VoxelFile.InsertSection(SectionIndex,'Copy Of '+VoxelFile.Section[SectionIndex-1].Name,VoxelFile.Section[SectionIndex-1].Tailer.XSize,VoxelFile.Section[SectionIndex-1].Tailer.YSize,VoxelFile.Section[SectionIndex-1].Tailer.ZSize);
for x := 0 to (VoxelFile.Section[SectionIndex-1].Tailer.XSize - 1) do
for y := 0 to (VoxelFile.Section[SectionIndex-1].Tailer.YSize - 1) do
for z := 0 to (VoxelFile.Section[SectionIndex-1].Tailer.ZSize - 1) do
VoxelFile.Section[SectionIndex].Data[x,y,z] := VoxelFile.Section[SectionIndex-1].Data[x,y,z];
with VoxelFile.Section[SectionIndex-1].Tailer do
begin
VoxelFile.Section[SectionIndex].Tailer.Det := Det;
for x := 1 to 3 do
begin
VoxelFile.Section[SectionIndex].Tailer.MaxBounds[x] := MaxBounds[x];
VoxelFile.Section[SectionIndex].Tailer.MinBounds[x] := MinBounds[x];
end;
VoxelFile.Section[SectionIndex].Tailer.SpanDataOfs := SpanDataOfs;
VoxelFile.Section[SectionIndex].Tailer.SpanEndOfs := SpanEndOfs;
VoxelFile.Section[SectionIndex].Tailer.SpanStartOfs := SpanStartOfs;
for x := 1 to 3 do
for y := 1 to 4 do
VoxelFile.Section[SectionIndex].Tailer.Transform[x,y] := Transform[x,y];
VoxelFile.Section[SectionIndex].Tailer.Unknown := Unknown;
end;
SectionCombo.Items.Clear;
for i:=0 to VoxelFile.Header.NumSections-1 do
begin
SectionCombo.Items.Add(VoxelFile.Section[i].Name);
end;
//MajorRepaint;
SectionCombo.ItemIndex:=SectionIndex;
SectionComboChange(Self);
VXLChanged := true;
end;
procedure TFrmMain.mnuHistoryClick(Sender: TObject);
var
p: ^TMenuItem;
s,VoxelName,HVAName : string;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: MenuHistoryClick');
{$endif}
if Sender.ClassNameIs('TMenuItem') then
begin //check to see if it is this class
//and now do some dirty things with pointers...
p:=@Sender;
s := Config.GetHistory(p^.Tag);
CheckVXLChanged;
if not fileexists(s) then
begin
Messagebox(0,'File Doesn''t Exist','Load Voxel',0);
exit;
end;
IsVXLLoading := true;
Application.OnIdle := nil;
VoxelName := Config.GetHistory(p^.Tag);
SetIsEditable(LoadVoxel(VoxelName));
if IsEditable then
begin
if p_Frm3DPreview <> nil then
begin
p_Frm3DPreview^.SpFrame.MaxValue := 1;
p_Frm3DPreview^.SpStopClick(nil);
end;
HVAName := copy(VoxelName,1,Length(VoxelName) - 3) + 'hva';
if FileExists(HVAName) then
begin
try
if not LoadHVA(HVAName) then
ClearHVA;
except
end;
end
else
ClearHVA;
DoAfterLoadingThings;
end;
IsVXLLoading := false;
end;
end;
procedure TFrmMain.BuildReopenMenu;
var
i : integer;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: BuildReopenMenu');
{$endif}
Config:=TConfiguration.Create;
for i:=HistoryDepth - 1 downto 0 do
begin
mnuHistory[i]:=TMenuItem.Create(Self);
mnuHistory[i].OnClick:=mnuHistoryClick;
mnuReOpen.Insert(0,mnuHistory[i]);
end;
UpdateHistoryMenu;
end;
procedure TFrmMain.BarReopenClick(Sender: TObject);
begin
//ReOpen1.Caption := Config.GetHistory(0);
end;
procedure TFrmMain.iberianSunPalette1Click(Sender: TObject);
begin
LoadPaletteFromFile(ExtractFileDir(ParamStr(0)) + '\palettes\TS\unittem.pal');
cnvPalette.Repaint;
end;
procedure TFrmMain.RedAlert2Palette1Click(Sender: TObject);
begin
LoadPaletteFromFile(ExtractFileDir(ParamStr(0)) + '\palettes\RA2\unittem.pal');
cnvPalette.Repaint;
end;
Procedure TFrmMain.LoadPalettes;
var
f: TSearchRec;
path: String;
item: TMenuItem;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: LoadPalettes');
{$endif}
// prepare
PaletteList.Data_no := 0;
SetLength(PaletteList.Data,PaletteList.Data_no);
Custom1.Visible := false;
path := Concat(ExtractFilePath(ParamStr(0)) + '\palettes\USER\','*.pal');
// find files
if FindFirst(path,faAnyFile,f) = 0 then
repeat
SetLength(PaletteList.Data,PaletteList.Data_no+1);
item := TMenuItem.Create(Owner);
item.Caption := copy(f.Name,1,length(f.Name)-length(extractfileext(f.Name)));
PaletteList.Data[PaletteList.Data_no] := ExtractFilePath(ParamStr(0)) + '\palettes\USER\' + f.Name;
item.Tag := PaletteList.Data_no; // so we know which it is
item.OnClick := blank1Click;
Custom1.Insert(PaletteList.Data_no,item);
Custom1.Visible := true;
N18.Visible := true;
inc(PaletteList.Data_no);
until FindNext(f) <> 0;
FindClose(f);
end;
procedure TFrmMain.blank1Click(Sender: TObject);
begin
LoadPaletteFromFile(PaletteList.Data[TMenuItem(Sender).tag]);
cnvPalette.Repaint;
end;
Procedure TFrmMain.CheckVXLChanged;
var
T : string;
begin
if VXLChanged then
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CheckVXLChanged');
{$endif}
T := ExtractFileName(VXLFilename);
if t = '' then
T := 'Save Untitled'
else
T := 'Save changes in ' + T;
if MessageDlg('Last changes not saved. ' + T +' ?',mtWarning,[mbYes,mbNo],0) = mrYes then begin
Save1.Click;
end;
end;
end;
procedure TFrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
CheckVXLChanged;
if p_Frm3DPreview <> nil then
begin
try
p_Frm3DPreview^.Release;
except;
end;
p_Frm3DPreview := nil;
end;
end;
procedure TFrmMain.SpeedButton7Click(Sender: TObject);
begin
SetVXLTool(VXLTool_Darken);
end;
procedure TFrmMain.SpeedButton12Click(Sender: TObject);
begin
SetVXLTool(VXLTool_Lighten);
end;
procedure TFrmMain.SpeedButton13Click(Sender: TObject);
begin
SetVXLTool(VXLTool_FloodFillErase);
end;
Procedure TFrmMain.SetDarkenLighten(Value : integer);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetDarkenLighten');
{$endif}
DarkenLighten := Value;
N110.Checked := false;
N21.Checked := false;
N31.Checked := false;
N41.Checked := false;
N51.Checked := false;
if Value = 1 then
N110.Checked := true
else if Value = 2 then
N21.Checked := true
else if Value = 3 then
N31.Checked := true
else if Value = 4 then
N41.Checked := true
else if Value = 5 then
N51.Checked := true;
end;
procedure TFrmMain.N110Click(Sender: TObject);
begin
SetDarkenLighten(1);
end;
procedure TFrmMain.N21Click(Sender: TObject);
begin
SetDarkenLighten(2);
end;
procedure TFrmMain.N31Click(Sender: TObject);
begin
SetDarkenLighten(3);
end;
procedure TFrmMain.N41Click(Sender: TObject);
begin
SetDarkenLighten(4);
end;
procedure TFrmMain.N51Click(Sender: TObject);
begin
SetDarkenLighten(5);
end;
procedure TFrmMain.ToolButton11Click(Sender: TObject);
var
x,y,z : integer;
v : tvoxelunpacked;
begin
if not isEditable then exit;
if MessageDlg('Clear Voxel Colour' +#13#13+
'This process will clear the voxels colours/normals with the currently selected colour.' +#13+
'If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: ToolButton1Click');
{$endif}
CreateVXLRestorePoint(ActiveSection,Undo);
UpdateUndo_RedoState;
for x := 0 to ActiveSection.Tailer.XSize-1 do
for y := 0 to ActiveSection.Tailer.YSize-1 do
for z := 0 to ActiveSection.Tailer.ZSize-1 do
begin
ActiveSection.GetVoxel(x,y,z,v);
if SpectrumMode = ModeColours then
v.Colour := ActiveColour
else
v.Normal := ActiveNormal;
ActiveSection.SetVoxel(x,y,z,v);
end;
RefreshAll;
VXLChanged := true;
end;
procedure TFrmMain.ClearLayer1Click(Sender: TObject);
begin
if not isEditable then exit;
if MessageDlg('Clear Layer' +#13#13+
'This process will remove all voxels from the current layer.' +#13+
'If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: ClearLayer1Click');
{$endif}
ClearVXLLayer(ActiveSection);
UpdateUndo_RedoState;
RefreshAll;
VXLChanged := true;
end;
procedure TFrmMain.Copy1Click(Sender: TObject);
begin
if not isEditable then exit;
VXLCopyToClipboard(ActiveSection);
end;
procedure TFrmMain.Cut1Click(Sender: TObject);
begin
if not isEditable then exit;
VXLCutToClipboard(ActiveSection);
UpdateUndo_RedoState;
RefreshAll;
VXLChanged := true;
end;
procedure TFrmMain.ClearUndoSystem1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: ClearUndoSystem1Click');
{$endif}
ResetUndoRedo;
UpdateUndo_RedoState;
end;
procedure TFrmMain.PasteFull1Click(Sender: TObject);
begin
if not isEditable then exit;
CreateVXLRestorePoint(ActiveSection,Undo);
UpdateUndo_RedoState;
PasteFullVXL(ActiveSection);
RefreshAll;
VXLChanged := true;
end;
procedure TFrmMain.Paste1Click(Sender: TObject);
begin
if not isEditable then exit;
CreateVXLRestorePoint(ActiveSection,Undo);
UpdateUndo_RedoState;
// --- 1.2: Removed
// PasteFullVXL(ActiveSection);
// --- Replaced with
PasteVXL(ActiveSection);
RefreshAll;
VXLChanged := true;
end;
procedure firstlastword(const words : string; var first,rest : string);
var
x,w : integer;
seps : array[0..50] of string;
endofword : boolean;
text : string;
begin
text := words;
seps[0] := ' ';
seps[1] := '(';
seps[2] := ')';
seps[3] := '[';
seps[4] := #09;
seps[5] := ']';
seps[6] := ':';
seps[7] := '''';
seps[8] := '"';
seps[9] := '=';
seps[10] := ',';
seps[11] := ';';
repeat
w := 0;
endofword:=false;
for x := 1 to length(text) do
if endofword=false then
if (copy(text,x,1) <> seps[0]) and (copy(text,x,1) <> seps[1])and (copy(text,x,1) <> seps[2]) and (copy(text,x,1) <> seps[3]) and (copy(text,x,1) <> seps[4]) and (copy(text,x,1) <> seps[5]) and (copy(text,x,1) <> seps[6]) and (copy(text,x,1) <> seps[7]) and (copy(text,x,1) <> seps[8]) and (copy(text,x,1) <> seps[9]) and (copy(text,x,1) <> seps[10]) and (copy(text,x,1) <> seps[11]) then
w := w + 1
else
endofword := true;
if w = 0 then
text := copy(text,2,length(text));
until (w > 0) or (length(text) = 0);
first := copy(text,1,w);
rest := copy(text,w+1,length(text));
end;
procedure firstlastword2(const words : string; var first,rest : string);
var
x,w : integer;
seps : array[0..50] of string;
endofword : boolean;
text : string;
begin
text := words;
seps[0] := #09;
seps[1] := ';';
seps[2] := '=';
repeat
w := 0;
endofword:=false;
for x := 1 to length(text) do
if endofword=false then
if (copy(text,x,1) <> seps[0]) and (copy(text,x,1) <> seps[1]) and (copy(text,x,1) <> seps[2]) then
w := w + 1
else
endofword := true;
if w = 0 then
text := copy(text,2,length(text));
until (w > 0) or (length(text) = 0);
first := copy(text,1,w);
rest := copy(text,w+1,length(text));
end;
function searchcscheme(s : tstringlist; f : string) : string;
var
x : integer;
first,rest : string;
begin
result := '!ERROR!';
for x := 0 to s.Count-1 do
if ansilowercase(copy(s.Strings[x],1,length(f))) = ansilowercase(f) then
begin
firstlastword(s.Strings[x],first,rest);
if f = 'name=' then
firstlastword2(rest,first,rest)
else
firstlastword(rest,first,rest);
result := first;
end;
end;
function TFrmMain.LoadCSchemes(Dir: string; c: integer): integer;
var
f: TSearchRec;
path: string;
Filename: string;
item, item2: TMenuItem;
{c,}x: integer;
s: TStringList;
Split: string;
GameType: string;
begin
// prepare
// c := 0;
// SetLength(ColourSchemes,0);
// ColourScheme1.Visible := false;
path := Concat(Dir, '*.cscheme');
// find files
if FindFirst(path, faAnyFile, f) = 0 then
repeat
Filename := Concat(Dir, f.Name);
Inc(c);
SetLength(ColourSchemes, c + 1);
ColourSchemes[c].FileName := Filename;
s := TStringList.Create;
s.LoadFromFile(Filename);
SetLength(ColourSchemes, c + 1);
Split := searchcscheme(s, 'split=');
item := TMenuItem.Create(Owner);
item.Caption := searchcscheme(s, 'name=');
item.Tag := c; // so we know which it is
item.OnClick := blank2Click;
item.ImageIndex := StrToInt(searchcscheme(s, 'imageindex='));
item2 := TMenuItem.Create(Owner);
item2.Caption := '-';
GameType := searchcscheme(s, 'gametype=');
if GameType = '0' then // Others
begin
if split = 'true' then
Others1.Insert(Others1.Count - 1, item2);
Others1.Insert(Others1.Count - 1, item);
Others1.Visible := True;
ColourScheme1.Visible := True;
end
else if GameType = '1' then // TS
begin
if split = 'true' then
iberianSun2.Insert(iberianSun2.Count - 1, item2);
iberianSun2.Insert(iberianSun2.Count - 1, item);
iberianSun2.Visible := True;
ColourScheme1.Visible := True;
end
else if GameType = '2' then // RA2
begin
if split = 'true' then
RedAlert22.Insert(RedAlert22.Count - 1, item2);
RedAlert22.Insert(RedAlert22.Count - 1, item);
RedAlert22.Visible := True;
ColourScheme1.Visible := True;
end
else if GameType = '3' then //YR
begin
if split = 'true' then
YurisRevenge1.Insert(YurisRevenge1.Count - 1, item2);
YurisRevenge1.Insert(YurisRevenge1.Count - 1, item);
YurisRevenge1.Visible := True;
ColourScheme1.Visible := True;
end
else if GameType = '4' then
begin
if split = 'true' then
Allied1.Insert(Allied1.Count - 1, item2);
Allied1.Insert(Allied1.Count - 1, item);
Allied1.Visible := True;
ColourScheme1.Visible := True;
PalPack1.Visible := True;
end
else if GameType = '5' then
begin
if split = 'true' then
Soviet1.Insert(Soviet1.Count - 1, item2);
Soviet1.Insert(Soviet1.Count - 1, item);
Soviet1.Visible := True;
ColourScheme1.Visible := True;
PalPack1.Visible := True;
end
else if GameType = '6' then
begin
if split = 'true' then
Yuri1.Insert(Yuri1.Count - 1, item2);
Yuri1.Insert(Yuri1.Count - 1, item);
Yuri1.Visible := True;
ColourScheme1.Visible := True;
PalPack1.Visible := True;
end
else if GameType = '7' then
begin
if split = 'true' then
Brick1.Insert(Brick1.Count - 1, item2);
Brick1.Insert(Brick1.Count - 1, item);
Brick1.Visible := True;
ColourScheme1.Visible := True;
PalPack1.Visible := True;
end
else if GameType = '8' then
begin
if split = 'true' then
Grayscale1.Insert(Grayscale1.Count - 1, item2);
Grayscale1.Insert(Grayscale1.Count - 1, item);
Grayscale1.Visible := True;
ColourScheme1.Visible := True;
PalPack1.Visible := True;
end
else if GameType = '9' then
begin
if split = 'true' then
Remap1.Insert(Remap1.Count - 1, item2);
Remap1.Insert(Remap1.Count - 1, item);
Remap1.Visible := True;
ColourScheme1.Visible := True;
end
else if GameType = '10' then
begin
if split = 'true' then
Brown11.Insert(Brown11.Count - 1, item2);
Brown11.Insert(Brown11.Count - 1, item);
Brown11.Visible := True;
ColourScheme1.Visible := True;
end
else if GameType = '11' then
begin
if split = 'true' then
Brown21.Insert(Brown21.Count - 1, item2);
Brown21.Insert(Brown21.Count - 1, item);
Brown21.Visible := True;
ColourScheme1.Visible := True;
PalPack1.Visible := True;
end
else if GameType = '12' then
begin
if split = 'true' then
Blue2.Insert(Blue2.Count - 1, item2);
Blue2.Insert(Blue2.Count - 1, item);
Blue2.Visible := True;
ColourScheme1.Visible := True;
PalPack1.Visible := True;
end
else if GameType = '13' then
begin
if split = 'true' then
Green2.Insert(Green2.Count - 1, item2);
Green2.Insert(Green2.Count - 1, item);
Green2.Visible := True;
ColourScheme1.Visible := True;
PalPack1.Visible := True;
end
else if GameType = '14' then
begin
if split = 'true' then
NoUnlit1.Insert(NoUnlit1.Count - 1, item2);
NoUnlit1.Insert(NoUnlit1.Count - 1, item);
NoUnlit1.Visible := True;
ColourScheme1.Visible := True;
PalPack1.Visible := True;
end
else if GameType = '15' then
begin
if split = 'true' then
Red2.Insert(Red2.Count - 1, item2);
Red2.Insert(Red2.Count - 1, item);
Red2.Visible := True;
ColourScheme1.Visible := True;
PalPack1.Visible := True;
end
else if GameType = '16' then
begin
if split = 'true' then
Yellow1.Insert(Yellow1.Count - 1, item2);
Yellow1.Insert(Yellow1.Count - 1, item);
Yellow1.Visible := True;
ColourScheme1.Visible := True;
PalPack1.Visible := True;
end;
until FindNext(f) <> 0;
FindClose(f);
Result := c;
end;
function TFrmMain.LoadCScheme : integer;
var
c : integer;
begin
SetLength(ColourSchemes,0);
c := LoadCSchemes(ExtractFilePath(ParamStr(0))+'\cscheme\USER\',0);
c := LoadCSchemes(ExtractFilePath(ParamStr(0))+'\cscheme\PalPack1\',c);
Result := LoadCSchemes(ExtractFilePath(ParamStr(0))+'\cscheme\PalPack2\',c);
end;
procedure TFrmMain.blank2Click(Sender: TObject);
var
x,y,z : integer;
s : tstringlist;
V : TVoxelUnpacked;
begin
s := TStringList.Create;
s.LoadFromFile(ColourSchemes[Tmenuitem(Sender).Tag].Filename);
tempview.Data_no := tempview.Data_no +0;
setlength(tempview.Data,tempview.Data_no +0);
for x := 0 to 255 do
ColourSchemes[Tmenuitem(Sender).Tag].Data[x] := strtoint(searchcscheme(s,inttostr(x)+'='));
for x := 0 to ActiveSection.Tailer.XSize-1 do
for y := 0 to ActiveSection.Tailer.YSize-1 do
for z := 0 to ActiveSection.Tailer.ZSize-1 do
begin
ActiveSection.GetVoxel(x,y,z,v);
if v.Used then
begin
V.Colour := ColourSchemes[Tmenuitem(Sender).Tag].Data[V.Colour];
tempview.Data_no := tempview.Data_no +1;
setlength(tempview.Data,tempview.Data_no +1);
tempview.Data[tempview.Data_no].VC.X := x;
tempview.Data[tempview.Data_no].VC.Y := y;
tempview.Data[tempview.Data_no].VC.Z := z;
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].V := v;
end;
end;
ApplyTempView(ActiveSection);
UpdateUndo_RedoState;
RefreshAll;
end;
procedure TFrmMain.About2Click(Sender: TObject);
var
frm: TFrmPalettePackAbout;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: About2Click');
{$endif}
frm:=TFrmPalettePackAbout.Create(Self);
frm.Visible:=False;
frm.ShowModal;
frm.Close;
frm.Free;
end;
procedure TFrmMain.EmptyVoxel1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: EmptyVoxel1Click');
{$endif}
NewVFile(2);
end;
procedure TFrmMain.EmptyVoxel2Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: EmptyVoxel2Click');
{$endif}
NewVFile(4);
end;
Procedure TFrmMain.NewVFile(Game : integer);
var
FrmNew: TFrmNew;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: NewVFile');
{$endif}
IsVXLLoading := true;
Application.OnIdle := nil;
CheckVXLChanged;
FrmNew:=TFrmNew.Create(Self);
with FrmNew do
begin
//FrmNew.Caption := ' New Voxel File';
Label9.Caption := 'New Voxel';
Label9.Caption := 'Enter the size you want the voxel to be';
//grpCurrentSize.Left := 400;
grpCurrentSize.Visible := false;
//grpNewSize.Width := 201;
grpNewSize.Left := (FrmNew.Width div 2) - (grpNewSize.Width div 2);
grpNewSize.Caption := 'Size';
Button2.Visible := false;
Button4.Left := Button2.Left;
Image1.Picture := TopBarImageHolder.Picture;
//grpCurrentSize.Visible := true;
grpVoxelType.Visible := true;
x := 10;//ActiveSection.Tailer.XSize;
y := 10;//ActiveSection.Tailer.YSize;
z := 10;//ActiveSection.Tailer.ZSize;
ShowModal;
end;
// 1.3: Before creating the new voxel, we add the type support.
if FrmNew.rbLand.Checked then
VoxelType := vtLand
else
VoxelType := vtAir;
SetIsEditable(NewVoxel(Game,FrmNew.x,FrmNew.y,FrmNew.z));
if IsEditable then
DoAfterLoadingThings;
IsVXLLoading := false;
end;
Procedure TFrmMain.SetCursor;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetCursor');
{$endif}
//CnvView[0].Cursor := Mouse_Current;
if VXLTool = VXLTool_Brush then
if VXLBrush = 4 then
Mouse_Current := MouseSpray
else
Mouse_Current := MouseDraw
else if VXLTool = VXLTool_Line then
Mouse_Current := MouseLine
else if VXLTool = VXLTool_Erase then
if VXLBrush = 4 then
Mouse_Current := MouseSpray
else
Mouse_Current := MouseDraw
else if VXLTool = VXLTool_FloodFill then
Mouse_Current := MouseFill
else if VXLTool = VXLTool_FloodFillErase then
Mouse_Current := MouseFill
else if VXLTool = VXLTool_Dropper then
Mouse_Current := MouseDropper
else if VXLTool = VXLTool_Rectangle then
Mouse_Current := MouseLine
else if VXLTool = VXLTool_FilledRectangle then
Mouse_Current := MouseLine
else if VXLTool = VXLTool_Darken then
if VXLBrush = 4 then
Mouse_Current := MouseSpray
else
Mouse_Current := MouseDraw
else if VXLTool = VXLTool_Lighten then
if VXLBrush = 4 then
Mouse_Current := MouseSpray
else
Mouse_Current := MouseDraw;
if not iseditable then
Mouse_Current := crDefault;
end;
procedure TFrmMain.DisableDrawPreview1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: DisableDrawPreview1Click');
{$endif}
DisableDrawPreview1.Checked := not DisableDrawPreview1.Checked;
end;
procedure TFrmMain.SmoothNormals1Click(Sender: TObject);
begin
if not isEditable then exit;
// ask the user to confirm
if MessageDlg('Smooth Normals v1.0' +#13#13+
'This process will modify the voxel''s normals.' +#13+
'If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then
Exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SmoothNormals1Click');
{$endif}
CreateVXLRestorePoint(ActiveSection,Undo);
UpdateUndo_RedoState;
SmoothVXLNormals(ActiveSection);
RefreshAll;
VXLChanged := true;
end;
procedure TFrmMain.VoxelTexture1Click(Sender: TObject);
var
frm: TFrmVoxelTexture;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: VoxelTexture1Click');
{$endif}
frm:=TFrmVoxelTexture.Create(Self);
frm.Visible:=False;
frm.Image3.Picture := TopBarImageHolder.Picture;
frm.ShowModal;
frm.Close;
frm.Free;
end;
procedure TFrmMain.OpenHyperlink(HyperLink: PChar);
begin
ShellExecute(Application.Handle,nil,HyperLink,'','',SW_SHOWNORMAL);
end;
procedure TFrmMain.CnCSource1Click(Sender: TObject);
begin
OpenHyperLink('http://www.cnc-source.com/');
end;
procedure TFrmMain.PPMForUpdates1Click(Sender: TObject);
begin
OpenHyperLink('http://www.ppmsite.com/index.php?go=vxlseinfo');
end;
procedure TFrmMain.CGen1Click(Sender: TObject);
begin
OpenHyperLink('http://cannis.net/');
end;
procedure TFrmMain.Dezire1Click(Sender: TObject);
begin
OpenHyperLink('http://www.deezire.net/');
end;
procedure TFrmMain.PPMModdingForums1Click(Sender: TObject);
begin
OpenHyperLink('http://www.ppmsite.com/forum/index.php?f=309');
end;
procedure TFrmMain.PlanetCNC1Click(Sender: TObject);
begin
OpenHyperLink('http://www.planetcnc.com/');
end;
procedure TFrmMain.PixelOps1Click(Sender: TObject);
begin
OpenHyperLink('http://cannis.net/pixelops/');
end;
procedure TFrmMain.ESource1Click(Sender: TObject);
begin
OpenHyperLink('http://cnc.raminator.de/');
end;
procedure TFrmMain.SavageWarTS1Click(Sender: TObject);
begin
OpenHyperLink('http://ts.savagewar.co.uk/');
end;
procedure TFrmMain.MadHQGraphicsDump1Click(Sender: TObject);
begin
OpenHyperLink('http://zombapro.net/depot/');
end;
procedure TFrmMain.YRArgentina1Click(Sender: TObject);
begin
OpenHyperLink('http://yrarg.cncguild.net/');
end;
procedure TFrmMain.ibEd1Click(Sender: TObject);
begin
OpenHyperLink('http://www.tibed.net/');
end;
procedure TFrmMain.XCC1Click(Sender: TObject);
begin
OpenHyperLink('http://xhp.xwis.net/');
end;
procedure TFrmMain.RedUtils1Click(Sender: TObject);
begin
OpenHyperLink('http://dc.strategy-x.com/');
end;
procedure TFrmMain.RockTheBattlefield1Click(Sender: TObject);
begin
OpenHyperLink('http://rp2.strategy-x.com/');
end;
procedure TFrmMain.RA2FAQ1Click(Sender: TObject);
begin
OpenHyperLink('http://ra2faq.savagewar.co.uk/');
end;
procedure TFrmMain.RenegadeProjects1Click(Sender: TObject);
begin
OpenHyperLink('http://www.renegadeprojects.com/');
end;
procedure TFrmMain.RevoraCCForums1Click(Sender: TObject);
begin
OpenHyperLink('http://forums.revora.net/index.php?showforum=1676');
end;
procedure TFrmMain.AcidVat1Click(Sender: TObject);
begin
OpenHyperLink('http://www.gamesmodding.com/');
end;
procedure TFrmMain.RA2GraphicsHeaven1Click(Sender: TObject);
begin
OpenHyperLink('http://www.migeater.net/');
end;
procedure TFrmMain.CnCGuild1Click(Sender: TObject);
begin
OpenHyperLink('http://www.cncguild.net/');
end;
procedure TFrmMain.CCFilefront1Click(Sender: TObject);
begin
OpenHyperLink('http://www.cnc-files.com/');
end;
procedure TFrmMain.CNCNZcom1Click(Sender: TObject);
begin
OpenHyperLink('http://www.cncnz.com/');
end;
procedure TFrmMain.iberiumSunCom1Click(Sender: TObject);
begin
OpenHyperLink('http://www.tiberiumweb.com/');
end;
procedure TFrmMain.VKHomepage1Click(Sender: TObject);
begin
OpenHyperLink('http://vk.cncguild.net/');
end;
procedure TFrmMain.ProjectSVN1Click(Sender: TObject);
begin
OpenHyperLink('http://svn.ppmsite.com/');
end;
procedure TFrmMain.test1Click(Sender: TObject);
begin
Update3dViewVOXEL(VoxelFile);
end;
procedure TFrmMain.Importfrommodel1Click(Sender: TObject);
var
tempvxl : TVoxel;
i, SectionIndex,tempsectionindex,u1,u2,{u3,}num: Integer;
frm: Tfrmimportsection;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: ImportFromModel1Click');
{$endif}
tempvxl := TVoxel.Create;
if OpenVXLDialog.execute then
begin
tempvxl.LoadFromFile(OpenVXLDialog.Filename);
tempsectionindex := 0;
if tempvxl.Header.NumSections > 1 then
begin
frm:=Tfrmimportsection.Create(Self);
frm.Visible:=False;
frm.ComboBox1.Items.Clear;
for i:=0 to tempvxl.Header.NumSections-1 do
begin
frm.ComboBox1.Items.Add(tempvxl.Section[i].Name);
end;
frm.ComboBox1.ItemIndex:=0;
frm.ShowModal;
tempsectionindex := frm.ComboBox1.ItemIndex;
frm.Free;
end;
SectionIndex:=ActiveSection.Header.Number;
Inc(SectionIndex);
ResetUndoRedo;
UpdateUndo_RedoState;
VoxelFile.InsertSection(SectionIndex,tempvxl.Section[tempsectionindex].Name,tempvxl.Section[tempsectionindex].Tailer.XSize,tempvxl.Section[tempsectionindex].Tailer.YSize,tempvxl.Section[tempsectionindex].Tailer.ZSize);
VoxelFile.Section[SectionIndex].Assign(tempvxl.Section[tempsectionindex]);
tempvxl.Free;
SetupSections;
VXLChanged := true;
end;
end;
procedure TFrmMain.Resize1Click(Sender: TObject);
var
FrmNew: TFrmNew;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Resize1Click');
{$endif}
FrmNew:=TFrmNew.Create(Self);
with FrmNew do
begin
//FrmNew.Caption := ' Resize';
//grpCurrentSize.Left := 8;
//grpNewSize.Left := 112;
//grpNewSize.Width := 97;
Label9.caption := 'Enter the size you want the canvas to be';
Label10.caption := 'Resize Canvas';
grpCurrentSize.Visible := true;
Image1.Picture := TopBarImageHolder.Picture;
grpVoxelType.Visible := false;
x := ActiveSection.Tailer.XSize;
y := ActiveSection.Tailer.YSize;
z := ActiveSection.Tailer.ZSize;
ShowModal;
if changed then
begin
//Save undo information
ResetUndoRedo;
UpdateUndo_RedoState;
SetIsEditable(false);
ActiveSection.Resize(x,y,z);
SetIsEditable(true);
SectionComboChange(Sender);
VXLChanged := true;
end;
end;
FrmNew.Free;
end;
procedure TFrmMain.SpinButton3UpClick(Sender: TObject);
begin
YCursorBar.Position := YCursorBar.Position +1;
end;
procedure TFrmMain.SpinButton3DownClick(Sender: TObject);
begin
YCursorBar.Position := YCursorBar.Position -1;
end;
procedure TFrmMain.SpinButton1DownClick(Sender: TObject);
begin
ZCursorBar.Position := ZCursorBar.Position -1;
end;
procedure TFrmMain.SpinButton1UpClick(Sender: TObject);
begin
ZCursorBar.Position := ZCursorBar.Position +1;
end;
procedure TFrmMain.SpinButton2DownClick(Sender: TObject);
begin
XCursorBar.Position := XCursorBar.Position -1;
end;
procedure TFrmMain.SpinButton2UpClick(Sender: TObject);
begin
XCursorBar.Position := XCursorBar.Position +1;
end;
procedure TFrmMain.FullResize1Click(Sender: TObject);
var
frm: TFrmFullResize;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: FullResize1Click');
{$endif}
frm:=TFrmFullResize.Create(Self);
with frm do
begin
x := ActiveSection.Tailer.XSize;
y := ActiveSection.Tailer.YSize;
z := ActiveSection.Tailer.ZSize;
Image1.Picture := TopBarImageHolder.Picture;
ShowModal;
if Changed then
begin
ResetUndoRedo;
UpdateUndo_RedoState;
SetIsEditable(false);
ActiveSection.ResizeBlowUp(Scale);
SetIsEditable(true);
SectionComboChange(Sender);
VXLChanged := true;
end;
end;
frm.Free;
end;
procedure TFrmMain.UpdatePositionStatus(x,y,z : integer);
begin
StatusBar1.Panels[3].Text := 'Pos: ' + inttostr(Y) + ',' + inttostr(Z) + ',' + inttostr(X);
end;
procedure TFrmMain.ToolButton9Click(Sender: TObject);
var
frm: TFrmPreferences;
begin
frm:=TFrmPreferences.Create(Self);
frm.ShowModal;
frm.Free;
end;
procedure TFrmMain.SpeedButton9Click(Sender: TObject);
begin
SetVXLTool(VXLTool_SmoothNormal);
Normals1.Click;
end;
procedure TFrmMain.ToolButton13Click(Sender: TObject);
var
frm: TFrmReplaceColour;
begin
frm:=TFrmReplaceColour.Create(Self);
frm.Visible:=False;
frm.Image1.Picture := TopBarImageHolder.Picture;
frm.ShowModal;
frm.Close;
frm.Free;
end;
Function CharToStr : String;
var
x : integer;
begin
for x := 1 to 16 do
Result := VoxelFile.Header.FileType[x];
end;
Function CleanString(S : string) : String;
var
x : integer;
begin
Result := '';
for x := 1 to Length(s) do
if (S[x] <> '&') and (S[x] <> 'x') then
Result := Result + S[x];
end;
procedure TFrmMain.N1x1Click(Sender: TObject);
begin
ActiveSection.Viewport[0].Zoom := Strtoint(CleanString(TMenuItem(Sender).caption));
CentreViews;
setupscrollbars;
CnvView0.Refresh;
end;
procedure TFrmMain.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: FormKeyDown');
{$endif}
if (Key = Ord('X')) or (Key = Ord('x')) then
begin
if ssShift in shift then
begin
if YCursorBar.Position > 0 then
YCursorBar.Position := YCursorBar.Position - 1;
end
else
begin
if YCursorBar.Position < YCursorBar.Max then
YCursorBar.Position := YCursorBar.Position + 1;
end;
XCursorBarChange(nil);
end
else if (Key = Ord('Y')) or (Key = Ord('y')) then
begin
if ssShift in shift then
begin
if ZCursorBar.Position > 0 then
ZCursorBar.Position := ZCursorBar.Position - 1;
end
else
begin
if ZCursorBar.Position < ZCursorBar.Max then
ZCursorBar.Position := ZCursorBar.Position + 1;
end;
XCursorBarChange(nil);
end;
if (Key = Ord('Z')) or (Key = Ord('z')) then
begin
if ssShift in shift then
begin
if XCursorBar.Position > 0 then
XCursorBar.Position := XCursorBar.Position - 1;
end
else
begin
if XCursorBar.Position < XCursorBar.Max then
XCursorBar.Position := XCursorBar.Position + 1;
end;
XCursorBarChange(nil);
end;
end;
procedure TFrmMain.Display3DWindow1Click(Sender: TObject);
begin
if p_Frm3DPreview = nil then
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Display3DWindow1Click');
{$endif}
Application.OnIdle := nil;
new(p_Frm3DPreview);
p_Frm3DPreview^ := TFrm3DPreview.Create(self);
p_Frm3DPreview^.Show;
if @Application.OnIdle = nil then
Application.OnIdle := Idle;
end;
end;
procedure TFrmMain.NewAutoNormals1Click(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CubedAutoNormals1Click');
{$endif}
// ask the user to confirm
if MessageDlg('Autonormals v6.1' +#13#13+
'This process will modify the voxel''s normals.' +#13+
'If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then
Exit;
//ResetUndoRedo;
CreateVXLRestorePoint(ActiveSection,Undo);
UpdateUndo_RedoState;
ApplyInfluenceNormalsToVXL(ActiveSection);
Refreshall;
VXLChanged := true;
end;
procedure TFrmMain.FormActivate(Sender: TObject);
begin
// Activate the view.
if (not Display3dView1.Checked) then
begin
if p_Frm3DPreview <> nil then
begin
p_Frm3DPreview^.AnimationTimer.Enabled := p_Frm3DPreview^.AnimationState;
end;
if @Application.OnIdle = nil then
Application.OnIdle := Idle;
end
else
Application.OnIdle := nil;
end;
procedure TFrmMain.FormDeactivate(Sender: TObject);
begin
Application.OnIdle := nil;
end;
end.
|
// Modified April 2010
// TCustomStrings.SetText method modified to account for either #10, #13 or #13#10 as line breaks
unit JMC_Strings;
interface
uses
Classes,
JMC_Parts,
Graphics,
Windows,
SysUtils,
Clipbrd,
JMC_FileUtils;
type
{ TCustomStrings }
TCustomStrings = class(TObject)
protected
function IndexInRange(const Index: Integer): Boolean;
function GetCount: Integer; virtual; abstract;
function GetLine(const Index: Integer): string; virtual; abstract;
function GetText: string;
procedure SetLine(const Index: Integer; const Value: string); virtual; abstract;
procedure SetText(const Value: string);
procedure Ins(const Index: Integer; const Line: string); virtual; abstract;
procedure Del(const Index: Integer); virtual; abstract;
public
constructor Create; virtual;
function LoadFromFile(const FileName: string): Boolean; virtual; abstract;
function SaveToFile(const FileName: string): Boolean; virtual; abstract;
procedure Add; overload; virtual;
procedure Add(const Line: string); overload; virtual; abstract;
procedure Append(const Index: Integer; const Value: string);
procedure AppendFrom(const Lines: TCustomStrings); overload;
procedure AppendFrom(const Lines: TStrings); overload;
procedure AppendTo(const Lines: TCustomStrings); overload;
procedure AppendTo(const Lines: TStrings); overload;
function Insert(const Index: Integer; const Line: string): Boolean;
function Delete(const Index: Integer): Boolean;
procedure Clear; virtual; abstract;
procedure Assign(const Strings: TStrings); overload;
procedure Assign(const Strings: TCustomStrings); overload;
procedure CopyToClipboard;
procedure CopyToStrings(const Strings: TStrings);
function Equals(const Strings: TCustomStrings): Boolean;
function Empty: Boolean;
function Find(const Line: string): Integer;
function MaxWidth(const Canvas: TCanvas): Integer;
property Text: string read GetText write SetText;
property Count: Integer read GetCount;
property Lines[const Index: Integer]: string read GetLine write SetLine; default;
end;
{ TStringArray }
TStringArray = class(TCustomStrings)
protected
FCount: Integer;
FLines: array of string;
function GetCount: Integer; override;
function GetLine(const Index: Integer): string; override;
procedure SetLine(const Index: Integer; const Value: string); override;
procedure Ins(const Index: Integer; const Line: string); override;
procedure Del(const Index: Integer); override;
public
destructor Destroy; override;
function LoadFromFile(const FileName: string): Boolean; override;
function SaveToFile(const FileName: string): Boolean; override;
procedure Clear; override;
procedure Add(const Line: string); override;
end;
{ TCustomIniFile }
TCustomIniFile = class(TObject)
private
FStrings: TCustomStrings;
function SectionFound(const LineIndex: Integer): Boolean;
protected
procedure SetStrings(const Value: TCustomStrings);
public
constructor Create; virtual;
function LoadFromFile(const FileName: string): Boolean; virtual;
function SaveToFile(const FileName: string): Boolean; virtual;
{ Parts }
function ReadPart(const LineIndex, PartIndex: Integer): string;
function WritePart(const Part: string; const LineIndex, PartIndex: Integer): Boolean;
{ Sections }
function WriteSection(const Section: string): Boolean;
function ReadSections(const Lines: TCustomStrings): Boolean;
function SectionIndex(const Section: string): Integer;
function SectionExists(const Section: string): Boolean;
function CountSections: Integer;
function RenameSection(const OldSection, NewSection: string): Boolean;
function DeleteSection(const Section: string): Boolean;
function ClearSection(const Section: string): Boolean;
{ Keys }
function ReadKeys(const Section: string; const Lines: TCustomStrings): Boolean;
function KeyIndex(const Section, Key: string): Integer;
function KeyExists(const Section, Key: string): Boolean;
function CountKeys(const Section: string): Integer;
function RenameKey(const Section, OldKey, NewKey: string): Boolean;
function DeleteKey(const Section, Key: string): Boolean;
{ Values }
function ReadValue(const Section, Key: string): string;
function ReadValues(const Section: string; const Lines: TCustomStrings): Boolean;
function WriteValue(const Section, Key, Value: string): Boolean;
{ Lines }
function ReadLine(const Section: string; const Index: Integer): string;
function ReadLines(const Section: string; const Lines: TCustomStrings; const SkipBlanks, TrimSpaces, AllowEmpty: Boolean): Boolean;
procedure WriteLine(const Section, NewLine: string);
procedure WriteLines(const Section: string; const Lines: TCustomStrings);
function LineIndex(const Section, Line: string): Integer;
function LineExists(const Section, Line: string): Boolean;
function CountLines(const Section: string): Integer;
function NextEmptyLineIndex(const StartIndex: Integer): Integer; overload;
function NextEmptyLineIndex(const Section: string): Integer; overload;
function ChangeLine(const Section, OldLine, NewLine: string): Boolean;
function DeleteLine(const Section, Line: string): Boolean;
{ Properties }
property Strings: TCustomStrings read FStrings;
end;
{ TLinkedIniFile }
TLinkedIniFile = class(TCustomIniFile)
public
property Strings write SetStrings;
end;
{ TStoredIniFile }
TStoredIniFile = class(TCustomIniFile)
public
constructor Create; override;
destructor Destroy; override;
end;
implementation
{ TCustomStrings }
procedure TCustomStrings.Add;
begin
Add('');
end;
procedure TCustomStrings.Append(const Index: Integer; const Value: string);
begin
Lines[Index] := Lines[Index] + Value;
end;
procedure TCustomStrings.AppendFrom(const Lines: TCustomStrings);
var
i: Integer;
begin
for i := 0 to Lines.Count - 1 do
Add(Lines[i]);
end;
procedure TCustomStrings.AppendFrom(const Lines: TStrings);
var
i: Integer;
begin
for i := 0 to Lines.Count - 1 do
Add(Lines[i]);
end;
procedure TCustomStrings.AppendTo(const Lines: TCustomStrings);
var
i: Integer;
begin
for i := 0 to Count - 1 do
Lines.Add(GetLine(i));
end;
procedure TCustomStrings.AppendTo(const Lines: TStrings);
var
i: Integer;
begin
for i := 0 to Count - 1 do
Lines.Add(GetLine(i));
end;
procedure TCustomStrings.Assign(const Strings: TCustomStrings);
var
i: Integer;
begin
Clear;
for i := 0 to Strings.Count - 1 do
Add(Strings[i]);
end;
procedure TCustomStrings.Assign(const Strings: TStrings);
begin
SetText(Strings.Text);
end;
procedure TCustomStrings.CopyToClipboard;
begin
Clipboard.SetTextBuf(PChar(Text));
end;
procedure TCustomStrings.CopyToStrings(const Strings: TStrings);
Begin
Strings.Text := GetText;
end;
constructor TCustomStrings.Create;
begin
inherited;
end;
function TCustomStrings.Delete(const Index: Integer): Boolean;
begin
Result := IndexInRange(Index);
if Result then
Del(Index);
end;
function TCustomStrings.Empty: Boolean;
begin
Result := Count = 0;
end;
function TCustomStrings.Equals(const Strings: TCustomStrings): Boolean;
var
i: Integer;
begin
Result := Count = Strings.Count;
if Result then
for i := 0 to Count - 1 do
if CompareStr(Lines[i], Strings[i]) <> 0 then
begin
Result := False;
Exit;
end;
end;
function TCustomStrings.Find(const Line: string): Integer;
var
i: Integer;
S: string;
begin
S := UpperCase(Line);
for i := 0 to Count - 1 do
if UpperCase(Lines[i]) = S then
begin
Result := i;
Exit;
end;
Result := -1;
end;
function TCustomStrings.GetText: string;
var
i: Integer;
begin
Result := '';
for i := 0 to Count - 1 do
begin
Result := Result + Lines[i];
if i < Count - 1 then
Result := Result + #13#10;
end;
end;
function TCustomStrings.IndexInRange(const Index: Integer): Boolean;
begin
Result := (Index >= 0) and (Index < Count);
end;
function TCustomStrings.Insert(const Index: Integer; const Line: string): Boolean;
begin
Result := IndexInRange(Index);
if Result then
Ins(Index, Line);
end;
function TCustomStrings.MaxWidth(const Canvas: TCanvas): Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to Count - 1 do
if Canvas.TextWidth(Lines[i]) > Result then
Result := Canvas.TextWidth(Lines[i]);
end;
procedure TCustomStrings.SetText(const Value: string);
var
i: Integer;
S: string;
begin
Clear;
if Value = '' then
Exit;
i := 1;
S := '';
while i <= Length(Value) do
begin
case Ord(Value[i]) of
10, 13:
begin
Add(S);
S := '';
if (Ord(Value[i]) = 13) and (i < Length(Value)) then
if Ord(Value[i + 1]) = 10 then
Inc(i);
end;
else
S := S + Value[i];
end;
Inc(i);
end;
Add(S);
end;
{ TStringArray }
procedure TStringArray.Add(const Line: string);
begin
Inc(FCount);
SetLength(FLines, FCount);
FLines[FCount - 1] := Line;
end;
procedure TStringArray.Clear;
begin
SetLength(FLines, 0);
FCount := 0;
end;
procedure TStringArray.Del(const Index: Integer);
var
i: Integer;
begin
Dec(FCount);
for i := Index to FCount - 1 do
FLines[i] := FLines[i + 1];
SetLength(FLines, FCount);
end;
destructor TStringArray.Destroy;
begin
SetLength(FLines, 0);
inherited;
end;
function TStringArray.GetCount: Integer;
begin
Result := FCount;
end;
function TStringArray.GetLine(const Index: Integer): string;
begin
if IndexInRange(Index) then
Result := FLines[Index]
else
Result := '';
end;
procedure TStringArray.Ins(const Index: Integer; const Line: string);
var
i: Integer;
begin
Inc(FCount);
SetLength(FLines, FCount);
for i := FCount - 1 downto Index + 1 do
FLines[i] := FLines[i - 1];
FLines[Index] := Line;
end;
function TStringArray.LoadFromFile(const FileName: string): Boolean;
var
S: string;
begin
Result := JMC_FileUtils.FileToStr(FileName, S);
SetText(S);
end;
function TStringArray.SaveToFile(const FileName: string): Boolean; // FileName must be fully qualified
var
F: TFileStream;
i: Integer;
S: string;
begin
try
if Count > 0 then
begin
F := TFileStream.Create(FileName, fmCreate or fmOpenWrite or fmShareDenyNone);
for i := 0 to Count - 2 do
begin
S := FLines[i] + #13#10;
F.Write(S[1], Length(S));
end;
F.Write(FLines[Count - 1][1], Length(FLines[Count - 1]));
F.Free;
Result := True;
end
else
Result := False;
except
Result := False;
end;
end;
procedure TStringArray.SetLine(const Index: Integer; const Value: string);
begin
if IndexInRange(Index) then
FLines[Index] := Value;
end;
{ TCustomIniFile }
function TCustomIniFile.ChangeLine(const Section, OldLine, NewLine: string): Boolean;
var
i: Integer;
begin
i := LineIndex(Section, OldLine);
Result := i > -1;
if Result then
FStrings[i] := NewLine;
end;
function TCustomIniFile.ClearSection(const Section: string): Boolean;
var
i: Integer;
begin
i := SectionIndex(Section);
Result := i > -1;
if Result then
begin
Inc(i);
while i < FStrings.Count do
begin
if SectionFound(i) then
Break;
FStrings.Del(i);
Inc(i);
end;
end;
end;
function TCustomIniFile.CountKeys(const Section: string): Integer;
var
i, n: Integer;
begin
Result := 0;
i := SectionIndex(Section);
if i > -1 then
for n := i to FStrings.Count - 1 do
begin
if SectionFound(n) then
Break;
if Pos('=', FStrings[n]) > 0 then
Inc(Result);
end;
end;
function TCustomIniFile.CountLines(const Section: string): Integer;
var
n, i: Integer;
begin
Result := 0;
i := SectionIndex(Section) + 1;
if i > -1 then
for n := i to FStrings.Count - 1 do
begin
if SectionFound(n) then
Break;
Inc(Result);
end;
end;
function TCustomIniFile.CountSections: Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to FStrings.Count - 1 do
if SectionFound(i) then
Inc(Result);
end;
constructor TCustomIniFile.Create;
begin
inherited;
end;
function TCustomIniFile.DeleteKey(const Section, Key: string): Boolean;
var
i: Integer;
begin
i := KeyIndex(Section, Key);
Result := i > -1;
if Result then
FStrings.Delete(i);
end;
function TCustomIniFile.DeleteLine(const Section, Line: string): Boolean;
var
i: Integer;
begin
i := LineIndex(Section, Line);
Result := i <> -1;
if Result then
FStrings.Delete(i);
end;
function TCustomIniFile.DeleteSection(const Section: string): Boolean;
var
i: Integer;
begin
i := SectionIndex(Section);
Result := i > -1;
if Result then
begin
FStrings.Del(i);
while i < FStrings.Count do
begin
if SectionFound(i) then
Break;
FStrings.Del(i);
Inc(i);
end;
end;
end;
function TCustomIniFile.KeyExists(const Section, Key: string): Boolean;
begin
Result := KeyIndex(Section, Key) > -1;
end;
function TCustomIniFile.KeyIndex(const Section, Key: string): Integer;
var
i, n: Integer;
begin
i := SectionIndex(Section);
if i > -1 then
for n := i + 1 to FStrings.Count - 1 do
begin
if SectionFound(n) then
Break;
if Pos('=', FStrings[n]) <= 0 then
Break;
if UpperCase(JMC_Parts.ReadPart(FStrings[n], 1, '=')) = UpperCase(Key) then
begin
Result := n;
Exit;
end;
end;
Result := -1;
end;
function TCustomIniFile.LineExists(const Section, Line: string): Boolean;
begin
Result := LineIndex(Section, Line) > -1;
end;
function TCustomIniFile.LineIndex(const Section, Line: string): Integer;
var
n, i: Integer;
begin
i := SectionIndex(Section);
if i > -1 then
for n := i + 1 to FStrings.Count - 1 do
begin
if SectionFound(n) then
Break;
if FStrings[n] = Line then
begin
Result := n;
Exit;
end;
end;
Result := -1;
end;
function TCustomIniFile.LoadFromFile(const FileName: string): Boolean;
begin
Result := FStrings.LoadFromFile(FileName);
end;
function TCustomIniFile.NextEmptyLineIndex(const Section: string): Integer;
begin
Result := SectionIndex(Section);
if Result > -1 then
Result := NextEmptyLineIndex(Result + 1);
end;
function TCustomIniFile.NextEmptyLineIndex(const StartIndex: Integer): Integer;
var
i: Integer;
begin
for i := StartIndex to FStrings.Count - 1 do
begin
if Trim(FStrings[i]) = '' then
begin
FStrings[i] := '';
Result := i;
if SectionFound(i + 1) then
FStrings.Insert(i + 1, '');
Exit;
end;
if SectionFound(i) then
begin
FStrings.Insert(i, '');
FStrings.Insert(i, '');
Result := i;
Exit;
end;
end;
FStrings.Add('');
Result := FStrings.Count - 1;
end;
function TCustomIniFile.ReadKeys(const Section: string; const Lines: TCustomStrings): Boolean;
var
i, n: Integer;
begin
Lines.Clear;
i := SectionIndex(Section);
if i > -1 then
for n := i + 1 to FStrings.Count - 1 do
begin
if SectionFound(n) then
Break;
if Pos('=', FStrings[n]) > 0 then
Lines.Add(ReadPart(n, 1));
end;
Result := Lines.Count > 0;
end;
function TCustomIniFile.ReadLine(const Section: string; const Index: Integer): string;
var
i: Integer;
begin
i := SectionIndex(Section);
if i > -1 then
Result := FStrings[i + Index + 1]
else
Result := '';
end;
function TCustomIniFile.ReadPart(const LineIndex, PartIndex: Integer): string;
begin
Result := JMC_Parts.ReadPart(FStrings[LineIndex], PartIndex, '=');
end;
function TCustomIniFile.ReadLines(const Section: string; const Lines: TCustomStrings; const SkipBlanks, TrimSpaces, AllowEmpty: Boolean): Boolean;
var
i, n: Integer;
function NextLineIsSection: Boolean;
begin
Result := False;
if n < FStrings.Count - 1 then
if Length(Trim(FStrings[n + 1])) > 1 then
if Trim(FStrings[n + 1])[1] = '[' then
Result := True;
end;
begin
Result := False;
Lines.Clear;
i := SectionIndex(Section);
if i < 0 then
Exit;
for n := i + 1 to FStrings.Count - 1 do
begin
if SectionFound(n) then
Break;
if (SkipBlanks and (Trim(FStrings[n]) <> '')) or ((not SkipBlanks) and (not NextLineIsSection)) then
if TrimSpaces then
Lines.Add(Trim(FStrings[n]))
else
Lines.Add(FStrings[n]);
end;
Result := (Lines.Count > 0) or AllowEmpty;
end;
function TCustomIniFile.ReadSections(const Lines: TCustomStrings): Boolean;
var
i: Integer;
begin
Lines.Clear;
for i := 0 to FStrings.Count - 1 do
if SectionFound(i) then
Lines.Add(JMC_Parts.ReadPart(JMC_Parts.ReadPart(FStrings[i], 2, '['), 1, ']'));
Result := Lines.Count > 0;
end;
function TCustomIniFile.ReadValue(const Section, Key: string): string;
var
i: Integer;
begin
i := KeyIndex(Section, Key);
if i > -1 then
Result := ReadPart(i, 2)
else
Result := '';
end;
function TCustomIniFile.ReadValues(const Section: string; const Lines: TCustomStrings): Boolean;
var
i, n: Integer;
begin
Lines.Clear;
i := SectionIndex(Section);
if i > -1 then
for n := i to FStrings.Count - 1 do
begin
if SectionFound(n) then
Break;
if Pos('=', FStrings[n]) > 0 then
Lines.Add(ReadPart(n, 2));
end;
Result := Lines.Count > 0;
end;
function TCustomIniFile.RenameKey(const Section, OldKey, NewKey: string): Boolean;
var
i: Integer;
begin
i := KeyIndex(Section, OldKey);
Result := i > -1;
if Result then
Result := WritePart(NewKey, i, 1);
end;
function TCustomIniFile.RenameSection(const OldSection, NewSection: string): Boolean;
var
i: Integer;
begin
i := SectionIndex(OldSection);
Result := i > -1;
if Result then
FStrings[i] := '[' + NewSection + ']';
end;
function TCustomIniFile.SaveToFile(const FileName: string): Boolean;
begin
Result := FStrings.SaveToFile(FileName);
end;
function TCustomIniFile.SectionExists(const Section: string): Boolean;
begin
Result := SectionIndex(Section) <> -1;
end;
function TCustomIniFile.SectionIndex(const Section: string): Integer;
var
i: Integer;
begin
for i := 0 to FStrings.Count - 1 do
if UpperCase(Trim(FStrings[i])) = '[' + UpperCase(Section) + ']' then
begin
Result := i;
Exit;
end;
Result := -1;
end;
function TCustomIniFile.SectionFound(const LineIndex: Integer): Boolean;
begin
Result := TrimLeft(Copy(FStrings[LineIndex], 1, 1)) = '[';
end;
procedure TCustomIniFile.SetStrings(const Value: TCustomStrings);
begin
FStrings := Value;
end;
procedure TCustomIniFile.WriteLine(const Section, NewLine: string);
var
i: Integer;
begin
i := SectionIndex(Section);
if i > -1 then
FStrings[NextEmptyLineIndex(i + 1)] := NewLine
else
if Section <> '' then
begin
if Trim(FStrings[FStrings.Count - 1]) <> '' then
FStrings.Add('');
FStrings.Add('[' + Section + ']');
FStrings.Add(NewLine);
end;
end;
procedure TCustomIniFile.WriteLines(const Section: string; const Lines: TCustomStrings);
var
n, i: Integer;
begin
i := SectionIndex(Section);
if i > -1 then
begin
n := NextEmptyLineIndex(i + 1);
for i := 0 to Lines.Count - 1 do
FStrings.Insert(n + i, Lines[i]);
end
else
if Section <> '' then
begin
if Trim(FStrings[FStrings.Count - 1]) <> '' then
FStrings.Add('');
FStrings.Add('[' + Section + ']');
for i := 0 to Lines.Count - 1 do
FStrings.Add(Lines[i]);
end;
end;
function TCustomIniFile.WritePart(const Part: string; const LineIndex, PartIndex: Integer): Boolean;
var
S: string;
begin
S := FStrings[LineIndex];
Result := JMC_Parts.WritePart(S, Part, PartIndex, '=');
if Result then
FStrings[LineIndex] := S;
end;
function TCustomIniFile.WriteSection(const Section: string): Boolean;
var
i: Integer;
begin
Result := False;
if Section = '' then
Exit;
i := SectionIndex(Section);
if i > -1 then
Exit;
if Trim(FStrings[FStrings.Count - 1]) <> '' then
FStrings.Add('');
FStrings.Add('[' + Section + ']');
Result := True;
end;
function TCustomIniFile.WriteValue(const Section, Key, Value: string): Boolean;
var
i: Integer;
begin
i := KeyIndex(Section, Key);
if i > -1 then
begin
Result := WritePart(Value, i, 2);
Exit;
end;
if Key <> '' then
begin
i := NextEmptyLineIndex(Section);
if i > -1 then
begin
FStrings[i] := Key + '=' + Value;
Result := True;
Exit;
end;
if Section <> '' then
begin
if Trim(FStrings[FStrings.Count - 1]) <> '' then
FStrings.Add('');
FStrings.Add('[' + Section + ']');
FStrings.Add(Key + '=' + Value);
Result := True;
Exit;
end;
end;
Result := False;
end;
{ TStoredIniFile }
constructor TStoredIniFile.Create;
begin
inherited;
FStrings := TStringArray.Create;
end;
destructor TStoredIniFile.Destroy;
begin
FStrings.Free;
inherited;
end;
end.
|
unit neuralNetwork;
interface
Const
numOfinputs = 2; // number of inputs (+1)
numOfoutupts = 0; // number of outputs (+1)
type
inputArray = array [0 .. numOfinputs] of double;
outputArray = array [0 .. numOfoutupts] of double;
synapticArray = Array [0 .. numOfoutupts, 0 .. numOfinputs] of double;
neauralNetwork = Class
private
class function sigmoid(x: double): double;
class function derivative(x: double): double;
class function CalcCorectWeights(input: double; fail: double; thinkout: double): double;
public
class var synapticWeights: synapticArray;
constructor Create;
class procedure RandomSynapticWeights;
class procedure learn(input: inputArray; target: outputArray);
class function think(input: inputArray): outputArray;
class function targetToOutput(target: integer): outputArray;
class function outputToTarget(output: outputArray): integer;
end;
implementation
uses SysUtils, Windows, Math, Unit1;
constructor neauralNetwork.Create;
begin
RandomSynapticWeights;
end;
//converts index of the most benevolent to output array (index = 1, other = 0)
class function neauralNetwork.targetToOutput(target: integer): outputArray;
var i: integer;
o: outputArray;
begin
for i:= 0 to 3 do if i = target then o[i] := 1
else o[i] := 0;
targetToOutput := o;
end;
//converts the output array to an index of the most benevolent
class function neauralNetwork.outputToTarget(output: outputArray): integer;
var i, max: integer;
begin
max := 0;
for i:= 1 to 3 do if output[max] < output[i] then max := i;
outputToTarget := max;
end;
class procedure neauralNetwork.RandomSynapticWeights;
var
i, j: integer;
begin
for i := 0 to numOfoutupts do
for j := 0 to numOfinputs do
synapticWeights[i][j] := Random(100) / 100;
end;
// Sigmoid, describes an S-shaped curve
// Normalizes between 0 and 1
class function neauralNetwork.sigmoid(x: double): double;
begin
// exp () performs e on x
sigmoid := 1 / (1 + exp(-x));
end;
// Derivatives for the Sigmoid Curve
class function neauralNetwork.derivative(x: double): double;
begin
derivative := x * (1 - x);
end;
// calculates the weight correction
class function neauralNetwork.CalcCorectWeights(input: double; fail: double; thinkout: double): double;
begin
CalcCorectWeights := input * fail * derivative(thinkout);
end;
//learns what input array to be the output array
class procedure neauralNetwork.learn(input: inputArray; target: outputArray);
var thinkOutput: outputArray;
fail: double;
i, j: integer;
begin
thinkOutput := think(input);
for i := 0 to numOfoutupts do begin
fail := target[i] - thinkOutput[i];
for j := 0 to numOfinputs do
synapticWeights[i][j] := synapticWeights[i][j] + CalcCorectWeights(input[j], fail, thinkoutput[i]);
end;
end;
//classifies by input array
class function neauralNetwork.think(input: inputArray): outputArray;
var
i, j: integer;
a: outputArray;
begin
for i := 0 to numOfoutupts do a[i] := 0;
for i := 0 to numOfoutupts do begin
for j := 0 to numOfinputs do a[i] := a[i] + synapticWeights[i][j] * input[j];
a[i] := sigmoid(a[i]);
end;
i := outputToTarget(a);
OutputDebugString(PChar('the situation is identified ' + IntToStr(i) + ' with probability ' + FloatToStr(a[i])));
think := a;
end;
end.
|
unit CtkTimer;
{
Catarinka Lua Timeout Library
Copyright (c) 2013-2020 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
}
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
CatCSTimer,
{$ELSE}
Classes,
{$ENDIF}
Lua, pLua;
type
TCatarinkaLuaTimer = class(TConsoleTimer)
private
fLuaState:plua_State;
procedure OnTimer(Sender: TObject);
public
func: lua_CFunction;
mode: integer;
argcount: integer;
script: string;
args : array of TLuaVariantRec;
constructor Create(L:plua_State);
end;
function utils_settimeout(L: plua_State): integer; cdecl;
implementation
procedure TCatarinkaLuaTimer.OnTimer(Sender: TObject);
var
i:integer;
begin
case mode of
LUA_TFUNCTION: begin
lua_pushcfunction(fLuaState, func);
for i := Low(args) to High(args) do begin
if args[i].LuaType <> LUA_TNONE then
plua_pushvariant(fLuaState, args[i].Value);
end;
lua_pcall(fLuaState, argcount, 0, 0);
end;
LUA_TSTRING: begin
plua_dostring(fLuaState, script);
end;
end;
Enabled := false;
Free;
end;
constructor TCatarinkaLuaTimer.Create(L:plua_State);
begin
inherited Create;
fLuaState := L;
OnTimerEvent := OnTimer;
end;
function utils_settimeout(L: plua_State): integer; cdecl;
var
t:TCatarinkaLuaTimer;
begin
t := TCatarinkaLuaTimer.Create(L);
if (lua_type(L, 1) = LUA_TNUMBER) and (lua_type(L, 2) = LUA_TFUNCTION) then begin
t.argcount := lua_gettop(L) - 2;
t.mode := LUA_TFUNCTION;
t.Interval := lua_tointeger(L, 1);
t.func := lua_tocfunction(L, 2);
// max 3 optional arguments allowed
t.args := [plua_tovariantrec(L, 3), plua_tovariantrec(L, 4), plua_tovariantrec(L, 5)];
t.Enabled := true;
end else begin
if plua_validateargs(L, result, [LUA_TNUMBER, LUA_TSTRING]).OK = true then begin
t.mode := LUA_TSTRING;
t.Interval := lua_tointeger(L, 1);
t.script := lua_tostring(L, 2);
t.Enabled := true;
end;
end;
end;
{function utils_settimeout_oldcallback(L: plua_State): integer; cdecl;
var
script:string;
func: lua_CFunction;
t:TConsoleTimer;
begin
if plua_validateargsets(L, result, [[LUA_TNUMBER], [LUA_TSTRING, LUA_TFUNCTION]]).OK = false then
Exit;
t := TConsoleTimer.Create;
t.Interval := lua_tointeger(L, 1);
t.Enabled := true;
if lua_type(L, 2) = LUA_TFUNCTION then begin
func := lua_tocfunction(L, 2);
t.OnTimerCallBack := procedure()
begin
lua_pushcfunction(L, func);
lua_pcall(L, 0, 0, 0);
t.Enabled := false;
t.Free;
end;
end else begin
script := lua_tostring(L, 2);
t.OnTimerCallBack := procedure()
begin
plua_dostring(L, script);
t.Enabled := false;
t.Free;
end;
end;
end; }
end. |
(*
Category: SWAG Title: EXECUTION ROUTINES
Original name: 0024.PAS
Description: Multiple DOS Calls
Author: FRANK DIACHEYSN
Date: 08-24-94 13:45
*)
{
Coded By Frank Diacheysn Of Gemini Software
FUNCTION MASSEXEC
Input......: DOS Command Line(s)
:
:
:
:
Output.....: Logical
: TRUE = No Errors During Execution
: FALSE = Error Occured During Execution
:
:
Example....: IF MASSEXEC('DIR,PAUSE') THEN
: WriteLn('No Errors!')
: ELSE
: WriteLn('DOS Error Occured!');
:
Description: Execute One Or More DOS Program Calls
: (Seperate Calls With A Comma)
:
:
:
}
USES DOS;
FUNCTION MASSEXEC( S:STRING ):BOOLEAN;
VAR nCount : INTEGER;
VAR ExS : STRING;
VAR Ch : CHAR;
BEGIN
REPEAT
nCount := 0;
ExS := '';
REPEAT
Inc(nCount);
Ch := S[nCount];
IF Ch <> ',' THEN
ExS := ExS + Ch;
UNTIL (Ch = ',') OR (nCount = Length(S));
IF POS(',',S)=0 THEN
S := ''
ELSE
DELETE(S,1,POS(',',S));
SWAPVECTORS;
EXEC( GETENV('COMSPEC'), '/C '+ ExS );
SWAPVECTORS;
MASSEXEC := DOSERROR = 0;
UNTIL S = '';
END;
BEGIN
IF MASSEXEC('DIR,PAUSE') THEN
WriteLn('No Errors!')
ELSE
WriteLn('DOS Error Occured!');
END.
|
unit glImageCropper;
interface
uses
{$IFDEF VER230} System.SysUtils, WinAPI.Windows, WinAPI.Messages
{$ELSE} Windows, Messages, SysUtils {$ENDIF}, Classes, Controls, JPEG, Graphics;
type
TglImageCropper = class(TCustomControl)
private
fMousePress, fEmpty: boolean;
FPhoto: TPicture;
// Для перемещения
FStartDragX, FStartDragY: integer;
FRect, FStartRect: TRect;
fBitmap, fMiniBitmap: TBitmap;
procedure WMMOUSEWHEEL(var msg: TWMMOUSEWHEEL); message WM_MOUSEWHEEL;
procedure PictureChanged(Sender: TObject);
procedure SetPhoto(Value: TPicture);
procedure DrawMiniBitmap(Scale: boolean);
procedure ScalingRectUp;
procedure ScalingRectDown;
procedure UpdateRect(Value: TRect; Scale: boolean);
protected
procedure Paint; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: integer); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure FreePhoto;
function isEmpty: boolean;
function GetThumbnail: TJPEGImage;
published
property Photo: TPicture read FPhoto write SetPhoto;
property TabOrder;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
property Align;
property Color;
property ParentColor;
property OnClick;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Golden Line', [TglImageCropper]);
end;
{ TglImageCropper }
constructor TglImageCropper.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := [csCaptureMouse, csClickEvents, csAcceptsControls];
FPhoto := TPicture.Create;
FPhoto.OnChange := PictureChanged;
fBitmap := TBitmap.Create;
fMiniBitmap := TBitmap.Create;
Width := 64;
Height := 64;
end;
destructor TglImageCropper.Destroy;
begin
FPhoto.Free;
fBitmap.Free;
fMiniBitmap.Free;
inherited;
end;
procedure TglImageCropper.DrawMiniBitmap;
begin
SetStretchBltMode(fMiniBitmap.Canvas.Handle, STRETCH_DELETESCANS);
fMiniBitmap.Canvas.CopyRect(Bounds(0, 0, fMiniBitmap.Width,
fMiniBitmap.Height), fBitmap.Canvas, FRect);
end;
procedure TglImageCropper.FreePhoto;
begin
if FPhoto <> nil then
FPhoto := nil;
fEmpty := true;
end;
function TglImageCropper.GetThumbnail;
var
nanoBMP: TBitmap;
begin
nanoBMP := TBitmap.Create;
nanoBMP.SetSize(115, 145);
SetStretchBltMode(nanoBMP.Canvas.Handle, HALFTONE);
nanoBMP.Canvas.StretchDraw(Rect(0, 0, 115, 145), fMiniBitmap);
Result := TJPEGImage.Create;
Result.Assign(nanoBMP);
end;
function TglImageCropper.isEmpty: boolean;
begin
Result := fEmpty;
end;
procedure TglImageCropper.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: integer);
begin
inherited;
fMousePress := true;
FStartDragX := X;
FStartDragY := Y;
FStartRect := FRect;
end;
procedure TglImageCropper.MouseMove(Shift: TShiftState; X, Y: integer);
var
fTemp: integer;
Rect: TRect;
begin
inherited;
if fMousePress then
begin
Rect := FRect;
fTemp := FStartRect.Left + (FStartDragX - X);
if (fTemp > -1) and (abs(fTemp) < (fBitmap.Width - fMiniBitmap.Width)) then
begin
Rect.Left := FStartRect.Left + (FStartDragX - X);
Rect.Right := FStartRect.Right + (FStartDragX - X);
end;
fTemp := FStartRect.Top + (FStartDragY - Y);
if (fTemp > -1) and
(abs(fTemp) < (fBitmap.Height - fMiniBitmap.Height)) then
begin
Rect.Top := FStartRect.Top + (FStartDragY - Y);
Rect.Bottom := FStartRect.Bottom + (FStartDragY - Y);
end;
UpdateRect(Rect, false);
end;
end;
procedure TglImageCropper.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: integer);
begin
inherited;
fMousePress := false;
end;
procedure TglImageCropper.Paint;
begin
inherited Paint;
if (csDesigning in ComponentState) then
begin
Canvas.Pen.Color := clGray;
Canvas.Pen.Style := psDash;
Canvas.Brush.Style := bsClear;
Canvas.Rectangle(0, 0, Width, Height);
end;
Canvas.Pen.Color := Color;
Canvas.Brush.Color := Color;
Canvas.Rectangle(BoundsRect);
Canvas.Draw(0, 0, fMiniBitmap);
end;
procedure TglImageCropper.PictureChanged(Sender: TObject);
begin
fBitmap.SetSize(FPhoto.Width, FPhoto.Height);
fBitmap.Canvas.Draw(0, 0, FPhoto.Graphic);
fMiniBitmap.SetSize(Self.Width, Self.Height);
if fBitmap.Empty then
begin
fMiniBitmap.Canvas.Pen.Color := Color;
fMiniBitmap.Canvas.Brush.Color := Color;
fMiniBitmap.Canvas.Rectangle(BoundsRect);
fEmpty := true;
end
else
begin
UpdateRect(Bounds((fBitmap.Width div 2) - (fMiniBitmap.Width div 2),
(fBitmap.Height div 2) - (fMiniBitmap.Height div 2), fMiniBitmap.Width,
fMiniBitmap.Height), false);
fEmpty := false;
end;
invalidate;
end;
procedure TglImageCropper.ScalingRectDown;
var
Rect: TRect;
differenceX, differenceY: integer;
begin
Rect := FRect;
differenceX := (Rect.Right - Rect.Left) * 5 div 100;
Rect.Left := Rect.Left + differenceX;
Rect.Right := Rect.Right - differenceX;
differenceY := (Rect.Bottom - Rect.Top) * 5 div 100;
Rect.Top := Rect.Top + differenceY;
Rect.Bottom := Rect.Bottom - differenceY;
UpdateRect(Rect, true);
end;
procedure TglImageCropper.ScalingRectUp;
var
Rect: TRect;
differenceX, differenceY: integer;
begin
Rect := FRect;
differenceX := (Rect.Right - Rect.Left) * 5 div 100;
Rect.Left := Rect.Left - differenceX;
Rect.Right := Rect.Right + differenceX;
differenceY := (Rect.Bottom - Rect.Top) * 5 div 100;
Rect.Top := Rect.Top - differenceY;
Rect.Bottom := Rect.Bottom + differenceY;
UpdateRect(Rect, true);
end;
procedure TglImageCropper.SetPhoto(Value: TPicture);
begin
FPhoto.Assign(Value);
end;
procedure TglImageCropper.UpdateRect;
begin
// if Value <> FRect then
// begin
if (Value.Left >= 0) and (Value.Top >= 0) and (Value.Right <= fBitmap.Width)
and (Value.Top <= fBitmap.Height) then
begin
FRect := Value;
DrawMiniBitmap(Scale);
invalidate;
end;
// end;
end;
procedure TglImageCropper.WMMOUSEWHEEL(var msg: TWMMOUSEWHEEL);
begin
inherited;
if not(csDesigning in ComponentState) then
begin
if msg.WheelDelta > 0 then
ScalingRectDown
else
ScalingRectUp;
end;
end;
end.
|
unit uFrmServiceOrderDiscount;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls,
ComCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit,
DB, cxDBData, cxGridLevel, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, ADODB,
Mask, SuperComboADO, cxContainer, cxTextEdit, cxMaskEdit, cxSpinEdit;
type
TFrmServiceOrderDiscount = class(TFrmParentAll)
pgDiscount: TPageControl;
tsConfig: TTabSheet;
tsApply: TTabSheet;
btnApply: TButton;
quPaymentDiscount: TADODataSet;
dsPaymentDiscount: TDataSource;
quPaymentDiscountIDPaymentDiscount: TIntegerField;
quPaymentDiscountPayment: TStringField;
quPaymentDiscountDiscountPercent: TBCDField;
grdDiscount: TcxGrid;
grdDiscountDBTableView: TcxGridDBTableView;
grdDiscountLevel: TcxGridLevel;
grdDiscountDBTableViewPayment: TcxGridDBColumn;
grdDiscountDBTableViewDiscountPercent: TcxGridDBColumn;
spnSpecialDiscount: TcxSpinEdit;
cmbPaymentType: TSuperComboADO;
lbPayment: TLabel;
lbDiscount: TLabel;
btnDelPet: TSpeedButton;
btnAddPet: TSpeedButton;
quPaymentDiscountIDMeioPag: TIntegerField;
cxGridApplyDisc: TcxGrid;
cxApplyDiscTableView: TcxGridDBTableView;
cxGridDBColumn1: TcxGridDBColumn;
cxGridDBColumn2: TcxGridDBColumn;
cxApplyDiscLevel: TcxGridLevel;
Label1: TLabel;
seApplyDiscount: TcxSpinEdit;
procedure btCloseClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnAddPetClick(Sender: TObject);
procedure btnDelPetClick(Sender: TObject);
procedure dsPaymentDiscountDataChange(Sender: TObject; Field: TField);
procedure btnApplyClick(Sender: TObject);
private
FIDSeviceOrder : Integer;
function ValidateConfig : Boolean;
procedure PaymentOpen;
procedure PaymentClose;
Procedure PaymentRefresh;
public
function Start(AType, AIDSeviceOrder : Integer):Boolean;
end;
implementation
uses uDM, uDMServiceOrder, uMsgConstant, uMsgBox;
{$R *.dfm}
procedure TFrmServiceOrderDiscount.btCloseClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TFrmServiceOrderDiscount.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TFrmServiceOrderDiscount.btnAddPetClick(Sender: TObject);
var
iID : Integer;
sSQL : String;
begin
inherited;
if ValidateConfig then
begin
iID := DM.GetNextID('Sal_PaymentDiscount.IDPaymentDiscount');
sSQL := 'INSERT Sal_PaymentDiscount (IDPaymentDiscount, IDMeioPag, DiscountPercent) ' +
'VALUES ('+IntToStr(iID)+','+ cmbPaymentType.LookUpValue +',' + IntToStr(spnSpecialDiscount.Value) + ')';
DM.RunSQL(sSQL);
PaymentRefresh;
cmbPaymentType.LookUpValue := '';
spnSpecialDiscount.Value := 0;
cmbPaymentType.SetFocus;
end;
end;
procedure TFrmServiceOrderDiscount.btnDelPetClick(Sender: TObject);
var
iID : Integer;
begin
inherited;
if quPaymentDiscount.Active and (not quPaymentDiscount.IsEmpty) then
begin
iID := quPaymentDiscountIDPaymentDiscount.AsInteger;
DM.RunSQL('DELETE Sal_PaymentDiscount WHERE IDPaymentDiscount = ' + IntToStr(iID));
PaymentRefresh;
end;
end;
function TFrmServiceOrderDiscount.Start(AType, AIDSeviceOrder: Integer): Boolean;
begin
tsConfig.TabVisible := False;
tsApply.TabVisible := False;
FIDSeviceOrder := AIDSeviceOrder;
if (AType = 0) then
begin
tsConfig.TabVisible := True;
btnApply.Visible := False;
end
else
begin
tsApply.TabVisible := True;
btnApply.Visible := True;
end;
PaymentRefresh;
ShowModal;
Result := True;
end;
function TFrmServiceOrderDiscount.ValidateConfig: Boolean;
begin
Result := False;
if (cmbPaymentType.LookUpValue = '') then
begin
MsgBox(MSG_INF_CHOOSE_PAYTYPE, vbOkOnly + vbCritical);
cmbPaymentType.SetFocus;
Exit;
end;
if (spnSpecialDiscount.Value = 0) then
begin
MsgBox(MSG_INF_NUMBER_ZERO_INVALID, vbOkOnly + vbCritical);
spnSpecialDiscount.SetFocus;
Exit;
end;
if quPaymentDiscount.Active then
if quPaymentDiscount.Locate('IDMeioPag', cmbPaymentType.LookUpValue, []) then
begin
MsgBox(MSG_INF_PAYTYPE_SELECTED, vbOkOnly + vbCritical);
Exit;
end;
Result := True;
end;
procedure TFrmServiceOrderDiscount.PaymentClose;
begin
with quPaymentDiscount do
if Active then
Close;
end;
procedure TFrmServiceOrderDiscount.PaymentOpen;
begin
with quPaymentDiscount do
if not Active then
Open;
end;
procedure TFrmServiceOrderDiscount.PaymentRefresh;
begin
PaymentClose;
PaymentOpen;
end;
procedure TFrmServiceOrderDiscount.dsPaymentDiscountDataChange(
Sender: TObject; Field: TField);
begin
inherited;
if tsApply.TabVisible then
seApplyDiscount.Value := quPaymentDiscountDiscountPercent.Value;
end;
procedure TFrmServiceOrderDiscount.btnApplyClick(Sender: TObject);
begin
inherited;
DMServiceOrder.ApplyPaymentDiscount(FIDSeviceOrder, seApplyDiscount.Value);
Close;
end;
end.
|
unit EMSPush1ClientFormU;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, IPPeerClient,
REST.Backend.PushTypes, System.JSON, REST.Backend.EMSPushDevice,
System.PushNotification, FMX.Edit, FMX.Controls.Presentation, FMX.ScrollBox,
FMX.Memo, FMX.StdCtrls, Data.Bind.Components, Data.Bind.ObjectScope,
REST.Backend.BindSource, REST.Backend.PushDevice, REST.Backend.EMSProvider,
System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt,
Fmx.Bind.DBEngExt, FMX.Layouts;
type
TForm1 = class(TForm)
EMSProvider1: TEMSProvider;
PushEvents1: TPushEvents;
ButtonRegister: TButton;
ButtonUnregister: TButton;
CheckBoxListen: TCheckBox;
Memo1: TMemo;
ButtonClear: TButton;
EditDeviceToken: TEdit;
EditInstallationID: TEdit;
EditHost: TEdit;
ButtonTestConnection: TButton;
Memo2: TMemo;
BindingsList1: TBindingsList;
LinkControlToField1: TLinkControlToField;
Layout1: TLayout;
Layout2: TLayout;
Layout3: TLayout;
procedure FormCreate(Sender: TObject);
procedure CheckBoxListenChange(Sender: TObject);
procedure ButtonRegisterClick(Sender: TObject);
procedure ButtonUnregisterClick(Sender: TObject);
procedure PushEvents1DeviceRegistered(Sender: TObject);
procedure PushEvents1DeviceTokenReceived(Sender: TObject);
procedure PushEvents1DeviceTokenRequestFailed(Sender: TObject;
const AErrorMessage: string);
procedure PushEvents1PushReceived(Sender: TObject; const AData: TPushData);
procedure ButtonTestConnectionClick(Sender: TObject);
procedure ButtonClearClick(Sender: TObject);
private
FChecking: Boolean;
procedure OnIdle(Sender: TObject; var Done: Boolean);
procedure Log(const AValue: string);
procedure UpdateConnection;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses REST.JSON;
procedure TForm1.ButtonClearClick(Sender: TObject);
begin
Memo1.Lines.Clear;
PushEvents1.ClearResult;
end;
procedure TForm1.ButtonRegisterClick(Sender: TObject);
begin
UpdateConnection;
PushEvents1.RegisterDevice;
end;
procedure TForm1.UpdateConnection;
begin
EMSProvider1.URLHost := EditHost.Text;
end;
procedure TForm1.Log(const AValue: string);
begin
Memo1.Lines.Add(AValue);
end;
procedure TForm1.ButtonTestConnectionClick(Sender: TObject);
begin
UpdateConnection;
EMSProvider1.AppHandshake(
procedure(const AObj: TJSONObject)
begin
Log(Rest.JSON.TJson.Format(AObj));
end);
end;
procedure TForm1.ButtonUnregisterClick(Sender: TObject);
begin
UpdateConnection;
PushEvents1.UnregisterDevice;
end;
procedure TForm1.CheckBoxListenChange(Sender: TObject);
begin
UpdateConnection;
if not FChecking then
PushEvents1.Active := not PushEvents1.Active;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
try
Application.OnIdle := OnIdle;
if PushEvents1.StartupNotification <> nil then
PushEvents1PushReceived(Self, PushEvents1.StartupNotification);
PushEvents1.Active := True;
if PushEvents1.DeviceToken = '' then
Log('No DeviceToken on startup');
except
Application.HandleException(Self);
end;
end;
procedure TForm1.OnIdle(Sender: TObject; var Done: Boolean);
var
LInstallationID: string;
begin
FChecking := True;
try
CheckBoxListen.IsChecked := PushEvents1.Active;
EditDeviceToken.Text := PushEvents1.DeviceToken;
if PushEvents1.InstallationValue.TryGetObjectID(LInstallationID) then
EditInstallationID.Text := LInstallationID
else
EditInstallationID.Text := '';
finally
FChecking := False;
end;
end;
procedure TForm1.PushEvents1DeviceRegistered(Sender: TObject);
begin
Log('DeviceRegistered');
end;
procedure TForm1.PushEvents1DeviceTokenReceived(Sender: TObject);
begin
Log('DeviceTokenReceived');
end;
procedure TForm1.PushEvents1DeviceTokenRequestFailed(Sender: TObject;
const AErrorMessage: string);
begin
Log('DeviceTokenRequestFailed');
end;
procedure TForm1.PushEvents1PushReceived(Sender: TObject;
const AData: TPushData);
var
S: TStrings;
begin
S := TStringList.Create;
try
S.Values['message'] := AData.Message;
S.Values['APS.Alert'] := AData.APS.Alert;
S.Values['APS.Badge'] := AData.APS.Badge;
S.Values['APS.Sound'] := AData.APS.Sound;
S.Values['GCM.Message'] := AData.GCM.Message;
S.Values['GCM.Title'] := AData.GCM.Title;
S.Values['GCM.Msg'] := AData.GCM.Msg;
S.Values['GCM.Action'] := AData.GCM.Action;
Log('PushReceived: ' + S.DelimitedText);
finally
S.Free;
end;
end;
end.
|
unit SpBankCardAddForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxMemo, cxButtonEdit, cxCheckBox, cxMaskEdit, cxDropDownEdit,
cxCalendar, cxControls, cxContainer, cxEdit, cxTextEdit,
cxLookAndFeelPainters, StdCtrls, cxButtons, ActnList, SpBankCardfmManCard,
FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet, Registry, cxLabel;
type
TfmSpBankCardAddForm = class(TForm)
cxTextEdit1: TcxTextEdit;
cxDateEdit1: TcxDateEdit;
cxCheckBox1: TcxCheckBox;
cxButtonEdit1: TcxButtonEdit;
cxMemo1: TcxMemo;
cxButton1: TcxButton;
cxButton2: TcxButton;
ActionList1: TActionList;
AClose: TAction;
AAdd: TAction;
Db: TpFIBDatabase;
DataSet: TpFIBDataSet;
Transaction: TpFIBTransaction;
ActionSelectLang: TAction;
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
cxLabel3: TcxLabel;
cxLabel4: TcxLabel;
procedure ACloseExecute(Sender: TObject);
procedure AAddExecute(Sender: TObject);
procedure cxButtonEdit1PropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure LoadCaption;
procedure ActionSelectLangExecute(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
id_bankcard_loc, id_dog_loc : int64;
mform : TfmSpBankCardfmManCard;
flag_add : boolean;
index_lang : integer;
public
constructor Create(AO : TComponent; id_bankcard : int64; myform : TfmSpBankCardfmManCard); reintroduce; overload;
end;
implementation
uses UWResourcesUnit,
MainSpBankCardUnit;
{$R *.dfm}
constructor TfmSpBankCardAddForm.Create(AO : TComponent; id_bankcard: int64;
myform: TfmSpBankCardfmManCard);
begin
inherited Create(AO);
mform := myform;
if id_bankcard <= 0 then
begin
id_dog_loc := -1;
cxDateEdit1.Date := date;
flag_add := true;
end else
begin
id_bankcard_loc := id_bankcard;
flag_add := false;
id_dog_loc := StrToInt64(mform.DataSetCard.fbn('R_ID_DOG_BANKCARD').AsString);
cxDateEdit1.Date := mform.DataSetCard.fbn('R_DATE_OPEN').AsDateTime;
if mform.DataSetCard.fbn('R_FLAG_CLOSE_CARD').AsInteger = 1
then cxCheckBox1.Checked := true;
cxMemo1.Text := mform.DataSetCard.fbn('R_N_COMMENT').AsString;
cxTextEdit1.Text := mform.DataSetCard.fbn('R_LIC_BANKSCH').AsString;
cxButtonEdit1.Text := mform.DataSetCard.fbn('R_SHORTNAME').AsString + ' ( ¹' + mform.DataSetCard.fbn('R_NUM_DOG').AsString + ' - ' + mform.DataSetCard.fbn('R_DATE_DOG').AsString + ' )';
end;
LoadCaption;
end;
procedure TfmSpBankCardAddForm.ACloseExecute(Sender: TObject);
begin
Close;
end;
procedure TfmSpBankCardAddForm.AAddExecute(Sender: TObject);
var
id_man : string;
flag : smallint;
begin
if cxTextEdit1.Text = '' then
begin
exit;
showmessage(UWResourcesUnit.SPBANKCARD_ADD_DONT_LIC[index_lang]);
cxTextEdit1.SetFocus;
end;
if cxCheckBox1.Checked then flag := 1 else flag := 0;
if id_dog_loc <= 0 then
begin
exit;
showmessage(UWResourcesUnit.SPBANKCARD_ADD_DONT_DOG[index_lang]);
cxButtonEdit1.SetFocus;
end;
db := mform.Database;
Transaction.DefaultDatabase := DB;
db.DefaultTransaction := Transaction;
DataSet.Database := DB;
DataSet.Transaction := Transaction;
Transaction.StartTransaction;
id_man := mform.DataSetGrid.fbn('ID_MAN').asString;
if flag_add then
begin
try
DataSet.Close;
DataSet.SQLs.SelectSQL.Text := 'select * from PUB_SP_BANKCARD_PEOPLE_INSERT('''+id_man+''', '+IntToStr(id_dog_loc)+', '''+cxTextEdit1.Text+''', '''+cxMemo1.Text+''', '+IntToStr(flag)+', '''+DateToStr(cxDateEdit1.Date)+''')';
showmessage(DataSet.SQLs.SelectSQL.Text);
DataSet.Open;
id_bankcard_loc := StrToint64(DataSet.fbn('R_ID').AsString);
DataSet.Close;
Transaction.Commit;
except on E:Exception do begin
Transaction.Rollback;
ShowMessage(E.Message);
end;
end;
end else
begin
try
DataSet.Close;
DataSet.SQLs.SelectSQL.Text := 'select * from PUB_SP_BANKCARD_PEOPLE_UPDATE('+IntToStr(id_bankcard_loc)+', '''+id_man+''', '''+cxTextEdit1.Text+''', '''+cxMemo1.Text+''', '+IntToStr(flag)+', '''+DateToStr(cxDateEdit1.Date)+''', '+IntToStr(id_dog_loc)+')';
DataSet.Open;
DataSet.Close;
Transaction.Commit;
except on E:Exception do begin
Transaction.Rollback;
ShowMessage(E.Message);
end;
end;
end;
if id_bankcard_loc > 0 then
begin
mform.RefreshMan;
mform.DataSetGrid.Locate('ID_MAN', id_man, []);
Close;
end;
end;
procedure TfmSpBankCardAddForm.cxButtonEdit1PropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
R : Variant;
begin
R := UVSpBankCardTakeDog(mform.Own, mform.id_user, mform.Database, true, true);
if VarArrayDimCount(R) > 0 then
begin
cxButtonEdit1.Text := VarToStr(r[3])+ ' ( ¹' + VarToStr(r[1]) + ' - '+ VarToStr(r[2]) + ' )';
id_dog_loc := r[0];
end;
end;
procedure TfmSpBankCardAddForm.LoadCaption;
var
reg : TRegistry;
begin
reg := TRegistry.Create;
try
reg.RootKey := HKEY_CURRENT_USER;
if reg.OpenKey('\Software\12303706759837\gnal\v\', False) then
begin
index_lang := StrToInt(reg.ReadString('index'));
end else
index_lang := 1;
finally
reg.Free;
end;
Caption := UWResourcesUnit.SPBANKCARD_ADD_CAPTION[index_lang];
AClose.Caption := UWResourcesUnit.MY_CONST_BUTTON_CANCEL[index_lang];
AAdd.Caption := UWResourcesUnit.MY_CONST_BUTTON_OK[index_lang];
cxLabel1.Caption := UWResourcesUnit.MY_CONST_LIC_SCH[index_lang];
cxLabel2.Caption := UWResourcesUnit.MY_CONST_DATE_OPEN[index_lang];
cxLabel3.Caption := UWResourcesUnit.SPBANKCARD_ADD_SELECT_DOG[index_lang];
cxLabel4.Caption := UWResourcesUnit.MY_CONST_COMMENT[index_lang];
cxCheckBox1.Properties.Caption := UWResourcesUnit.SPBANKCARD_ADD_FLAG_OPEN[index_lang];
end;
procedure TfmSpBankCardAddForm.ActionSelectLangExecute(Sender: TObject);
var
reg : TRegistry;
begin
reg := TRegistry.Create;
try
reg.RootKey := HKEY_CURRENT_USER;
if reg.OpenKey('\Software\12303706759837\gnal\v\',true) then
begin
if index_lang + 1 > UWResourcesUnit.IndexLang
then reg.writeString('index', '1')
else reg.writeString('index', IntToStr(index_lang + 1));
reg.CloseKey;
end
finally
reg.Free;
end;
LoadCaption;
end;
procedure TfmSpBankCardAddForm.FormActivate(Sender: TObject);
begin
LoadCaption;
end;
end.
|
unit Objekt.DHLShipment2;
interface
uses
SysUtils, Classes, geschaeftskundenversand_api_2,
Objekt.DHLShipmentdetails, Objekt.DHLShipper, Objekt.DHLReceiver;
type
TDHLShipment2 = class
private
fShipment2API: Shipment2;
fShipmentdetails: TDHLShipmentdetails;
fShipper: TDHLShipper;
fReceiver: TDHLReceiver;
public
constructor Create;
destructor Destroy; override;
function Shipment2API: Shipment2;
property Shipmentdetails: TDHLShipmentdetails read fShipmentdetails write fShipmentdetails;
property Shipper: TDHLShipper read fShipper write fShipper;
property Receiver: TDHLReceiver read fReceiver write fReceiver;
procedure Copy(aShipment2: TDHLShipment2);
end;
implementation
{ TDHLShipment2 }
constructor TDHLShipment2.Create;
begin
fShipment2API := Shipment2.Create;
fShipper := TDHLShipper.Create;
fReceiver := TDHLReceiver.Create;
fShipmentdetails := TDHLShipmentdetails.Create;
fShipment2API.ShipmentDetails := Shipmentdetails.ShipmentDetailsTypeTypeAPI;
fShipment2API.Shipper := fShipper.ShipperTypeAPI;
fShipment2API.Receiver := fReceiver.ReceiverTypeAPI;
end;
destructor TDHLShipment2.Destroy;
begin
FreeAndNil(fReceiver);
FreeAndNil(fShipper);
FreeAndNil(fShipmentdetails);
//FreeAndNil(fShipment2API);
inherited;
end;
function TDHLShipment2.Shipment2API: Shipment2;
begin
Result := fShipment2API;
end;
procedure TDHLShipment2.Copy(aShipment2: TDHLShipment2);
begin
fShipmentdetails.Copy(aShipment2.Shipmentdetails);
fShipper.Copy(aShipment2.Shipper);
fReceiver.Copy(aShipment2.Receiver);
end;
end.
|
unit Grijjy.FBSDK.iOS;
{ Provides class abstraction for the Facebook SDK libraries for iOS }
{ To bypass compile errors you must add a custom modified FMX.Platform.iOS to
your project, see the instructions at https://github.com/grijjy/DelphiSocialFrameworks for more details }
interface
uses
System.SysUtils,
System.Messaging,
FMX.Platform,
Macapi.ObjCRuntime,
iOSapi.Foundation,
iOSapi.UIKit,
FMX.Platform.iOS,
Grijjy.FBSDK.iOS.API;
type
TgoFacebookSDK = class
private
FLoginManager: FBSDKLoginManager;
private
{ Application Delegates }
procedure applicationDidFinishLaunchingWithOptions(const Sender: TObject;
const M: TMessage);
procedure applicationOpenURLWithSourceAnnotation(const Sender: TObject;
const M: TMessage);
procedure applicationDidBecomeActive(const Sender: TObject;
const M: TMessage);
private
{ Login }
procedure LoginHandler(result: FBSDKLoginManagerLoginResult; error: NSError);
private
{ Graph Requests }
procedure GraphRequestHandler(connection: FBSDKGraphRequestConnection; result: Pointer; error: NSError);
public
{ Login }
procedure LogInWithReadPermissions(const APermissions: TArray<String>; const AViewController: UIViewController = nil;
const AHandler: FBSDKLoginManagerRequestTokenHandler = nil);
function CurrentAccessToken: String;
function CurrentUserId: String;
public
{ Graph Requests }
procedure GraphPath(const APath: String);
public
constructor Create;
destructor Destroy; override;
end;
var
FacebookSDK: TgoFacebookSDK;
implementation
uses
System.Types,
System.UITypes,
System.Classes,
iOSapi.CocoaTypes,
iOSapi.CoreGraphics,
Macapi.OCBlocks,
Grijjy.Accounts.iOS.API,
Grijjy.FBSDK.Types,
Macapi.ObjectiveC,
Macapi.Helpers;
function _StringsToNSArray(const AStrings: TArray<String>): NSMutableArray;
var
S: NSString;
AString: String;
begin
Result := TNSMutableArray.Create;
for AString in AStrings do
begin
S := StrToNSStr(AString);
Result.addObject((S as ILocalObject).GetObjectID);
end;
end;
function _NSSetToStrings(const ANSSet: NSSet): TArray<String>;
var
StringArray: NSArray;
I: Integer;
AString: String;
begin
if ANSSet <> nil then
begin
SetLength(Result, ANSSet.count);
StringArray := ANSSet.allObjects;
for I := 0 to StringArray.Count - 1 do
begin
AString := NSStrToStr(TNSString.Wrap(StringArray.objectAtIndex(I)));
Result[I] := AString;
end;
end;
end;
function _ValueForKey(const AKey: String; const ANSDictionary: NSDictionary): String;
var
Key: NSString;
begin
Key := StrToNSStr(AKey);
Result := NSStrToStr(TNSString.Wrap(ANSDictionary.valueForKey(key)));
end;
{ TgoFacebookSDK }
constructor TgoFacebookSDK.Create;
begin
FLoginManager := TFBSDKLoginManager.Create;
end;
destructor TgoFacebookSDK.Destroy;
begin
FLoginManager.release;
inherited;
end;
procedure TgoFacebookSDK.applicationDidFinishLaunchingWithOptions(const Sender: TObject;
const M: TMessage);
var
SharedInstance: FBSDKApplicationDelegate;
{ To bypass compile errors you must add a custom modified FMX.Platform.iOS to
your project, see the instructions at https://github.com/grijjy/DelphiSocialFrameworks for more details }
AppDelegateMessage_applicationDidFinishLaunchingWithOptions: TAppDelegateMessage_applicationDidFinishLaunchingWithOptions;
begin
AppDelegateMessage_applicationDidFinishLaunchingWithOptions := M as TAppDelegateMessage_applicationDidFinishLaunchingWithOptions;
SharedInstance := TFBSDKApplicationDelegate.Wrap(TFBSDKApplicationDelegate.OCClass.sharedInstance);
SharedInstance.application(AppDelegateMessage_applicationDidFinishLaunchingWithOptions.Value.Application,
AppDelegateMessage_applicationDidFinishLaunchingWithOptions.Value.Options);
end;
procedure TgoFacebookSDK.applicationOpenURLWithSourceAnnotation(const Sender: TObject;
const M: TMessage);
var
SharedInstance: FBSDKApplicationDelegate;
AppDelegateMessage_applicationOpenURLWithSourceAnnotation: TAppDelegateMessage_applicationOpenURLWithSourceAnnotation;
begin
AppDelegateMessage_applicationOpenURLWithSourceAnnotation := M as TAppDelegateMessage_applicationOpenURLWithSourceAnnotation;
SharedInstance := TFBSDKApplicationDelegate.Wrap(TFBSDKApplicationDelegate.OCClass.sharedInstance);
SharedInstance.application(AppDelegateMessage_applicationOpenURLWithSourceAnnotation.Value.Application,
AppDelegateMessage_applicationOpenURLWithSourceAnnotation.Value.Url,
AppDelegateMessage_applicationOpenURLWithSourceAnnotation.Value.SourceApplication,
AppDelegateMessage_applicationOpenURLWithSourceAnnotation.Value.Annotation);
end;
procedure TgoFacebookSDK.applicationDidBecomeActive(const Sender: TObject;
const M: TMessage);
begin
TFBSDKAppEvents.OCClass.activateApp;
end;
procedure TgoFacebookSDK.LoginHandler(result: FBSDKLoginManagerLoginResult; error: NSError);
var
LoginResult: TFacebookLoginResult;
LoginResultMessage: TFacebookLoginResultMessage;
begin
LoginResult.Initialize;
if error <> nil then
begin
// error
LoginResult.Error := error.code;
LoginResult.ErrorDesc := NSStrToStr(error.localizedDescription);
end
else
if result.isCancelled then
begin
// cancelled
LoginResult.IsCancelled := True;
LoginResult.GrantedPermissions := _NSSetToStrings(result.grantedPermissions);
if result.token <> nil then
begin
LoginResult.Token := NSStrToStr(result.token.tokenString);
if result.token.userId <> nil then
LoginResult.UserID := NSStrToStr(result.token.userID);
end;
end
else
begin
LoginResult.Result := True;
LoginResult.GrantedPermissions := _NSSetToStrings(result.grantedPermissions);
if result.token <> nil then
begin
LoginResult.Token := NSStrToStr(result.token.tokenString);
if result.token.userId <> nil then
LoginResult.UserID := NSStrToStr(result.token.userID);
end;
end;
LoginResultMessage := TFacebookLoginResultMessage.Create(LoginResult);
TMessageManager.DefaultManager.SendMessage(Self, LoginResultMessage);
end;
procedure TgoFacebookSDK.LogInWithReadPermissions(const APermissions: TArray<String>; const AViewController: UIViewController;
const AHandler: FBSDKLoginManagerRequestTokenHandler);
begin
if not Assigned(AHandler) then
FLoginManager.logInWithReadPermissions(_StringsToNSArray(APermissions), nil, LoginHandler)
else
FLoginManager.logInWithReadPermissions(_StringsToNSArray(APermissions), nil, AHandler);
end;
function TgoFacebookSDK.CurrentAccessToken: String;
var
AccessToken: FBSDKAccessToken;
begin
AccessToken := TFBSDKAccessToken.Wrap(TFBSDKAccessToken.OCClass.currentAccessToken);
Result := NSStrToStr(AccessToken.tokenString);
end;
function TgoFacebookSDK.CurrentUserId: String;
var
AccessToken: FBSDKAccessToken;
begin
AccessToken := TFBSDKAccessToken.Wrap(TFBSDKAccessToken.OCClass.currentAccessToken);
Result := NSStrToStr(AccessToken.userID);
end;
procedure TgoFacebookSDK.GraphRequestHandler(connection: FBSDKGraphRequestConnection; result: Pointer; error: NSError);
var
GraphResult: TFacebookGraphResult;
GraphResultMessage: TFacebookGraphResultMessage;
Err: Pointer;
JsonData: NSData;
S: NSString;
begin
GraphResult.Initialize;
if error <> nil then
begin
GraphResult.Error := error.code;
GraphResult.ErrorDesc := NSStrToStr(error.localizedDescription);
end
else
begin
JsonData := TNSJSONSerialization.OCClass.dataWithJSONObject(result, 0, @Err);
S := TNSString.Wrap(TNSString.Alloc.initWithData(JsonData, NSUTF8StringEncoding));
try
if S <> nil then
GraphResult.Json := NSStrToStr(S);
finally
S.release;
end;
GraphResult.Result := True;
end;
GraphResultMessage := TFacebookGraphResultMessage.Create(GraphResult);
TMessageManager.DefaultManager.SendMessage(Self, GraphResultMessage);
end;
procedure TgoFacebookSDK.GraphPath(const APath: String);
var
GraphRequest: FBSDKGraphRequest;
begin
GraphRequest := TFBSDKGraphRequest.Alloc.initWithGraphPath(StrToNSStr(APath), nil);
GraphRequest.startWithCompletionHandler(GraphRequestHandler);
end;
initialization
{ we need to initialize before startup to handle didFinishLaunchingWithOptions
from the application delegate }
FacebookSDK := TgoFacebookSDK.Create;
TMessageManager.DefaultManager.SubscribeToMessage(TAppDelegateMessage_applicationDidFinishLaunchingWithOptions,
FacebookSDK.applicationDidFinishLaunchingWithOptions);
TMessageManager.DefaultManager.SubscribeToMessage(TAppDelegateMessage_applicationOpenURLWithSourceAnnotation,
FacebookSDK.applicationOpenURLWithSourceAnnotation);
TMessageManager.DefaultManager.SubscribeToMessage(TAppDelegateMessage_applicationDidBecomeActive,
FacebookSDK.applicationDidBecomeActive);
finalization
TMessageManager.DefaultManager.Unsubscribe(TAppDelegateMessage_applicationDidFinishLaunchingWithOptions,
FacebookSDK.applicationDidFinishLaunchingWithOptions);
TMessageManager.DefaultManager.Unsubscribe(TAppDelegateMessage_applicationOpenURLWithSourceAnnotation,
FacebookSDK.applicationOpenURLWithSourceAnnotation);
TMessageManager.DefaultManager.Unsubscribe(TAppDelegateMessage_applicationDidBecomeActive,
FacebookSDK.applicationDidBecomeActive);
FacebookSDK.Free;
end.
|
unit ThHtmlDocument;
interface
uses
Classes;
type
TThHtmlDocument = class
private
FBody: TStringList;
FDocType: string;
FEmitHeaders: Boolean;
FHeaders: TStringList;
FHtml: TStringList;
FStyles: TStringList;
FScript: TStringList;
FTitle: string;
protected
function GetHtml: TStringList;
procedure SetBody(const Value: TStringList);
procedure SetDocType(const Value: string);
procedure SetHeaders(const Value: TStringList);
procedure SetScript(const Value: TStringList);
procedure SetStyles(const Value: TStringList);
procedure SetTitle(const Value: string);
protected
procedure AddFooter;
procedure AddHeader;
procedure AddScript;
procedure AddStyles;
procedure AddTitle;
public
constructor Create;
destructor Destroy; override;
public
property DocType: string read FDocType write SetDocType;
property EmitHeaders: Boolean read FEmitHeaders write FEmitHeaders;
property Headers: TStringList read FHeaders write SetHeaders;
property Title: string read FTitle write SetTitle;
property Script: TStringList read FScript write SetScript;
property Styles: TStringList read FStyles write SetStyles;
property Body: TStringList read FBody write SetBody;
property Html: TStringList read GetHtml;
end;
implementation
{ TThHtmlDocument }
constructor TThHtmlDocument.Create;
begin
FDocType := '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">';
FBody := TStringList.Create;
FHeaders := TStringList.Create;
FHtml := TStringList.Create;
FScript := TStringList.Create;
FStyles := TStringList.Create;
end;
destructor TThHtmlDocument.Destroy;
begin
FStyles.Free;
FScript.Free;
FHtml.Free;
FHeaders.Free;
FBody.Free;
inherited;
end;
procedure TThHtmlDocument.SetBody(const Value: TStringList);
begin
FBody.Assign(Value);
end;
procedure TThHtmlDocument.SetDocType(const Value: string);
begin
FDocType := Value;
end;
procedure TThHtmlDocument.SetHeaders(const Value: TStringList);
begin
FHeaders.Assign(Value);
end;
procedure TThHtmlDocument.SetScript(const Value: TStringList);
begin
FScript.Assign(Value);
end;
procedure TThHtmlDocument.SetStyles(const Value: TStringList);
begin
FStyles.Assign(Value);
end;
procedure TThHtmlDocument.SetTitle(const Value: string);
begin
FTitle := Value;
end;
procedure TThHtmlDocument.AddTitle;
begin
if FTitle <> '' then
FHtml.Add('<title>' + FTitle + '</title>');
end;
procedure TThHtmlDocument.AddStyles;
begin
if Styles.Count > 0 then
with FHtml do
begin
Add('<style type="text/css">');
Add('<!--');
AddStrings(Styles);
Add('-->');
Add('</style>');
end;
end;
procedure TThHtmlDocument.AddScript;
begin
if Script.Count > 0 then
with FHtml do
begin
Add('<script language="javascript" type="text/javascript">');
Add('<!--');
AddStrings(Script);
Add('-->');
Add('</script>');
end;
end;
procedure TThHtmlDocument.AddHeader;
begin
with FHtml do
begin
Add(DocType);
Add('<html>');
Add('<head>');
AddTitle;
AddStrings(Headers);
AddStyles;
AddScript;
Add('</head>');
Add('<body>');
end;
end;
procedure TThHtmlDocument.AddFooter;
begin
with FHtml do
begin
Add('</body>');
Add('</html>');
end;
end;
function TThHtmlDocument.GetHtml: TStringList;
begin
FHtml.Clear;
if EmitHeaders then
AddHeader;
FHtml.AddStrings(Body);
if EmitHeaders then
AddFooter;
Result := FHtml;
end;
end.
|
unit NpcConfig;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Spin;
type
TFrmNpcConfig = class(TForm)
GroupBox1: TGroupBox;
MemoNpc: TMemo;
Label1: TLabel;
SEdtRatio: TSpinEdit;
BtnMakeNpc: TButton;
BtnSave: TButton;
BtnSelDir: TButton;
Label2: TLabel;
EdtDuanXinNum: TEdit;
procedure BtnMakeNpcClick(Sender: TObject);
procedure BtnSaveClick(Sender: TObject);
procedure BtnSelDirClick(Sender: TObject);
private
{ Private declarations }
public
procedure Open();
end;
var
FrmNpcConfig: TFrmNpcConfig;
sDir: string;
implementation
uses Share;
{$R *.dfm}
{ TFrmNpcConfig }
procedure TFrmNpcConfig.Open;
begin
SEdtRatio.Value := 5;
EdtDuanXinNum.Text := '';
BtnSave.Enabled := False;
sDir := '';
MemoNpc.Lines.Clear;
ShowModal();
end;
procedure TFrmNpcConfig.BtnMakeNpcClick(Sender: TObject);
var
nRatio: Integer;
I: Integer;
begin
if EdtDuanXinNum.Text = '' then begin
Application.MessageBox('请填写短信代码号!'+#13+'提示:请到找支付后台查看您的短信代码号', '提示', MB_OK + MB_ICONASTERISK);
Exit;
end;
nRatio := SEdtRatio.Value;
MemoNpc.Clear;
MemoNpc.Lines.Add('[@main]');
MemoNpc.Lines.Add('#IF');
MemoNpc.Lines.Add('#SAY');
MemoNpc.Lines.Add('<$USERNAME>你好,欢迎来到<$SERVERNAME>,很高兴为您服务\');
MemoNpc.Lines.Add('找支付充值元宝注意事项-----本区元宝比例1元RMB='+IntToStr(SEdtRatio.Value)+'元宝\');
MemoNpc.Lines.Add('①本系统支持网银和盛大卡,俊网卡,征途卡,神州行,久游,魔兽世界,声讯等\');
MemoNpc.Lines.Add('②充值后能三分钟能马上得到元宝,无须等GM发装备\');
MemoNpc.Lines.Add('③<本平台推出:只要你想买就一定能买的到充值系统>|<www.zhaopay.com>\');
MemoNpc.Lines.Add('④资费:比例1元RMB='+IntToStr(SEdtRatio.Value)+'元宝 详见本服官方网站。欢迎大家使用\');
MemoNpc.Lines.Add('⑤如果订购不成功,不收取任何费用.保证百分百不掉单现象\');
MemoNpc.Lines.Add('<元宝充值/@充值>┆<元宝领取/@领取1>┆<元宝查询/@元宝查询>┆<退出/@exit>\');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@元宝查询]');
MemoNpc.Lines.Add('#SAY');
MemoNpc.Lines.Add('您当前的元宝为:<$GAMEGOLD>个 ');
MemoNpc.Lines.Add('\');
MemoNpc.Lines.Add('\');
MemoNpc.Lines.Add('<继续领取元宝/@领取1>┆┆┆\');
MemoNpc.Lines.Add('<返回/@main>┆┆┆<退出/@exit>\\');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@充值]');
MemoNpc.Lines.Add('#IF');
MemoNpc.Lines.Add('#SAY');
MemoNpc.Lines.Add('<本服充值点卡类平台请看本服主页┆>\');
MemoNpc.Lines.Add('<移动1元 编辑WDC'+EdtDuanXinNum.Text+'游戏帐号 发送到106696588>(<充值说明/@106696588>)\');
MemoNpc.Lines.Add('<移动1.5元 编辑192'+EdtDuanXinNum.Text+'游戏帐号 发送到106698815>(<充值说明/@106698815>)\');
MemoNpc.Lines.Add('<移动1元 编辑192'+EdtDuanXinNum.Text+'游戏帐号 发送到106698812>(<充值说明/@106698812>)\');
MemoNpc.Lines.Add('<下一页短信通道/@充值2>┆<元宝领取/@领取1>┆<元宝查询/@元宝查询>┆<返回/@main>\');
MemoNpc.Lines.Add('<找支付平台:点击下一页短信通道有更多选择^^^^^^^^^\');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@充值2]');
MemoNpc.Lines.Add('#IF');
MemoNpc.Lines.Add('#SAY');
MemoNpc.Lines.Add('<本服充值点卡类平台请看本服主页┆>\');
MemoNpc.Lines.Add('<移动1元 编辑 54'+EdtDuanXinNum.Text+'游戏帐号 发送到10665123906>(<充值说明/@10665123906>)\');
MemoNpc.Lines.Add('<移动1元 编辑543'+EdtDuanXinNum.Text+'游戏帐号 发送到10666000968>(<充值说明/@10666000968>)\');
MemoNpc.Lines.Add('<联通2元 编辑 4#'+EdtDuanXinNum.Text+'游戏帐号 发送到1066960016720>(<充值说明/@1066960016720>)\');
MemoNpc.Lines.Add('<移动2元 编辑337'+EdtDuanXinNum.Text+'游戏帐号 发送到10666000923>(<充值说明/@10666000923>)\');
MemoNpc.Lines.Add('<移动2元 编辑237'+EdtDuanXinNum.Text+'游戏帐号 发送到10666000168>(<充值说明/@10666000168>)\');
MemoNpc.Lines.Add('<移动IVR 5元10元20元 编辑237'+EdtDuanXinNum.Text+'游戏帐号 发送到10666000168>(<充值说明/@10666000168>)\');
MemoNpc.Lines.Add('<上一页通道/@充值>┆<元宝领取/@领取1>┆<元宝查询/@元宝查询>┆<返回/@main>\');
MemoNpc.Lines.Add('<找支付平台:你的支持是我们发展的动力^^^^^^^^^\');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@106698815]');
MemoNpc.Lines.Add('<充值范围:1元中国移动 除浙江北京内蒙不支持.日10条月30条(不掉单通道)>\');
MemoNpc.Lines.Add('<示例:游戏帐号为aaaaa 请编写192'+EdtDuanXinNum.Text+'aaaaa 发送到106698815>\');
MemoNpc.Lines.Add('<以上是代码示例请不要发送。>\');
MemoNpc.Lines.Add('<发送完后1-5分钟内能领取到元宝,如果扣费成功领取不到元宝联系本服GM或客服>\');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@106698812]');
MemoNpc.Lines.Add('<充值范围:1元中国移动 除北京 内蒙 不支持.日10条月30条(不掉单通道)>\');
MemoNpc.Lines.Add('<示例:游戏帐号为aaaaa 请编写192'+EdtDuanXinNum.Text+'aaaaa 发送到106698812>\');
MemoNpc.Lines.Add('<以上是代码示例请不要发送。>\');
MemoNpc.Lines.Add('<发送完后1-5分钟内能领取到元宝,如果扣费成功领取不到元宝联系本服GM或客服>\');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@106696588]');
MemoNpc.Lines.Add('<充值范围:1元 北京,上海,不支持.日10条月30条>\');
MemoNpc.Lines.Add('<充值种类:只限中国移动> 推荐使用本条通道。\ ');
MemoNpc.Lines.Add('<示例:游戏帐号为aaaaa 请编写WDC'+EdtDuanXinNum.Text+'aaaaa 发送到106696588>\');
MemoNpc.Lines.Add('<以上是代码示例请不要发送。>\');
MemoNpc.Lines.Add('<发送完后1-5分钟内能领取到元宝,如果扣费成功领取不到元宝联系本服GM或客服>\');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@10665123906]');
MemoNpc.Lines.Add('<充值范围:1元 中国移动 上海,江西,浙江,北京,辽宁,不支持.日10条月30条>\');
MemoNpc.Lines.Add('<示例:游戏帐号为aaaaa 请编写4#'+EdtDuanXinNum.Text+'aaaaa 发送到10665123906>\');
MemoNpc.Lines.Add('<以上是代码示例请不要发送。>\');
MemoNpc.Lines.Add('<发送完后1-5分钟内能领取到元宝,如果扣费成功领取不到元宝联系本服GM或客服>\');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@1066960016720]');
MemoNpc.Lines.Add('<充值范围:2元 全国联通. 日7条月15条>推荐使用本条通道\');
MemoNpc.Lines.Add('<示例:游戏帐号为aaaaa 请编写4#'+EdtDuanXinNum.Text+'aaaaa 发送到1066960016720>\');
MemoNpc.Lines.Add('<以上是代码示例请不要发送。>\');
MemoNpc.Lines.Add('<发送完后1-5分钟内能领取到元宝,如果扣费成功领取不到元宝联系本服GM或客服>\');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@10666000008]');
MemoNpc.Lines.Add('<充值范围:全国移动声询IVR 5元10元20元 .日20元月40元>\');
MemoNpc.Lines.Add('<用移动手机打12590775517然后按4号键听5或10、20分钟后会自动挂断>\');
MemoNpc.Lines.Add('<最后到<查看充值代码/@充值>发送代码.先听歌再发送代码,比短信多一个步骤>\');
MemoNpc.Lines.Add('<示例:游戏帐号为aaaaa 请编写337'+EdtDuanXinNum.Text+'aaaaa 发送到10666000008>\');
MemoNpc.Lines.Add('<以上是代码示例请不要发送。>\');
MemoNpc.Lines.Add('<发送完后1-5分钟内能领取到元宝,如果扣费成功领取不到元宝联系本服GM或客服>\');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@10666000968]');
MemoNpc.Lines.Add('<充值范围:1元 全国移动支持.日15条月30条>\');
MemoNpc.Lines.Add('<示例:游戏帐号为aaaaa 请编写543'+EdtDuanXinNum.Text+'aaaaa 发送到10666000968>\');
MemoNpc.Lines.Add('<以上是代码示例请不要发送。>\');
MemoNpc.Lines.Add('<发送完后1-5分钟内能领取到元宝,如果扣费成功领取不到元宝联系本服GM或客服>\');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@10666000968]');
MemoNpc.Lines.Add('<充值范围:2元移动 只支持天津、江西、浙江、陕西、新疆省份日7条月15条>\');
MemoNpc.Lines.Add('<示例:游戏帐号为aaaaa 请编写543'+EdtDuanXinNum.Text+'aaaaa 发送到10666000968>\');
MemoNpc.Lines.Add('<以上是代码示例请不要发送。>\');
MemoNpc.Lines.Add('<发送完后1-5分钟内能领取到元宝,如果扣费成功领取不到元宝联系本服GM或客服>\');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@10666000168]');
MemoNpc.Lines.Add('<充值范围:2元彩信通道 全国移动支持.日7条月15条>\');
MemoNpc.Lines.Add('<示例:游戏帐号为aaaaa 请编写237'+EdtDuanXinNum.Text+'aaaaa 发送到10666000168>\');
MemoNpc.Lines.Add('<以上是代码示例请不要发送。>\');
MemoNpc.Lines.Add('<发送完后1-5分钟内能领取到元宝,如果扣费成功领取不到元宝联系本服GM或客服>\');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@领取1]');
MemoNpc.Lines.Add('#IF');
MemoNpc.Lines.Add('CHECKACCOUNTLIST 56yb/1y/1y1.txt ;此路径请不要随意修改');
MemoNpc.Lines.Add('#ACT');
MemoNpc.Lines.Add('GAMEGOLD + '+IntToStr(1*nRatio));
MemoNpc.Lines.Add('DELACCOUNTLIST 56yb/1y/1y1.txt ;此路径请不要随意修改');
MemoNpc.Lines.Add('SendMsg 7 领取成功.您当前的元宝为:<$GAMEGOLD>个');
MemoNpc.Lines.Add('SENDMSG 1 ★恭喜玩家<$USERNAME>使用我服推出的在线充值功能,获得元宝。如果你也想要,请赶紧找元宝使者购买吧!');
for I:=2 to 100 do begin
MemoNpc.Lines.Add('goto @领取'+IntToStr(I));
end;
for I:=102 to 107 do begin
MemoNpc.Lines.Add('goto @领取'+IntToStr(I));
end;
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('#ElseACT');
for I:=2 to 100 do begin
MemoNpc.Lines.Add('goto @领取'+IntToStr(I));
end;
for I:=102 to 107 do begin
MemoNpc.Lines.Add('goto @领取'+IntToStr(I));
end;
MemoNpc.Lines.Add('#Elsesay');
MemoNpc.Lines.Add('您当前还没有充值或已领取成功,请查看自己的元宝数量!\');
MemoNpc.Lines.Add('没有充值请按提示进行充值!\');
MemoNpc.Lines.Add('如有任何问题,请登陆冲值服务网站:<pay.zhaopay.com>\');
MemoNpc.Lines.Add('<继续领取元宝/@领取1>┆┆┆<元宝查询/@元宝查询>\');
MemoNpc.Lines.Add('<返回/@main>┆┆┆<退出/@exit>\\');
for I:=2 to 100 do begin
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@领取'+IntToStr(I)+']');
MemoNpc.Lines.Add('#IF');
MemoNpc.Lines.Add('CHECKACCOUNTLIST 56yb/'+IntToStr(I)+'y/'+IntToStr(I)+'y1.txt ;此路径请不要随意修改');
MemoNpc.Lines.Add('#ACT');
MemoNpc.Lines.Add('GAMEGOLD + ' + IntToStr(I*nRatio));
MemoNpc.Lines.Add('DELACCOUNTLIST 56yb/'+IntToStr(I)+'y/'+IntToStr(I)+'y1.txt ;此路径请不要随意修改');
MemoNpc.Lines.Add('sendmsg 7 领取成功.您当前的元宝为:<$GAMEGOLD>个');
MemoNpc.Lines.Add('SENDMSG 1 ★恭喜玩家<$USERNAME>使用我服推出的在线充值功能,获得元宝。如果你也想要,请赶紧找元宝使者购买吧!');
end;
MemoNpc.Lines.Add('[@领取101]');
MemoNpc.Lines.Add('#IF');
MemoNpc.Lines.Add('CHECKACCOUNTLIST 56yb/0.5y/0.5y1.txt ;此路径请不要随意修改');
MemoNpc.Lines.Add('#ACT');
MemoNpc.Lines.Add('GAMEGOLD + ' + IntToStr(Trunc(0.5*nRatio))); //只取整数部分
MemoNpc.Lines.Add('DELACCOUNTLIST 56yb/0.5y/0.5y1.txt ;此路径请不要随意修改');
MemoNpc.Lines.Add('sendmsg 7 领取成功.您当前的元宝为:<$GAMEGOLD>个');
MemoNpc.Lines.Add('SENDMSG 1 ★恭喜玩家<$USERNAME>使用我服推出的在线充值功能,获得元宝。如果你也想要,请赶紧找元宝使者购买吧!');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@领取102]');
MemoNpc.Lines.Add('#IF');
MemoNpc.Lines.Add('CHECKACCOUNTLIST 56yb/1.5y/1.5y1.txt ;此路径请不要随意修改');
MemoNpc.Lines.Add('#ACT');
MemoNpc.Lines.Add('GAMEGOLD + '+ IntToStr(Trunc(1.5*nRatio))); //只取整数部分
MemoNpc.Lines.Add('DELACCOUNTLIST 56yb/1.5y/1.5y1.txt ;此路径请不要随意修改');
MemoNpc.Lines.Add('sendmsg 7 领取成功.您当前的元宝为:<$GAMEGOLD>个');
MemoNpc.Lines.Add('SENDMSG 1 ★恭喜玩家<$USERNAME>使用我服推出的在线充值功能,获得元宝。如果你也想要,请赶紧找元宝使者购买吧!');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@领取103]');
MemoNpc.Lines.Add('#IF');
MemoNpc.Lines.Add('CHECKACCOUNTLIST 56yb/150y/150y1.txt ;此路径请不要随意修改');
MemoNpc.Lines.Add('#ACT');
MemoNpc.Lines.Add('GAMEGOLD + ' + IntToStr(150*nRatio));
MemoNpc.Lines.Add('DELACCOUNTLIST 56yb/150y/150y1.txt ;此路径请不要随意修改');
MemoNpc.Lines.Add('sendmsg 7 领取成功.您当前的元宝为:<$GAMEGOLD>个');
MemoNpc.Lines.Add('SENDMSG 1 ★恭喜玩家<$USERNAME>使用我服推出的在线充值功能,获得元宝。如果你也想要,请赶紧找元宝使者购买吧!');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@领取104]');
MemoNpc.Lines.Add('#IF');
MemoNpc.Lines.Add('CHECKACCOUNTLIST 56yb/200y/200y1.txt ;此路径请不要随意修改');
MemoNpc.Lines.Add('#ACT');
MemoNpc.Lines.Add('GAMEGOLD + '+ IntToStr(200*nRatio));
MemoNpc.Lines.Add('DELACCOUNTLIST 56yb/200y/200y1.txt ;此路径请不要随意修改');
MemoNpc.Lines.Add('sendmsg 7 领取成功.您当前的元宝为:<$GAMEGOLD>个');
MemoNpc.Lines.Add('SENDMSG 1 ★恭喜玩家<$USERNAME>使用短信购买元宝功能,获得元宝。如果你也想要,请赶紧找元宝使者购买吧!');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@领取105]');
MemoNpc.Lines.Add('#IF');
MemoNpc.Lines.Add('CHECKACCOUNTLIST 56yb/300y/300y1.txt ;此路径请不要随意修改');
MemoNpc.Lines.Add('#ACT');
MemoNpc.Lines.Add('GAMEGOLD + ' + IntToStr(300*nRatio));
MemoNpc.Lines.Add('DELACCOUNTLIST 56yb/300y/300y1.txt ;此路径请不要随意修改');
MemoNpc.Lines.Add('sendmsg 7 领取成功.您当前的元宝为:<$GAMEGOLD>个');
MemoNpc.Lines.Add('SENDMSG 1 ★恭喜玩家<$USERNAME>使用我服推出的在线充值功能,获得元宝。如果你也想要,请赶紧找元宝使者购买吧!');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@领取106]');
MemoNpc.Lines.Add('#IF');
MemoNpc.Lines.Add('CHECKACCOUNTLIST 56yb/500y/500y1.txt ;此路径请不要随意修改');
MemoNpc.Lines.Add('#ACT');
MemoNpc.Lines.Add('GAMEGOLD + ' + IntToStr(500*nRatio));
MemoNpc.Lines.Add('DELACCOUNTLIST 56yb/500y/500y1.txt ;此路径请不要随意修改');
MemoNpc.Lines.Add('sendmsg 7 领取成功.您当前的元宝为:<$GAMEGOLD>个');
MemoNpc.Lines.Add('SENDMSG 1 ★恭喜玩家<$USERNAME>使用我服推出的在线充值功能,获得元宝。如果你也想要,请赶紧找元宝使者购买吧!');
MemoNpc.Lines.Add('');
MemoNpc.Lines.Add('[@领取107]');
MemoNpc.Lines.Add('#IF');
MemoNpc.Lines.Add('CHECKACCOUNTLIST 56yb/1000y/1000y1.txt ;此路径请不要随意修改');
MemoNpc.Lines.Add('#ACT');
MemoNpc.Lines.Add('GAMEGOLD + ' + IntToStr(1000*nRatio));
MemoNpc.Lines.Add('DELACCOUNTLIST 56yb/1000y/1000y1.txt ;此路径请不要随意修改');
MemoNpc.Lines.Add('sendmsg 7 领取成功.您当前的元宝为:<$GAMEGOLD>个');
MemoNpc.Lines.Add('SENDMSG 1 ★恭喜玩家<$USERNAME>使用我服推出的在线充值功能,获得元宝。如果你也想要,请赶紧找元宝使者购买吧!');
BtnSave.Enabled := True;
end;
procedure TFrmNpcConfig.BtnSaveClick(Sender: TObject);
var
I: Integer;
F : TextFile;
LoadList: TStringList;
bo15: Boolean;
s10: string;
begin
if sDir = '' then begin
Application.MessageBox('请点选择路径按钮来选择分区目录', '提示', MB_OK + MB_ICONASTERISK);
Exit;
end;
try
MemoNpc.Lines.SaveToFile(sDir+'Mir200\Envir\Npc_def\短信元宝使者-3.txt');
except
Application.MessageBox(PChar('你的服务端'+sDir+'Mir200\Envir\Npc_def\ 此目录不存在'+#13+'请选择正确的服务端目录!'), '提示', MB_OK + MB_ICONASTERISK);
Exit;
end;
LoadList := TStringList.Create;
if FileExists(sDir+'Mir200\Envir\Npcs.txt') then begin
try
LoadList.LoadFromFile(sDir+'Mir200\Envir\Npcs.txt');
except
Application.MessageBox(PChar('文件读取失败 => ' + sDir+'Mir200\Envir\Npcs.txt'), '提示', MB_OK + MB_ICONASTERISK);
LoadList.Free;
Exit;
end;
end;
bo15 := False;
if LoadList.Count > 0 then begin//20080629
for I := 0 to LoadList.Count - 1 do begin
s10 := Trim(LoadList.Strings[I]);
if CompareText('短信元宝使者 0 3 343 336 0 12', s10) = 0 then begin
bo15 := True;
Break;
end;
end;
end;
if not bo15 then begin
LoadList.Add('短信元宝使者 0 3 343 336 0 12');
try
LoadList.SaveToFile(sDir+'Mir200\Envir\Npcs.txt');
except
Application.MessageBox(PChar('文件保存失败 => ' + sDir+'Mir200\Envir\Npcs.txt'), '提示', MB_OK + MB_ICONASTERISK);
LoadList.Free;
Exit;
end;
end;
LoadList.Free;
for I:=1 to 100 do begin
if ForceDirectories(sDir+'Mir200\Envir\Npc_def\56yb\'+IntToStr(I)+'y') then begin
AssignFile(F, sDir+'Mir200\Envir\Npc_def\56yb\'+IntToStr(I)+'y\'+IntToStr(I)+'y1.txt'); // 将文件与F变量建立连接,后面可以使用F变量对文件进行操作。
if not FileExists(sDir+'Mir200\Envir\Npc_def\56yb\'+IntToStr(I)+'y\'+IntToStr(I)+'y1.txt') then begin
ReWrite(f);
CloseFile(f);
end;
end;
end;
if ForceDirectories(sDir+'Mir200\Envir\Npc_def\56yb\0.5y') then begin
AssignFile(F, sDir+'Mir200\Envir\Npc_def\56yb\0.5y\0.5y1.txt'); // 将文件与F变量建立连接,后面可以使用F变量对文件进行操作。
if not FileExists(sDir+'Mir200\Envir\Npc_def\56yb\0.5y\0.5y1.txt') then begin
ReWrite(f);
CloseFile(f);
end;
end;
if ForceDirectories(sDir+'Mir200\Envir\Npc_def\56yb\1.5y') then begin
AssignFile(F, sDir+'Mir200\Envir\Npc_def\56yb\1.5y\1.5y1.txt'); // 将文件与F变量建立连接,后面可以使用F变量对文件进行操作。
if not FileExists(sDir+'Mir200\Envir\Npc_def\56yb\1.5y\1.5y1.txt') then begin
ReWrite(f);
CloseFile(f);
end;
end;
if ForceDirectories(sDir+'Mir200\Envir\Npc_def\56yb\150y') then begin
AssignFile(F, sDir+'Mir200\Envir\Npc_def\56yb\150y\150y1.txt'); // 将文件与F变量建立连接,后面可以使用F变量对文件进行操作。
if not FileExists(sDir+'Mir200\Envir\Npc_def\56yb\150y\150y1.txt') then begin
ReWrite(f);
CloseFile(f);
end;
end;
if ForceDirectories(sDir+'Mir200\Envir\Npc_def\56yb\200y') then begin
AssignFile(F, sDir+'Mir200\Envir\Npc_def\56yb\200y\200y1.txt'); // 将文件与F变量建立连接,后面可以使用F变量对文件进行操作。
if not FileExists(sDir+'Mir200\Envir\Npc_def\56yb\200y\200y1.txt') then begin
ReWrite(f);
CloseFile(f);
end;
end;
if ForceDirectories(sDir+'Mir200\Envir\Npc_def\56yb\300y') then begin
AssignFile(F, sDir+'Mir200\Envir\Npc_def\56yb\300y\300y1.txt'); // 将文件与F变量建立连接,后面可以使用F变量对文件进行操作。
if not FileExists(sDir+'Mir200\Envir\Npc_def\56yb\300y\300y1.txt') then begin
ReWrite(f);
CloseFile(f);
end;
end;
if ForceDirectories(sDir+'Mir200\Envir\Npc_def\56yb\500y') then begin
AssignFile(F, sDir+'Mir200\Envir\Npc_def\56yb\500y\500y1.txt'); // 将文件与F变量建立连接,后面可以使用F变量对文件进行操作。
if not FileExists(sDir+'Mir200\Envir\Npc_def\56yb\500y\500y1.txt') then begin
ReWrite(f);
CloseFile(f);
end;
end;
if ForceDirectories(sDir+'Mir200\Envir\Npc_def\56yb\1000y') then begin
AssignFile(F, sDir+'Mir200\Envir\Npc_def\56yb\1000y\1000y1.txt'); // 将文件与F变量建立连接,后面可以使用F变量对文件进行操作。
if not FileExists(sDir+'Mir200\Envir\Npc_def\56yb\1000y\1000y1.txt') then begin
ReWrite(f);
CloseFile(f);
end;
end;
Application.MessageBox('文件保存成功!'+#13+'短信元宝使者会出现在盟重安全区', '提示', MB_OK + MB_ICONASTERISK);
end;
procedure TFrmNpcConfig.BtnSelDirClick(Sender: TObject);
//检查是否传奇服务端目录
function CheckMirServerDir(DirName: string): Boolean;
begin
if (not DirectoryExists(DirName + 'Mir200')) or
(not DirectoryExists(DirName + 'Mud2')) or
(not DirectoryExists(DirName + 'DBServer')) or
(not FileExists(DirName + 'Mir200\M2Server.exe')) then
Result := FALSE else Result := True;
end;
var
dir: string;
begin
if SelectDirectory('选择你分区的服务端目录'+#13+'例:X:\MirServer\', '选择目录', Dir, Handle) then begin
sDir := Dir + '\';
if not CheckMirServerDir(sDir) then begin
Application.MessageBox('你选择的服务端目录是错的'+#13+'提示:选择服务端的总目录就可以'+#13+'例子:X:\MirServer\', '提示', MB_OK + MB_ICONASTERISK);
sDir := '';
Exit;
end;
end;
end;
end.
|
unit Benjamim.Utils;
interface
uses
System.Variants, System.JSON, System.Hash;
type
TJwtAlgorithm = (HS256, HS384, HS512);
TSHA2Version = THashSHA2.TSHA2Version;
const
DEFAULT_EXPIRE_IN_HOURS = 2;
DEFAULT_PASSWORD = 'your-256-bit-secret';
DEFAULT_ALGORITHM = TJwtAlgorithm.HS256;
type
TJwtAlgorithmHelper = record Helper for TJwtAlgorithm
function AsAlgorithm: TSHA2Version;
function AsString: String;
end;
TSHA2VersionHelper = record Helper for TSHA2Version
function AsJwtAlgorithm: TJwtAlgorithm;
function AsString: String;
end;
TStringHelper = record Helper for
String
const
Empty = '';
function AsJwtAlgorithm: TJwtAlgorithm;
function ClearLineBreak: String;
function AsJSONObject: TJSONObject;
function AsBase64: String;
function FixBase64: string;
function AsBase64url: String;
function AsString: String;
// function StartsWith(const Value: string): Boolean;
end;
TVariantHelper = record Helper for Variant
function AsString: String;
end;
implementation
uses
System.TypInfo, System.SysUtils, System.StrUtils, System.NetEncoding;
{ TJwtAlgorithmHelper }
function TJwtAlgorithmHelper.AsAlgorithm: TSHA2Version;
var
LValue: string;
begin
LValue := Self.AsString;
LValue := 'SHA' + LValue[3] + LValue[4] + LValue[5];
Result := TSHA2Version(GetEnumValue(TypeInfo(TSHA2Version), LValue));
end;
function TJwtAlgorithmHelper.AsString: String;
begin
Result := GetEnumName(TypeInfo(TJwtAlgorithm), integer(Self));
end;
{ TSHA2VersionHelper }
function TSHA2VersionHelper.AsJwtAlgorithm: TJwtAlgorithm;
var
LValue: string;
begin
LValue := Self.AsString;
LValue := 'HS' + LValue[4] + LValue[5] + LValue[6];
Result := TJwtAlgorithm(GetEnumValue(TypeInfo(TJwtAlgorithm), LValue));
end;
function TSHA2VersionHelper.AsString: String;
begin
Result := GetEnumName(TypeInfo(TSHA2Version), integer(Self));
end;
{ TStringHelper }
function TStringHelper.AsJwtAlgorithm: TJwtAlgorithm;
begin
Result := TJwtAlgorithm(GetEnumValue(TypeInfo(TJwtAlgorithm), String(Self)));
end;
function TStringHelper.ClearLineBreak: String;
begin
Self := StringReplace(Self, sLineBreak, '', [rfReplaceAll]);
Result := Self;
end;
function TStringHelper.AsJSONObject: TJSONObject;
begin
Result := System.JSON.TJSONObject(System.JSON.TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(Self), 0));
end;
function Fix(aValue: string): string;
const
STR_TO_CLEAR = '= ';
var
I: integer;
begin
Result := aValue;
for I := 1 to Length(STR_TO_CLEAR) do
Result := StringReplace(Result, STR_TO_CLEAR[I], '', [rfReplaceAll]);
end;
function TStringHelper.FixBase64: string;
begin
Result := Self;
Result := StringReplace(Result, '+', '-', [rfReplaceAll]);
Result := StringReplace(Result, '/', '_', [rfReplaceAll]);
Result := StringReplace(Result, '=', '', [rfReplaceAll]);
end;
function TStringHelper.AsBase64url: String;
begin
Result := System.NetEncoding.TBase64Encoding.Base64.Encode(Self).FixBase64;
end;
function TStringHelper.AsBase64: String;
begin
Result := Fix(System.NetEncoding.TBase64Encoding.Base64.Encode(Self));
end;
function TStringHelper.AsString: String;
begin
Result := System.NetEncoding.TBase64Encoding.Base64.Decode(Self);
end;
{ TVariantHelper }
function TVariantHelper.AsString: String;
begin
Result := System.Variants.VarToStrDef(Self, EmptyStr);
end;
end.
|
//
// Generated by JavaToPas v1.4 20140515 - 181641
////////////////////////////////////////////////////////////////////////////////
unit java.util.concurrent.locks.AbstractQueuedLongSynchronizer_ConditionObject;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JAbstractQueuedLongSynchronizer_ConditionObject = interface;
JAbstractQueuedLongSynchronizer_ConditionObjectClass = interface(JObjectClass)
['{4CA7906C-8C21-4BC5-BAE8-647B45FAEE08}']
function await(time : Int64; &unit : JTimeUnit) : boolean; cdecl; overload; // (JLjava/util/concurrent/TimeUnit;)Z A: $11
function awaitNanos(nanosTimeout : Int64) : Int64; cdecl; // (J)J A: $11
function awaitUntil(deadline : JDate) : boolean; cdecl; // (Ljava/util/Date;)Z A: $11
function init(JAbstractQueuedLongSynchronizerparam0 : JAbstractQueuedLongSynchronizer) : JAbstractQueuedLongSynchronizer_ConditionObject; cdecl;// (Ljava/util/concurrent/locks/AbstractQueuedLongSynchronizer;)V A: $1
procedure await ; cdecl; overload; // ()V A: $11
procedure awaitUninterruptibly ; cdecl; // ()V A: $11
procedure signal ; cdecl; // ()V A: $11
procedure signalAll ; cdecl; // ()V A: $11
end;
[JavaSignature('java/util/concurrent/locks/AbstractQueuedLongSynchronizer_ConditionObject')]
JAbstractQueuedLongSynchronizer_ConditionObject = interface(JObject)
['{9C7F6D7B-5443-4727-9327-7DB654CC8FE6}']
end;
TJAbstractQueuedLongSynchronizer_ConditionObject = class(TJavaGenericImport<JAbstractQueuedLongSynchronizer_ConditionObjectClass, JAbstractQueuedLongSynchronizer_ConditionObject>)
end;
implementation
end.
|
unit uAttributes;
interface
uses
classes, ComCtrls;
type
TCustomAttribute = class;
TAttributeType = (atNone, atAddress, atDocument, atInt, atString, atFloat, atBoolean,
atDate, atTime, atDateTime, atImage, atList, atSubList, atCategory,
atBook, atTable, atChildObject, atObjectLink);
TSetAttributeType = set of TAttributeType;
TCustomAttributeArray = array of TCustomAttribute;
TCustomAttribute = class
private
FParentAttribute: TCustomAttribute;
FListItems: TStringList;
FIsChilded: boolean;
FChildedAttr: TCustomAttributeArray;
FParentChildedAttribute: TCustomAttribute;
FOkofID: integer;
FOkofKOD: string;
FOkofName: string;
FObjectLinkName: string;
FCanAddRecord: boolean;
FBuhID: integer;
FBuhName: string;
FBuhKod: string;
FUsedInReport: boolean;
procedure SetDeleted(const Value: boolean);
procedure SetUpdated(const Value: boolean);
procedure SetAttrType(const Value: TAttributeType);
function GetListItemsText: string;
procedure SetListItemsText(const Value: string);
procedure SetInserted(const Value: boolean);
protected
FAttr: TCustomAttributeArray;
FID: integer;
FName: string;
FInserted: boolean;
FUpdated: boolean;
FDeleted: boolean;
FTAttrType: TAttributeType;
FL1: integer;
FL2: integer;
FNode: TTreeNode;
procedure SetName(const Value: string); virtual;
procedure SetObjectLinkName(const Value: string);
procedure SetL1(const Value: integer); virtual;
procedure SetL2(const Value: integer); virtual;
function ParentID_str: string; virtual;
function OwnerObjectID: integer; virtual;
function FindChildedParentAttribute: TCustomAttribute; virtual;
procedure UpdateChildLink; virtual;
public
property ParentAttribute: TCustomAttribute read FParentAttribute write FParentAttribute;
property ParentChildedAttribute: TCustomAttribute read FParentChildedAttribute write FParentChildedAttribute;
property Attr: TCustomAttributeArray read FAttr;
property ChildedAttr: TCustomAttributeArray read FChildedAttr;
property AttrType: TAttributeType read FTAttrType write SetAttrType;
property ID: integer read FID write FID;
property Name: string read FName write SetName;
property ObjectLinkName: string read FObjectLinkName write SetObjectLinkName;
property L1: integer read FL1 write SetL1;
property L2: integer read FL2 write SetL2;
property OkofID: integer read FOkofID write FOkofID;
property OkofKOD: string read FOkofKOD write FOkofKOD;
property OkofName: string read FOkofName write FOkofName;
property CanAddRecord: boolean read FCanAddRecord write FCanAddRecord;
property BuhID: integer read FBuhID write FBuhID;
property BuhName: string read FBuhName write FBuhName;
property BuhKod: string read FBuhKod write FBuhKod;
property ListItemsText: string read GetListItemsText write SetListItemsText;
property ListItems: TStringList read FListItems write FListItems;
property Inserted: boolean read FInserted write SetInserted;
property Updated: boolean read FUpdated write SetUpdated;
property Deleted: boolean read FDeleted write SetDeleted;
property UsedInReport: boolean read FUsedInReport write FUsedInReport default false;
property IsChilded: boolean read FIsChilded write FIsChilded;
property Node: TTreeNode read FNode write FNode;
procedure Add(AAttr: TCustomAttribute); virtual;
procedure AddChilded(AAttr: TCustomAttribute); virtual;
procedure DeleteAttr(AAttr: TCustomAttribute); virtual;
function Count: integer; virtual;
function CountChilded: integer; virtual;
procedure LoadListItems; virtual;
constructor Create; virtual;
destructor Destroy; override;
end;
TStandartAttribute = class(TCustomAttribute)
public
end;
TCategoryAttribute = class(TCustomAttribute)
public
end;
TSubListAttribute = class(TCustomAttribute)
public
end;
TUserTable = class(TCustomAttribute)
end;
TChildObject = class(TCustomAttribute)
end;
TObjectLinkAttribute = class(TCustomAttribute)
end;
TUserTableArray = array of TUserTable;
TCanChangeTypeTable = array[TAttributeType, TAttributeType] of boolean;
TUpdateType = (utNone, utInserted, utUpdated, utDeleted);
TTables = class
private
FTables: TUserTableArray;
FObjectType: string;
protected
procedure AlterTableStructureOnServer(a: TCustomAttribute); virtual;
function RealUpdateType(i, u, d: boolean): TUpdateType;
procedure InsertTable(t: TCustomAttribute); virtual;
procedure UpdateTable(t: TCustomAttribute); virtual;
procedure DeleteTable(t: TCustomAttribute); virtual;
procedure SaveListItems(a: TCustomAttribute); virtual;
procedure InsertStandartAttribute(a: TCustomAttribute); virtual;
procedure UpdateStandartAttribute(a: TCustomAttribute); virtual;
procedure DeleteStandartAttribute(a: TCustomAttribute); virtual;
procedure InsertSubListAttribute(a: TCustomAttribute); virtual;
procedure InsertObjectAttribute(a: TCustomAttribute); virtual;
procedure InsertObjectLinkAttribute(a: TCustomAttribute); virtual;
public
property Tables: TUserTableArray read FTables;
property ObjectType: string read FObjectType write FObjectType;
procedure AddTable(ATable: TUserTable); virtual;
function Count: integer; virtual;
procedure CreateTableAttr(ObjID: integer; t: TCustomAttribute; ForBands: boolean = false); virtual;
procedure CreateTables(BaseObjectID: integer; ForBands: boolean = false); virtual;
procedure SetUpdate(Value: boolean); virtual;
procedure AlterStructureOnServer; virtual;
destructor Destroy; override;
end;
var
CanChangeTypeTable: TCanChangeTypeTable;
GlobalNeedSaveStructure: boolean;
procedure CreateCanChangeTypeTable;
implementation
uses
uCommonUtils, AdoDB, SysUtils, GlobalVars, dialogs, uException, Variants;
{ TCustomAttribute }
procedure CreateCanChangeTypeTable;
var
qry: TAdoQuery;
i, n: byte;
begin
qry:=CreateQuery('sp_ТипДанных_ВозможнаяИзмена');
try
qry.Open;
i:=0;
while not qry.Eof do begin
for n:=0 to qry.FieldCount-2 do
CanChangeTypeTable[TAttributeType(i), TAttributeType(n)]:=qry.Fields[n+1].Value;
inc(i);
qry.Next;
end;
finally
qry.Free;
end;
end;
procedure TCustomAttribute.DeleteAttr(AAttr: TCustomAttribute);
function FindIndex(AAttr: TCustomAttribute): integer;
var
i: integer;
begin
result:=-1;
for i:=0 to high(Attr) do
if Attr[i]=AAttr then begin
result:=i;
break;
end;
end;
var
i: integer;
ifrom: integer;
begin
ifrom:=FindIndex(AAttr);
if ifrom=-1 then exit;
for i:=ifrom+1 to high(FAttr) do
Attr[i-1]:=Attr[i];
SetLength(FAttr, length(FAttr)-1);
end;
procedure TCustomAttribute.Add(AAttr: TCustomAttribute);
begin
SetLength(FAttr, length(Attr)+1);
Attr[high(Attr)]:=AAttr;
end;
procedure TCustomAttribute.AddChilded(AAttr: TCustomAttribute);
begin
SetLength(FChildedAttr, length(ChildedAttr)+1);
ChildedAttr[high(ChildedAttr)]:=AAttr;
AAttr.ParentChildedAttribute:=self;
end;
function TCustomAttribute.Count: integer;
begin
result:=length(Attr);
end;
function TCustomAttribute.CountChilded: integer;
begin
result:=length(ChildedAttr);
end;
constructor TCustomAttribute.Create;
begin
inherited;
FParentAttribute:=nil;
FListItems:=TStringList.Create;
end;
destructor TCustomAttribute.Destroy;
var
i: integer;
begin
FListItems.Free;
for i:=0 to Count-1 do
Attr[i].Destroy;
inherited;
end;
function TCustomAttribute.FindChildedParentAttribute: TCustomAttribute;
var
a: TCustomAttribute;
i: integer;
begin
result:=nil;
if self.ParentAttribute.AttrType in [atCategory, atSubList] then
a:=self.ParentAttribute.ParentChildedAttribute
else
a:=self.ParentAttribute.ParentAttribute;
if Assigned(a) then
for i:=0 to a.Count-1 do
if (a.Attr[i].Name=Name) and (a.Attr[i].AttrType=AttrType) then begin
result:=a.Attr[i];
break;
end;
if not Assigned(a) then
raise EAlterStructureException.Create('FindChildedParentAttribute: Не удалось найти родителя');
for i:=0 to a.Count-1 do
if (a.Attr[i].Name=Name) and (a.Attr[i].AttrType=AttrType) then begin
result:=a.Attr[i];
break;
end;
if not Assigned(result) then
raise EAlterStructureException.Create('FindChildedParentAttribute: Не удалось найти родителя при наследовании');
end;
function TCustomAttribute.GetListItemsText: string;
begin
result:=ListItems.Text;
end;
procedure TCustomAttribute.LoadListItems;
var
qry: TAdoQuery;
begin
if FListItems.Count<>0 then exit;
qry:=CreateQuery('sp_Список_получить @код_Атрибут = '+IntToStr(ID));
try
qry.Open;
while not qry.Eof do begin
ListItems.Add(qry['Значение']);
qry.Next;
end;
finally
qry.Free;
end;
end;
function TCustomAttribute.OwnerObjectID: integer;
var
a: TCustomAttribute;
begin
a:=self.ParentAttribute;
while not (a.AttrType in [atTable, atSubList, atChildObject]) do
a:=a.ParentAttribute;
result:=a.ID;
end;
function TCustomAttribute.ParentID_str: string;
begin
if Assigned(ParentAttribute) and (ParentAttribute.AttrType in [atCategory]) then
result:=IntToStr(ParentAttribute.ID)
else
result:='null'
end;
procedure TCustomAttribute.SetAttrType(const Value: TAttributeType);
begin
if FTAttrType=Value then exit;
FTAttrType := Value;
FUpdated:=true;
end;
procedure TCustomAttribute.SetDeleted(const Value: boolean);
var
i: integer;
begin
FDeleted:=Value;
for i:=0 to Count-1 do
Attr[i].Deleted:=Value;
GlobalNeedSaveStructure:=Value;
end;
procedure TCustomAttribute.SetInserted(const Value: boolean);
begin
FInserted:=Value;
GlobalNeedSaveStructure:=Value;
end;
procedure TCustomAttribute.SetL1(const Value: integer);
begin
if (self.AttrType=atBook) and (FL1>0) and (FL1<>Value) then
ShowMessage('aaaaa');
if FL1=Value then exit;
FL1:=Value;
Updated:=true;
end;
procedure TCustomAttribute.SetL2(const Value: integer);
begin
if FL2=Value then exit;
FL2:=Value;
Updated:=true;
end;
procedure TCustomAttribute.SetListItemsText(const Value: string);
begin
if ListItemsText=Value then exit;
ListItems.Text:=Value;
FUpdated:=true;
end;
procedure TCustomAttribute.SetName(const Value: string);
var
i: integer;
begin
if FName=Value then exit;
if self.UsedInReport then
raise Exception.Create('Нельзя изменить имя атрибута, т.к. атрибут используется в отчетах');
FName:=Value;
if Assigned(Node) then
Node.Text:=Value;
Updated:=true;
for i:=0 to CountChilded-1 do
if (ChildedAttr[i].IsChilded and (ChildedAttr[i].AttrType<>atChildObject)) then
ChildedAttr[i].Name:=Value;
end;
procedure TCustomAttribute.SetObjectLinkName(const Value: string);
begin
FObjectLinkName:=Value;
end;
procedure TCustomAttribute.SetUpdated(const Value: boolean);
var
i: integer;
begin
FUpdated:=Value;
for i:=0 to Count-1 do
Attr[i].Updated:=Value;
GlobalNeedSaveStructure:=Value;
end;
procedure TCustomAttribute.UpdateChildLink;
var
i: integer;
pa: TCustomAttribute;
begin
for i:=0 to Count-1 do begin
if Attr[i].IsChilded and (Attr[i].AttrType in [atSubList, atCategory]) then begin
pa:=Attr[i].FindChildedParentAttribute;
pa.AddChilded(Attr[i]);
end;
Attr[i].UpdateChildLink;
end;
if AttrType in [atTable, atChildObject] then
for i:=0 to Count-1 do begin
if (Attr[i].AttrType in [atChildObject]) then begin
AddChilded(Attr[i]);
end
end;
end;
{ TTables }
procedure TTables.AddTable(ATable: TUserTable);
begin
SetLength(FTables, Count+1);
Tables[Count-1]:=ATable;
end;
procedure TTables.CreateTableAttr(ObjID: integer; t: TCustomAttribute; ForBands: boolean = false);
var
qry: TAdoQuery;
a, pa: TCustomAttribute;
st_b: string;
begin
st_b:=BoolToString(ForBands);
if t.AttrType in [atTable, atSubList, atChildObject] then begin
qry:=CreateQuery('sp_ОбъектыДочерниеДляРедактирования_получить @код_Родитель = '+IntToStr(t.ID));
try
qry.Open;
while not qry.Eof do begin
if qry['Тип объекта'] = 'подч. список' then begin
a:=TSubListAttribute.Create;
a.AttrType:=atSubList;
end
else
if qry['Тип объекта'] = 'объект' then begin
a:=TChildObject.Create;
a.AttrType:=atChildObject;
end;
a.ParentAttribute:=t;
a.Name:=qry['Псевдоним'];
a.ID:=qry['код_Объект'];
a.IsChilded:=qry['Наследник'];
a.CanAddRecord:=qry['МожноДобавлятьЗаписи'];
a.UsedInReport:=qry['УчаствуетВОтчетах'];
if not VarIsNullMy(qry['ОКОФ']) then begin
a.OkofID:=qry['ОКОФ'];
a.OkofKOD:=qry['ОКОФКод'];
a.OkofName:=qry['ОКОФНаименование'];
end
else
a.OkofID:=0;
if not VarIsNullMy(qry['Бухгалтерский счет']) then begin
a.BuhID:=qry['Бухгалтерский счет'];
a.BuhKod:=qry['БухСчет'];
a.BuhName:=qry['БухНазвание_счета'];
end
else
a.BuhID:=0;
t.Add(a);
CreateTableAttr(a.ID, a, ForBands);
qry.Next;
end
finally
qry.Free;
end
end;
if t is TCategoryAttribute then
qry:=CreateQuery(format('sp_ОбъектыАтрибуты_получить @код_Объект = %d, @код_АтрибутРодитель = %d, @РезультатДляБендов = %s', [ObjID, t.ID, st_b]))
else
qry:=CreateQuery(format('sp_ОбъектыАтрибуты_получить @код_Объект = %d, @РезультатДляБендов = %s', [ObjID, st_b]));
try
qry.Open;
while not qry.Eof do begin
if qry['вк_ТипДанных'] = 14 then//категория
a:=TCategoryAttribute.Create
else
if qry['вк_ТипДанных'] = 18 then//ссылка на объект
a:=TObjectLinkAttribute.Create
else
a:=TStandartAttribute.Create;
a.ParentAttribute:=t;
a.Name:=qry['Псевдоним'];
a.ID:=qry['код_Атрибут'];
a.L1:=qry['Парам1'];
a.L2:=qry['Парам2'];
a.IsChilded:=qry['Наследник'];
a.AttrType:=TAttributeType(qry['вк_ТипДанных']-1);
a.UsedInReport:=qry['УчаствуетВОтчетах'];
if a.AttrType=atObjectLink then
a.ObjectLinkName:=ExecSQLExpr('select Псевдоним from sys_Объект where код_Объект = '+IntToStr(a.L1));
t.Add(a);
if a is TCategoryAttribute then
CreateTableAttr(ObjID, a, ForBands);
if a is TSubListAttribute then
CreateTableAttr(ObjID, a, ForBands);
qry.Next;
end;
finally
qry.Free;
end;
end;
procedure TTables.CreateTables(BaseObjectID: integer; ForBands: boolean = false);
var
qry, qryOKOF: TAdoQuery;
t: TUserTable;
// st_b: string;
begin
// st_b:=BoolToString(ForBands);
if BaseObjectID=-1 then
qry:=CreateQuery('sp_ОбъектыДляРедактирования_получить @Тип_объекта = '''+ObjectType+'''')
else
qry:=CreateQuery('sp_ОбъектыДляРедактирования_получить @код_Объект='+IntToStr(BaseObjectID)+', @Тип_объекта = '''+ObjectType+'''');
try
qry.Open;
while not qry.Eof do begin
t:=TUserTable.Create;
t.AttrType:=atTable;
t.Name:=qry['Псевдоним'];
t.ID:=qry['код_Объект'];
t.IsChilded:=qry['Наследник'];
t.CanAddRecord:=qry['МожноДобавлятьЗаписи'];
t.UsedInReport:=qry['УчаствуетВОтчетах'];
if not VarIsNull(qry['ОКОФ']) then begin
t.OkofID:=qry['ОКОФ'];
t.OkofKOD:=qry['ОКОФКод'];
t.OkofName:=qry['ОКОФНаименование'];
end
else
t.OkofID:=0;
if not VarIsNullMy(qry['Бухгалтерский счет']) then begin
t.BuhID:=qry['Бухгалтерский счет'];
t.BuhKod:=qry['БухСчет'];
t.BuhName:=qry['БухНазвание_счета'];
end
else
t.BuhID:=0;
CreateTableAttr(t.ID, t, ForBands);
AddTable(t);
if self.ObjectType='объект' then
t.UpdateChildLink;
qry.Next;
end;
finally
qry.Free;
end;
end;
function TTables.Count: integer;
begin
result:=length(Tables);
end;
destructor TTables.Destroy;
var
i: integer;
begin
for i:=0 to Count-1 do
Tables[i].Destroy;
inherited;
end;
procedure TTables.SetUpdate(Value: boolean);
var
i: integer;
begin
for i:=0 to Count-1 do
Tables[i].Updated:=Value;
end;
procedure TTables.AlterStructureOnServer;
var
i: integer;
begin
Connection.BeginTrans;
try
for i:=0 to Count-1 do
AlterTableStructureOnServer(Tables[i]);
Connection.CommitTrans;
GlobalNeedSaveStructure:=false;
except
Connection.RollbackTrans;
raise;
end;
end;
procedure TTables.AlterTableStructureOnServer(a: TCustomAttribute);
var
i: integer;
u: TUpdateType;
begin
u:=RealUpdateType(a.Inserted, a.Updated, a.Deleted);
if u=utInserted then begin
if a is TUserTable then InsertTable(a);
if a is TStandartAttribute then InsertStandartAttribute(a);
if a is TCategoryAttribute then InsertStandartAttribute(a);
if a is TSubListAttribute then InsertSubListAttribute(a);
if a is TChildObject then InsertObjectAttribute(a);
if a is TObjectLinkAttribute then InsertObjectLinkAttribute(a);
a.Inserted:=false;
a.Updated:=false;
a.Deleted:=false;
end;
if u=utUpdated then begin
if a is TUserTable then UpdateTable(a);
if a is TStandartAttribute then UpdateStandartAttribute(a);
if a is TCategoryAttribute then UpdateStandartAttribute(a);
if a is TSubListAttribute then UpdateTable(a);
if a is TChildObject then UpdateTable(a);
if a is TObjectLinkAttribute then UpdateStandartAttribute(a);
a.Inserted:=false;
a.Updated:=false;
a.Deleted:=false;
end;
if u=utDeleted then begin
if a is TUserTable then DeleteTable(a);
if a is TStandartAttribute then DeleteStandartAttribute(a);
if a is TCategoryAttribute then DeleteStandartAttribute(a);
if a is TSubListAttribute then DeleteTable(a);
if a is TChildObject then DeleteTable(a);
if a is TObjectLinkAttribute then DeleteStandartAttribute(a);
a.Inserted:=false;
a.Updated:=false;
a.Deleted:=false;
end;
for i:=0 to a.Count-1 do begin
if not (a.Attr[i].AttrType in [atTable, atChildObject]) then
AlterTableStructureOnServer(a.Attr[i]);
end;
for i:=0 to a.Count-1 do begin
AlterTableStructureOnServer(a.Attr[i]);
end;
end;
function TTables.RealUpdateType(i, u, d: boolean): TUpdateType;
const
res_table: array[boolean, boolean, boolean] of TUpdateType = (((utNone, utDeleted), (utUpdated, utDeleted)), ((utInserted, utNone), (utInserted, utNone)));
begin
result:=res_table[i, u, d];
end;
procedure TTables.InsertTable(t: TCustomAttribute);
var
qry: TAdoQuery;
sql: string;
begin
sql:='sp_Объект_создать @Наименование = ''%s'', @вк_Родитель = null, @вк_Владелец = null, @Тип = ''%s'', @Подтип =''пользователь'', @ОКОФ = %s, @МожноДобавлятьЗаписи = %s, @вк_Бухгалтерский_счет = %s';
sql:=format(sql, [t.Name, ObjectType, NullIF_str(t.OkofID, 0), BoolToString(t.CanAddRecord), NullIF_str(t.BuhID, 0)]);
qry:=CreateQuery(sql);
try
qry.Open;
t.ID:=qry.Fields[0].Value;
finally
qry.Free;
end;
end;
procedure TTables.UpdateTable(t: TCustomAttribute);
var
qry: TAdoQuery;
sql: string;
begin
sql:='sp_Объект_изменить @код_Объект = %d, @Наименование = ''%s'', @ОКОФ = %s, @МожноДобавлятьЗаписи = %s, @вк_Бухгалтерский_счет = %s';
sql:=format(sql, [t.ID, t.Name, NullIF_str(t.OkofID, 0), BoolToString(t.CanAddRecord), NullIF_str(t.BuhID, 0)]);
qry:=CreateQuery(sql);
try
qry.ExecSQL;
finally
qry.Free;
end;
end;
procedure TTables.DeleteTable(t: TCustomAttribute);
var
qry: TAdoQuery;
sql: string;
i: integer;
begin
sql:='sp_Объект_удалить @код_Объект = %d';
sql:=format(sql, [t.ID]);
qry:=CreateQuery(sql);
try
qry.ExecSql;
finally
qry.Free;
end;
end;
procedure TTables.InsertStandartAttribute(a: TCustomAttribute);
var
qry: TAdoQuery;
sql: string;
begin
sql:='sp_Атрибут_создать @вк_Объект = %d, @Псевдоним=''%s'', @вк_Атрибут = %s, @Наследник = %d, @вк_ТипДанных = %d, @Парам1 = %d, @Парам2 = %d';
sql:=format(sql, [a.OwnerObjectID, a.Name, a.ParentID_str, BoolToInt(a.IsChilded), byte(a.AttrType)+1, a.L1, a.L2]);
qry:=CreateQuery(sql);
try
qry.Open;
a.ID:=qry.Fields[0].Value;
if a.AttrType=atList then
SaveListItems(a);
finally
qry.Free;
end;
end;
procedure TTables.UpdateStandartAttribute(a: TCustomAttribute);
var
qry: TAdoQuery;
sql: string;
begin
sql:='sp_Атрибут_изменить @код_Атрибут = %d, @Псевдоним = ''%s'', @вк_Атрибут = %s, @вк_ТипДанных = %d, @Парам1 = %d, @Парам2 = %d';
sql:=format(sql, [a.ID, a.Name, a.ParentID_str, byte(a.AttrType)+1, a.L1, a.L2]);
qry:=CreateQuery(sql);
try
qry.ExecSQL;
if a.AttrType=atList then
SaveListItems(a);
finally
qry.Free;
end;
end;
procedure TTables.DeleteStandartAttribute(a: TCustomAttribute);
var
qry: TAdoQuery;
sql: string;
i: integer;
begin
for i:=0 to a.Count-1 do
DeleteStandartAttribute(a.Attr[i]);
sql:='sp_Атрибут_удалить @код_Атрибут = %d';
sql:=format(sql, [a.ID]);
qry:=CreateQuery(sql);
try
qry.ExecSQL;
finally
qry.Free;
end;
end;
procedure TTables.InsertSubListAttribute(a: TCustomAttribute);
var
qry: TAdoQuery;
sql: string;
param: string;
begin
sql:='sp_Объект_создать @Наименование = ''%s'', @вк_Родитель = %d, @вк_Владелец = %s, @Тип = ''подч. список'', @Подтип =''пользователь'', @Наследник = %d';
if Assigned(a.ParentChildedAttribute) then
param:=IntToStr(a.ParentChildedAttribute.ID)
else
param:='null';
sql:=format(sql, [a.Name, a.OwnerObjectID, param, BoolToInt(a.IsChilded)]);
qry:=CreateQuery(sql);
try
qry.Open;
a.ID:=qry.Fields[0].Value;
finally
qry.Free;
end;
end;
procedure TTables.SaveListItems(a: TCustomAttribute);
var
qry: TAdoQuery;
i: integer;
begin
qry:=CreateQuery('sp_Список_удалить @код_Атрибут = '+IntToStr(a.ID));
try
qry.ExecSQL;
for i:=0 to a.ListItems.Count-1 do begin
if (i>0) and (trim(a.ListItems[i])='') then continue;
qry.SQL.Text:=format('sp_Список_добавить @код_Атрибут = %d, @Значение = ''%s''', [a.ID, a.ListItems[i]]);
qry.ExecSQL;
end;
finally
qry.Free;
end;
end;
procedure TTables.InsertObjectAttribute(a: TCustomAttribute);
var
qry: TAdoQuery;
sql: string;
begin
sql:='sp_Объект_создать @Наименование = ''%s'', @вк_Родитель = %d, @вк_владелец = %d, @Тип = ''объект'', @Подтип =''пользователь'', @Наследник = 1, @ОКОФ = %s';
sql:=format(sql, [a.Name, a.OwnerObjectID, a.OwnerObjectID, NullIF_str(a.OkofID, 0)]);
qry:=CreateQuery(sql);
try
qry.Open;
a.ID:=qry.Fields[0].Value;
finally
qry.Free;
end;
end;
procedure TTables.InsertObjectLinkAttribute(a: TCustomAttribute);
var
qry: TAdoQuery;
sql: string;
begin
sql:='sp_Атрибут_создать @вк_Объект = %d, @Псевдоним=''%s'' , @вк_Атрибут = %s, @Наследник = %d, @вк_ТипДанных = %d, @Парам1 = %d, @Парам2 = %d';
sql:=format(sql, [a.OwnerObjectID, a.Name, a.ParentID_str, BoolToInt(a.IsChilded), byte(a.AttrType)+1, a.L1, a.L2]);
qry:=CreateQuery(sql);
try
qry.Open;
a.ID:=qry.Fields[0].Value;
finally
qry.Free;
end;
end;
end.
|
unit androidwifiadb;
interface
uses
DAW.Model.Device,
System.Generics.Collections,
DAW.Adb;
type
IdawView = interface
['{1900284A-C00D-423E-9488-C7D32C06919C}']
procedure showNoConnectedDevicesNotification();
procedure showConnectedDeviceNotification(ADevice: TdawDevice);
procedure showDisconnectedDeviceNotification(ADevice: TdawDevice);
procedure showErrorConnectingDeviceNotification(ADevice: TdawDevice);
procedure showErrorDisconnectingDeviceNotification(ADevice: TdawDevice);
procedure showADBNotInstalledNotification();
end;
TAlertService = class(TInterfacedObject, IdawView)
procedure showNoConnectedDevicesNotification();
procedure showConnectedDeviceNotification(ADevice: TdawDevice);
procedure showDisconnectedDeviceNotification(ADevice: TdawDevice);
procedure showErrorConnectingDeviceNotification(ADevice: TdawDevice);
procedure showErrorDisconnectingDeviceNotification(ADevice: TdawDevice);
procedure showADBNotInstalledNotification();
end;
TAndroidWiFiADB = class
private
FAdb: TdawAdb;
FView: IdawView;
FDevices: TDictionary<string, TdawDevice>;
function checkDeviceExistance(connectedDevice: TdawDevice): boolean;
procedure showConnectionResultNotification(Adevices: TArray<TdawDevice>);
procedure showDisconnectionResultNotification(Adevices: TArray<TdawDevice>);
public
procedure updateDeviceConnectionState(updatedDevice: TdawDevice);
procedure removeNotConnectedDevices;
function isADBInstalled: boolean;
function refreshDevicesList: boolean;
procedure connectDevices;
procedure connectDevice(Device: TdawDevice);
procedure disconnectDevice(Device: TdawDevice);
constructor Create(AAdb: TdawAdb; AView: IdawView);
destructor Destroy; override;
function getDevices: TList<TdawDevice>;
end;
implementation
uses System.SysUtils;
{ TAndroidWiFiADB }
function TAndroidWiFiADB.checkDeviceExistance(connectedDevice
: TdawDevice): boolean;
var
LDevice: TdawDevice;
begin
Result := False;
for LDevice in FDevices.Values do
if connectedDevice.ID.Equals(LDevice.ID) then
Exit(True);
end;
procedure TAndroidWiFiADB.connectDevice(Device: TdawDevice);
var
connectedDevices: TList<TdawDevice>;
LDevice: TdawDevice;
begin
if not(isADBInstalled()) then
begin
FView.showADBNotInstalledNotification();
Exit;
end;
connectedDevices := TList<TdawDevice>.Create;
try
connectedDevices.AddRange(FAdb.connectDevices([Device]));
for LDevice in connectedDevices do
updateDeviceConnectionState(LDevice);
showConnectionResultNotification(connectedDevices.ToArray);
finally
connectedDevices.Free;
end;
end;
procedure TAndroidWiFiADB.connectDevices;
begin
if not isADBInstalled() then
begin
FView.showADBNotInstalledNotification();
Exit;
end;
FDevices.clear();
FDevices.AddRange(FAdb.getDevicesConnectedByUSB());
if (FDevices.Count = 0) then
begin
FView.showNoConnectedDevicesNotification();
Exit;
end;
FDevices.AddRange(FAdb.connectDevices(FDevices.ToArray));
showConnectionResultNotification(FDevices.ToArray);
end;
constructor TAndroidWiFiADB.Create(AAdb: TdawAdb; AView: IdawView);
begin
FDevices := TList<TdawDevice>.Create;
FAdb := AAdb;
FView := AView;
end;
destructor TAndroidWiFiADB.Destroy;
begin
FDevices.Free;
inherited;
end;
procedure TAndroidWiFiADB.disconnectDevice(Device: TdawDevice);
var
disconnectedDevices: TList<TdawDevice>;
LDevice: TdawDevice;
begin
if not(isADBInstalled()) then
begin
FView.showADBNotInstalledNotification();
Exit;
end;
disconnectedDevices := TList<TdawDevice>.Create;
try
disconnectedDevices.AddRange(FAdb.disconnectDevices([Device]));
for LDevice in disconnectedDevices do
FDevices.Add(LDevice);
showDisconnectionResultNotification(disconnectedDevices.ToArray);
finally
disconnectedDevices.Free;
end;
end;
function TAndroidWiFiADB.getDevices: TList<TdawDevice>;
begin
Result := FDevices;
end;
function TAndroidWiFiADB.isADBInstalled: boolean;
begin
Result := FAdb.IsInstalled;
end;
function TAndroidWiFiADB.refreshDevicesList: boolean;
var
Lconnected: TArray<TdawDevice>;
LconnectedDevice: TdawDevice;
begin
if not isADBInstalled() then
begin
Exit(False);
end;
removeNotConnectedDevices();
// connectDevices;
Lconnected := FAdb.getDevicesConnectedByUSB();
for LconnectedDevice in Lconnected do
begin
if not checkDeviceExistance(LconnectedDevice) then
begin
LconnectedDevice.setIp(FAdb.getDeviceIp(LconnectedDevice));
FDevices.Add(LconnectedDevice);
end
else
begin
FDevices.Add(LconnectedDevice);
end;
end;
Result := True;
end;
procedure TAndroidWiFiADB.removeNotConnectedDevices;
var
connectedDevices: TList<TdawDevice>;
LDevice: TdawDevice;
begin
connectedDevices := TList<TdawDevice>.Create();
try
for LDevice in FDevices do
begin
if LDevice.IsConnected then
connectedDevices.Add(LDevice);
end;
FDevices.clear();
FDevices.AddRange(connectedDevices);
finally
connectedDevices.Free;
end;
end;
procedure TAndroidWiFiADB.showConnectionResultNotification
(Adevices: TArray<TdawDevice>);
var
LDevice: TdawDevice;
begin
for LDevice in Adevices do
begin
if LDevice.IsConnected then
FView.showConnectedDeviceNotification(LDevice)
else
FView.showErrorConnectingDeviceNotification(LDevice);
end;
end;
procedure TAndroidWiFiADB.showDisconnectionResultNotification
(Adevices: TArray<TdawDevice>);
var
LDevice: TdawDevice;
begin
for LDevice in Adevices do
begin
if not LDevice.IsConnected then
FView.showDisconnectedDeviceNotification(LDevice)
else
FView.showErrorDisconnectingDeviceNotification(LDevice);
end;
end;
procedure TAndroidWiFiADB.updateDeviceConnectionState(updatedDevice
: TdawDevice);
begin
FDevices.Add(updatedDevice);
end;
{ TAlertService }
procedure TAlertService.showADBNotInstalledNotification;
begin
end;
procedure TAlertService.showConnectedDeviceNotification(ADevice: TdawDevice);
begin
end;
procedure TAlertService.showDisconnectedDeviceNotification(ADevice: TdawDevice);
begin
end;
procedure TAlertService.showErrorConnectingDeviceNotification
(ADevice: TdawDevice);
begin
end;
procedure TAlertService.showErrorDisconnectingDeviceNotification
(ADevice: TdawDevice);
begin
end;
procedure TAlertService.showNoConnectedDevicesNotification;
begin
end;
end.
|
unit LoggerPro.RedisAppender;
{ <@abstract(The unit to include if you want to use @link(TLoggerProRedisAppender))
@author(Daniele Teti) }
interface
uses
LoggerPro, System.Classes, System.DateUtils,
Redis.Commons {Redis.Commons is included in DelphiRedisClient, also available with GETIT} ,
Redis.NetLib.INDY {Redis.NetLib.INDY is included in DelphiRedisClient, also available with GETIT};
type
{
@abstract(Logs to a Redis instance)
To learn how to use this appender, check the sample @code(remote_redis_appender.dproj)
@author(Daniele Teti - d.teti@bittime.it)
}
TLoggerProRedisAppender = class(TLoggerProAppenderBase)
private
FRedis: IRedisClient;
FLogKeyPrefix: string;
FMaxSize: Int64;
public
constructor Create(aRedis: IRedisClient; aMaxSize: Int64 = 5000; aKeyPrefix: String = 'lplogs'); reintroduce;
procedure Setup; override;
procedure TearDown; override;
procedure WriteLog(const aLogItem: TLogItem); override;
procedure TryToRestart(var Restarted: Boolean); override;
end;
implementation
uses
System.SysUtils;
const
DEFAULT_LOG_FORMAT = '%0:s [TID %1:-8d][%2:-8s] %3:s [%4:s]';
constructor TLoggerProRedisAppender.Create(aRedis: IRedisClient; aMaxSize: Int64; aKeyPrefix: String);
begin
inherited Create;
FRedis := aRedis;
FLogKeyPrefix := aKeyPrefix;
FMaxSize := aMaxSize;
end;
procedure TLoggerProRedisAppender.Setup;
begin
FRedis.Connect;
end;
procedure TLoggerProRedisAppender.TearDown;
begin
// do nothing
end;
procedure TLoggerProRedisAppender.TryToRestart(var Restarted: Boolean);
begin
inherited;
Restarted := False;
try
FRedis.Disconnect
except
end;
try
FRedis.Connect;
Restarted := True;
except
end;
end;
procedure TLoggerProRedisAppender.WriteLog(const aLogItem: TLogItem);
var
lText: string;
lKey: string;
begin
lText := Format(DEFAULT_LOG_FORMAT, [datetimetostr(aLogItem.TimeStamp),
aLogItem.ThreadID, aLogItem.LogTypeAsString, aLogItem.LogMessage,
aLogItem.LogTag]);
lKey := FLogKeyPrefix + '::' + aLogItem.LogTypeAsString.ToLower;
// Push the log item to the right of the list (logs:info, logs:warning, log:error)
FRedis.RPUSH(lKey, [lText]);
// Trim the list to the FMaxSize last elements
FRedis.LTRIM(lKey, -FMaxSize, -1);
end;
end.
|
unit uOperacoesEmLote_Calculos_Controller;
interface
uses
uOperacoesEmLote_Calculos_Interface, Data.DB;
type
TController_OperacoesEmLote_Calculos = class(TInterfacedObject,
iController_OperacoesEmLote_Calculos)
FDataSet: TDataSet;
class function New: iController_OperacoesEmLote_Calculos;
function SetDataSet(DataSet: TDataSet)
: iController_OperacoesEmLote_Calculos;
function SumValues: Double;
function DivideValues: Double;
end;
implementation
{ TController_OperacoesEmLote_Soma }
function TController_OperacoesEmLote_Calculos.DivideValues: Double;
var
ValorRegistro, Total: Double;
I: Integer;
begin
{ Calculos de Divisão }
Total := 0;
FDataSet.First;
for I := 1 to FDataSet.RecordCount - 1 do
begin
ValorRegistro := FDataSet.FieldByName('Valor').AsFloat;
Total := Total + ((ValorRegistro + 10) / ValorRegistro);
FDataSet.Next;
end;
Result := Total;
end;
class function TController_OperacoesEmLote_Calculos.New
: iController_OperacoesEmLote_Calculos;
begin
Result := Self.Create;
end;
function TController_OperacoesEmLote_Calculos.SetDataSet(DataSet: TDataSet)
: iController_OperacoesEmLote_Calculos;
begin
Result := Self;
FDataSet := DataSet;
end;
function TController_OperacoesEmLote_Calculos.SumValues: Double;
Var
Total: Double;
begin
{ Calculos de soma }
Total := 0;
FDataSet.First;
while not FDataSet.Eof do
begin
Total := Total + FDataSet.FieldByName('Valor').AsFloat;
FDataSet.Next;
end;
Result := Total;
end;
end.
|
unit PrihChart;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, TeEngine, Series, DB, MemDS, DBAccess, Ora, ExtCtrls, TeeProcs,
Chart, DBChart, StdCtrls, Mask, ToolEdit, Math, UDbFunc;
type
TPrihChartForm = class(TForm)
Chart: TDBChart;
qChart: TOraQuery;
DocSeries: TBarSeries;
FactSeries: TBarSeries;
DiffAgrSeries: TLineSeries;
DiffSeries: TBarSeries;
pnlFilters: TPanel;
pnlChartDate: TPanel;
lblBeginDate: TLabel;
lblEndDate: TLabel;
deBeginDate: TDateEdit;
deEndDate: TDateEdit;
lblTitleChart: TLabel;
procedure FormShow(Sender: TObject);
procedure DiffSeriesBeforeDrawValues(Sender: TObject);
procedure deBeginDateChange(Sender: TObject);
private
FFuelId: integer;
procedure SetFuelId(const Value: integer);
public
property FuelId: integer read FFuelId write SetFuelId;
procedure RefreshData;
end;
var
PrihChartForm: TPrihChartForm;
implementation
{$R *.dfm}
procedure TPrihChartForm.FormShow(Sender: TObject);
begin
RefreshData;
end;
procedure TPrihChartForm.RefreshData;
begin
qChart.Close;
qChart.ParamByName('BeginDate').AsDateTime := deBeginDate.Date;
qChart.ParamByName('EndDate').AsDateTime := deEndDate.Date;
qChart.ParamByName('fuel_id').AsInteger := FuelId;
qChart.Open;
end;
procedure TPrihChartForm.DiffSeriesBeforeDrawValues(Sender: TObject);
var
i: integer;
begin
for i := 0 to DiffSeries.Count - 1 do
case sign(DiffSeries.YValues[i]) of
1: DiffSeries.ValueColor[i] := clGreen;
-1: DiffSeries.ValueColor[i] := clRed;
end;
end;
procedure TPrihChartForm.deBeginDateChange(Sender: TObject);
begin
RefreshData;
end;
procedure TPrihChartForm.SetFuelId(const Value: integer);
begin
lblTitleChart.Caption := Format('Разница при приходе по топливу %s',[GetNpGName(Value)]);
FFuelId := Value;
end;
end.
|
unit URegularFunctions;
interface
uses UConst;
function normalize(x: array of real): array of real;
function convert_mass_to_volume_fractions(mass_fractions: array of real;
densities: array of real := UConst.DENSITIES): array of real;
function convert_mass_to_mole_fractions(mass_fractions: array of real;
molar_masses: array of real := UConst.MR): array of real;
function get_flow_density(mass_fractions: array of real;
densities: array of real := UConst.DENSITIES): real;
function get_flow_molar_mass(mass_fractions:array of real;
molar_masses: array of real := UConst.MR): real;
function get_heat_capacity(mass_fractions: array of real; temperature: real;
coef: array of array of real := UConst.HEATCAPACITYCOEFFS): real;
function convert_mass_to_molar_fractions(mass_fractions:array of real;
densities: array of real := UConst.DENSITIES;
molar_masses: array of real := UConst.MR): array of real;
function convert_molar_to_mass_fractions(molar_fractions: array of real;
molar_masses: array of real := UConst.MR): array of real;
function runge_kutt(func: function(time: real; c, k: array of real): array of real;
c, k:array of real; start, stop: real;
h: real := 0.01): array of array of real;
function get_gas_densities(temperature, pressure: real;
molar_masses: array of real := UConst.MR): array of real;
implementation
function normalize(x: array of real): array of real;
begin
var s := x.Sum;
result := ArrFill(x.Length, 0.0);
foreach var i in x.Indices do
result[i] := x[i] / s
end;
function convert_mass_to_volume_fractions(mass_fractions,
densities: array of real): array of real;
begin
result := ArrFill(mass_fractions.Length, 0.0);
var s := 0.0;
foreach var i in mass_fractions.Indices do
s += mass_fractions[i] * densities[i];
foreach var i in mass_fractions.Indices do
result[i] := mass_fractions[i] * densities[i] / s
end;
function convert_mass_to_mole_fractions(mass_fractions,
molar_masses: array of real): array of real;
begin
result := ArrFill(mass_fractions.Length, 0.0);
var s := 0.0;
foreach var i in mass_fractions.Indices do
s += mass_fractions[i] / molar_masses[i];
foreach var i in mass_fractions.Indices do
result[i] := mass_fractions[i] / molar_masses[i] / s
end;
function get_flow_density(mass_fractions,
densities: array of real): real;
begin
var s := 0.0;
foreach var i in mass_fractions.Indices do
s += mass_fractions[i] / densities[i];
result := 1 / s
end;
function get_flow_molar_mass(mass_fractions,
molar_masses: array of real): real;
begin
var s := 0.0;
foreach var i in mass_fractions.Indices do
s += mass_fractions[i] / molar_masses[i];
result := 1 / s
end;
function get_heat_capacity(mass_fractions: array of real; temperature: real;
coef: array of array of real): real;
begin
var comp_heat_capacity := ArrFill(mass_fractions.Length, 0.0);
foreach var i in mass_fractions.Indices do
foreach var j in coef[i].Indices do
comp_heat_capacity[i] += coef[i][j] * temperature ** j;
result := 0.0;
foreach var i in mass_fractions.Indices do
result += mass_fractions[i] * comp_heat_capacity[i]
end;
function convert_mass_to_molar_fractions(mass_fractions:array of real;
densities: array of real; molar_masses:array of real): array of real;
begin
result := ArrFill(mass_fractions.Length, 0.0);
var flow_density := get_flow_density(mass_fractions, densities);
for var i := 0 to result.High do
result[i] := mass_fractions[i] / molar_masses[i] * flow_density * 1000;
end;
function convert_molar_to_mass_fractions(molar_fractions: array of real;
molar_masses: array of real): array of real;
begin
result := ArrFill(molar_fractions.Length, 0.0);
var flow_density := 0.0;
for var i := 0 to molar_fractions.High do
flow_density += molar_fractions[i] * molar_masses[i];
for var i := 0 to result.High do
result[i] := molar_fractions[i] * molar_masses[i] / flow_density;
end;
function runge_kutt(func: function(time: real; c, k: array of real): array of real;
c, k:array of real; start, stop: real;
h: real): array of array of real;
function sum(a: real; arr1, arr2: array of real): array of real;
begin
result := ArrFill(arr1.Length, 0.0);
for var i := 0 to arr1.High do
result[i] += arr1[i] + arr2[i] * a
end;
begin
var k1, k2, k3, k4: array of real;
var time := start;
var iter := Trunc((stop - start) / h) + 1;
var c_ := copy(c);
SetLength(result, iter);
for var i := 0 to iter-1 do
SetLength(result[i], c.Length+1);
for var i := 0 to result.High do
begin
result[i][0] := time;
for var j := 0 to c_.High do
result[i][j+1] := c_[j];
k1 := func(time, c_, k);
k2 := func(time + h / 2, sum(h / 2, c_, k1), k);
k3 := func(time + h / 2, sum(h / 2, c_, k2), k);
k4 := func(time + h, sum(h, c_, k3), k);
for var j := 0 to c_.High do
c_[j] += h / 6 * (k1[j] + 2 * k2[j] + 2 * k3[j] + k4[j]);
time += h
end;
end;
function get_gas_densities(temperature, pressure: real;
molar_masses: array of real): array of real;
begin
result := ArrFill(molar_masses.Length, 0.0);
for var i := 0 to result.High do
result[i] := pressure * molar_masses[i] / (8.314 * temperature)
end;
end. |
unit htButton;
interface
uses
SysUtils, Classes, Controls, Graphics, Types,
LrGraphics, LrTextPainter,
htStyle, htControls, htMarkup;
type
ThtButton = class(ThtGraphicControl)
private
FTextPainter: TLrTextPainter;
protected
procedure BuildStyle; override;
procedure Generate(const inContainer: string;
inMarkup: ThtMarkup); override;
function GetBoxHeight: Integer; override;
function GetBoxRect: TRect; override;
function GetBoxWidth: Integer; override;
procedure PerformAutoSize; override;
procedure StylePaint; override;
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
property TextPainter: TLrTextPainter read FTextPainter;
published
property Align;
property AutoSize;
property Caption;
property Outline;
property Style;
end;
implementation
uses
htUtils;
{ ThtButton }
constructor ThtButton.Create(inOwner: TComponent);
begin
inherited;
SetBounds(0, 0, 75, 25);
FTextPainter := TLrTextPainter.Create;
TextPainter.Canvas := Canvas;
TextPainter.Transparent := true;
TextPainter.HAlign := haCenter;
TextPainter.VAlign := vaMiddle;
//TextPainter.OnChange := TextPainterChange;
end;
destructor ThtButton.Destroy;
begin
TextPainter.Free;
inherited;
end;
function ThtButton.GetBoxHeight: Integer;
begin
Result := ClientHeight;
end;
function ThtButton.GetBoxRect: TRect;
begin
Result := ClientRect;
end;
function ThtButton.GetBoxWidth: Integer;
begin
Result := ClientWidth;
end;
procedure ThtButton.BuildStyle;
begin
inherited;
if not htVisibleColor(CtrlStyle.Color) then
CtrlStyle.Color := clBtnFace;
if not CtrlStyle.Border.BorderVisible then
begin
CtrlStyle.Border.BorderStyle := bsOutset;
CtrlStyle.Border.BorderWidth := '1';
end;
//
//CtrlStyle.Font.ToFont(Font);
//Canvas.Font := Font;
Color := CtrlStyle.Color;
end;
procedure ThtButton.PerformAutoSize;
begin
SetBounds(Left, Top, TextPainter.Width(Caption),
TextPainter.Height(Caption, ClientRect));
end;
procedure ThtButton.StylePaint;
begin
inherited;
TextPainter.PaintText(Caption, ClientRect);
end;
procedure ThtButton.Generate(const inContainer: string;
inMarkup: ThtMarkup);
var
n, s: string;
begin
n := Name;
s := {Ctrl}Style.InlineAttribute;
if (s <> '') then
inMarkup.Styles.Add(Format('#%s { %s }', [ n, s ]));
inMarkup.Add(
Format('<input id="%s" name="%s" type="%s" value="%s" %s/>',
[ n, n, 'button', Caption, ExtraAttributes ]));
end;
end.
|
unit uCmdLine;
interface
uses
SysUtils, uHashTable;
const
UNIT_NAME = 'uCmdLine';
type
TCommandLine = class(TObject)
private
fs:string;
FCmdLineAsStringHash : THashStringTable;
function CommandLineToStringHash(sCmdLine : string; ht : THashStringTable ) : boolean;
protected
public
constructor Create(var Commandline:PChar); // copies the commandline
destructor Destroy; override;
function GetParameter(N:string) : string; overload;
function GetParameter(N : string; StripQuotes : boolean ) : string; overload;
function Exists(N:string) : boolean;
published
end;
implementation
{ TCommandline }
function TCommandLine.CommandLineToStringHash(sCmdLine : string;
ht : THashStringTable ): boolean;
var
MyStr, str, sTokenName : string;
i : integer;
inComment, isTokenName : boolean;
begin
// ClearLog;
result := false;
sTokenName := 'EXEName';
try
str := '';
inComment := false;
MyStr := sCmdLine;
for i := 1 to Length( MyStr ) do begin
if ( MyStr[i] = '"' ) then begin
if ( not inComment ) then
inComment := true
else begin
inComment := false;
if ( Length(sTokenName) > 0 ) then ht.Add( sTokenName, str );
str := '';
sTokenName := '';
end;
end else begin
if ( inComment ) then begin
str := str + MyStr[i];
end else begin
if (( MyStr[i] = '-' ) or ( MyStr[i] = '/' )) then begin
isTokenName := true;
if ( Length(sTokenName) > 0 ) then ht.Add( sTokenName, str );
str := '';
sTokenName := '';
end else if ( MyStr[i] = ' ' ) then begin
if (isTokenName) then begin
if ( Length(sTokenName) > 0 ) then ht.Add( sTokenName, str );
isTokenName := false;
sTokenName := str;
str := '';
end;
end else begin
str := str + MyStr[i];
end;
end;
end;
end;
if ( Length( str ) > 0 ) then begin
if (isTokenName) then begin
sTokenName := str;
str := '';
end;
ht.Add( sTokenName, str );
//ht.setValue( sTokenName, TStringObject.Create(str));
end;
result := ( ht.Count > 0 );
finally
end;
end;
constructor TCommandline.Create(var Commandline:PChar);
var i:integer;
begin
inherited create;
fs:=Commandline; // get the PCHAR into the Delphi string
self.FCmdLineAsStringHash := THashStringTable.Create;
CommandLineToStringHash( fs, self.FCmdLineAsStringHash );
end; //create
destructor TCommandline.Destroy;
begin
setlength(fs,0); // get rid of the commandline string
self.FCmdLineAsStringHash.clear;
FreeAndNil( self.FCmdLineAsStringHash );
inherited;
end;
function TCommandLine.Exists( N: string ): boolean;
begin
Result := self.FCmdLineAsStringHash.containsKey(N);
end;
function TCommandLine.GetParameter(N: string; StripQuotes: boolean): string;
var
sParmValue : string;
begin
sParmValue := GetParameter( N );
if ( StripQuotes ) then begin
if ( sParmValue[1] = '''' ) then
sParmValue := Copy(sParmValue, 2, Length( sParmValue ));
if ( sParmValue[Length( sParmValue )] = '''' ) then
sParmValue := Copy(sParmValue, 1, Length( sParmValue ) - 1);
end;
Result := sParmValue;
end;
function TCommandline.GetParameter( N:string ) : string;
Begin
if ( not self.FCmdLineAsStringHash.containsKey(N) ) then
result := ''
else
result := FCmdLineAsStringHash.Get(N);
End;
end.
|
unit DSA.Tree.BST;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
Rtti,
DSA.List_Stack_Queue.ArrayListStack,
DSA.List_Stack_Queue.LoopListQueue,
DSA.Interfaces.Comparer;
type
{ TBST }
generic TBST<T, TComparer> = class
private
type
{ TNode }
TNode = class
public
Elment: T;
Left, Right: TNode;
constructor Create(e: T); overload;
end;
TArrayListStack_TNode = specialize TArrayListStack<TNode>;
TLoopListQueue_TNode = specialize TLoopListQueue<TNode>;
var
__root: TNode;
__size: integer;
__cmp: specialize IDSA_Comparer<T>;
/// <summary> 以TNode为根的二分搜索树中是否包含元素e,递归算法 </summary>
function __contains(node: TNode; e: T): boolean;
/// <summary>
/// 向以TNode为根的二分搜索树中插入元素e,递归算法.
/// 返回插入新节点后二分搜索树的根
/// </summary>
function __add(node: TNode; e: T): TNode;
/// <summary> 前序遍历以node为根的二分搜索树,递归算法 </summary>
procedure __preOrder(node: TNode);
/// <summary> 中序遍历以node为根的二分搜索树,递归算法 </summary>
procedure __inOrder(node: TNode);
/// <summary> 后序遍历以node为根的二分搜索树,递归算法 </summary>
procedure __postOrder(node: TNode);
/// <summary> 返回以node为根的二分搜索树的最小值所在的节点 </summary>
function __minimum(node: TNode): TNode;
/// <summary> 返回以node为根的二分搜索树的最大值所在的节点 </summary>
function __maximum(node: TNode): TNode;
/// <summary>
/// 删除二分搜索树的最小值所在的节点, 返回删除节点后二分搜索树的根
/// </summary>
function __removeMin(node: TNode): TNode;
/// <summary>
/// 删除二分搜索树的最大值所在的节点, 返回删除节点后二分搜索树的根
/// </summary>
function __removeMax(node: TNode): TNode;
/// <summary>
/// 删除以node为根的二分搜索树中值为e的节点,递归算法.
/// 返回删除节点后新的二分搜索树的根
/// </summary>
function __remove(node: TNode; e: T): TNode;
/// <summary> 返回e的字符串 </summary>
function __fromValueToStr(const e: T): string;
function __destroy(node: TNode): TNode;
public
constructor Create;
destructor Destroy; override;
function GetSize: integer;
function IsEmpty: boolean;
/// <summary> 二分搜索树中是否包含元素e </summary>
function Contains(e: T): boolean;
/// <summary> 向二分搜索树中添加新的元素e </summary>
procedure Add(e: T);
/// <summary> 二分搜索树的前序遍历 </summary>
procedure PreOrderNR;
/// <summary> 二分搜索树的前序遍历 </summary>
procedure PreOrder;
/// <summary> 二分搜索树的中序遍历 </summary>
procedure InOrder;
/// <summary> 二分搜索树的后序遍历 </summary>
procedure PostOrder;
/// <summary> 二分搜索树的层序遍历 </summary>
procedure LevelOrder;
/// <summary> 寻找二分搜索树的最小元素 </summary>
function Minimum: T;
/// <summary> 寻找二分搜索树的最大元素 </summary>
function Maximum: T;
/// <summary> 删除二分搜索树的最小值所在的节点,返回最小值 </summary>
function RemoveMin: T;
/// <summary> 删除二分搜索树的最大值所在的节点,返回最大值 </summary>
function RemoveMax: T;
/// <summary> 删除二分搜索树中值为e的节点 </summary>
procedure Remove(e: T);
/// <summary> 清空BST </summary>
procedure Clear;
end;
procedure Main;
implementation
uses
DSA.List_Stack_Queue.ArrayList;
type
TComparer_int = specialize TComparer<integer>;
TBST_int = specialize TBST<integer, TComparer_int>;
TArrayList_int = specialize TArrayList<integer>;
procedure Main;
var
arr: array of integer;
BST: TBST_int;
i, n: integer;
nums: TArrayList_int;
begin
BST := TBST_int.Create;
arr := [5, 3, 7, 8, 4, 2, 6];
for i := low(arr) to high(arr) do
BST.Add(arr[i]);
BST.PreOrder;
WriteLn;
BST.PreOrderNR;
WriteLn;
BST.InOrder;
WriteLn;
BST.PostOrder;
WriteLn;
BST.LevelOrder;
WriteLn;
n := 1000;
Randomize;
for i := 0 to n - 1 do
BST.Add(Random(10000) + 1);
nums := TArrayList_int.Create();
while BST.IsEmpty = False do
nums.AddLast(BST.RemoveMin);
for i := 1 to nums.GetSize - 1 do
if nums[i - 1] > nums[i] then
raise Exception.Create('Error.');
WriteLn(nums.ToString);
WriteLn('RemoveMin test completed.');
end;
{ TBST<T>.TNode }
constructor TBST.TNode.Create(e: T);
begin
Elment := e;
Left := nil;
Right := nil;
end;
{ TBST<T> }
procedure TBST.Add(e: T);
begin
__root := __add(__root, e);
end;
function TBST.Contains(e: T): boolean;
begin
Result := __contains(__root, e);
end;
constructor TBST.Create;
begin
__root := nil;
__cmp := TComparer.Default;
end;
destructor TBST.Destroy;
begin
__root := __destroy(__root);
FreeAndNil(__root);
inherited;
end;
function TBST.GetSize: integer;
begin
Result := __size;
end;
procedure TBST.InOrder;
begin
__inOrder(__root);
end;
function TBST.IsEmpty: boolean;
begin
Result := __size = 0;
end;
procedure TBST.LevelOrder;
var
queue: TLoopListQueue_TNode;
cur: TNode;
begin
queue := TLoopListQueue_TNode.Create();
try
queue.EnQueue(__root);
while not queue.IsEmpty do
begin
cur := queue.DeQueue;
Write(__fromValueToStr(cur.Elment), ' ');
if cur.Left <> nil then
queue.EnQueue(cur.Left);
if cur.Right <> nil then
queue.EnQueue(cur.Right);
end;
finally
FreeAndNil(queue);
end;
end;
function TBST.Maximum: T;
begin
if IsEmpty then
raise Exception.Create('BST is empty');
Result := __maximum(__root).Elment;
end;
function TBST.Minimum: T;
begin
if IsEmpty then
raise Exception.Create('BST is empty');
Result := __minimum(__root).Elment;
end;
procedure TBST.PostOrder;
begin
__postOrder(__root);
end;
procedure TBST.PreOrder;
begin
__preOrder(__root);
end;
procedure TBST.PreOrderNR;
var
stack: TArrayListStack_TNode;
cur: TNode;
begin
stack := TArrayListStack_TNode.Create();
try
stack.Push(__root);
while not (stack.IsEmpty) do
begin
cur := stack.Pop;
Write(__fromValueToStr(cur.Elment), ' ');
if cur.Right <> nil then
stack.Push(cur.Right);
if cur.Left <> nil then
stack.Push(cur.Left);
end;
finally
FreeAndNil(stack);
end;
end;
procedure TBST.Remove(e: T);
begin
__root := __remove(__root, e);
end;
procedure TBST.Clear;
begin
__root := __destroy(__root);
end;
function TBST.RemoveMax: T;
begin
Result := Maximum;
__root := __removeMax(__root);
end;
function TBST.RemoveMin: T;
begin
Result := Minimum;
__root := __removeMin(__root);
end;
function TBST.__add(node: TNode; e: T): TNode;
var
bool: integer;
begin
if node = nil then
begin
Inc(__size);
Result := TNode.Create(e);
Exit;
end;
bool := __cmp.Compare(e, node.Elment);
if bool < 0 then
node.Left := __add(node.Left, e)
else if bool > 0 then
node.Right := __add(node.Right, e);
Result := node;
end;
function TBST.__contains(node: TNode; e: T): boolean;
var
bool: integer;
begin
if node = nil then
begin
Result := False;
Exit;
end;
bool := __cmp.Compare(e, node.Elment);
if bool < 0 then
Result := __contains(node.Left, e)
else if bool > 0 then
Result := __contains(node.Right, e)
else
Result := True;
end;
function TBST.__destroy(node: TNode): TNode;
begin
if node = nil then
Exit(nil);
__destroy(node.Left);
__destroy(node.Right);
FreeAndNil(node);
Dec(__size);
Result := node;
end;
function TBST.__fromValueToStr(const e: T): string;
var
val: TValue;
begin
TValue.Make(@e, TypeInfo(T), val);
Result := val.ToString;
end;
procedure TBST.__inOrder(node: TNode);
begin
if node = nil then
Exit;
__inOrder(node.Left);
Write(__fromValueToStr(node.Elment), ' ');
__inOrder(node.Right);
end;
function TBST.__maximum(node: TNode): TNode;
begin
if node.Right = nil then
begin
Exit(node);
end;
Result := __maximum(node.Right);
end;
function TBST.__minimum(node: TNode): TNode;
begin
if node.Left = nil then
begin
Exit(node);
end;
Result := __minimum(node.Left);
end;
procedure TBST.__postOrder(node: TNode);
begin
if node = nil then
Exit;
__postOrder(node.Left);
__postOrder(node.Right);
Write(__fromValueToStr(node.Elment), ' ');
end;
procedure TBST.__preOrder(node: TNode);
begin
if node = nil then
Exit;
Write(__fromValueToStr(node.Elment), ' ');
__preOrder(node.Left);
__preOrder(node.Right);
end;
function TBST.__remove(node: TNode; e: T): TNode;
var
succesorNode: TNode;
bool: integer;
begin
if node = nil then
Exit(nil);
bool := __cmp.Compare(e, node.Elment);
if bool < 0 then
begin
node.Left := __remove(node.Left, e);
Result := node;
end
else if bool > 0 then
begin
node.Right := __remove(node.Right, e);
Result := node;
end
else // e = node.Elment
begin
if node.Left = nil then
begin
Result := node.Right;
FreeAndNil(node);
Dec(__size);
end
else if node.Right = nil then
begin
Result := node.Left;
FreeAndNil(node);
Dec(__size);
end
else
begin
// 待删除节点左右子树均不空的情况
// 找到比待删除节点大的最小节点,即待删除节点右子树的最小节点
// 用这个节点顶替待删除节点的位置
succesorNode := TNode.Create(__minimum(node.Right).Elment);
succesorNode.Right := __removeMin(node.Right);
succesorNode.Left := node.Left;
FreeAndNil(node);
Result := succesorNode;
end;
end;
end;
function TBST.__removeMax(node: TNode): TNode;
var
leftNode: TNode;
begin
if node.Right = nil then
begin
leftNode := node.Left;
Result := leftNode;
Dec(__size);
FreeAndNil(node);
Exit;
end;
node.Right := __removeMax(node.Right);
Result := node;
end;
function TBST.__removeMin(node: TNode): TNode;
var
rightNode: TNode;
begin
if node.Left = nil then
begin
rightNode := node.Right;
Result := rightNode;
Dec(__size);
FreeAndNil(node);
Exit;
end;
node.Left := __removeMin(node.Left);
Result := node;
end;
end.
|
unit frmAffirmBox;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TAffirmBoxForm = class(TForm)
cboClass: TComboBox;
Label1: TLabel;
Label2: TLabel;
mRemark: TMemo;
btnSave: TButton;
groupbox1: TGroupBox;
procedure btnSaveClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
procedure CreateNewRemark(GF_ID:string;step_no:string;operation_code:string);
implementation
uses StrUtils, uDictionary, UAppOption,
uFNMArtInfo, uGlobal, ServerDllPub, uFNMResource,
uLogin, uShowMessage;
{$R *.dfm}
var
AffirmBoxForm: TAffirmBoxForm;
mGF_ID:string;
mStep_NO :string;
mOperation_Code:string;
procedure CreateNewRemark(GF_ID:string;step_no:string;operation_code:string);
begin
if AffirmBoxForm = nil then
AffirmBoxForm:=TAffirmBoxForm.Create(Application);
with AffirmBoxForm do
begin
mGF_ID := GF_ID;
mStep_NO := step_no;
mOperation_Code := operation_code;
end;
AffirmBoxForm.ShowModal;
end;
procedure TAffirmBoxForm.btnSaveClick(Sender: TObject);
var
sCondition,sErrorMsg: WideString;
i:Integer;
begin
sCondition := QuotedStr(mGF_ID)+ ','
+ mStep_NO+ ','
+ QuotedStr(mOperation_Code) + ','
+ QuotedStr(login.CurrentDepartment) + ','
+ QuotedStr(cboClass.Text) + ','
+ QuotedStr(mRemark.Lines.Text);
FNMServerObj.SaveDataBySQL('SaveAffirmRmark',sCondition,sErrorMsg);
if sErrorMsg <> '' then
begin
TMsgDialog.ShowMsgDialog('ÐÞ¸Äʧ°Ü!',mtError);
Exit;
end;
AffirmBoxForm.Close;
AffirmBoxForm := nil;
end;
end.
|
{***************************
表格配置
为了减少表格类型,数据保存位置的耦合, 让任一模块都可快速的修改和替换
可分为三个逻辑(1:窗体表格显示;2:控制表格列的属性;3:列信息读取保存处理)
mx 2014-11-28
****************************}
unit uGridConfig;
interface
uses
Windows, Classes, Db, DBClient, SysUtils, Controls, cxGrid, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGraphics, uBaseInfoDef, uModelBaseIntf, uModelFunIntf, cxEdit, uDefCom, cxCustomData, uOtherDefine,
cxStyles;
const
SpecialCharList: array[0..1] of string = ('[', ']');
MaxRowCount = 500;
type
//表格单元格双击事件
TCellDblClickEvent = procedure(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean) of object;
TGridEditKeyPressEvent = procedure(Sender: TcxCustomGridTableView;
AItem: TcxCustomGridTableItem; AEdit: TcxCustomEdit; var Key: Char) of object;
TLoadUpDownDataEvent = procedure(Sender: TObject; ATypeid: String) of Object;
//表格每列的信息
TColInfo = class(TObject)
private
FGridColumn: TcxGridColumn;
FFieldName: string;
FColShowType: TColField; //字段类型
FBasicType: TBasicType; //点击列单元格的时候显示哪种TC
FExpression: string; //自定义的公式 bb*cc
FDataToDisplay: TStringList; //字段显示与查询数据对应列表
procedure GetDisplayText(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: string);
public
procedure AddExpression(AExpression: string);
procedure SetDisplayText(ADisplayText: TIDDisplayText); //设置查询数据与显示数据的对应关系
constructor Create(AGridColumn: TcxGridColumn; AFieldName: string);
destructor Destroy; override;
published
property GridColumn: TcxGridColumn read FGridColumn write FGridColumn;
end;
//管理每个表格对应的数据和操作
TGridItem = class(TObject)
private
FModelFun: IModelFun;
FGridID: string;
FGrid: TcxGrid;
FGridTV: TcxGridTableView;
FBasicType: TBasicType; //表格如果要分组的需要根据类型在去ptypeid等的儿子数来看是否显示*
FColList: array of TColInfo; //记录添加的所以列信息
FTypeClassList: TStringList; //记录ID对应的商品是否有子类格式 00001=0 or 00001=1,0没有儿子,1有儿子;为了减少每行的查询操作
FCdsSource: TClientDataSet; //通过数据集加载是的数据集
FCanEdit: Boolean; //是否能够修改单元格类容
FShowMaxRow: Boolean; //是否能显示最大的行数,不管是否修改或加载数据
FOnSelectBasic: TSelectBasicinfoEvent; //弹出TC类选择框
FOldCellDblClick: TCellDblClickEvent; //表格单元格原来的双击事件
FOldGridEditKey: TcxGridEditKeyEvent; //表格单元格原来的按键事件
FOldGridEditKeyPress: TGridEditKeyPressEvent; //表格单元格原来的按键事件
FOnLoadUpDownData: TLoadUpDownDataEvent; //加载上一层或者下一层数据
//给表格增加序号
procedure XHOnCustomDrawCell(Sender: TcxGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxCustomGridIndicatorItemViewInfo; var ADone: Boolean);
procedure ReClassList; //要在子类加载数据完成后执行.刷新表格记录ID的PSonnum,在判断是否是类显示*的时候需要用到
procedure GridCellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
procedure GridEditKeyEvent(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem;
AEdit: TcxCustomEdit; var Key: Word; Shift: TShiftState);
procedure GridEditKeyPressEvent(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem; AEdit: TcxCustomEdit; var Key: Char); //表格单元格输入事件
procedure ColumnPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); //添加基本信息时,单元格内的按钮点击事件
function GetRowIndex: Integer; //获取当前选中的行
procedure SetRowIndex(Value: Integer); //设置选中的行
procedure GridColEditValueChanged(Sender: TObject); //设置公式字段后,单元格值改变事件时计算公式
procedure InitExpression; //初始化公式设置
public
constructor Create(AGridID: string; AGrid: TcxGrid; AGridTV: TcxGridTableView);
destructor Destroy; override;
procedure ClearField; //清空表格的所有列数据
procedure ClearData; //清空表格的所有行数据
function AddField(AFileName, AShowCaption: string; AWidth: Integer = 100; AColShowType: TColField = cfString): TColInfo; overload;
procedure AddField(ABasicType: TBasicType); overload;
function AddCheckBoxCol(AFileName, AShowCaption: string; AValueChecked, ValueUnchecked: Variant): TColInfo;
function AddBtnCol(AFileName, AShowCaption, ABtnCaption: string; AClickEvent: TcxEditButtonClickEvent): TColInfo;
function GetCellValue(ADBName: string; ARowIndex: Integer): Variant; //获取单元格值
procedure SetCellValue(ADBName: string; ARowIndex: Integer; AValue: Variant); //设置单元格值
procedure InitGridData;
procedure GridPost; //提交修改的数据
function GetFirstRow: Integer; //获取行的首行
function GetLastRow: Integer; //获取行的末行
function SelectedRowCount: Integer; //选中的行数
procedure LoadData(ACdsData: TClientDataSet); //加载数据
function LoadUpDownData(ALoadUp: Boolean): Boolean;//加载下一级或者上一级数据
procedure SetGridCellSelect(ACellSelect: Boolean); //是否能选中单元格和此行其它单元格不是选中状态
procedure SetGoToNextCellOnEnter(ANextCellOnEnter: Boolean); //是否是否通过回车换行
procedure MultiSelect(AMultiSelect: Boolean); //是否运行多选
function FindColByCaption(AShowCaption: string): TColInfo; //根据表头查找列
function FindColByFieldName(AFieldName: string): TColInfo; //根据数据库字段名称查找列
procedure AddFooterSummary(AColInfo: TColInfo; ASummaryKind: TcxSummaryKind); //增加一个合计行字段
function AddRow: Integer; //增加一行
function RecordCount: Integer; //有多少数据行
procedure DeleteRow(ARow: Integer); //删除指定行
procedure SetReadOnly(AReadOnly: Boolean); //是否能修改表格
property ShowMaxRow: Boolean read FShowMaxRow write FShowMaxRow;
published
property BasicType: TBasicType read FBasicType write FBasicType;
property RowIndex: Integer read GetRowIndex write SetRowIndex;
property OnSelectBasic: TSelectBasicinfoEvent read FOnSelectBasic write FOnSelectBasic;
property CdsSource: TClientDataSet read FCdsSource write FCdsSource;
property OnLoadUpDownData: TLoadUpDownDataEvent read FOnLoadUpDownData write FOnLoadUpDownData;
end;
//管理和控制所有的表格初始化操作,如列的宽度等
TGridControl = class(TObject)
private
procedure AddGradItem(AGridItem: TGridItem);
public
constructor Create;
destructor Destroy; override;
end;
var
FColCfg: TGridControl;
implementation
uses uSysSvc, uOtherIntf, cxDataStorage, cxCheckBox, cxButtonEdit, cxTextEdit, uPubFun, Graphics, Variants, uCalcExpress, uDM;
{ TGridItem }
function TGridItem.AddField(AFileName, AShowCaption: string;
AWidth: Integer; AColShowType: TColField): TColInfo;
var
aCol: TcxGridColumn;
aColInfo: TColInfo;
i: Integer;
aStrSpecial: string;
begin
for i := 0 to Length(SpecialCharList) - 1 do
begin
aStrSpecial := SpecialCharList[i];
if Pos(aStrSpecial, AShowCaption) >= 1 then
begin
raise(SysService as IExManagement).CreateSysEx('表格列显示名称"' + AShowCaption + '"错误,请重新设置!');
end;
end;
aCol := FGridTV.CreateColumn;
aCol.Caption := AShowCaption;
aCol.PropertiesClass := TcxTextEditProperties;
aCol.Properties.Alignment.Vert := taVCenter; //单元格内容上下居中
aCol.Options.Sorting := False; //不能排序
aCol.Width := AWidth;
if AWidth <= 0 then aCol.Visible := False;
case AColShowType of
cfString: aCol.DataBinding.ValueTypeClass := TcxStringValueType;
cfInt, cfPlusInt: aCol.DataBinding.ValueTypeClass := TcxIntegerValueType;
cfFloat, cfPlusFloat, cfQty, cfPrice, cfTotal, cfDiscount: aCol.DataBinding.ValueTypeClass := TcxFloatValueType;
// gctDate: aCol.DataBinding.ValueTypeClass := ; //日期类型是什么,没有找到 2014-12-02
cfDatime: aCol.DataBinding.ValueTypeClass := TcxDateTimeValueType;
cfCheck: aCol.DataBinding.ValueTypeClass := TcxBooleanValueType;
else
aCol.DataBinding.ValueTypeClass := TcxStringValueType;
end;
aColInfo := TColInfo.Create(aCol, AFileName);
aColInfo.FColShowType := AColShowType;
SetLength(FColList, Length(FColList) + 1);
FColList[Length(FColList) - 1] := aColInfo;
Result := aColInfo;
end;
function TGridItem.AddCheckBoxCol(AFileName, AShowCaption: string;
AValueChecked, ValueUnchecked: Variant): TColInfo;
var
aCol: TcxGridColumn;
aColInfo: TColInfo;
begin
aCol := FGridTV.CreateColumn;
aCol.Caption := AShowCaption;
aCol.PropertiesClass := TcxCheckBoxProperties;
TcxCheckBoxProperties(aCol.Properties).ValueChecked := AValueChecked;
TcxCheckBoxProperties(aCol.Properties).ValueUnchecked := ValueUnchecked;
aColInfo := TColInfo.Create(aCol, AFileName);
SetLength(FColList, Length(FColList) + 1);
FColList[Length(FColList) - 1] := aColInfo;
Result := aColInfo;
end;
procedure TGridItem.ClearField;
begin
FGridTV.ClearItems;
end;
constructor TGridItem.Create(AGridID: string; AGrid: TcxGrid; AGridTV: TcxGridTableView);
begin
FGridID := AGridID;
FGrid := AGrid;
FGridTV := AGridTV;
FGridTV.OnCustomDrawIndicatorCell := XHOnCustomDrawCell;
FOldCellDblClick := FGridTV.OnCellDblClick;
FGridTV.OnCellDblClick := GridCellDblClick;//在编辑单元格进行双击的时候不能触发
FOldGridEditKey := FGridTV.OnEditKeyDown; //基本信息单元格回车的时候弹出TC
FGridTV.OnEditKeyDown := GridEditKeyEvent;
FOldGridEditKeyPress := FGridTV.OnEditKeyPress; //根据字段类型,判断是否能够输入字符
FGridTV.OnEditKeyPress := GridEditKeyPressEvent;
FModelFun := SysService as IModelFun;
//显示行号的那一列
FGridTV.OptionsView.Indicator := True;
FGridTV.OptionsView.IndicatorWidth := 40;
FGridTV.OptionsSelection.CellSelect := False; //是否能选中单元格
FGridTV.OptionsView.NoDataToDisplayInfoText := '没有数据'; //表格没有数据时显示的内容
FGridTV.OptionsView.GroupByBox := False; //不显示表头的分组功能
FGridTV.OptionsBehavior.FocusCellOnCycle := True; //切换时可以循环
FGridTV.OptionsBehavior.GoToNextCellOnEnter := True; //通过回车切换单元格
FGridTV.Styles.Selection := TcxStyle.Create(nil);
FGridTV.Styles.Selection.Color := $00C08000; //clGradientActiveCaption;
FColCfg.AddGradItem(Self);
FTypeClassList := TStringList.Create;
FCdsSource := TClientDataSet.Create(nil);
SetLength(FColList, 0);
FBasicType := btNo;
FCanEdit := False;
FShowMaxRow := True;
end;
destructor TGridItem.Destroy;
var
i: Integer;
begin
for i := 0 to Length(FColList) - 1 do
begin
FColList[i].Free;
end;
FCdsSource.Free;
FTypeClassList.Free;
inherited;
end;
procedure TGridItem.XHOnCustomDrawCell(Sender: TcxGridTableView; ACanvas: TcxCanvas;
AViewInfo: TcxCustomGridIndicatorItemViewInfo; var ADone: Boolean);
var
FValue: string;
FBounds: TRect;
begin
if (AViewInfo is TcxGridIndicatorHeaderItemViewInfo) then
begin
FValue := '序号';
end
else if (AViewInfo is TcxGridIndicatorRowItemViewInfo) then
begin
FValue := IntToStr(TcxGridIndicatorRowItemViewInfo(AViewInfo).GridRecord.Index + 1);
if Assigned(FTypeClassList) then
begin
if FTypeClassList.IndexOf(FValue) >= 0 then
FValue := FValue + '*';
end;
end
else if (AViewInfo is TcxGridIndicatorFooterItemViewInfo) then
begin
FValue := '合计';
end;
FBounds := AViewInfo.Bounds;
ACanvas.FillRect(FBounds);
ACanvas.DrawComplexFrame(FBounds, clBlack, clBlack, [bBottom, bLeft, bRight], 1);
InflateRect(FBounds, -3, -2);
ACanvas.Font.Color := clBlack;
ACanvas.Brush.Style := bsClear;
ACanvas.DrawText(FValue, FBounds, cxAlignCenter or cxAlignTop);
ADone := True;
end;
procedure TGridItem.InitGridData;
begin
//设置公式
InitExpression();
FGridTV.DataController.RecordCount := MaxRowCount;
end;
function TGridItem.GetCellValue(ADBName: string; ARowIndex: Integer): Variant;
var
aCol: Integer;
aColItem: TColInfo;
aFindCol: Boolean;
aValue: OleVariant;
begin
try
aFindCol := False;
for aCol := 0 to Length(FColList) - 1 do
begin
aColItem := FColList[aCol];
if UpperCase(aColItem.FFieldName) = UpperCase(ADBName) then
begin
if aColItem.FColShowType in [cfInt, cfFloat, cfPlusFloat, cfQty, cfPrice, cfTotal, cfDiscount, cfCheck, cfDatime] then
begin
Result := 0;
end
else
begin
Result := '';
end;
aValue := FGridTV.DataController.GetValue(ARowIndex, aColItem.FGridColumn.Index);
aFindCol := True;
if aValue <> null then
Result := aValue;
Break;
end;
end;
finally
if not aFindCol then
begin
raise(SysService as IExManagement).CreateSysEx('读取表格列[' + ADBName + ']数据错误,请设置表格列字段!');
end;
end;
end;
procedure TGridItem.ReClassList;
var
aTypeId, aSonnum: string;
aRowIndex: Integer;
begin
FTypeClassList.Clear;
if GetBaseTypesLevels(BasicType) <= 1 then Exit;
for aRowIndex := GetFirstRow to GetLastRow do
begin
aTypeId := GetCellValue(GetBaseTypeid(BasicType), aRowIndex);
if StringEmpty(aTypeId) then Continue;
aSonnum := FModelFun.GetLocalValue(BasicType, GetBaseTypeSonnumStr(BasicType), aTypeId);
if StringToInt(aSonnum) > 0 then
begin
FTypeClassList.Add(IntToStr(aRowIndex + 1))
end;
end;
end;
function TGridItem.GetFirstRow: Integer;
begin
Result := 0;
end;
function TGridItem.GetLastRow: Integer;
begin
Result := FGridTV.DataController.RecordCount - 1;
end;
procedure TGridItem.LoadData(ACdsData: TClientDataSet);
var
i, aRow, aCdsCol: Integer;
aFieldName: string;
begin
CdsSource.Data := ACdsData.Data;
FGridTV.DataController.RecordCount := ACdsData.RecordCount;
ACdsData.First;
aRow := 0;
FGridTV.BeginUpdate;
try
while not ACdsData.Eof do
begin
for i := 0 to Length(FColList) - 1 do
begin
aFieldName := FColList[i].FFieldName;
aCdsCol := ACdsData.FieldDefs.IndexOf(aFieldName);
if aCdsCol <> -1 then
FGridTV.DataController.Values[aRow, i] := ACdsData.FieldValues[aFieldName];
end;
inc(aRow);
ACdsData.Next;
end;
if FCanEdit and ShowMaxRow then
begin
if FGridTV.DataController.RecordCount < MaxRowCount then
begin
FGridTV.DataController.RecordCount := MaxRowCount;
end;
end;
if FGridTV.DataController.RecordCount > 0 then
begin
FGridTV.DataController.FocusedRowIndex := 0;
end;
finally
ReClassList();
FGridTV.EndUpdate;
end;
end;
procedure TGridItem.SetGridCellSelect(ACellSelect: Boolean);
begin
//是否能选中单元格
FGridTV.OptionsSelection.CellSelect := ACellSelect;
FGridTV.OptionsSelection.InvertSelect := not ACellSelect;
FCanEdit := ACellSelect;
end;
procedure TGridItem.GridCellDblClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
var
i, aReturnCount: Integer;
aBasicType: TBasicType;
aSelectParam: TSelectBasicParam;
aSelectOptions: TSelectBasicOptions;
aReturnArray: TSelectBasicDatas;
begin
if not FCanEdit then;
if LoadUpDownData(False) then Exit; //加载下一级数据
if Assigned(FOldCellDblClick) then FOldCellDblClick(Sender, ACellViewInfo, AButton, AShift, AHandled);
for i := 0 to Length(FColList) - 1 do
begin
if FColList[i].FGridColumn = FGridTV.Controller.FocusedColumn then
begin
if FColList[i].FFieldName = 'PFullname' then
begin
OnSelectBasic(FGridTV, ABasicType, ASelectParam, ASelectOptions, AReturnArray, aReturnCount);
Break;
end;
end;
end;
end;
procedure TGridItem.AddField(ABasicType: TBasicType);
var
aColInfo: TColInfo;
aDelBtn: TcxEditButton;
begin
if ABasicType = btPtype then
begin
AddField('PTypeId', 'PTypeId', -1);
aColInfo := AddField('PFullname', '商品名称');
aColInfo.FGridColumn.PropertiesClass := TcxButtonEditProperties;
aColInfo.FBasicType := btPtype;
aDelBtn :=(aColInfo.FGridColumn.Properties as TcxButtonEditProperties).Buttons.Add;
aDelBtn.Kind := bkGlyph;
// aDelBtn.Glyph.LoadFromFile('E:\Code\Delphi\wmpj\Img\delete_16px.bmp');
DMApp.GetBitmap(imDelRow, aDelBtn.Glyph);
(aColInfo.FGridColumn.Properties as TcxButtonEditProperties).OnButtonClick := ColumnPropertiesButtonClick; //关联点击事件
aColInfo := AddField('PUsercode', '商品编码');
aColInfo.GridColumn.Options.Editing := False;
end
else if ABasicType = btBtype then
begin
AddField('BTypeId', 'BTypeId', -1);
AddField('BFullname', '单位名称');
AddField('BUsercode', '单位编码');
end
else if ABasicType = btEtype then
begin
AddField('ETypeId', 'ETypeId', -1);
AddField('EFullname', '职员名称');
AddField('EUsercode', '职员编码');
end
else if ABasicType = btDtype then
begin
AddField('DTypeId', 'DTypeId', -1);
AddField('DFullname', '部门名称');
AddField('DUsercode', '部门编码');
end
else if ABasicType = btKtype then
begin
AddField('KTypeId', 'KTypeId', -1);
AddField('KFullname', '仓库名称');
AddField('KUsercode', '仓库编码');
end
else if ABasicType = btVtype then
begin
AddField('VTypeId', 'VTypeId', -1);
AddField('VchType', 'VchType', -1, cfInt);
AddField('VFullname', '单据类型', 100, cfString);
end
else
begin
raise(SysService as IExManagement).CreateSysEx('没有配置[' + BasicTypeToString(ABasicType) + ']此基本信息对应的列,请配置!');
end;
end;
procedure TGridItem.ColumnPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
i, aReturnCount: Integer;
aBasicType: TBasicType;
aSelectParam: TSelectBasicParam;
aSelectOptions: TSelectBasicOptions;
aReturnArray: TSelectBasicDatas;
begin
for i := 0 to Length(FColList) - 1 do
begin
if FColList[i].FGridColumn = FGridTV.Controller.FocusedColumn then
begin
if FColList[i].FBasicType <> btNo then
begin
case AButtonIndex of
0: OnSelectBasic(FGrid, FColList[i].FBasicType, aSelectParam, aSelectOptions, aReturnArray, aReturnCount);
1:
begin
if FColList[i].FBasicType = btPtype then
begin
SetCellValue('PTypeId', RowIndex, '');
SetCellValue('PFullname', RowIndex, '');
SetCellValue('PUsercode', RowIndex, '');
end;
end;
else ;
end;
end;
end;
end;
end;
function TGridItem.GetRowIndex: Integer;
begin
Result := -1;
//Result := FGridTV.Controller.FocusedRowIndex;
if FGridTV.Controller.SelectedRowCount > 0 then
Result := FGridTV.Controller.SelectedRows[0].RecordIndex;
end;
procedure TGridItem.SetRowIndex(Value: Integer);
begin
FGridTV.Controller.FocusedRowIndex := Value;
end;
procedure TGridItem.GridEditKeyEvent(Sender: TcxCustomGridTableView;
AItem: TcxCustomGridTableItem; AEdit: TcxCustomEdit; var Key: Word;
Shift: TShiftState);
begin
if Assigned(FOldGridEditKey) then FOldGridEditKey(Sender, AItem, AEdit, Key, Shift);
if Key = VK_RETURN then
begin
ColumnPropertiesButtonClick(nil, 0);
end;
end;
procedure TGridItem.SetCellValue(ADBName: string; ARowIndex: Integer;
AValue: Variant);
var
i: Integer;
aFieldName: string;
aFindCol: Boolean;
begin
try
aFindCol := False;
for i := 0 to Length(FColList) - 1 do
begin
aFieldName := FColList[i].FFieldName;
if UpperCase(aFieldName) = UpperCase(ADBName) then
begin
FGridTV.DataController.Values[ARowIndex, FColList[i].FGridColumn.Index] := AValue;
aFindCol := True;
Break;
end;
end;
finally
if not aFindCol then
begin
raise(SysService as IExManagement).CreateSysEx('设置表格列[' + ADBName + ']数据错误,请设置表格列字段!');
end;
end;
end;
procedure TGridItem.SetGoToNextCellOnEnter(ANextCellOnEnter: Boolean);
begin
FGridTV.OptionsBehavior.FocusCellOnCycle := ANextCellOnEnter; //切换时可以循环
FGridTV.OptionsBehavior.GoToNextCellOnEnter := ANextCellOnEnter; //通过回车切换单元格
end;
function TGridItem.SelectedRowCount: Integer;
begin
Result := FGridTV.Controller.SelectedRowCount;
end;
procedure TGridItem.MultiSelect(AMultiSelect: Boolean);
begin
FGridTV.OptionsSelection.MultiSelect := AMultiSelect;
end;
procedure TGridItem.GridEditKeyPressEvent(Sender: TcxCustomGridTableView;
AItem: TcxCustomGridTableItem; AEdit: TcxCustomEdit; var Key: Char);
var
i: Integer;
aColInfo: TColInfo;
begin
if Assigned(FOldGridEditKeyPress) then FOldGridEditKeyPress(Sender, AItem, AEdit, Key);
if key = #13 then Exit;
for i := 0 to Length(FColList) - 1 do
begin
aColInfo := FColList[i];
if aColInfo.FGridColumn = AItem then
begin
if aColInfo.FColShowType in [cfInt, cfPlusInt] then //整数的时候
begin
if not (key in ['0'..'9', #8]) then
begin
key := #0;
end;
end
else if aColInfo.FColShowType in [cfFloat, cfPlusFloat, cfQty, cfPrice, cfTotal, cfDiscount] then
begin
if not (key in ['0'..'9', #8, '.']) then
begin
key := #0;
end;
end
else if aColInfo.FColShowType in [cfDate, cfTime, cfDatime] then
begin
if not (key in ['0'..'9', #8, '.', '-']) then
begin
key := #0;
end;
end;
Break;
end;
end;
end;
procedure TGridItem.ClearData;
begin
FGridTV.DataController.RecordCount := 0;
FGridTV.DataController.RecordCount := MaxRowCount;
end;
procedure TGridItem.GridColEditValueChanged(Sender: TObject);
var
i, j, aIndex, aArgsIndex: Integer;
aExpression, aExpFieldName, aFieldName, aFormula, aSetFied: string;
aRow, aCol: Integer;
aParamValue: Variant;
aCalc: TCalcExpress;
aArgs: array[0..100] of Extended; // array of arguments - variable values
aVariables: TStringList;
begin
aRow := RowIndex;
if (aRow < GetFirstRow) or (aRow > GetLastRow) then Exit;
GridPost();
//计算公式
for i := 0 to Length(FColList) - 1 do
begin
if FColList[i].FGridColumn <> FGridTV.Controller.FocusedColumn then Continue;
aExpression := Trim(FColList[i].FExpression);
if aExpression <> EmptyStr then
begin
aSetFied := Copy(aExpression, 1, Pos('=', aExpression) - 1);
aExpression := Copy(aExpression, Pos('=', aExpression) + 1, Length(aExpression));
aFormula := aExpression;
aArgsIndex := 0;
aVariables := TStringList.Create;
try
for j := 0 to Length(FColList) - 1 do
begin
aFieldName := FColList[j].FFieldName;
aExpFieldName := '[' + aFieldName + ']';
aIndex := Pos(aExpFieldName, aExpression);
if aIndex > 0 then
begin
aParamValue := GetCellValue(aFieldName, aRow);
if VarIsNull(aParamValue) then Exit;
aVariables.Add(aFieldName);
aArgs[aArgsIndex] := aParamValue;
Inc(aArgsIndex);
end;
end;
aFormula := StringReplace(aFormula, '[', '', [rfReplaceAll]);
aFormula := StringReplace(aFormula, ']', '', [rfReplaceAll]);
aCalc := TCalcExpress.Create;
try
aCalc.Formula := aFormula;
aCalc.Variables := aVariables;
try
SetCellValue(aSetFied, aRow, aCalc.calc(aArgs));
except
SetCellValue(aSetFied, aRow, 0);
end;
// SetCellValue(FColList[i].FFieldName, aRow, aCalc.calc(aArgs));
finally
aCalc.Free;
end;
finally
aVariables.Free;
end;
end;
end;
end;
procedure TGridItem.InitExpression;
var
i, j, aIndex: Integer;
aExpression, aFieldName: string;
begin
//设置公式
for i := 0 to Length(FColList) - 1 do
begin
aExpression := Trim(FColList[i].FExpression);
if aExpression <> EmptyStr then
begin
FColList[i].FGridColumn.Properties.OnEditValueChanged := GridColEditValueChanged;
for j := 0 to Length(FColList) - 1 do
begin
aFieldName := FColList[j].FFieldName;
aFieldName := '[' + aFieldName + ']';
aIndex := Pos(aFieldName, aExpression);
if aIndex > 0 then
begin
FColList[j].FGridColumn.Properties.OnEditValueChanged := GridColEditValueChanged;
end;
end;
end;
end;
end;
procedure TGridItem.GridPost;
begin
FGridTV.DataController.Post; //必须先提交,不然修改和取值的数据会乱
end;
function TGridItem.FindColByCaption(AShowCaption: string): TColInfo;
var
i: Integer;
aCaption: string;
begin
Result := nil;
for i := 0 to Length(FColList) - 1 do
begin
aCaption := Trim(FColList[i].GridColumn.Caption);
if AShowCaption = aCaption then
begin
Result := FColList[i];
Exit;
end;
end;
end;
function TGridItem.FindColByFieldName(AFieldName: string): TColInfo;
var
i: Integer;
aColDBName: string;
begin
Result := nil;
for i := 0 to Length(FColList) - 1 do
begin
aColDBName := Trim(FColList[i].FFieldName);
if AFieldName = aColDBName then
begin
Result := FColList[i];
Exit;
end;
end;
end;
function TGridItem.LoadUpDownData(ALoadUp: Boolean): Boolean;
var
aRowIndex: Integer;
aTypeId, aSonnum, aParTypeId: string;
begin
Result := False;
if GetBaseTypesLevels(BasicType) <= 1 then Exit;
aRowIndex := GetRowIndex;
if (aRowIndex >= GetFirstRow) and (aRowIndex <= GetLastRow) then
begin
aTypeId := GetCellValue(GetBaseTypeid(BasicType), aRowIndex);
if StringEmpty(aTypeId) then Exit;
if ALoadUp then
begin
//进入上一级
aParTypeId := FModelFun.GetParIdFromId(BasicType, aTypeId);
if aParTypeId = ROOT_ID then Exit;
aTypeId := FModelFun.GetParIdFromId(BasicType, aParTypeId);
end
else
begin
//进入下一级
aSonnum := FModelFun.GetLocalValue(BasicType, GetBaseTypeSonnumStr(BasicType), aTypeId);
if StringToInt(aSonnum) <= 0 then Exit;
end;
end;
if Assigned(OnLoadUpDownData) then
begin
OnLoadUpDownData(Self, aTypeId);
end;
Result := True;
end;
procedure TGridItem.AddFooterSummary(AColInfo: TColInfo;
ASummaryKind: TcxSummaryKind);
var
aFooter: TcxDataSummaryItem;
begin
aFooter := FGridTV.DataController.Summary.FooterSummaryItems.Add;
aFooter.Kind := ASummaryKind;
TcxGridTableSummaryItem(aFooter).Column := AColInfo.GridColumn;
FGridTV.OptionsView.Footer := True;
end;
function TGridItem.AddRow: Integer;
var
aRecordCount: Integer;
begin
aRecordCount := FGridTV.DataController.RecordCount + 1;
if aRecordCount > MaxRowCount then
begin
raise(SysService as IExManagement).CreateSysEx('超过表格最大行数,不能在增加行!');
end;
FGridTV.DataController.RecordCount := aRecordCount;
Result := aRecordCount - 1;
end;
function TGridItem.RecordCount: Integer;
begin
Result := FGridTV.DataController.RecordCount;
end;
procedure TGridItem.DeleteRow(ARow: Integer);
begin
FGridTV.DataController.DeleteRecord(ARow);
end;
function TGridItem.AddBtnCol(AFileName, AShowCaption, ABtnCaption: string; AClickEvent: TcxEditButtonClickEvent): TColInfo;
var
aCol: TcxGridColumn;
aColInfo: TColInfo;
begin
aCol := FGridTV.CreateColumn;
aCol.Caption := AShowCaption;
aCol.PropertiesClass := TcxButtonEditProperties;
aCol.Options.ShowEditButtons := isebAlways;
TcxButtonEditProperties(aCol.Properties).Buttons[0].Caption := ABtnCaption;
TcxButtonEditProperties(aCol.Properties).Buttons[0].Kind := bkText;
TcxButtonEditProperties(aCol.Properties).OnButtonClick := AClickEvent;
aColInfo := TColInfo.Create(aCol, AFileName);
SetLength(FColList, Length(FColList) + 1);
FColList[Length(FColList) - 1] := aColInfo;
Result := aColInfo;
end;
procedure TGridItem.SetReadOnly(AReadOnly: Boolean);
begin
FGridTV.OptionsData.Editing := not AReadOnly;
end;
{ TGridControl }
procedure TGridControl.AddGradItem(AGridItem: TGridItem);
begin
end;
constructor TGridControl.Create;
begin
end;
destructor TGridControl.Destroy;
begin
inherited;
end;
{ TColInfo }
procedure TColInfo.AddExpression(AExpression: string);
begin
FExpression := Trim(AExpression);
end;
constructor TColInfo.Create(AGridColumn: TcxGridColumn;
AFieldName: string);
begin
FGridColumn := AGridColumn;
FFieldName := AFieldName;
FBasicType := btNo;
end;
destructor TColInfo.Destroy;
begin
if Assigned(FDataToDisplay) then FDataToDisplay.Free;
inherited;
end;
procedure TColInfo.GetDisplayText(Sender: TcxCustomGridTableItem;
ARecord: TcxCustomGridRecord; var AText: string);
var
aDataIndex: Integer;
begin
aDataIndex := FDataToDisplay.IndexOfName(AText);
if aDataIndex <> -1 then
begin
AText := FDataToDisplay.ValueFromIndex[aDataIndex];
end;
end;
procedure TColInfo.SetDisplayText(ADisplayText: TIDDisplayText);
begin
if not Assigned(FDataToDisplay) then
begin
FDataToDisplay := TStringList.Create;
FGridColumn.OnGetDisplayText := GetDisplayText;
end;
FDataToDisplay.AddStrings(ADisplayText);
end;
initialization
FColCfg := TGridControl.Create;
finalization
FColCfg.Free;
end.
|
// Implementation of Gauss' method for linear systems
unit Gauss;
interface
const
MAXSIZE = 10;
type
TVector = array [1..MAXSIZE] of Real;
TMatrix = array [1..MAXSIZE] of TVector;
TError = procedure (const E: string);
procedure SolveLinearSystem(var T: TMatrix; var x: TVector; m: Integer; Error: TError);
implementation
procedure TriangularizeMatrix(var T: TMatrix; m: Integer; Error: TError);
var
i, j, k: Integer;
r: Real;
begin
for k := 1 to m - 1 do
for i := k + 1 to m do
begin
if T[k, k] = 0 then Error('Diagonal element is zero');
r := -T[i, k] / T[k, k];
for j := k to m + 1 do
T[i, j] := T[i, j] + r * T[k, j];
end;
end;
procedure SolveLinearSystem(var T: TMatrix; var x: TVector; m: Integer; Error: TError);
var
i, j: Integer;
s: Real;
begin
TriangularizeMatrix(T, m, Error);
for i := m downto 1 do
begin
s := T[i, m + 1];
for j := m downto i + 1 do
s := s - T[i, j] * x[j];
if T[i, i] = 0 then Error('Singular matrix');
x[i] := s / T[i, i];
end; // for
end;
end.
|
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* 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 TurboPower Abbrevia
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1997-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* ABBREVIA: DGABOUT.PAS *}
{* Copyright (c) TurboPower Software Co 1997 *}
{* All rights reserved. *}
{*********************************************************}
{* ABBREVIA Example program file *}
{*********************************************************}
unit dgAbout;
interface
uses
Windows, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ExtCtrls;
type
TdlgAboutBox = class(TForm)
Panel1: TPanel;
ProgramIcon: TImage;
Label7: TLabel;
Label8: TLabel;
Panel2: TPanel;
lnTitleShadow: TLabel;
lblTitle: TLabel;
Label5: TLabel;
Label86: TLabel;
Label85: TLabel;
Label84: TLabel;
OKButton: TButton;
Version: TLabel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label6: TLabel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
dlgAboutBox: TdlgAboutBox;
implementation
{$R *.DFM}
uses
AbConst;
procedure TdlgAboutBox.FormCreate(Sender: TObject);
begin
Version.Caption := 'Abbrevia ' + AbVersion;
end;
end.
|
{------------------------------------------------------------------------------}
{ 单元名称: Magiceff.pas }
{ }
{ 单元作者: 清清 (QQ:272987775 Email:272987775@QQ.com) }
{ 创建日期: 2007-10-28 20:30:00 }
{ }
{ 功能介绍: }
{ 传奇2 客户端魔法效果的绘制与表现,当然也不包括魔法伤害实现 }
{ }
{ 使用说明: }
{ }
{ }
{ }
{ 更新历史: }
{ }
{ 尚存问题: }
{ }
{ }
{------------------------------------------------------------------------------}
unit magiceff;
interface
uses
Windows, Grobal2, DxDraws, CliUtil, ClFunc, HUtil32, WIl, SysUtils;
const
FLYBASE = 10;
EXPLOSIONBASE = 170;
FLYOMAAXEBASE = 447;
THORNBASE = 2967;
ARCHERBASE = 2607;
ARCHERBASE2 = 272; //2609;
FIREGUNFRAME = 6;
MAXEFFECT = 101;//最大效果魔法效果图数 20071028 update
{EffectBase类:保存对应魔法效果IDX的值对应WIL文件 图片的数值}
EffectBase: array[0..MAXEFFECT-1] of integer = (
0,{1}
200,{2}
400,{3}
600,{4}
0,{5}
900,{6}
920,{7}
940,{8}
20,{9}
940,{10}
940,{11}
940,{12}
0,{13}
1380,{14}
1500,{15}
1520,{16}
940,{17}
1560,{18}
1590,{19}
1620,{20}
1650,{21}
1680,{22}
0,{23}
0,{24}
0,{25}
3960,{26}
1790,{27}
0,{28}
3880,{29}
3920,{30}
3840,{31}
0,{32}
40,{33}
130, {34}
160,{35}
190,{36}
0,{37}
210,{38}
400,{39}
600,{40}
1260,{41} //召唤月灵
//650,{42}
0,{42} //分身术 20080415
710,{43}
740,{44}
910,{45}
940,{46}
990,{47}
1040,{48}
1110,{49}
0,{50}
630,{51} //流星火雨 20080510
710,{52} //四级魔法盾
0,{53}
0,{54}
0,{55}
0,{56}
0,{57}
0,{58}
0,{59}
10,{60} //破魂斩
440,{61} //劈星斩
270,{62} //雷霆一击
610,{63} //噬魂沼泽
210,{64} //末日审判
540,{65} //火龙气焰
690,{66}
0,{67}
0,{68}
0,{69}
0,{70}
0,{71}
0,{72}
0,{73}
0,{74}
0,{75}
0,{76}
0,{77}
0,{78}
0,{79}
0,{80}
0,{81}
0,{82}
0,{83}
0,{84}
0,{85}
0,{86}
0,{87}
0,{88}
0,{89}
0,{90}
790,{91} //护体神盾
0,{92}
0,{93}
0,{94}
0,{95}
0,{96}
0,{97}
0,{98}
0,{99}
120,{100} //4级灵魂火符 20080111
80{101} //4级灭天火 20080111
);
MAXHITEFFECT = 12;//最大效果攻击效果图数 20080212 update
//实体攻击 比如 武士攻击的烈火,半月
HitEffectBase: array[0..MAXHITEFFECT-1] of integer = (
800,{1} //好攻杀
1410,{2} //刺杀
1700,{3} //半月
3480,{4} //烈火
//510,
3390,{5} //
40, {6} //抱月
470,{220} {7} //开天斩重击
740, {8} //
0,{9} //4级烈火 20080112
630,{10} //开天斩轻击 2008.02.12
510,{11} //逐日剑法 20080511
310{12} //雷霆一击 战士效果
);
MAXMAGICTYPE = 16;
type
TMagicType = (mtReady,{准备} mtFly,{飞} mtExplosion{爆发},
{魔法类型} mtFlyAxe{飞斧}, mtFireWind{火风}, mtFireGun{火炮},
mtLightingThunder{照明雷}, mtThunder{雷1}, mtExploBujauk,
mtBujaukGroundEffect, mtKyulKai, mtFlyArrow,
mt12, mt13{怪物魔法}, mt14,
mt15, mt16, mtRedThunder{红色雷电}, mtLava{岩浆}
);
TUseMagicInfo = record
ServerMagicCode: integer;
MagicSerial: integer;
Target: integer; //recogcode
EffectType: TMagicType;
EffectNumber: integer;
TargX: integer;
TargY: integer;
Recusion: Boolean;
AniTime: integer;
end;
PTUseMagicInfo = ^TUseMagicInfo;
TMagicEff = class//Size 0xC8
m_boActive: Boolean; //0x04 活动的
ServerMagicId: integer; //0x08
MagOwner: TObject; //0x0C
TargetActor: TObject; //0x10 目标
ImgLib: TWMImages; //0x14
EffectBase: integer; //0x18
MagExplosionBase: integer; //0x1C
px, py: integer; //0x20 0x24
RX, RY: integer; //0x28 0x2C
Dir16, OldDir16: byte; //0x30 0x31
TargetX, TargetY: integer; //0x34 0x38
TargetRx, TargetRy: integer; //0x3C 0x40
FlyX, FlyY, OldFlyX, OldFlyY: integer; //0x44 0x48 0x4C 0x50
FlyXf, FlyYf: Real; //0x54 0x5C
Repetition: Boolean; //0x64 //重复
FixedEffect: Boolean; //0x65//固定结果
MagicType: integer; //0x68
NextEffect: TMagicEff; //0x6C
ExplosionFrame: integer; //0x70
NextFrameTime: integer; //0x74
Light: integer; //0x78
n7C:Integer;
bt80:Byte;
bt81:Byte;
start: integer; //0x84 //开始浈
curframe: integer; //0x88
frame: integer; //0x8C //有效帧
private
m_dwFrameTime: longword; //0x90
m_dwStartTime: longword; //0x94
repeattime: longword; //0x98 馆汗 局聪皋捞记 矫埃 (-1: 拌加)
steptime: longword; //0x9C
fireX, fireY: integer; //0xA0 0xA4
firedisX, firedisY: integer; //0xA8 0xAC
newfiredisX, newfiredisY: integer;//0xB0 0xB4
FireMyselfX, FireMyselfY: integer;//0xB8 0xBC
prevdisx, prevdisy: integer; //0xC0 0xC4
protected
procedure GetFlyXY (ms: integer; var fx, fy: integer);
public
constructor Create (id, effnum, sx, sy, tx, ty: integer; mtype: TMagicType; Recusion: Boolean; anitime: integer);
destructor Destroy; override;
function Run: Boolean; dynamic; //false:场车澜.
function Shift: Boolean; dynamic;
procedure DrawEff (surface: TDirectDrawSurface); dynamic;
end;
TFlyingAxe = class (TMagicEff)
FlyImageBase: integer;
ReadyFrame: integer;
public
constructor Create (id, effnum, sx, sy, tx, ty: integer; mtype: TMagicType; Recusion: Boolean; anitime: integer);
procedure DrawEff (surface: TDirectDrawSurface); override;
end;
TFlyingBug = class (TMagicEff)//Size 0xD0
FlyImageBase: integer;//0xC8
ReadyFrame: integer;//0xCC
public
constructor Create (id, effnum, sx, sy, tx, ty: integer; mtype: TMagicType; Recusion: Boolean; anitime: integer);
procedure DrawEff (surface: TDirectDrawSurface); override;
end;
TFlyingArrow = class (TFlyingAxe)
public
procedure DrawEff (surface: TDirectDrawSurface); override;
end;
TFlyingFireBall = class (TFlyingAxe) //0xD0
public
procedure DrawEff (surface: TDirectDrawSurface); override;
end;
TCharEffect = class (TMagicEff)
public
constructor Create (effbase, effframe: integer; target: TObject);
function Run: Boolean; override; //false:场车澜.
procedure DrawEff (surface: TDirectDrawSurface); override;
end;
TMapEffect = class (TMagicEff)
public
RepeatCount: integer;
constructor Create (effbase, effframe: integer; x, y: integer);
function Run: Boolean; override; //false:场车澜.
procedure DrawEff (surface: TDirectDrawSurface); override;
end;
TScrollHideEffect = class (TMapEffect)
public
constructor Create (effbase, effframe: integer; x, y: integer; target: TObject);
function Run: Boolean; override;
end;
TLightingEffect = class (TMagicEff)
public
constructor Create (effbase, effframe: integer; x, y: integer);
function Run: Boolean; override;
end;
TFireNode = record
x: integer;
y: integer;
firenumber: Integer;
end;
TFireGunEffect = class (TMagicEff)
public
OutofOil: Boolean;
firetime: longword;
FireNodes: array[0..FIREGUNFRAME-1] of TFireNode;
constructor Create (effbase, sx, sy, tx, ty: integer);
function Run: Boolean; override;
procedure DrawEff (surface: TDirectDrawSurface); override;
end;
{******************************************************************************}
//分身术
TfenshenThunder = class (TMagicEff)
private
Rx,Ry,dir:Integer;
public
constructor Create (effbase, sx, sy, tx, ty: integer; aowner: TObject);
procedure DrawEff (surface: TDirectDrawSurface); override;
end;
{******************************************************************************}
TThuderEffect = class (TMagicEff)
public
constructor Create (effbase, tx, ty: integer; target: TObject);
procedure DrawEff (surface: TDirectDrawSurface); override;
end;
TLightingThunder = class (TMagicEff)
public
constructor Create (effbase, sx, sy, tx, ty: integer; target: TObject);
procedure DrawEff (surface: TDirectDrawSurface); override;
end;
TPHHitEffect = class (TMagicEff) //破魂斩类 20080226
private
Rx, Ry: Integer;
public
constructor Create (effbase, sx, sy, tx, ty:Integer; aowner: TObject);
procedure DrawEff (surface: TdirectDrawSurface);override;
end;
TExploBujaukEffect = class (TMagicEff)
public
constructor Create (effbase, sx, sy, tx, ty: integer; target: TObject);
procedure DrawEff (surface: TDirectDrawSurface); override;
end;
TBujaukGroundEffect = class (TMagicEff)//Size 0xD0
public
MagicNumber: integer; //0xC8
BoGroundEffect: Boolean; //0xCC
constructor Create (effbase, magicnumb, sx, sy, tx, ty: integer);
function Run: Boolean; override;
procedure DrawEff (surface: TDirectDrawSurface); override;
end;
TNormalDrawEffect = class (TMagicEff)//Size 0xCC
boC8:Boolean;
public
constructor Create(XX,YY:Integer;WmImage:TWMImages;effbase,nX:Integer;frmTime:LongWord;boFlag:Boolean);
function Run: Boolean; override;
procedure DrawEff (surface: TDirectDrawSurface); override;
end;
TRedThunderEffect = class (TMagicEff)
n0:integer;
public
constructor Create (effbase, tx, ty: integer; target: TObject);
procedure DrawEff (surface: TDirectDrawSurface); override;
end;
TLavaEffect = class (TMagicEff)
public
constructor Create (effbase, tx, ty: integer; target: TObject);
procedure DrawEff (surface: TDirectDrawSurface); override;
end;
TFairyEffect = class (TMagicEff) //月灵重击
public
constructor Create (effbase, tx, ty: integer; target: TObject);
procedure DrawEff (surface: TDirectDrawSurface); override;
end;
TObjectEffects = class (TMagicEff)
ObjectID : TObject;
boC8:Boolean;
public
constructor Create(ObjectiD2:TObject;WmImage:TWMImages;effbase,nX:Integer;frmTime:LongWord;boFlag:Boolean);
function Run: Boolean; override;
procedure DrawEff (surface: TDirectDrawSurface); override;
end;
procedure GetEffectBase (mag, mtype: integer; var wimg: TWMImages; var idx: integer);
implementation
uses
ClMain, Actor, SoundUtil, MShare;
{------------------------------------------------------------------------------}
//取得魔法效果所在图库(20071028)
//GetEffectBase(mag, mtype,wimg,idx)
//参数:mag--即技能数据表中的Effect字段(魔法效果),如劈星斩此处为61-1
// mtype--无实际意思的参数,此处 取值
// wimg--TWMImages类,即图片显示的地方
// idx---在对应的WIL文件 里,图片所处的位置
//
//***{EffectBase类:保存对应IDX的值对应WIL文件 图片的数值}*** 例: idx := EffectBase[mag];
{------------------------------------------------------------------------------}
procedure GetEffectBase (mag, mtype: integer; var wimg: TWMImages; var idx: integer);
begin
wimg := nil;
idx := 0;
case mtype of
0: begin //魔法效果
case mag of
59: wimg := g_WMagic4Images;
60,61,62,63,64: begin //英雄合击-劈星斩,雷霆一击,噬魂沼泽,末日审判,火龙气焰
wimg := g_WMagic4Images;
if mag in [0..MAXEFFECT-1] then
idx := EffectBase[mag];
end;
8,27,33..35,37..39,42,43,44,45{46}..48: begin
wimg := g_WMagic2Images;
if mag in [0..MAXEFFECT-1] then
idx := EffectBase[mag];
end;
31: begin
wimg := {FrmMain.WMon21Img20080720注释}g_WMonImagesArr[20];
if mag in [0..MAXEFFECT-1] then
idx := EffectBase[mag];
end;
36: begin
wimg := {FrmMain.WMon22Img20080720注释}g_WMonImagesArr[21];
if mag in [0..MAXEFFECT-1] then
idx := EffectBase[mag];
end;
40: begin //召唤月灵
wimg := {FrmMain.WMon18Img20080720注释}g_WMonImagesArr[17];
if mag in [0..MAXEFFECT-1] then
idx := EffectBase[mag];
end;
41: begin //分身术
wimg := g_WMagic5Images;
if mag in [0..MAXEFFECT-1] then
idx := EffectBase[mag];
end;
50,51: begin //流星火雨 20080510
wimg := g_WMagic6Images;
if mag in [0..MAXEFFECT-1] then
idx := EffectBase[mag];
end;
65: begin //酒气护体
wimg := g_WMain2Images;
if mag in [0..MAXEFFECT-1] then
idx := EffectBase[mag];
end;
80..82: begin
wimg := {FrmMain.WDragonImg}g_WDragonImages;
if mag = 80 then begin
if g_Myself.m_nCurrX >= 84 then begin
idx:=130;
end else begin
idx:=140;
end;
end;
if mag = 81 then begin
if (g_Myself.m_nCurrX >= 78) and (g_Myself.m_nCurrY >= 48) then begin
idx:=150;
end else begin
idx:=160;
end;
end;
if mag = 82 then begin
idx:=180;
end;
end;
89: begin
wimg := {FrmMain.WDragonImg}g_WDragonImages;
idx:=350;
end;
90: begin //护体神盾
wimg := g_WMagic5Images;
if mag in [0..MAXEFFECT-1] then
idx := EffectBase[mag];
end;
99: begin //4级火符 20080111
wimg := g_WMagic6Images;
if mag in [0..MAXEFFECT-1] then
idx := EffectBase[mag];
end;
100: begin
wimg := g_WMagic6Images;
if mag in [0..MAXEFFECT-1] then
idx := EffectBase[mag];
end;
else begin
wimg := g_WMagicImages;
if mag in [0..MAXEFFECT-1] then
idx := EffectBase[mag];
end;
end;
end;
1: begin //攻击效果
wimg := g_WMagicImages;
if mag in [0..MAXHITEFFECT-1] then begin
idx := HitEffectBase[mag];
end;
//if mag = 3 then wimg := g_WMagic6Images;
if mag = 5 then wimg := g_WMagic2Images;
if mag = 6 then wimg := g_Wmagic5Images; //开天斩重击
if mag = 9 then wimg := g_Wmagic5Images; //开天斩轻击
if mag = 7 then wimg := g_WMagic2Images; //龙影剑法
if mag in [8,10] then wimg := g_WMagic6Images; //4级烈火 20080112
if mag = 11 then wimg := g_Wmagic4Images; //雷霆一击战士效果 20080611
end;
end;
end;
constructor TMagicEff.Create (id, effnum, sx, sy, tx, ty: integer; mtype: TMagicType; Recusion: Boolean; anitime: integer);
var
tax, tay: integer;
begin
ImgLib := g_WMagicImages; //扁夯
case mtype of
mtReady: begin
start := 0;
frame := -1;
ExplosionFrame := 20;
curframe := start;
FixedEffect := TRUE;
Repetition := FALSE;
end;
mtFly,mtBujaukGroundEffect,mtExploBujauk: begin //里面有火球术 2007.10.31
start:=0;
frame:=6;
curframe:=start;
FixedEffect:=False;
Repetition:=Recusion;
ExplosionFrame:=10;
if id = 38 then frame:=10;
if id = 39 then begin
frame:=4;
ExplosionFrame:=8;
end;
if (id - 81 - 3) < 0 then begin
bt80:=1;
Repetition:=True;
if id = 81 then begin
if g_MySelf.m_nCurrX >= 84 then begin
EffectBase:=130;
end else begin
EffectBase:=140;
end;
bt81:=1;
end;
if id = 82 then begin
if (g_MySelf.m_nCurrX >= 78) and (g_MySelf.m_nCurrY >= 48) then begin
EffectBase:=150;
end else begin
EffectBase:=160;
end;
bt81:=2;
end;
if id = 83 then begin
EffectBase:=180;
bt81:=3;
end;
start:=0;
frame:=10;
MagExplosionBase:=190;
ExplosionFrame:=10;
end;
end;
mt12: begin
start:=0;
frame:=6;
curframe:=start;
FixedEffect:=False;
Repetition:=Recusion;
ExplosionFrame:=1;
end;
mt13: begin
start:=0;
frame:=20;
curframe:=start;
FixedEffect:=True;
Repetition:=False;
ExplosionFrame:=20;
ImgLib:={FrmMain.WMon21Img20080720注释}g_WMonImagesArr[20];
end;
mtExplosion,mtThunder,mtLightingThunder,mtRedThunder,mtLava: begin
start := 0;
frame := -1;
ExplosionFrame := 10;
curframe := start;
FixedEffect := TRUE;
Repetition := FALSE;
if id = 80 then begin
bt80:=2;
case Random(6) of
0:begin
EffectBase:=230;
end;
1:begin
EffectBase:=240;
end;
2:begin
EffectBase:=250;
end;
3:begin
EffectBase:=230;
end;
4:begin
EffectBase:=240;
end;
5:begin
EffectBase:=250;
end;
end;
Light:=4;
ExplosionFrame:=5;
end;
if id = 70 then begin
bt80:=3;
case Random(3) of
0:begin
EffectBase:=400;
end;
1:begin
EffectBase:=410;
end;
2:begin
EffectBase:=420;
end;
end;
Light:=4;
ExplosionFrame:=5;
end;
if id = 71 then begin
bt80:=3;
ExplosionFrame:=20;
end;
if id = 72 then begin
bt80:=3;
Light:=3;
ExplosionFrame:=10;
end;
if id = 73 then begin
bt80:=3;
Light:=5;
ExplosionFrame:=20;
end;
if id = 74 then begin
bt80:=3;
Light:=4;
ExplosionFrame:=35;
end;
if id = 90 then begin
EffectBase:=350;
MagExplosionBase:=350;
ExplosionFrame:=30;
end;
end;
mt14: begin
start:=0;
frame:=-1;
curframe:=start;
FixedEffect:=True;
Repetition:=False;
ImgLib:=g_WMagic2Images;
end;
mtFlyAxe: begin
start := 0;
frame := 3;
curframe := start;
FixedEffect := FALSE;
Repetition := Recusion;
ExplosionFrame := 3;
end;
mtFlyArrow: begin
start := 0;
frame := 1;
curframe := start;
FixedEffect := FALSE;
Repetition := Recusion;
ExplosionFrame := 1;
end;
mt15: begin
start := 0;
frame := 6;
curframe := start;
FixedEffect := FALSE;
Repetition := Recusion;
ExplosionFrame := 2;
end;
mt16: begin
start := 0;
frame := 1;
curframe := start;
FixedEffect := FALSE;
Repetition := Recusion;
ExplosionFrame := 1;
end;
else begin
end;
end;
n7C:=0;
ServerMagicId := id; //辑滚狼 ID
EffectBase := effnum; //MagicDB - Effect
TargetX := tx; // " target x
TargetY := ty; // " target y
if bt80 =1 then begin
if id = 81 then begin
dec(sx,14);
inc(sy,20);
end;
if id = 81 then begin
dec(sx,70);
dec(sy,10);
end;
if id = 83 then begin
dec(sx,60);
dec(sy,70);
end;
PlaySound(8208);
end;
fireX := sx; //
fireY := sy; //
FlyX := sx; //
FlyY := sy;
OldFlyX := sx;
OldFlyY := sy;
FlyXf := sx;
FlyYf := sy;
FireMyselfX := g_MySelf.m_nRx * UNITX + g_MySelf.m_nShiftX;
FireMyselfY := g_MySelf.m_nRy * UNITY + g_MySelf.m_nShiftY;
if bt80 = 0 then begin
MagExplosionBase := EffectBase + EXPLOSIONBASE;
end;
light := 1;
if fireX <> TargetX then tax := abs(TargetX-fireX)
else tax := 1;
if fireY <> TargetY then tay := abs(TargetY-fireY)
else tay := 1;
if abs(fireX-TargetX) > abs(fireY-TargetY) then begin
firedisX := Round((TargetX-fireX) * (500 / tax));
firedisY := Round((TargetY-fireY) * (500 / tax));
end else begin
firedisX := Round((TargetX-fireX) * (500 / tay));
firedisY := Round((TargetY-fireY) * (500 / tay));
end;
NextFrameTime := 50;
m_dwFrameTime := GetTickCount;
m_dwStartTime := GetTickCount;
steptime := GetTickCount;
RepeatTime := anitime;
Dir16 := GetFlyDirection16 (sx, sy, tx, ty);
OldDir16 := Dir16;
NextEffect := nil;
m_boActive := TRUE;
prevdisx := 99999;
prevdisy := 99999;
end;
destructor TMagicEff.Destroy;
begin
inherited Destroy;
end;
function TMagicEff.Shift: Boolean;
function OverThrough (olddir, newdir: integer): Boolean;
begin
Result := FALSE;
if abs(olddir-newdir) >= 2 then begin
Result := TRUE;
if ((olddir=0) and (newdir=15)) or ((olddir=15) and (newdir=0)) then
Result := FALSE;
end;
end;
var
{rrx, rry,} ms, stepx, stepy: integer;
tax, tay, shx, shy, passdir16: integer;
crash: Boolean;//碰撞
stepxf, stepyf: Real;
begin
Result := TRUE;
if Repetition then begin
if GetTickCount - steptime > longword(NextFrameTime) then begin
steptime := GetTickCount;
Inc (curframe);
if curframe > start+frame-1 then
curframe := start;
end;
end else begin
if (frame > 0) and (GetTickCount - steptime > longword(NextFrameTime)) then begin
steptime := GetTickCount;
Inc (curframe);
if curframe > start+frame-1 then begin
curframe := start+frame-1;
Result := FALSE;
end;
end;
end;
if (not FixedEffect) then begin //如果为不固定的结果
crash := FALSE;
if TargetActor <> nil then begin
ms := GetTickCount - m_dwFrameTime; //捞傈 瓤苞甫 弊赴饶 倔付唱 矫埃捞 汝范绰瘤?
m_dwFrameTime := GetTickCount;
//TargetX, TargetY 犁汲沥
PlayScene.ScreenXYfromMCXY (TActor(TargetActor).m_nRx,
TActor(TargetActor).m_nRy,
TargetX,
TargetY);
shx := (g_MySelf.m_nRx * UNITX + g_MySelf.m_nShiftX) - FireMyselfX;
shy := (g_MySelf.m_nRy * UNITY + g_MySelf.m_nShiftY) - FireMyselfY;
TargetX := TargetX + shx;
TargetY := TargetY + shy;
//货肺款 鸥百阑 谅钎甫 货肺 汲沥茄促.
if FlyX <> TargetX then tax := abs(TargetX-FlyX)
else tax := 1;
if FlyY <> TargetY then tay := abs(TargetY-FlyY)
else tay := 1;
if abs(FlyX-TargetX) > abs(FlyY-TargetY) then begin
newfiredisX := Round((TargetX-FlyX) * (500 / tax));
newfiredisY := Round((TargetY-FlyY) * (500 / tax));
end else begin
newfiredisX := Round((TargetX-FlyX) * (500 / tay));
newfiredisY := Round((TargetY-FlyY) * (500 / tay));
end;
if firedisX < newfiredisX then firedisX := firedisX + _MAX(1, (newfiredisX - firedisX) div 10);
if firedisX > newfiredisX then firedisX := firedisX - _MAX(1, (firedisX - newfiredisX) div 10);
if firedisY < newfiredisY then firedisY := firedisY + _MAX(1, (newfiredisY - firedisY) div 10);
if firedisY > newfiredisY then firedisY := firedisY - _MAX(1, (firedisY - newfiredisY) div 10);
stepxf := (firedisX/700) * ms;
stepyf := (firedisY/700) * ms;
FlyXf := FlyXf + stepxf;
FlyYf := FlyYf + stepyf;
FlyX := Round (FlyXf);
FlyY := Round (FlyYf);
//规氢 犁汲沥
// Dir16 := GetFlyDirection16 (OldFlyX, OldFlyY, FlyX, FlyY);
OldFlyX := FlyX;
OldFlyY := FlyY;
//烹苞咯何甫 犬牢窍扁 困窍咯
passdir16 := GetFlyDirection16 (FlyX, FlyY, TargetX, TargetY);
//DebugOutStr (IntToStr(prevdisx) + ' ' + IntToStr(prevdisy) + ' / ' + IntToStr(abs(TargetX-FlyX)) + ' ' + IntToStr(abs(TargetY-FlyY)) + ' ' +
// IntToStr(FlyX) + '.' + IntToStr(FlyY) + ' ' +
// IntToStr(TargetX) + '.' + IntToStr(TargetY));
if ((abs(TargetX-FlyX) <= 15) and (abs(TargetY-FlyY) <= 15)) or
((abs(TargetX-FlyX) >= prevdisx) and (abs(TargetY-FlyY) >= prevdisy)) or
OverThrough(OldDir16, passdir16) then begin
crash := TRUE;
end else begin
prevdisx := abs(TargetX-FlyX);
prevdisy := abs(TargetY-FlyY);
//if (prevdisx <= 5) and (prevdisy <= 5) then crash := TRUE;
end;
OldDir16 := passdir16;
end else begin
ms := GetTickCount - m_dwFrameTime; //瓤苞狼 矫累饶 倔付唱 矫埃捞 汝范绰瘤?
{rrx := TargetX - fireX;
rry := TargetY - fireY; }
stepx := Round ((firedisX/900) * ms);
stepy := Round ((firedisY/900) * ms);
FlyX := fireX + stepx;
FlyY := fireY + stepy;
end;
PlayScene.CXYfromMouseXY (FlyX, FlyY, Rx, Ry);
if crash and (TargetActor <> nil) then begin
FixedEffect := TRUE; //气惯
start := 0;
frame := ExplosionFrame;
curframe := start;
Repetition := FALSE;
//磐瘤绰 荤款靛
PlaySound (TActor(MagOwner).m_nMagicExplosionSound);
end;
//if not Map.CanFly (Rx, Ry) then
// Result := FALSE;
end;
if FixedEffect then begin //固定结果
if frame = -1 then frame := ExplosionFrame;
if TargetActor = nil then begin
FlyX := TargetX - ((g_MySelf.m_nRx * UNITX + g_MySelf.m_nShiftX) - FireMyselfX);
FlyY := TargetY - ((g_MySelf.m_nRy * UNITY + g_MySelf.m_nShiftY) - FireMyselfY);
PlayScene.CXYfromMouseXY (FlyX, FlyY, Rx, Ry);
end else begin
Rx := TActor(TargetActor).m_nRx;
Ry := TActor(TargetActor).m_nRy;
PlayScene.ScreenXYfromMCXY (Rx, Ry, FlyX, FlyY);
FlyX := FlyX + TActor(TargetActor).m_nShiftX;
FlyY := FlyY + TActor(TargetActor).m_nShiftY;
end;
end;
end;
procedure TMagicEff.GetFlyXY (ms: integer; var fx, fy: integer);
var
{rrx, rry,} stepx, stepy: integer;
begin
{rrx := TargetX - fireX;
rry := TargetY - fireY; }
stepx := Round ((firedisX/900) * ms);
stepy := Round ((firedisY/900) * ms);
fx := fireX + stepx;
fy := fireY + stepy;
end;
function TMagicEff.Run: Boolean;
begin
Result := Shift;
if Result then
if GetTickCount - m_dwStartTime > 10000 then //2000 then
Result := FALSE
else Result := TRUE;
end;
{------------------------------------------------------------------------------}
//此过程显示魔法技能飘移过程(20071031)
//DrawEff (surface: TDirectDrawSurface);
//
//***EffectBase:为EffectBase数组里的数***
{------------------------------------------------------------------------------}
procedure TMagicEff.DrawEff (surface: TDirectDrawSurface);
var
img: integer;
d: TDirectDrawSurface;
shx, shy: integer;
ErrorCode: Integer;
begin
try
ErrorCode := 0;
if m_boActive and ((Abs(FlyX-fireX) > 15) or (Abs(FlyY-fireY) > 15) or FixedEffect) then begin
ErrorCode := 1;
shx := (g_MySelf.m_nRx * UNITX + g_MySelf.m_nShiftX) - FireMyselfX;
shy := (g_MySelf.m_nRy * UNITY + g_MySelf.m_nShiftY) - FireMyselfY;
ErrorCode := 2;
if not FixedEffect then begin
ErrorCode := 3;
//与方向有关的魔法效果
img := EffectBase + FLYBASE + Dir16 * 10;
ErrorCode := 4;
d := ImgLib.GetCachedImage (img + curframe, px, py);
ErrorCode := 5;
if d <> nil then begin
DrawBlend (surface,
FlyX + px - UNITX div 2 - shx,
FlyY + py - UNITY div 2 - shy,
d, 1);
end;
ErrorCode := 6;
end else begin
ErrorCode := 7;
//与方向无关的魔法效果(例如爆炸)
img := MagExplosionBase + curframe; //EXPLOSIONBASE;
ErrorCode := 8;
d := ImgLib.GetCachedImage (img, px, py);
ErrorCode := 9;
if d <> nil then begin
DrawBlend (surface,
FlyX + px - UNITX div 2,
FlyY + py - UNITY div 2,
d, 1);
end;
ErrorCode := 10;
end;
end;
except
DebugOutStr ('TMagicEff.DrawEff:'+IntToStr(ErrorCode));
end;
end;
{-----------------------------------------------------------}
// TFlyingAxe : 朝酒啊绰 档尝
{------------------------------------------------------------}
constructor TFlyingAxe.Create (id, effnum, sx, sy, tx, ty: integer; mtype: TMagicType; Recusion: Boolean; anitime: integer);
begin
inherited Create (id, effnum, sx, sy, tx, ty, mtype, Recusion, anitime);
FlyImageBase := FLYOMAAXEBASE;
ReadyFrame := 65;
end;
procedure TFlyingAxe.DrawEff (surface: TDirectDrawSurface);
var
img: integer;
d: TDirectDrawSurface;
shx, shy: integer;
begin
try
if m_boActive and ((Abs(FlyX-fireX) > ReadyFrame) or (Abs(FlyY-fireY) > ReadyFrame)) then begin
shx := (g_MySelf.m_nRx * UNITX + g_MySelf.m_nShiftX) - FireMyselfX;
shy := (g_MySelf.m_nRy * UNITY + g_MySelf.m_nShiftY) - FireMyselfY;
if not FixedEffect then begin
//
img := FlyImageBase + Dir16 * 10;
d := ImgLib.GetCachedImage (img + curframe, px, py);
if d <> nil then begin
surface.Draw (FlyX + px - UNITX div 2 - shx,
FlyY + py - UNITY div 2 - shy,
d.ClientRect, d, TRUE);
end;
end else begin
end;
end;
except
DebugOutStr('TFlyingAxe.DrawEff');
end;
end;
{------------------------------------------------------------}
// TFlyingArrow : 朝酒啊绰 拳混
{------------------------------------------------------------}
procedure TFlyingArrow.DrawEff (surface: TDirectDrawSurface);
var
img: integer;
d: TDirectDrawSurface;
shx, shy: integer;
begin
try
//(**6岿菩摹
if m_boActive and ((Abs(FlyX-fireX) > 40) or (Abs(FlyY-fireY) > 40)) then begin
//*)
(**捞傈
if Active then begin //and ((Abs(FlyX-fireX) > 65) or (Abs(FlyY-fireY) > 65)) then begin
//*)
shx := (g_MySelf.m_nRx * UNITX + g_MySelf.m_nShiftX) - FireMyselfX;
shy := (g_MySelf.m_nRy * UNITY + g_MySelf.m_nShiftY) - FireMyselfY;
if not FixedEffect then begin
//朝酒啊绰芭
img := FlyImageBase + Dir16; // * 10;
d := ImgLib.GetCachedImage (img + curframe, px, py);
//(**6岿菩摹
if d <> nil then begin
//舅颇喉珐爹窍瘤 臼澜
surface.Draw (FlyX + px - UNITX div 2 - shx,
FlyY + py - UNITY div 2 - shy - 46,
d.ClientRect, d, TRUE);
end;
//**)
(***捞傈
if d <> nil then begin
//舅颇喉珐爹窍瘤 臼澜
surface.Draw (FlyX + px - UNITX div 2 - shx,
FlyY + py - UNITY div 2 - shy,
d.ClientRect, d, TRUE);
end;
//**)
end;
end;
except
DebugOutStr('TFlyingArrow.DrawEff');
end;
end;
{--------------------------------------------------------}
constructor TCharEffect.Create (effbase, effframe: integer; target: TObject);
begin
inherited Create (111, effbase,
TActor(target).m_nCurrX, TActor(target).m_nCurrY,
TActor(target).m_nCurrX, TActor(target).m_nCurrY,
mtExplosion,
FALSE,
0);
TargetActor := target;
frame := effframe;
NextFrameTime := 30;
end;
function TCharEffect.Run: Boolean;
begin
Result := TRUE;
if GetTickCount - steptime > longword(NextFrameTime) then begin
steptime := GetTickCount;
Inc (curframe);
if curframe > start+frame-1 then begin
curframe := start+frame-1;
Result := FALSE;
end;
end;
end;
procedure TCharEffect.DrawEff (surface: TDirectDrawSurface);
var
d: TDirectDrawSurface;
begin
try
if TargetActor <> nil then begin
Rx := TActor(TargetActor).m_nRx;
Ry := TActor(TargetActor).m_nRy;
PlayScene.ScreenXYfromMCXY (Rx, Ry, FlyX, FlyY);
FlyX := FlyX + TActor(TargetActor).m_nShiftX;
FlyY := FlyY + TActor(TargetActor).m_nShiftY;
d := ImgLib.GetCachedImage (EffectBase + curframe, px, py);
if d <> nil then begin
DrawBlend (surface,
FlyX + px - UNITX div 2,
FlyY + py - UNITY div 2,
d, 1);
end;
end;
except
DebugOutStr('TCharEffect.DrawEff');
end;
end;
{--------------------------------------------------------}
constructor TMapEffect.Create (effbase, effframe: integer; x, y: integer);
begin
inherited Create (111, effbase,
x, y,
x, y,
mtExplosion,
FALSE,
0);
TargetActor := nil;
frame := effframe;
NextFrameTime := 30;
RepeatCount := 0;
end;
function TMapEffect.Run: Boolean;
begin
Result := TRUE;
if GetTickCount - steptime > longword(NextFrameTime) then begin
steptime := GetTickCount;
Inc (curframe);
if curframe > start+frame-1 then begin
curframe := start+frame-1;
if RepeatCount > 0 then begin
Dec (RepeatCount);
curframe := start;
end else
Result := FALSE;
end;
end;
end;
procedure TMapEffect.DrawEff (surface: TDirectDrawSurface);
var
d: TDirectDrawSurface;
begin
try
Rx := TargetX;
Ry := TargetY;
PlayScene.ScreenXYfromMCXY (Rx, Ry, FlyX, FlyY);
d := ImgLib.GetCachedImage (EffectBase + curframe, px, py);
if d <> nil then begin
DrawBlend (surface,
FlyX + px - UNITX div 2,
FlyY + py - UNITY div 2,
d, 1);
end;
except
DebugOutStr('TMapEffect.DrawEff');
end;
end;
{--------------------------------------------------------}
constructor TScrollHideEffect.Create (effbase, effframe: integer; x, y: integer; target: TObject);
begin
inherited Create (effbase, effframe, x, y);
//TargetCret := TActor(target);//在出现有人用随机之类时,将设置目标
end;
function TScrollHideEffect.Run: Boolean;
begin
Result := inherited Run;
if frame = 7 then
if g_TargetCret <> nil then
PlayScene.DeleteActor (g_TargetCret.m_nRecogId);
end;
{--------------------------------------------------------}
constructor TLightingEffect.Create (effbase, effframe: integer; x, y: integer);
begin
end;
function TLightingEffect.Run: Boolean;
begin
Result:=False;//Jacky
end;
{--------------------------------------------------------}
constructor TFireGunEffect.Create (effbase, sx, sy, tx, ty: integer);
begin
inherited Create (111, effbase,
sx, sy,
tx, ty, //TActor(target).XX, TActor(target).m_nCurrY,
mtFireGun,
TRUE,
0);
NextFrameTime := 50;
FillChar (FireNodes, sizeof(TFireNode)*FIREGUNFRAME, #0);
OutofOil := FALSE;
firetime := GetTickCount;
end;
function TFireGunEffect.Run: Boolean;
var
i: integer;
allgone: Boolean;
begin
Result := TRUE;
if GetTickCount - steptime > longword(NextFrameTime) then begin
Shift;
steptime := GetTickCount;
//if not FixedEffect then begin //格钎俊 嘎瘤 臼疽栏搁
if not OutofOil then begin
if (abs(RX-TActor(MagOwner).m_nRx) >= 5) or (abs(RY-TActor(MagOwner).m_nRy) >= 5) or (GetTickCount - firetime > 800) then
OutofOil := TRUE;
for i:=FIREGUNFRAME-2 downto 0 do begin
FireNodes[i].FireNumber := FireNodes[i].FireNumber + 1;
FireNodes[i+1] := FireNodes[i];
end;
FireNodes[0].FireNumber := 1;
FireNodes[0].x := FlyX;
FireNodes[0].y := FlyY;
end else begin
allgone := TRUE;
for i:=FIREGUNFRAME-2 downto 0 do begin
if FireNodes[i].FireNumber <= FIREGUNFRAME then begin
FireNodes[i].FireNumber := FireNodes[i].FireNumber + 1;
FireNodes[i+1] := FireNodes[i];
allgone := FALSE;
end;
end;
if allgone then Result := FALSE;
end;
end;
end;
procedure TFireGunEffect.DrawEff (surface: TDirectDrawSurface);
var
i, shx, shy, firex, firey, prx, pry, img: integer;
d: TDirectDrawSurface;
begin
try
prx := -1;
pry := -1;
for i:=0 to FIREGUNFRAME-1 do begin
if (FireNodes[i].FireNumber <= FIREGUNFRAME) and (FireNodes[i].FireNumber > 0) then begin
shx := (g_MySelf.m_nRx * UNITX + g_MySelf.m_nShiftX) - FireMyselfX;
shy := (g_MySelf.m_nRy * UNITY + g_MySelf.m_nShiftY) - FireMyselfY;
img := EffectBase + (FireNodes[i].FireNumber - 1);
d := ImgLib.GetCachedImage (img, px, py);
if d <> nil then begin
firex := FireNodes[i].x + px - UNITX div 2 - shx;
firey := FireNodes[i].y + py - UNITY div 2 - shy;
if (firex <> prx) or (firey <> pry) then begin
prx := firex;
pry := firey;
DrawBlend (surface, firex, firey, d, 1);
end;
end;
end;
end;
except
DebugOutStr('TFireGunEffect.DrawEff');
end;
end;
{--------------------------------------------------------}
constructor TThuderEffect.Create (effbase, tx, ty: integer; target: TObject);
begin
inherited Create (111, effbase,
tx, ty,
tx, ty, //TActor(target).XX, TActor(target).m_nCurrY,
mtThunder,
FALSE,
0);
TargetActor := target;
end;
procedure TThuderEffect.DrawEff (surface: TDirectDrawSurface);
var
img, px, py: integer;
d: TDirectDrawSurface;
begin
try
img := EffectBase;
d := ImgLib.GetCachedImage (img + curframe, px, py);
if d <> nil then begin
DrawBlend (surface,
FlyX + px - UNITX div 2,
FlyY + py - UNITY div 2,
d, 1);
end;
except
DebugOutStr('TThuderEffect.DrawEff');
end;
end;
{--------------------------------------------------------}
constructor TLightingThunder.Create (effbase, sx, sy, tx, ty: integer; target: TObject);
begin
inherited Create (111, effbase,
sx, sy,
tx, ty, //TActor(target).XX, TActor(target).m_nCurrY,
mtLightingThunder,
FALSE,
0);
TargetActor := target;
end;
procedure TLightingThunder.DrawEff (surface: TDirectDrawSurface);
var
img, sx, sy, px, py {shx, shy}: integer;
d: TDirectDrawSurface;
begin
try
img := EffectBase + Dir16 * 10;
if curframe < 6 then begin
{shx := (g_MySelf.m_nRx * UNITX + g_MySelf.m_nShiftX) - FireMyselfX;
shy := (g_MySelf.m_nRy * UNITY + g_MySelf.m_nShiftY) - FireMyselfY; }
d := ImgLib.GetCachedImage (img + curframe, px, py);
if d <> nil then begin
PlayScene.ScreenXYfromMCXY (TActor(MagOwner).m_nRx,
TActor(MagOwner).m_nRy,
sx,
sy);
DrawBlend (surface,
sx + px - UNITX div 2,
sy + py - UNITY div 2,
d, 1);
end;
end;
except
DebugOutStr('TLightingThunder.DrawEff');
end;
{if (curframe < 10) and (TargetActor <> nil) then begin
d := ImgLib.GetCachedImage (EffectBase + 17*10 + curframe, px, py);
if d <> nil then begin
PlayScene.ScreenXYfromMCXY (TActor(TargetActor).RX,
TActor(TargetActor).RY,
sx,
sy);
DrawBlend (surface,
sx + px - UNITX div 2,
sy + py - UNITY div 2,
d, 1);
end;
end;}
end;
{--------------------------------------------------------}
//破魂魔法过程类 20080226
constructor TPHHitEffect.Create (effbase, sx, sy, tx, ty: integer; aowner: TObject);
begin
inherited Create (111, effbase,
sx, sy,
tx, ty,
mtReady,
FALSE,
0);
NextFrameTime := 80;
Rx := TActor(aowner).m_nRx;
Ry := TActor(aowner).m_nRy;
end;
procedure TPHHitEffect.DrawEff (surface: TDirectDrawSurface);
var
img, sx, sy, px, py : integer;
d: TDirectDrawSurface;
begin
try
img := (Dir16 div 2) * 20 + 10;
if curframe < 20 then begin
d := g_WMagic4Images.GetCachedImage (img + curframe, px, py);
if d <> nil then begin
PlayScene.ScreenXYfromMCXY (Rx, Ry, sx, sy);
DrawBlend (surface,
sx + px - UNITX div 2,
sy + py - UNITY div 2,
d, 1);
end;
end;
except
DebugOutStr('TPHHitEffect.DrawEff');
end;
end;
{--------------------------------------------------------}
constructor TExploBujaukEffect.Create (effbase, sx, sy, tx, ty: integer; target: TObject);
begin
inherited Create (111, effbase,
sx, sy,
tx, ty,
mtExploBujauk,
TRUE,
0);
frame := 3;
TargetActor := target;
NextFrameTime := 50;
end;
procedure TExploBujaukEffect.DrawEff (surface: TDirectDrawSurface);
var
img: integer;
d: TDirectDrawSurface;
shx, shy: integer;
begin
try
if m_boActive and ((Abs(FlyX-fireX) > 50) or (Abs(FlyY-fireY) > 50) or FixedEffect) then begin
shx := (g_MySelf.m_nRx * UNITX + g_MySelf.m_nShiftX) - FireMyselfX;
shy := (g_MySelf.m_nRy * UNITY + g_MySelf.m_nShiftY) - FireMyselfY;
if not FixedEffect then begin
//朝酒啊绰芭
img := EffectBase + Dir16 * 10;
d := ImgLib.GetCachedImage (img + curframe, px, py);
if d <> nil then begin
//舅颇喉珐爹窍瘤 臼澜
surface.Draw (FlyX + px - UNITX div 2 - shx,
FlyY + py - UNITY div 2 - shy,
d.ClientRect, d, TRUE);
end;
if EffectBase = 140 then
d := ImgLib.GetCachedImage (img + curframe+170, px, py);
if d <> nil then begin
DrawBlend (surface,
FlyX + px - UNITX div 2 - shx,
FlyY + py - UNITY div 2 - shy,
d, 1);
end;
end else begin
//气惯
img := MagExplosionBase + curframe;
d := ImgLib.GetCachedImage (img, px, py);
if d <> nil then begin
DrawBlend (surface,
FLyX + px - UNITX div 2,
FlyY + py - UNITY div 2,
d, 1);
end;
end;
end;
except
DebugOutStr('TExploBujaukEffect.DrawEff');
end;
end;
{--------------------------------------------------------}
constructor TBujaukGroundEffect.Create (effbase, magicnumb, sx, sy, tx, ty: integer);
begin
inherited Create (111, effbase,
sx, sy,
tx, ty,
mtBujaukGroundEffect,
TRUE,
0);
frame := 3;
MagicNumber := magicnumb;
BoGroundEffect := FALSE;
NextFrameTime := 50;
end;
function TBujaukGroundEffect.Run: Boolean;
begin
Result := inherited Run;
if not FixedEffect then begin
if ((abs(TargetX-FlyX) <= 15) and (abs(TargetY-FlyY) <= 15)) or
((abs(TargetX-FlyX) >= prevdisx) and (abs(TargetY-FlyY) >= prevdisy)) then begin
FixedEffect := TRUE; //气惯
start := 0;
frame := ExplosionFrame;
curframe := start;
Repetition := FALSE;
//磐瘤绰 荤款靛
PlaySound (TActor(MagOwner).m_nMagicExplosionSound);
Result := TRUE;
end else begin
prevdisx := abs(TargetX-FlyX);
prevdisy := abs(TargetY-FlyY);
end;
end;
end;
procedure TBujaukGroundEffect.DrawEff (surface: TDirectDrawSurface);
var
img: integer;
d: TDirectDrawSurface;
shx, shy: integer;
begin
try
if m_boActive and ((Abs(FlyX-fireX) > 30) or (Abs(FlyY-fireY) > 30) or FixedEffect) then begin
shx := (g_MySelf.m_nRx * UNITX + g_MySelf.m_nShiftX) - FireMyselfX;
shy := (g_MySelf.m_nRy * UNITY + g_MySelf.m_nShiftY) - FireMyselfY;
if not FixedEffect then begin
//朝酒啊绰芭
img := EffectBase + Dir16 * 10;
d := ImgLib.GetCachedImage (img + curframe, px, py);
if d <> nil then begin
//舅颇喉珐爹窍瘤 臼澜
surface.Draw (FlyX + px - UNITX div 2 - shx,
FlyY + py - UNITY div 2 - shy,
d.ClientRect, d, TRUE);
end;
end else begin
//气惯
if MagicNumber = 11 then //付
img := EffectBase + 16 * 10 + curframe
else //规
img := EffectBase + 18 * 10 + curframe;
if MagicNumber = 46 then begin
GetEffectBase (MagicNumber -1 , 0,ImgLib,img);
img := img + 10 + curframe;
end;
d := ImgLib.GetCachedImage (img, px, py);
if d <> nil then begin
DrawBlend (surface,
FLyX + px - UNITX div 2, // - shx,
FlyY + py - UNITY div 2, // - shy,
d, 1);
end;
{if not BoGroundEffect and (curframe = 8) then begin
BoGroundEffect := TRUE;
meff := TMapEffect.Create (img+2, 6, TargetRx, TargetRy);
meff.NextFrameTime := 100;
//meff.RepeatCount := 1;
PlayScene.GroundEffectList.Add (meff);
end; }
end;
end;
except
DebugOutStr('TBujaukGroundEffect.DrawEff');
end;
end;
{ TNormalDrawEffect }
constructor TNormalDrawEffect.Create(XX,YY:Integer;WmImage:TWMImages;effbase,nX:Integer;frmTime:LongWord;boFlag:Boolean);
begin
inherited Create (111,effbase, XX, YY, XX, YY,mtReady,TRUE,0);
ImgLib:=WmImage;
EffectBase:=effbase;
start:=0;
curframe:=0;
frame:=nX;
NextFrameTime:=frmTime;
boC8:=boFlag;
end;
procedure TNormalDrawEffect.DrawEff(surface: TDirectDrawSurface);
var
d: TDirectDrawSurface;
nRx,nRy,nPx,nPy:integer;
begin
try
d := ImgLib.GetCachedImage (EffectBase + curframe, nPx, nPy);
if d <> nil then begin
PlayScene.ScreenXYfromMCXY (FlyX, FlyY, nRx, nRy);
if boC8 then begin
DrawBlend (surface,nRx + nPx - UNITX div 2,nRy + nPy - UNITY div 2,d, 1);
end else begin
surface.Draw (nRx + nPx - UNITX div 2,nRy + nPy - UNITY div 2,d.ClientRect, d, TRUE);
end;
end;
except
DebugOutStr('TNormalDrawEffect.DrawEff');
end;
end;
function TNormalDrawEffect.Run: Boolean;
begin
Result := TRUE;
if m_boActive and (GetTickCount - steptime > longword(NextFrameTime)) then begin
steptime := GetTickCount;
Inc (curframe);
if curframe > start+frame-1 then begin
curframe := start;
Result := FALSE;
end;
end;
end;
{ TFlyingBug }
constructor TFlyingBug.Create(id, effnum, sx, sy, tx, ty: integer;
mtype: TMagicType; Recusion: Boolean; anitime: integer);
begin
inherited Create (id, effnum, sx, sy, tx, ty, mtype, Recusion, anitime);
FlyImageBase := FLYOMAAXEBASE;
ReadyFrame := 65;
end;
procedure TFlyingBug.DrawEff(surface: TDirectDrawSurface);
var
img: integer;
d: TDirectDrawSurface;
shx, shy: integer;
begin
try
if m_boActive and ((Abs(FlyX-fireX) > ReadyFrame) or (Abs(FlyY-fireY) > ReadyFrame)) then begin
shx := (g_MySelf.m_nRx * UNITX + g_MySelf.m_nShiftX) - FireMyselfX;
shy := (g_MySelf.m_nRy * UNITY + g_MySelf.m_nShiftY) - FireMyselfY;
if not FixedEffect then begin
img := FlyImageBase + (Dir16 div 2) * 10;
d := ImgLib.GetCachedImage (img + curframe, px, py);
if d <> nil then begin
surface.Draw (FlyX + px - UNITX div 2 - shx,
FlyY + py - UNITY div 2 - shy,
d.ClientRect, d, TRUE);
end;
end else begin
img := curframe + MagExplosionBase;
d := ImgLib.GetCachedImage (img, px, py);
if d <> nil then begin
surface.Draw (FlyX + px - UNITX div 2,
FlyY + py - UNITY div 2,
d.ClientRect, d, TRUE);
end;
end;
end;
except
DebugOutStr('TFlyingBug.DrawEff');
end;
end;
{ TFlyingFireBall }
procedure TFlyingFireBall.DrawEff(surface: TDirectDrawSurface);
var
d: TDirectDrawSurface;
begin
try
if m_boActive and ((Abs(FlyX-fireX) > ReadyFrame) or (Abs(FlyY-fireY) > ReadyFrame)) then begin
d := ImgLib.GetCachedImage (FlyImageBase + (GetFlyDirection (FlyX, FlyY, TargetX, TargetY) * 10) + curframe, px, py);
if d <> nil then
DrawBlend (surface,
FLyX + px - UNITX div 2,
FlyY + py - UNITY div 2,
d, 1);
end;
except
DebugOutStr('TFlyingFireBall.DrawEff');
end;
end;
{ TRedThunderEffect }
constructor TRedThunderEffect.Create (effbase, tx, ty: integer; target: TObject);
begin
inherited Create (111, effbase,
tx, ty,
tx, ty, //TActor(target).XX, TActor(target).m_nCurrY,
mtRedThunder,
FALSE,
0);
TargetActor := target;
n0:=random(7);
end;
procedure TRedThunderEffect.DrawEff (surface: TDirectDrawSurface);
var
img, px, py: integer;
d: TDirectDrawSurface;
begin
try
ImgLib:={FrmMain.WDragonImg}g_WDragonImages;
img := EffectBase;
d := ImgLib.GetCachedImage (img + (7 * n0) + curframe, px, py);
if d <> nil then begin
DrawBlend (surface,
FlyX + px - UNITX div 2,
FlyY + py - UNITY div 2,
d, 1);
end;
except
DebugOutStr('TRedThunderEffect.DrawEff');
end;
end;
{ TLavaEffect }
constructor TLavaEffect.Create (effbase, tx, ty: integer; target: TObject);
begin
inherited Create (111, effbase,
tx, ty,
tx, ty, //TActor(target).XX, TActor(target).m_nCurrY,
mtLava,
FALSE,
0);
TargetActor := target;
frame :=10;
end;
procedure TLavaEffect.DrawEff (surface: TDirectDrawSurface);
var
img, px, py: integer;
d: TDirectDrawSurface;
begin
try
ImgLib:=g_WDragonImages;
//draw explosion
if curframe < 10 then begin
img := 470;
d := ImgLib.GetCachedImage (img + curframe, px, py);
if d <> nil then begin
DrawBlend (surface,
FlyX + px - UNITX div 2,
FlyY + py - UNITY div 2,
d, 1);
end;
end;
//draw the rest
img := EffectBase;
d := ImgLib.GetCachedImage (img + curframe, px, py);
if d <> nil then begin
DrawBlend (surface,
FlyX + px - UNITX div 2,
FlyY + py - UNITY div 2,
d, 1);
end;
except
DebugOutStr('TLavaEffect.DrawEff');
end;
end;
{ TfenshenThunder }
constructor TfenshenThunder.Create(effbase, sx, sy, tx, ty: integer;
aowner: TObject);
begin
Rx := TActor(aowner).m_nRx;
Ry:= TActor(aowner).m_nRy;
dir := TActor(aowner).m_btDir;
inherited Create (111, effbase,
sx, sy,
tx, ty, //TActor(target).XX, TActor(target).m_nCurrY,
mtLightingThunder,
FALSE,
0);
end;
procedure TfenshenThunder.DrawEff(surface: TDirectDrawSurface);
procedure GetFrontPosition (sx, sy, dir: integer; var newx, newy: integer);
begin
newx := sx;
newy := sy;
case dir of
DR_UP: newy := newy-100;
DR_DOWN: newy := newy+100;
DR_LEFT: newx := newx-145;
DR_RIGHT: newx := newx+145;
DR_UPLEFT:
begin
newx := newx - 140;
newy := newy - 105;
end;
DR_UPRIGHT:
begin
newx := newx + 145;
newy := newy - 100;
end;
DR_DOWNLEFT:
begin
newx := newx - 145;
newy := newy + 90;
end;
DR_DOWNRIGHT:
begin
newx := newx + 145;
newy := newy + 90;
end;
end;
end;
var
img, sx, sy, px, py: integer;
d: TDirectDrawSurface;
nx,ny:integer;
begin
try
img := EffectBase + Dir * 10;
if curframe < 10 then begin
d := ImgLib.GetCachedImage (img + curframe, px, py);
if d <> nil then begin
PlayScene.ScreenXYfromMCXY (Rx,
Ry,
sx,
sy);
GetFrontPosition(sx + px - UNITX div 2,
sy + py - UNITY div 2,Dir,nx,ny);
DrawBlend (surface,
nx,
ny,
d, 1);
end;
img := 90;
if curframe < 10 then begin
d := ImgLib.GetCachedImage (img + curframe, px, py);
if d <> nil then begin
PlayScene.ScreenXYfromMCXY (Rx,
Ry,
sx,
sy);
GetFrontPosition(sx + px - UNITX div 2,
sy + py - UNITY div 2,Dir,nx,ny);
DrawBlend (surface,
nx,
ny,
d, 1);
end;
end;
end;
except
DebugOutStr('TfenshenThunder.DrawEff');
end;
end;
{ TFairyEffect }
constructor TFairyEffect.Create(effbase, tx, ty: integer; target: TObject);
begin
end;
procedure TFairyEffect.DrawEff(surface: TDirectDrawSurface);
begin
inherited;
end;
{ TObjectEffects }
//自定义魔法类 20080809
constructor TObjectEffects.Create(ObjectID2:TObject;WmImage:TWMImages;effbase,nX:Integer;frmTime:LongWord;boFlag:Boolean);
begin
inherited Create (111,effbase, 0, 0, 0, 0,mtReady,TRUE,0);
ImgLib:=WmImage;
EffectBase:=effbase;
start:=0;
curframe:=0;
frame:=nX;
NextFrameTime:=frmTime;
boC8:=boFlag;
ObjectID:=ObjectID2;
end;
procedure TObjectEffects.DrawEff(surface: TDirectDrawSurface);
var
d: TDirectDrawSurface;
Rx,Ry,nRx,nRy,nPx,nPy:integer;
begin
try
d := ImgLib.GetCachedImage (EffectBase + curframe, nPx, nPy);
if (d <> nil) and (ObjectID <> nil) then begin
Rx := TActor(ObjectID).m_nRx;
Ry := TActor(ObjectID).m_nRy;
PlayScene.ScreenXYfromMCXY (Rx, Ry, nRx, nRy);
nRx := nRx + TActor(ObjectID).m_nShiftX;
nRy := nRy + TActor(ObjectID).m_nShiftY;
if boC8 then begin
DrawBlend (surface,
nRx + npx - UNITX div 2,
nRy + npy - UNITY div 2,
d, 1);
end else begin
surface.Draw (nRx + nPx - UNITX div 2,nRy + nPy - UNITY div 2,d.ClientRect, d, TRUE);
end;
end;
except
DebugOutStr('TObjectEffects.DrawEff');
end;
end;
function TObjectEffects.Run: Boolean;
begin
Result := TRUE;
if m_boActive and (GetTickCount - steptime > longword(NextFrameTime)) then begin
steptime := GetTickCount;
Inc (curframe);
if curframe > start+frame-1 then begin
curframe := start;
Result := FALSE;
end;
end;
end;
end.
|
unit SimpleRestRequest;
interface
uses
SimpleRestRequest.Interfaces,
IdBaseComponent,
IdComponent,
IdTCPConnection,
IdTCPClient,
IdHTTP,
System.JSON,
System.Classes;
type
TSimpleRestRequest = class(TInterfacedObject, iSimpleRestResquest)
private
FIdHTTP : TIdHTTP;
FBaseURL : String;
FStreamSend : TStringStream;
FReturn : String;
function IsBasicAuthentication : Boolean;
public
constructor Create;
destructor Destroy; override;
class function New : iSimpleRestResquest;
function StatusCode : Integer;
function Password ( aValue : string) : iSimpleRestResquest;
function Username ( aValue : string) : iSimpleRestResquest;
function AddHeaders ( aKey : String; aValue : String) : iSimpleRestResquest;
function ContentType (aValue : String) : iSimpleRestResquest;
function Connection (aValue : String) : iSimpleRestResquest;
function UserAgent (aValue : String) : iSimpleRestResquest;
function HandleRedirects ( aValue : Boolean ) : iSimpleRestResquest;
function BaseURL (aValue : String) : iSimpleRestResquest;
function Body (aValue : String) : iSimpleRestResquest; overload;
function Body (aValue : TJsonObject) : iSimpleRestResquest; overload;
function Post : iSimpleRestResquest;
function Get : iSimpleRestResquest;
function Delete : iSimpleRestResquest;
function Put : iSimpleRestResquest;
function Return : String;
end;
implementation
{ TSimpleRestRequest }
function TSimpleRestRequest.AddHeaders(aKey,
aValue: String): iSimpleRestResquest;
begin
Result := Self;
FIdHTTP.Request.CustomHeaders.AddValue(aKey, aValue);
end;
function TSimpleRestRequest.BaseURL(aValue: String): iSimpleRestResquest;
begin
Result := Self;
FBaseURL := aValue;
end;
function TSimpleRestRequest.Body(aValue: String): iSimpleRestResquest;
begin
Result := Self;
FStreamSend := TStringStream.Create(aValue);
end;
function TSimpleRestRequest.Body(aValue: TJsonObject): iSimpleRestResquest;
begin
Result := Self;
FStreamSend := TStringStream.Create(aValue.ToJSON);
end;
function TSimpleRestRequest.Connection(aValue: String): iSimpleRestResquest;
begin
Result := Self;
FIdHTTP.Request.Connection := aValue;
end;
function TSimpleRestRequest.ContentType(aValue: String): iSimpleRestResquest;
begin
Result := Self;
FIdHTTP.Request.ContentType := aValue;
end;
constructor TSimpleRestRequest.Create;
begin
FIdHTTP := TIdHTTP.Create(nil);
FIdHTTP.Request.Connection := 'Keep-Alive';
FIdHTTP.Request.UserAgent := 'User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36';
FIdHTTP.HandleRedirects := true;
end;
function TSimpleRestRequest.Delete: iSimpleRestResquest;
var
FStreamResult : TStringStream;
begin
Result := Self;
FStreamResult := TStringStream.Create;
try
FIdHTTP.Delete(FBaseURL, FStreamResult);
FReturn := FStreamResult.DataString;
finally
FStreamResult.Free;
end;
end;
destructor TSimpleRestRequest.Destroy;
begin
if Assigned(FStreamSend) then
FStreamSend.Free;
FIdHTTP.Free;
inherited;
end;
function TSimpleRestRequest.Get: iSimpleRestResquest;
var
FStreamResult : TStringStream;
begin
Result := Self;
FStreamResult := TStringStream.Create;
try
FIdHTTP.Get(FBaseURL, FStreamResult);
FReturn := FStreamResult.DataString;
finally
FStreamResult.Free;
end;
end;
function TSimpleRestRequest.HandleRedirects(
aValue: Boolean): iSimpleRestResquest;
begin
Result := Self;
FIdHTTP.HandleRedirects := aValue;
end;
function TSimpleRestRequest.IsBasicAuthentication: Boolean;
begin
Result := (FIdHTTP.Request.Password <> '') and (FIdHTTP.Request.Username <> '');
end;
class function TSimpleRestRequest.New: iSimpleRestResquest;
begin
Result := Self.Create;
end;
function TSimpleRestRequest.Password(aValue: string): iSimpleRestResquest;
begin
Result := Self;
FIdHTTP.Request.Password := aValue;
FIdHTTP.Request.BasicAuthentication := IsBasicAuthentication;
end;
function TSimpleRestRequest.Post: iSimpleRestResquest;
begin
Result := Self;
FReturn := FIdHTTP.Post(FBaseURL, FStreamSend);
end;
function TSimpleRestRequest.Put: iSimpleRestResquest;
var
FStreamResult : TStringStream;
begin
Result := Self;
FStreamResult := TStringStream.Create;
try
if not Assigned(FStreamSend) then
FStreamSend := TStringStream.Create;
FIdHTTP.Put(FBaseURL, FStreamSend, FStreamResult);
FReturn := FStreamResult.DataString;
finally
FStreamResult.Free;
end;
end;
function TSimpleRestRequest.Return: String;
begin
Result := FReturn;
end;
function TSimpleRestRequest.StatusCode: Integer;
begin
Result := FIdHTTP.ResponseCode;
end;
function TSimpleRestRequest.UserAgent(aValue: String): iSimpleRestResquest;
begin
Result := Self;
FIdHTTP.Request.UserAgent := aValue;
end;
function TSimpleRestRequest.Username(aValue: string): iSimpleRestResquest;
begin
Result := Self;
FIdHTTP.Request.Username := aValue;
FIdHTTP.Request.BasicAuthentication := IsBasicAuthentication;
end;
end.
|
unit ufrmElectricCustomer;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterBrowse, ExtCtrls, ActnList, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB,
cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus,
cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBExtLookupComboBox,
ufraFooter4Button, cxButtons, cxTextEdit, cxMaskEdit, cxCalendar, cxLabel,
cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, cxPC, Vcl.StdCtrls, System.Actions;
type
data_customer = record
elcust_id: Integer;
cust_id: Integer;
cust_unit_id: Integer;
cust_elec_rate_id: Integer;
cust_elec_rate_unit_id: Integer;
end;
data_electric_rate = record
elec_rate_id: Integer;
elec_rate_unit_id: Integer;
elec_rate_group: string;
elec_rate_power: Double;
elec_rate_charge: Currency;
end;
TfrmElectricCustomer = class(TfrmMasterBrowse)
pnl1: TPanel;
lblComboGrid: TLabel;
edtCustName: TEdit;
cbpCustCode: TcxExtLookupComboBox;
actlstElectricCustomer: TActionList;
actAddElectricCustomer: TAction;
actEditElectricCustomer: TAction;
actDeleteElectricCustomer: TAction;
cxcolGridViewColumn1: TcxGridDBColumn;
cxcolGridViewColumn2: TcxGridDBColumn;
cxcolGridViewColumn3: TcxGridDBColumn;
cxcolGridViewColumn4: TcxGridDBColumn;
cxcolGridViewColumn5: TcxGridDBColumn;
cxcolGridViewColumn6: TcxGridDBColumn;
cxcolGridViewColumn7: TcxGridDBColumn;
cxcolGridViewColumn8: TcxGridDBColumn;
cxcolGridViewColumn9: TcxGridDBColumn;
cxcolGridViewColumn10: TcxGridDBColumn;
btnShow: TcxButton;
btnPrint: TcxButton;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cbpCustCodeChange(Sender: TObject);
procedure btnShowClick(Sender: TObject);
procedure actAddExecute(Sender: TObject);
procedure strgElectricCustomerCanEditCell(Sender: TObject; ARow,
ACol: Integer; var CanEdit: Boolean);
procedure actDeleteElectricCustomerExecute(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure strgElectricCustomerComboChange(Sender: TObject; ACol, ARow,
AItemIndex: Integer; ASelection: String);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btnPrintClick(Sender: TObject);
private
{ Private declarations }
dataCustCode: TDataSet;
// FNewElectrical_Customer: TNewElectrical_Customer;
isOnAdd: Boolean;
isOnEdit: Boolean;
procedure LoadDropDownData(ACombo: TcxExtLookupComboBox; AColsOfData: Integer);
// procedure ParseGridElectricRateCombobox(aUnit_ID: Integer=0);
public
procedure RefreshData; override;
{ Public declarations }
end;
var
frmElectricCustomer: TfrmElectricCustomer;
is_cell_editable: Boolean;
implementation
uses uTSCommonDlg, uConstanta, DateUtils, uRetnoUnit;
const
_KolNo : Byte = 0;
_KolCustomer_Code : Byte = 1;
_KolCustomer_Name : Byte = 2;
_KolKavling : Byte = 3;
_KolBegin_Periode : Byte = 4;
_KolGroup : Byte = 5;
_KolPower : Byte = 6;
_KolCharge : Byte = 7;
_KolLast_Periode : Byte = 8;
_KolActive : Byte = 9;
var
list_customer: array of data_customer;
list_electric_rate: array of data_electric_rate;
{$R *.dfm}
procedure TfrmElectricCustomer.FormShow(Sender: TObject);
begin
inherited;
// if not Assigned(FNewElectrical_Customer) then
// FNewElectrical_Customer := TNewElectrical_Customer.CreateWithUser(Self, FLoginId, FLoginUnitId);
isOnAdd := False;
isOnEdit := False;
// dataCustCode := GetListCustomerByUnitId(MasterNewUnit.ID);
// dataCustCode.Last;
// LoadDropDownData(cbpCustCode,dataCustCode.RecordCount);
end;
procedure TfrmElectricCustomer.LoadDropDownData(ACombo: TcxExtLookupComboBox;
AColsOfData: Integer);
begin
{Flush the old data}
// ACombo.ClearGridData;
{Make sure the allocated storage is big enough}
// if AColsOfData < 1 then AColsOfData := 0;
//// ACombo.RowCount := AColsOfData + 2;
//// ACombo.ColCount := 3;
//
// {Load the data}
// if Acombo = cbpCustCode then
// begin
//// ACombo.AddRow(['','CODE','NAME']);
//// ACombo.AddRow(['-','-','< ALL >']);
//
// if dataCustCode.RecordCount > 0 then
// begin
// dataCustCode.First;
// while not dataCustCode.Eof do
// begin
// try
//// ACombo.AddRow([dataCustCode.FieldByName('CUST_CODE').AsString,
//// dataCustCode.FieldByName('CUST_CODE').AsString,
//// dataCustCode.FieldByName('CUST_NAME').AsString]);
// except
// end;
// dataCustCode.Next;
// end; //END WHILE
// end; //END <> NIL
// end;
{Now shring the grid so its just big enough for the data}
// ACombo.SizeGridToData;
//trik to activate acombo
// ACombo.FixedRows := 1;
end;
procedure TfrmElectricCustomer.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action:= caFree;
end;
procedure TfrmElectricCustomer.FormDestroy(Sender: TObject);
begin
inherited;
// FNewElectrical_Customer.Free;
frmElectricCustomer:= nil;
end;
procedure TfrmElectricCustomer.FormCreate(Sender: TObject);
//var i: Integer;
begin
inherited;
lblHeader.Caption := 'List Electric Customer';
// for i:= 0 to strgElectricCustomer.ColCount-1 do begin
// strgElectricCustomer.Alignments[i,0]:= taCenter;
// end;
is_cell_editable:= False;
end;
procedure TfrmElectricCustomer.cbpCustCodeChange(Sender: TObject);
begin
inherited;
// edtCustName.Text := cbpCustCode.Cells[2, cbpCustCode.Row];
end;
procedure TfrmElectricCustomer.btnShowClick(Sender: TObject);
//var dataElectricCustomer: TDataSet;
// i: Integer;
// aCustCode: String;
begin
inherited;
{
strgElectricCustomer.ClearNormalCells;
strgElectricCustomer.RowCount:= 2;
if cbpCustCode.Cells[0,cbpCustCode.Row] <> '' then begin
if cbpCustCode.Cells[0,cbpCustCode.Row] = '-' then
begin
SetLength(arrParam,0);
aCustCode := '';
end
else begin
SetLength(arrParam,1);
arrParam[0].tipe := ptString;
arrParam[0].data := cbpCustCode.Cells[0,cbpCustCode.Row];
aCustCode := cbpCustCode.Cells[0,cbpCustCode.Row];
end;
dataElectricCustomer := GetListElectricCustomerByCustomerId(aCustCode);
dataElectricCustomer.Last;
if not dataElectricCustomer.IsEmpty then begin
with strgElectricCustomer do begin
ClearNormalCells;
is_cell_editable:= False;
RowCount:= dataElectricCustomer.RecordCount + 1;
AddCheckBox(_KolCustomer_Code,0,False,False);
SetCheckBoxState(_KolCustomer_Code,0,False);
AddCheckBox(_KolActive,0,False,False);
dataElectricCustomer.First;
SetLength(list_customer, dataElectricCustomer.RecordCount);
for i:= 1 to RowCount-1 do begin
Cells[_KolNo,i]:= IntToStr(i);
Alignments[_KolNo,i]:= taCenter;
AddCheckBox(_KolCustomer_Code,i,False,False);
Cells[_KolCustomer_Code,i]:= dataElectricCustomer.FieldByName('CUST_CODE').AsString;
Cells[_KolCustomer_Name,i]:= dataElectricCustomer.FieldByName('CUST_NAME').AsString;
Cells[_KolKavling,i]:= dataElectricCustomer.FieldByName('ELCUST_KAVLING_CODE').AsString;
Cells[_KolBegin_Periode,i]:= FormatDateTime('mmmm yyyy', dataElectricCustomer.FieldByName('ELCUST_DATE_BEGIN').AsDateTime);
Cells[_KolGroup,i]:= dataElectricCustomer.FieldByName('ELECTR_GROUP').AsString;
Cells[_KolPower,i]:= dataElectricCustomer.FieldByName('ELECTR_POWER').AsString;
Alignments[_KolPower,i]:= taRightJustify;
Cells[_KolCharge,i]:= FormatCurr('#,##0.##', dataElectricCustomer.FieldByName('ELECTR_COST_ABODEMEN').AsCurrency);
Alignments[_KolCharge,i]:= taRightJustify;
Cells[_KolLast_Periode, i] := FormatDateTime('mmmm yyyy', dataElectricCustomer.FieldByName('ELCUST_LAST_PROCESS').AsDateTime);
if dataElectricCustomer.FieldByName('ELCUST_IS_ACTIVE').AsInteger=0 then
AddCheckBox(_KolActive,i,False,False)
else
AddCheckBox(_KolActive,i,True,False);
//Cells[_KolActive, i] := dataElectricCustomer.FieldByName('ELCUST_IS_ACTIVE').AsString;
Alignments[_KolActive,i]:= taCenter;
list_customer[i-1].elcust_id:= dataElectricCustomer.FieldByName('ELCUST_ID').AsInteger;
dataElectricCustomer.Next;
end;
AutoSizeCol(_KolCustomer_Code);
AutoSizeCol(_KolCustomer_Name);
end;
end
else begin
strgElectricCustomer.RemoveCheckBox(_KolCustomer_Code,0);
end;
end;
}
end;
procedure TfrmElectricCustomer.actAddExecute(Sender: TObject);
//var dataAddElectricCustomer: TDataSet;
// isSaveError: Boolean;
// i: Integer;
// Year, Month, Day: Word;
// aDate_Begin: TDateTime;
begin
inherited;
// if Mastercompany.ID = 0 then begin
CommonDlg.ShowError(ER_COMPANY_NOT_SPECIFIC);
Exit;
// end
// else if MasterNewUnit.ID = 0 then begin
CommonDlg.ShowError(ER_UNIT_NOT_SPECIFIC);
// Exit;
// end;
{
strgElectricCustomer.RemoveCheckBox(_KolCustomer_Code,0);
if fraFooter4Button1.btnAdd.Tag = 0 then begin //ADD New cust
ParseGridElectricRateCombobox();
SetLength(arrParam,0);
dataAddElectricCustomer := GetListAddElectricCustByCustId();
dataAddElectricCustomer.Last;
if dataAddElectricCustomer.RecordCount > 0 then begin
fraFooter4Button1.btnAdd.Tag := 1;
fraFooter4Button1.btnAdd.Caption:= '&Save';
isOnAdd := True;
fraFooter4Button1.btnUpdate.Enabled:= False;
fraFooter4Button1.btnDelete.Enabled:= False;
btnShow.Enabled:= False;
fraFooter4Button1.btnClose.Tag := 1;
fraFooter4Button1.btnClose.Caption:= 'Abort';
is_cell_editable:= True;
SetLength(list_customer, dataAddElectricCustomer.RecordCount);
with strgElectricCustomer do begin
ClearNormalCells;
RowCount:= dataAddElectricCustomer.RecordCount + 1;
dataAddElectricCustomer.First;
for i:= 1 to RowCount-1 do begin
Cells[_KolNo,i]:= IntToStr(i);
Alignments[_KolNo,i]:= taCenter;
Cells[_KolCustomer_Code,i]:= dataAddElectricCustomer.FieldByName('CUST_CODE').AsString;
Cells[_KolCustomer_Name,i]:= dataAddElectricCustomer.FieldByName('CUST_NAME').AsString;
CellProperties[_KolKavling,i].BrushColor:= clInfoBk;
//Cells[_KolBegin_Periode,i]:= FormatDateTime('mmmm yyyy',Now);
CellProperties[_KolBegin_Periode,i].BrushColor:= clInfoBk;
Cells[_KolBegin_Periode,i]:= DateToStr(StartOfTheMonth(Now));
Cells[_KolGroup,i]:= list_electric_rate[0].elec_rate_group;
Alignments[_KolGroup,i]:= taRightJustify;
CellProperties[_KolGroup,i].BrushColor:= clInfoBk;
Cells[_KolPower,i]:= FloatToStr(list_electric_rate[0].elec_rate_power);
Alignments[_KolPower,i]:= taRightJustify;
Cells[_KolCharge,i]:= CurrToStr(list_electric_rate[0].elec_rate_charge);
Alignments[_KolCharge,i]:= taRightJustify;
list_customer[i-1].cust_id:= dataAddElectricCustomer.FieldByName('CUST_ID').AsInteger;
list_customer[i-1].cust_unit_id:= dataAddElectricCustomer.FieldByName('CUST_UNT_ID').AsInteger;
list_customer[i-1].cust_elec_rate_id:= list_electric_rate[0].elec_rate_id;
list_customer[i-1].cust_elec_rate_unit_id:= list_electric_rate[0].elec_rate_unit_id;
dataAddElectricCustomer.Next;
end;
end;
end
else begin
CommonDlg.ShowError('There''s no customer to add.');
end;
end
else begin //Save New Cust w Kavling
fraFooter4Button1.btnAdd.Tag := 0;
fraFooter4Button1.btnAdd.Caption:= '&Add';
isOnAdd := False;
fraFooter4Button1.btnUpdate.Enabled:= True;
fraFooter4Button1.btnDelete.Enabled:= True;
btnShow.Enabled:= True;
fraFooter4Button1.btnClose.Tag := 0;
fraFooter4Button1.btnClose.Caption:= 'Close';
is_cell_editable:= False;
with strgElectricCustomer do begin
for i:= 1 to RowCount-1 do begin
if Cells[_KolKavling,i] <> '' then begin
// insert ke tabel electric_customer
try
DecodeDate(StrToDate(Cells[_KolBegin_Periode,i]), Year, Month, Day);
except
DecodeDate(Now, Year, Month, Day); //ELCUST_DATE_BEGIN
end;
aDate_Begin := EncodeDate(Year, Month, 1);
FNewElectrical_Customer.UpdateData(0, list_customer[i-1].cust_id, list_customer[i-1].cust_unit_id,
StartOfTheMonth(aDate_Begin), list_customer[i-1].cust_elec_rate_id, list_customer[i-1].cust_elec_rate_unit_id,
1, (Cells[_KolKavling,i]), 0, StartOfTheMonth(aDate_Begin), MasterNewUnit.ID);
if FNewElectrical_Customer.SaveToDB then
begin
cCommitTrans;
end else
begin
cRollbackTrans;
CommonDlg.ShowError('Gagal Menyimpan Data'+#13#10+'Customer "' + Cells[_KolCustomer_Code, i]
+ ' - ' + Cells[_KolCustomer_Name, i] + '"');
end;
end;
end;
end;
SetLength(list_customer, 0);
btnShowClick(Self);
end;
}
end;
procedure TfrmElectricCustomer.strgElectricCustomerCanEditCell(
Sender: TObject; ARow, ACol: Integer; var CanEdit: Boolean);
begin
inherited;
{
if (ACol = _KolKavling) and is_cell_editable then begin
CanEdit:= True;
end
else if (ACol = _KolBegin_Periode) and is_cell_editable and (fraFooter4Button1.btnUpdate.Tag = 1) then begin
CanEdit:= True;
end
else if (ACol = _KolCustomer_Code) and (not is_cell_editable)
and (strgElectricCustomer.Cells[_KolNo,ARow] <> '') then begin
CanEdit:= True;
end
else if (ACol = _KolGroup) and is_cell_editable then
CanEdit:= True
else if (ACol = _KolCustomer_Code) and (is_cell_editable)
and (strgElectricCustomer.Cells[_KolNo,ARow] <> '') then begin
CanEdit:= True;
end
else if (ACol = _KolBegin_Periode) and is_cell_editable and (fraFooter4Button1.btnAdd.Tag = 1) then
CanEdit:= True
else if (ACol = _KolActive) and is_cell_editable and (fraFooter4Button1.btnUpdate.Tag = 1) then
CanEdit:= True
else begin
CanEdit:= False;
end;
}
end;
procedure TfrmElectricCustomer.actDeleteElectricCustomerExecute(
Sender: TObject);
//var i: Integer;
// isChecked: Boolean;
begin
inherited;
if CommonDlg.Confirm('Are you sure you want to delete the selected data ?') = mrYes then begin
{for i:= 1 to strgElectricCustomer.RowCount-1 do begin
isChecked:= False;
strgElectricCustomer.GetCheckBoxState(_KolCustomer_Code,i, isChecked);
if isChecked then begin
// delete
if FNewElectrical_Customer.LoadByID(list_customer[i-1].elcust_id, MasterNewUnit.ID) then
begin
try
if FNewElectrical_Customer.RemoveFromDB then
begin
cCommitTrans;
CommonDlg.ShowMessage('Berhasil Menghapus Data');
end else begin
cRollbackTrans;
CommonDlg.ShowMessage('Gagal menghapus data');
end;
finally
cRollbackTrans;
end;
end;
end;
end;}
btnShowClick(Self);
end;
end;
procedure TfrmElectricCustomer.actEditExecute(Sender: TObject);
//var dataEditElectricCustomer: TDataSet;
// iCustomerState: Integer;
// isActive: Boolean;
// i: Integer;
// aDate_Begin, aDate_Last: TDateTime;
// Year, Month, Day: Word;
// aCustCode: String;
// isCheck, isAnyUpdate, isError: Boolean;
begin
inherited;
{strgElectricCustomer.RemoveCheckBox(_KolCustomer_Code,0);
if fraFooter4Button1.btnUpdate.Tag = 0 then begin //View Editable Cust
ParseGridElectricRateCombobox();
if cbpCustCode.Cells[_KolNo,cbpCustCode.Row] <> '' then begin
if cbpCustCode.Cells[_KolNo,cbpCustCode.Row] = '-' then
begin
SetLength(arrParam,0);
aCustCode := '';
end
else begin
SetLength(arrParam,1);
arrParam[0].tipe := ptString;
arrParam[0].data := cbpCustCode.Cells[_KolNo,cbpCustCode.Row];
aCustCode := cbpCustCode.Cells[_KolNo,cbpCustCode.Row];
end;
end;
dataEditElectricCustomer := GetListEditElectricCustomerByCustomerCode(aCustCode);
dataEditElectricCustomer.Last;
if dataEditElectricCustomer.RecordCount > 0 then begin
fraFooter4Button1.btnUpdate.Tag := 1;
fraFooter4Button1.btnUpdate.Caption:= '&Save';
isOnEdit := True;
fraFooter4Button1.btnAdd.Enabled:= False;
fraFooter4Button1.btnDelete.Enabled:= False;
btnShow.Enabled:= False;
fraFooter4Button1.btnClose.Tag := 1;
fraFooter4Button1.btnClose.Caption:= 'Abort';
is_cell_editable:= True;
SetLength(list_customer, dataEditElectricCustomer.RecordCount);
with strgElectricCustomer do begin
ClearNormalCells;
RowCount:= dataEditElectricCustomer.RecordCount + 1;
AddCheckBox(_KolCustomer_Code,0,False,False);
SetCheckBoxState(_KolCustomer_Code,0,False);
dataEditElectricCustomer.First;
for i:= 1 to RowCount-1 do begin
Cells[_KolNo,i]:= IntToStr(i);
Alignments[_KolNo,i]:= taCenter;
AddCheckBox(_KolCustomer_Code,i,False,False);
Cells[_KolCustomer_Code,i]:= dataEditElectricCustomer.FieldByName('CUST_CODE').AsString;
Cells[_KolCustomer_Name,i]:= dataEditElectricCustomer.FieldByName('CUST_NAME').AsString;
CellProperties[_KolKavling,i].BrushColor:= clInfoBk;
Cells[_KolKavling,i]:= dataEditElectricCustomer.FieldByName('ELCUST_KAVLING_CODE').AsString;
CellProperties[_KolBegin_Periode,i].BrushColor:= clInfoBk;
Cells[_KolBegin_Periode,i]:= dataEditElectricCustomer.FieldByName('ELCUST_DATE_BEGIN').AsString;
Cells[_KolGroup,i]:= dataEditElectricCustomer.FieldByName('ELECTR_GROUP').AsString;
CellProperties[_KolGroup,i].BrushColor:= clInfoBk;
Cells[_KolPower,i]:= dataEditElectricCustomer.FieldByName('ELECTR_POWER').AsString;
Alignments[_KolPower,i]:= taRightJustify;
Cells[_KolCharge,i]:= FormatCurr('#,##0.##', dataEditElectricCustomer.FieldByName('ELECTR_COST_ABODEMEN').AsCurrency);
Alignments[_KolCharge,i]:= taRightJustify;
Cells[_KolLast_Periode, i] := FormatDateTime('mmmm yyyy', dataEditElectricCustomer.FieldByName('ELCUST_LAST_PROCESS').AsDateTime);
if dataEditElectricCustomer.FieldByName('ELCUST_IS_ACTIVE').AsInteger=0 then
AddCheckBox(_KolActive,i,False,False)
else
AddCheckBox(_KolActive,i,True,False);
Alignments[_KolActive,i]:= taCenter;
CellProperties[_KolActive,i].BrushColor:= clInfoBk;
list_customer[i-1].elcust_id:= dataEditElectricCustomer.FieldByName('ELCUST_ID').AsInteger;
list_customer[i-1].cust_id:= dataEditElectricCustomer.FieldByName('CUST_ID').AsInteger;
list_customer[i-1].cust_unit_id:= dataEditElectricCustomer.FieldByName('CUST_UNT_ID').AsInteger;
list_customer[i-1].cust_elec_rate_id:= dataEditElectricCustomer.FieldByName('ELECTR_ID').AsInteger;
list_customer[i-1].cust_elec_rate_unit_id:= dataEditElectricCustomer.FieldByName('ELECTR_UNT_ID').AsInteger;
dataEditElectricCustomer.Next;
end;
end;
end
else begin
CommonDlg.ShowError('There''s no customer to edit.');
end;
end
else begin //SAVE after Edit
is_cell_editable:= False;
isAnyUpdate := False;
isError := False;
with strgElectricCustomer do begin
for i:= 1 to RowCount-1 do begin
// update tabel electric_customer
isCheck := False;
strgElectricCustomer.GetCheckBoxState(_KolCustomer_Code,i, isCheck);
if isCheck then begin
if (FNewElectrical_Customer.LoadByID(list_customer[i-1].elcust_id, MasterNewUnit.ID) ) then
begin
isAnyUpdate := True;
try
DecodeDate(StrToDate(Cells[_KolBegin_Periode,i]), Year, Month, Day);
except
DecodeDate(Now, Year, Month, Day); //ELCUST_DATE_BEGIN
end;
aDate_Begin := EncodeDate(Year, Month, 1);
if FNewElectrical_Customer.LAST_PROCESS<aDate_Begin then
aDate_Last := aDate_Begin
else
aDate_Last := FNewElectrical_Customer.LAST_PROCESS;
GetCheckBoxState(_KolActive,i, isActive);
if isActive then
iCustomerState := 1
else
iCustomerState := 0;
FNewElectrical_Customer.UpdateData(list_customer[i-1].elcust_id, list_customer[i-1].cust_id,
list_customer[i-1].cust_unit_id, aDate_Begin, list_customer[i-1].cust_elec_rate_id, list_customer[i-1].cust_elec_rate_unit_id,
iCustomerState, Cells[_KolKavling,i], 0, aDate_Last, MasterNewUnit.ID );
if FNewElectrical_Customer.SaveToDB then
begin
cCommitTrans;
end else
begin
isError := True;
cRollbackTrans;
CommonDlg.ShowError('Gagal Menyimpan Data'+#13#10+'Customer "' + Cells[_KolCustomer_Code, i]
+ ' - ' + Cells[_KolCustomer_Name, i] + '"');
end;
end;
end;
end;
end;
if isAnyUpdate and not isError then
begin
fraFooter4Button1.btnUpdate.Tag := 0;
fraFooter4Button1.btnUpdate.Caption:= '&Edit';
fraFooter4Button1.btnAdd.Enabled:= True;
isOnEdit := False;
fraFooter4Button1.btnDelete.Enabled:= True;
btnShow.Enabled:= True;
fraFooter4Button1.btnClose.Tag := 0;
fraFooter4Button1.btnClose.Caption:= 'Close';
SetLength(list_customer, 0);
btnShowClick(Self);
end
else if not isError then
begin
is_cell_editable:= True;
CommonDlg.ShowMessage('Cek Box untuk Customer yang di Edit');
end;
end;
}
end;
procedure TfrmElectricCustomer.strgElectricCustomerComboChange(
Sender: TObject; ACol, ARow, AItemIndex: Integer; ASelection: String);
begin
inherited;
// strgElectricCustomer.Cells[_KolPower,ARow]:= FloatToStr(list_electric_rate[AItemIndex].elec_rate_power);
// strgElectricCustomer.Cells[_KolCharge,ARow]:= CurrToStr(list_electric_rate[AItemIndex].elec_rate_charge);
list_customer[ARow-1].cust_elec_rate_id:= list_electric_rate[AItemIndex].elec_rate_id;
list_customer[ARow-1].cust_elec_rate_unit_id:= list_electric_rate[AItemIndex].elec_rate_unit_id;
end;
//procedure TfrmElectricCustomer.ParseGridElectricRateCombobox(aUnit_ID:
// Integer=0);
//var
// dataElectricRate: TDataSet;
// j: Integer;
//begin
// {dataElectricRate:= GetAllListElectricRate(aUnit_ID);
// dataElectricRate.Last;
// SetLength(list_electric_rate, dataElectricRate.RecordCount);
// if not dataElectricRate.IsEmpty then begin
// dataElectricRate.First;
// strgElectricCustomer.Combobox.Clear;
// for j:= 0 to dataElectricRate.RecordCount-1 do begin
// list_electric_rate[j].elec_rate_id:= dataElectricRate.FieldByName('ELECTR_ID').AsInteger;
// list_electric_rate[j].elec_rate_unit_id:= dataElectricRate.FieldByName('ELECTR_UNT_ID').AsInteger;
// list_electric_rate[j].elec_rate_group:= dataElectricRate.FieldByName('ELECTR_GROUP').AsString;
// list_electric_rate[j].elec_rate_power:= dataElectricRate.FieldByName('ELECTR_POWER').AsFloat;
// list_electric_rate[j].elec_rate_charge:= dataElectricRate.FieldByName('ELECTR_COST_ABODEMEN').AsCurrency;
//
// strgElectricCustomer.Combobox.Items.Add(dataElectricRate.FieldByName('ELECTR_GROUP').AsString);
// dataElectricRate.Next;
// end;
// strgElectricCustomer.Combobox.ItemIndex:= 0;
// end;
// }
//end;
procedure TfrmElectricCustomer.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
// inherited;
if(Key = Ord('C')) and (ssctrl in Shift) then
begin
if not isOnAdd then
actAddExecute(Self)
else
Exit
end
else if(Key = Ord('E')) and (ssctrl in Shift) then
begin
if not isOnEdit then
actEditExecute(Self)
else
Exit
end
else if(Key = VK_RETURN) and (ssctrl in Shift) then
begin
if isOnAdd then
actAddExecute(Self)
else if isOnEdit then
actEditExecute(Self)
else
Exit
end
else if(Key = VK_Delete) and (ssctrl in Shift) then //History PO
begin
// if Not isOnAdd then
// actDeleteElectricCustomerExecute(Self)
// else if not isOnEdit then
// actDeleteElectricCustomerExecute(Self)
// else
// Exit
end
else if(Key = VK_Escape) and (ssctrl in Shift) then //History PO
begin
if isOnAdd then
Exit
else if isOnEdit then
Exit
else
Close
end
end;
procedure TfrmElectricCustomer.btnPrintClick(Sender: TObject);
//var
// sSQL: string;
// aCustCode: String;
begin
inherited;
{
if cbpCustCode.Cells[0,cbpCustCode.Row] <> '' then begin
if cbpCustCode.Cells[0,cbpCustCode.Row] = '-' then
begin
SetLength(arrParam,0);
aCustCode := '';
end
else begin
SetLength(arrParam,1);
arrParam[0].tipe := ptString;
arrParam[0].data := cbpCustCode.Cells[0,cbpCustCode.Row];
aCustCode := cbpCustCode.Cells[0,cbpCustCode.Row];
end;
end;
sSQL := GetListElectricCustomerByCustomerIdSQL(aCustCode);
frVariables.Variable['Floginname'] := fLoginFullname;
frVariables.Variable['Funitname'] := MasterNewUnit.Nama;
frVariables.Variable['FCustCode'] := aCustCode;
frVariables.Variable['FCustName'] := edtCustName.Text;
dmReportNew.EksekusiReport('frListElectricCustomer', sSQL, '', True);
}
end;
procedure TfrmElectricCustomer.RefreshData;
begin
inherited;
// TODO -cMM: TfrmElectricCustomer.RefreshData default body inserted
end;
end.
|
unit uArrayListOfLayer;
interface
uses uArrayList, uLayer;
{
Automatic dynamic layers array
}
type ArrayListOfLayer = class(ArrayList)
public
procedure add(l: Layer); overload;
procedure put(l: Layer; index: integer); overload;
function remove(index: integer): Layer; overload;
procedure remove(l: Layer); overload;
function get(index: integer): Layer; overload;
function find(l: Layer): integer; overload;
end;
implementation
// ArrayListOfLayer
procedure ArrayListOfLayer.add(l: Layer);
begin
inherited add(l);
end;
// ArrayListOfLayer
procedure ArrayListOfLayer.put(l: Layer; index: integer);
begin
inherited put(l, index);
end;
// ArrayListOfLayer
function ArrayListOfLayer.remove(index: integer): Layer;
begin
remove := inherited remove(index) as Layer;
end;
// ArrayListOfLayer
procedure ArrayListOfLayer.remove(l: Layer);
var i: integer;
begin
for i := 0 to size() - 1 do begin
if (arr[i] as Layer) = l then begin
remove(i);
break;
end;
end;
end;
// ArrayListOfLayer
function ArrayListOfLayer.get(index: integer): Layer;
begin
get := inherited get(index) as Layer;
end;
// ArrayListOfLayer
function ArrayListOfLayer.find(l: Layer): integer;
var i: integer;
begin
find := -1;
for i := 0 to len - 1 do
if l = get(i) then begin
find := i;
break;
end;
end;
end.
|
unit Scanner;
interface
const
TOK_EOF = 0;
TOK_IDENT = 1;
TOK_CURL_OPEN = 2;
TOK_CURL_CLOSE = 3;
TOK_COLON = 4;
TOK_SQUARE_OPEN = 5;
TOK_SQUARE_CLOSE = 6;
TOK_COMMA = 7;
TOK_ASSIGN = 8;
TOK_ARROW = 9;
TOK_DOT = 10;
TOK_ANGLE_OPEN = 11;
TOK_ANGLE_CLOSE = 12;
TOK_INVALID = 255;
var
lastToken: integer;
lastIdent: string;
procedure TokenOpenFile(name: string);
procedure TokenNext();
implementation
uses
Sysutils;
var
lastChar: char;
inputFile: TextFile;
charAvailable: boolean;
procedure NextChar();
begin
if not charAvailable or eof(inputFile) then
charAvailable := false
else
read(inputFile, lastChar);
end;
procedure TokenOpenFile(name: string);
begin
AssignFile(inputFile, name);
try
Reset(inputFile);
charAvailable := true;
NextChar();
TokenNext();
except
on E: EInOutError do
writeln('File handling error occurred. Details: ', E.Message);
end;
end;
procedure TokenNext();
begin
while charAvailable and ((lastChar = ' ') or (lastChar = #10)) do
NextChar();
if not charAvailable then
begin
lastToken := TOK_EOF
end
else if lastChar in ['a'..'z', 'A'..'Z'] then
begin
lastIdent := '';
while lastChar in ['a'..'z', 'A'..'Z','0'..'9','_'] do
begin
lastIdent := lastIdent + lastChar;
NextChar();
end;
lastToken := TOK_IDENT;
end
else
begin
case lastChar of
':': begin
NextChar();
case lastChar of
'=': lastToken := TOK_ASSIGN;
else
lastToken := TOK_COLON;
end;
end;
'{': begin
lastToken := TOK_CURL_OPEN;
NextChar();
end;
'}': begin
lastToken := TOK_CURL_CLOSE;
NextChar();
end;
'[': begin
lastToken := TOK_SQUARE_OPEN;
NextChar();
end;
']': begin
lastToken := TOK_SQUARE_CLOSE;
NextChar();
end;
'<': begin
lastToken := TOK_ANGLE_OPEN;
NextChar();
end;
'>': begin
lastToken := TOK_ANGLE_CLOSE;
NextChar();
end;
',': begin
lastToken := TOK_COMMA;
NextChar();
end;
'.': begin
lastToken := TOK_DOT;
NextChar();
end;
'-': begin
NextChar();
case lastChar of
'>': begin
lastToken := TOK_ARROW;
NextChar();
end;
else
lastToken := TOK_INVALID;
end;
end;
else
lastToken := TOK_INVALID
end;
end;
end;
end.
|
unit Demo;
interface
uses
System.Types,
System.Classes,
System.SysUtils,
System.Generics.Collections,
Duktape;
type
TDemo = class;
TDemoClass = class of TDemo;
TDemoInfo = record
Name: String;
Clazz: TDemoClass;
end;
TDemo = class abstract
{$REGION 'Internal Declarations'}
private class var
FDemos: TList<TDemoInfo>;
FOutput: TStrings;
private
FDuktape: TDuktape;
protected
procedure PushResource(const AResourceName: String);
class procedure Log(const AMsg: String); static;
property Duktape: TDuktape read FDuktape;
protected
class function NativePrint(const ADuktape: TDuktape): TdtResult; cdecl; static;
public
class constructor Create;
class destructor Destroy;
{$ENDREGION 'Internal Declarations'}
public
class procedure Register(const AName: String; const AClass: TDemoClass); static;
class function GetDemos: TArray<TDemoInfo>; static;
public
constructor Create(const AOutput: TStrings); virtual;
destructor Destroy; override;
procedure Run; virtual; abstract;
end;
implementation
{$R 'Resources.res'}
{ TDemo }
class constructor TDemo.Create;
begin
FDemos := TList<TDemoInfo>.Create;
end;
constructor TDemo.Create(const AOutput: TStrings);
begin
inherited Create;
FOutput := AOutput;
FDuktape := TDuktape.Create(True);
FDuktape.PushDelphiFunction(NativePrint, DT_VARARGS);
FDuktape.PutGlobalString('print');
end;
destructor TDemo.Destroy;
begin
FDuktape.Free;
FOutput := nil;
inherited;
end;
class destructor TDemo.Destroy;
begin
FDemos.Free;
end;
class function TDemo.GetDemos: TArray<TDemoInfo>;
begin
Result := FDemos.ToArray;
end;
class procedure TDemo.Log(const AMsg: String);
begin
FOutput.Add(AMsg);
end;
class function TDemo.NativePrint(const ADuktape: TDuktape): TdtResult;
var
S: DuktapeString;
begin
ADuktape.PushString(' ');
ADuktape.Insert(0);
ADuktape.Join(ADuktape.GetTop - 1);
S := ADuktape.SafeToString(-1);
Log(String(S));
Result := TdtResult.NoResult;
end;
procedure TDemo.PushResource(const AResourceName: String);
var
Stream: TResourceStream;
Source: DuktapeString;
begin
Stream := TResourceStream.Create(HInstance, AResourceName, RT_RCDATA);
try
SetLength(Source, Stream.Size);
Stream.ReadBuffer(Source[Low(DuktapeString)], Stream.Size);
finally
Stream.Free;
end;
FDuktape.PushString(Source);
end;
class procedure TDemo.Register(const AName: String; const AClass: TDemoClass);
var
Info: TDemoInfo;
begin
Info.Name := AName;
Info.Clazz := AClass;
FDemos.Add(Info);
end;
end.
|
namespace Anonymous_Methods;
interface
uses
System.Windows.Forms,
System.Drawing,
System.Threading;
type
/// <summary>
/// Summary description for MainForm.
/// </summary>
MainForm = class(System.Windows.Forms.Form)
{$REGION Windows Form Designer generated fields}
private
btnRestore: System.Windows.Forms.Button;
txtName: System.Windows.Forms.TextBox;
groupBox1: System.Windows.Forms.GroupBox;
label1: System.Windows.Forms.Label;
btnFindByName: System.Windows.Forms.Button;
btnSort: System.Windows.Forms.Button;
lbCustomers: System.Windows.Forms.ListBox;
fCustomers: System.Collections.Generic.List<Customer>;
threadSafeTextBox: Anonymous_Methods.ThreadSafeTextBox;
btnUsingInThreads: System.Windows.Forms.Button;
gbLog: System.Windows.Forms.GroupBox;
components: System.ComponentModel.Container := nil;
method InitializeComponent;
{$ENDREGION}
private
method CreateThreadSafeTextBox;
method txtName_KeyDown(sender: System.Object; e: System.Windows.Forms.KeyEventArgs);
method btnRestore_Click(sender: System.Object; e: System.EventArgs);
method btnFindByName_Click(sender: System.Object; e: System.EventArgs);
method btnSort_Click(sender: System.Object; e: System.EventArgs);
method MainForm_Load(sender: System.Object; e: System.EventArgs);
method btnUsingInThreads_Click(sender: System.Object; e: System.EventArgs);
protected
method Dispose(aDisposing: Boolean); override;
public
constructor;
end;
ThreadSafeTextBox = public class(System.Windows.Forms.TextBox)
public
constructor;
method AppendLine(aText: String);
end;
Customer = public class
private
fAge: Integer;
fName: String;
fID: Integer;
public
constructor(aID: Integer; aName: String; anAge: Integer);
method ToString: String; override;
property ID: Integer read fID write fID;
property Name: String read fName write fName;
property Age: Integer read fAge write fAge;
end;
implementation
{$REGION Construction and Disposition}
constructor MainForm;
begin
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
CreateThreadSafeTextBox;
end;
method MainForm.Dispose(aDisposing: boolean);
begin
if aDisposing then begin
if assigned(components) then
components.Dispose();
//
// TODO: Add custom disposition code here
//
end;
inherited Dispose(aDisposing);
end;
{$ENDREGION}
{$REGION Windows Form Designer generated code}
method MainForm.InitializeComponent;
begin
var resources: System.ComponentModel.ComponentResourceManager := new System.ComponentModel.ComponentResourceManager(typeOf(MainForm));
self.gbLog := new System.Windows.Forms.GroupBox();
self.label1 := new System.Windows.Forms.Label();
self.btnUsingInThreads := new System.Windows.Forms.Button();
self.lbCustomers := new System.Windows.Forms.ListBox();
self.btnSort := new System.Windows.Forms.Button();
self.btnFindByName := new System.Windows.Forms.Button();
self.groupBox1 := new System.Windows.Forms.GroupBox();
self.txtName := new System.Windows.Forms.TextBox();
self.btnRestore := new System.Windows.Forms.Button();
self.gbLog.SuspendLayout();
self.groupBox1.SuspendLayout();
self.SuspendLayout();
//
// gbLog
//
self.gbLog.Controls.Add(self.label1);
self.gbLog.Controls.Add(self.btnUsingInThreads);
self.gbLog.Location := new System.Drawing.Point(12, 12);
self.gbLog.Name := 'gbLog';
self.gbLog.Size := new System.Drawing.Size(208, 235);
self.gbLog.TabIndex := 0;
self.gbLog.TabStop := false;
self.gbLog.Text := 'Using with Threads';
//
// label1
//
self.label1.Anchor := ((((System.Windows.Forms.AnchorStyles.Top or System.Windows.Forms.AnchorStyles.Bottom)
or System.Windows.Forms.AnchorStyles.Left)
or System.Windows.Forms.AnchorStyles.Right) as System.Windows.Forms.AnchorStyles);
self.label1.Location := new System.Drawing.Point(6, 50);
self.label1.Name := 'label1';
self.label1.Size := new System.Drawing.Size(196, 32);
self.label1.TabIndex := 1;
self.label1.Text := 'TextBox below provides AppendLine method that is thread-safe';
self.label1.TextAlign := System.Drawing.ContentAlignment.MiddleCenter;
//
// btnUsingInThreads
//
self.btnUsingInThreads.Location := new System.Drawing.Point(6, 19);
self.btnUsingInThreads.Name := 'btnUsingInThreads';
self.btnUsingInThreads.Size := new System.Drawing.Size(196, 23);
self.btnUsingInThreads.TabIndex := 0;
self.btnUsingInThreads.Text := 'Run Threads';
self.btnUsingInThreads.UseVisualStyleBackColor := true;
self.btnUsingInThreads.Click += new System.EventHandler(@self.btnUsingInThreads_Click);
//
// lbCustomers
//
self.lbCustomers.Anchor := ((((System.Windows.Forms.AnchorStyles.Top or System.Windows.Forms.AnchorStyles.Bottom)
or System.Windows.Forms.AnchorStyles.Left)
or System.Windows.Forms.AnchorStyles.Right) as System.Windows.Forms.AnchorStyles);
self.lbCustomers.FormattingEnabled := true;
self.lbCustomers.Location := new System.Drawing.Point(6, 19);
self.lbCustomers.Name := 'lbCustomers';
self.lbCustomers.Size := new System.Drawing.Size(222, 121);
self.lbCustomers.TabIndex := 0;
//
// btnSort
//
self.btnSort.Location := new System.Drawing.Point(6, 148);
self.btnSort.Name := 'btnSort';
self.btnSort.Size := new System.Drawing.Size(222, 23);
self.btnSort.TabIndex := 1;
self.btnSort.Text := 'Sort Customers by Age';
self.btnSort.UseVisualStyleBackColor := true;
self.btnSort.Click += new System.EventHandler(@self.btnSort_Click);
//
// btnFindByName
//
self.btnFindByName.Location := new System.Drawing.Point(145, 177);
self.btnFindByName.Name := 'btnFindByName';
self.btnFindByName.Size := new System.Drawing.Size(83, 23);
self.btnFindByName.TabIndex := 3;
self.btnFindByName.Text := 'Find By Name';
self.btnFindByName.UseVisualStyleBackColor := true;
self.btnFindByName.Click += new System.EventHandler(@self.btnFindByName_Click);
//
// groupBox1
//
self.groupBox1.Controls.Add(self.txtName);
self.groupBox1.Controls.Add(self.btnRestore);
self.groupBox1.Controls.Add(self.lbCustomers);
self.groupBox1.Controls.Add(self.btnFindByName);
self.groupBox1.Controls.Add(self.btnSort);
self.groupBox1.Location := new System.Drawing.Point(226, 12);
self.groupBox1.Name := 'groupBox1';
self.groupBox1.Size := new System.Drawing.Size(234, 235);
self.groupBox1.TabIndex := 1;
self.groupBox1.TabStop := false;
self.groupBox1.Text := 'Working with Collections';
//
// txtName
//
self.txtName.Location := new System.Drawing.Point(6, 179);
self.txtName.Name := 'txtName';
self.txtName.Size := new System.Drawing.Size(133, 20);
self.txtName.TabIndex := 2;
self.txtName.Text := 'Alex';
self.txtName.KeyDown += new System.Windows.Forms.KeyEventHandler(@self.txtName_KeyDown);
//
// btnRestore
//
self.btnRestore.Location := new System.Drawing.Point(6, 206);
self.btnRestore.Name := 'btnRestore';
self.btnRestore.Size := new System.Drawing.Size(222, 23);
self.btnRestore.TabIndex := 4;
self.btnRestore.Text := 'Restore List';
self.btnRestore.UseVisualStyleBackColor := true;
self.btnRestore.Click += new System.EventHandler(@self.btnRestore_Click);
//
// MainForm
//
self.ClientSize := new System.Drawing.Size(483, 271);
self.Controls.Add(self.groupBox1);
self.Controls.Add(self.gbLog);
self.FormBorderStyle := System.Windows.Forms.FormBorderStyle.FixedDialog;
self.Icon := (resources.GetObject('$this.Icon') as System.Drawing.Icon);
self.MaximizeBox := false;
self.MaximumSize := new System.Drawing.Size(489, 299);
self.MinimumSize := new System.Drawing.Size(489, 299);
self.Name := 'MainForm';
self.Text := 'Anonymous Methods';
self.Load += new System.EventHandler(@self.MainForm_Load);
self.gbLog.ResumeLayout(false);
self.groupBox1.ResumeLayout(false);
self.groupBox1.PerformLayout();
self.ResumeLayout(false);
end;
{$ENDREGION}
method MainForm.CreateThreadSafeTextBox;
begin
self.threadSafeTextBox := new Anonymous_Methods.ThreadSafeTextBox();
self.threadSafeTextBox.Anchor := ((((System.Windows.Forms.AnchorStyles.Top or System.Windows.Forms.AnchorStyles.Bottom)
or System.Windows.Forms.AnchorStyles.Left)
or System.Windows.Forms.AnchorStyles.Right) as System.Windows.Forms.AnchorStyles);
self.threadSafeTextBox.Location := new System.Drawing.Point(6, 80);
self.threadSafeTextBox.Multiline := true;
self.threadSafeTextBox.Name := 'threadSafeTextBox';
self.threadSafeTextBox.Size := new System.Drawing.Size(196, 149);
self.threadSafeTextBox.TabIndex := 2;
self.threadSafeTextBox.ScrollBars := ScrollBars.Both;
self.gbLog.Controls.Add(self.threadSafeTextBox);
end;
constructor Customer(aID: Integer; aName: String; anAge: Integer);
begin
fID := aID;
fName := aName;
fAge := anAge;
end;
method Customer.ToString: String;
begin
exit(String.Format('Id:{0}; Name:{1}; Age:{2}', fID, fName, fAge));
end;
constructor ThreadSafeTextBox;
begin
Multiline := true;
end;
method ThreadSafeTextBox.AppendLine(aText: String);
begin
if(Self.InvokeRequired) then begin
Invoke(
method;
begin
Self.Text := Self.Text + aText + Environment.NewLine;
Self.SelectionStart := Self.Text.Length;
Self.ScrollToCaret();
end
);
end else
inherited Text := inherited Text + aText;
end;
method MainForm.btnUsingInThreads_Click(sender: System.Object; e: System.EventArgs);
var
lThreadCount: Integer := 5;
begin
var lMyParam: String := 'Hello from thread #{0}. i={1}';
for i: Integer := 0 to lThreadCount - 1 do begin
new Thread(
method();
begin
var lThreadID: Int32 := Thread.CurrentThread.ManagedThreadId;
threadSafeTextBox.AppendLine(String.Format(lMyParam, lThreadID, i));
end
).Start();
end;
end;
method MainForm.MainForm_Load(sender: System.Object; e: System.EventArgs);
begin
fCustomers := new System.Collections.Generic.List<Customer>;
btnRestore_Click(nil, nil);
end;
method MainForm.btnSort_Click(sender: System.Object; e: System.EventArgs);
begin
lbCustomers.DataSource := nil;
fCustomers.Sort(
method(c1: Customer; c2: Customer): Integer;
begin
exit(c1.Age.CompareTo(c2.Age));
end
);
lbCustomers.DataSource := fCustomers;
end;
method MainForm.btnFindByName_Click(sender: System.Object; e: System.EventArgs);
begin
var lPattern: String := txtName.Text;
lbCustomers.DataSource :=
fCustomers.FindAll(
method(c: Customer): Boolean;
begin
exit(c.Name.ToLower.Contains(lPattern.ToLower()));
end
);
end;
method MainForm.btnRestore_Click(sender: System.Object; e: System.EventArgs);
begin
lbCustomers.DataSource := nil;
fCustomers.Clear();
fCustomers.Add(new Customer(1, 'Antonio Moreno', 32));
fCustomers.Add(new Customer(2, 'Elizabeth Lincoln', 41));
fCustomers.Add(new Customer(3, 'Aria Cruz', 37));
fCustomers.Add(new Customer(4, 'Helena Doe', 28));
fCustomers.Add(new Customer(5, 'Philip Cramer', 34));
fCustomers.Add(new Customer(6, 'Alexander Feuer', 30));
fCustomers.Add(new Customer(7, 'Michael Holz', 45));
lbCustomers.DataSource := fCustomers;
end;
method MainForm.txtName_KeyDown(sender: System.Object; e: System.Windows.Forms.KeyEventArgs);
begin
if e.KeyCode = Keys.Return then btnFindByName_Click(sender, nil);
end;
end. |
//**********************************************************************************************************************
// $Id: uTranEdPlugin.pas,v 1.6 2006-09-12 13:29:40 dale Exp $
//----------------------------------------------------------------------------------------------------------------------
// DKLang Translation Editor
// Copyright ęDK Software, http://www.dk-soft.org/
//**********************************************************************************************************************
// Translation Editor plugin interface declarations
//
unit uTranEdPlugin;
interface
uses Windows;
type
IDKLang_TranEd_Plugin = interface;
IDKLang_TranEd_Application = interface;
IDKLang_TranEd_Translator = interface;
//===================================================================================================================
// Prototypes of procedures exported from a plugin DLL
//===================================================================================================================
// Returns version of plugin subsystem module plugins implement. Should return value of
// IDKLang_TranEd_PluginSubsystemVersion constant (declared below). Must be named 'DKLTE_GetPluginSubsystemVersion'
TDKLang_TranEd_GetPluginSubsystemVersionProc = procedure(out iVersion: Integer); stdcall;
// Returns number of distinct plugins implemented in a module. Must be named 'DKLTE_GetPluginCount'
TDKLang_TranEd_GetPluginCountProc = procedure(out iCount: Integer); stdcall;
// Instantiates and returns plugin with a specific index (ranged 0..PluginCount-1). Must be named 'DKLTE_GetPlugin'.
// TranEdApplication is Translation Editor application environment
TDKLang_TranEd_GetPluginProc = procedure(iIndex: Integer; TranEdApplication: IDKLang_TranEd_Application; out Plugin: IDKLang_TranEd_Plugin); stdcall;
//===================================================================================================================
// Translation Editor application environment
//===================================================================================================================
IDKLang_TranEd_Application = interface(IInterface)
['{7270D20E-7320-484B-B7DB-DFA3AEEA1E6E}']
// Closes all open files. Returns True if succeeded, False when the translation file is unsaved and the user has
// cancelled the action
function FilesClose: LongBool; stdcall;
// Uses the specified file names as suggested, shows select files dialog and loads the files. Returns True if user
// clicked OK
function FilesOpen(const wsLangSrcFileName, wsDisplayFileName, wsTranFileName: WideString): LongBool; stdcall;
// Loads the specified files
procedure FilesLoad(const wsLangSrcFileName, wsDisplayFileName, wsTranFileName: WideString); stdcall;
// Saves the translation currently open into the specified file. bUnicode specifies whether it should be in ANSI
// encoding (bUnicode=False) or in Unicode (bUnicode=True). Returns True if saved OK, False when the user was
// warned about source and translation file encodings differ and cancelled the action
function FilesSave(const wsFileName: WideString; bUnicode: LongBool): LongBool; stdcall;
// Translates selected entries using the supplied Translator interface
procedure TranslateSelected(Translator: IDKLang_TranEd_Translator); stdcall;
// Prop handlers
function GetAppHandle: HWND; stdcall;
function GetDisplayFileName: WideString; stdcall;
function GetIsFileOpen: LongBool; stdcall;
function GetIsModified: LongBool; stdcall;
function GetLangIDSource: LANGID; stdcall;
function GetLangIDTranslation: LANGID; stdcall;
function GetLanguageSourceFileName: WideString; stdcall;
function GetMainWindowHandle: HWND; stdcall;
function GetSelectedItemCount: Integer; stdcall;
function GetTranslationFileName: WideString; stdcall;
// Props
// -- Application window's handle
property AppHandle: HWND read GetAppHandle;
// -- Full path to translation file used to display original values. Empty string if there is no open language
// source file or no display file is used
property DisplayFileName: WideString read GetTranslationFileName;
// -- True when there is an open language source file
property IsFileOpen: LongBool read GetIsFileOpen;
// -- True if the translation file was modified and not yet saved
property IsModified: LongBool read GetIsModified;
// -- Source translation language ID
property LangIDSource: LANGID read GetLangIDSource;
// -- Target translation language ID
property LangIDTranslation: LANGID read GetLangIDTranslation;
// -- Full path to language source file. Empty string if there is no open language source file
property LanguageSourceFileName: WideString read GetLanguageSourceFileName;
// -- Main program window's handle
property MainWindowHandle: HWND read GetMainWindowHandle;
// -- Number of items currently selected
property SelectedItemCount: Integer read GetSelectedItemCount;
// -- Full path to translation file. Empty string if there is no open language source file or an unsaved
// translation is being edited
property TranslationFileName: WideString read GetTranslationFileName;
end;
//===================================================================================================================
// Single item translator interface
//===================================================================================================================
IDKLang_TranEd_Translator = interface(IInterface)
['{C05CA756-72B8-4218-94C7-63979DF07D59}']
// Performs translation from source LANGID to target one. Should return True on successful translation, False if
// translation failed
function Translate(wSourceLangID, wTargetLangID: LANGID; const wsSourceText: WideString; out wsResult: WideString): LongBool; stdcall;
end;
//===================================================================================================================
// An abstract Translation Editor plugin
//===================================================================================================================
IDKLang_TranEd_PluginAction = interface;
IDKLang_TranEd_Plugin = interface(IInterface)
['{561450F5-AD45-4C60-A84D-36668DA248A0}']
// Prop handlers
function GetActionCount: Integer; stdcall;
function GetActions(iIndex: Integer): IDKLang_TranEd_PluginAction; stdcall;
function GetName: WideString; stdcall;
// Props
// -- Plugin name. Example: 'SuperPlugin'
property Name: WideString read GetName;
// -- Number of different actions plugin implements
property ActionCount: Integer read GetActionCount;
// -- Plugin actions by index (iIndex is in range [0..ActionCount-1]; actions may be instantiated on read)
property Actions[iIndex: Integer]: IDKLang_TranEd_PluginAction read GetActions;
end;
//===================================================================================================================
// Plugin information, optional interface a plugin may implement
//===================================================================================================================
IDKLang_TranEd_PluginInfo = interface(IInterface)
['{561450F5-AD45-4C60-A84D-36668DA248A1}']
// Prop handlers
function GetInfoAuthor: WideString; stdcall;
function GetInfoCopyright: WideString; stdcall;
function GetInfoDescription: WideString; stdcall;
function GetInfoVersion: Cardinal; stdcall;
function GetInfoVersionText: WideString; stdcall;
function GetInfoWebsiteURL: WideString; stdcall;
// Props
// -- Module author info. Example: 'SuperSoft Solutions Inc.'
property InfoAuthor: WideString read GetInfoAuthor;
// -- Module copyright info. Example: 'Copyright (c)1890-2005 SuperSoft Solutions Inc.'
property InfoCopyright: WideString read GetInfoCopyright;
// -- Module description. Example: 'A plugin doing just everything'
property InfoDescription: WideString read GetInfoDescription;
// -- Module version; each byte represents a single version part. Example: version 1.1.10.78 will be $01010a4e
property InfoVersion: Cardinal read GetInfoVersion;
// -- Module text version; should match InfoVersion value, but additionally can include a version qualifier.
// Example: '1.1.10.78 beta'
property InfoVersionText: WideString read GetInfoVersionText;
// -- Module website or download URL. Example: 'http://www.dk-soft.org/';
property InfoWebsiteURL: WideString read GetInfoWebsiteURL;
end;
//===================================================================================================================
// Plugin action (executed with a menu item, a button etc.)
//===================================================================================================================
IDKLang_TranEd_PluginAction = interface(IInterface)
['{32768B1A-9654-40EA-900B-AB94B8245A22}']
// Should execute the action
procedure Execute; stdcall;
// Prop handlers
function GetHint: WideString; stdcall;
function GetIsEnabled: LongBool; stdcall;
function GetName: WideString; stdcall;
function GetStartsGroup: LongBool; stdcall;
// Props
// -- Action hint (displayed as a tooltip and in the status bar; use pipe ('|') character to separate tooltip and
// status bar text). Example: 'Translate using Universal Mind|Translates selected entries using Universal Mind'
property Hint: WideString read GetHint;
// -- True if action is enabled, False otherwise
property IsEnabled: LongBool read GetIsEnabled;
// -- Action name (menu item or button text). Example: '&Translate using Universal Mind'
property Name: WideString read GetName;
// -- If True, a separator is inserted before the item
property StartsGroup: LongBool read GetStartsGroup;
end;
const
// Version of the plugin subsystem plugins implement
IDKLang_TranEd_PluginSubsystemVersion = 1;
implementation
end.
|
unit uSaleCommission;
interface
uses SysUtils, Classes;
type
TSaleCommission = class
private
FIDSale: Integer;
FSaleType: Integer;
FCommissionList: TStringList;
procedure InsertCommission;
procedure DeleteCommission;
procedure AddCommission(AID: Integer; AName: String; APercent: Double);
public
constructor Create;
destructor Destroy; override;
procedure LoadCommissionList;
property IDSale: Integer read FIDSale write FIDSale;
property SaleType: Integer read FSaleType write FSaleType;
property CommissionList: TStringList read FCommissionList write FCommissionList;
end;
implementation
uses ADODB, uFrmPOSFunctions, uSystemConst, uDM;
{ TSaleCommission }
procedure TSaleCommission.AddCommission(AID: Integer; AName: String; APercent: Double);
var
SalesPerson: TSalesPerson;
begin
SalesPerson := TSalesPerson.Create;
SalesPerson.IDPessoa := AID;
SalesPerson.Pessoa := AName;
SalesPerson.Percent := APercent;
FCommissionList.AddObject(SalesPerson.Pessoa + ' - ' +
FloattoStr(SalesPerson.Percent) + '%', SalesPerson);
end;
constructor TSaleCommission.Create;
begin
FCommissionList := TStringList.Create;
end;
procedure TSaleCommission.DeleteCommission;
begin
end;
destructor TSaleCommission.Destroy;
begin
FreeAndNil(FCommissionList);
inherited;
end;
procedure TSaleCommission.InsertCommission;
begin
end;
procedure TSaleCommission.LoadCommissionList;
const
SQLCommisionList = 'select Pessoa, IDPessoa, CommissionPercent ' +
'from SaleItemCommission SIC ' +
'join Pessoa P on (SIC.IDCoMmission = P.IDPessoa) ' +
'where ';
begin
FCommissionList.Clear;
with TADOQuery.Create(nil) do
try
Connection := DM.ADODBConnect;
case FSaleType of
SALE_INVOICE:
SQL.Text := SQLCommisionList + 'IDInventoryMov = ' + InttoStr(FIDSale)
else
SQL.Text := SQLCommisionList + 'IDPreInventoryMov = ' + InttoStr(FIDSale);
end;
First;
while not EOF do
begin
AddCommission(FieldByName('IDPessoa').AsInteger,
FieldByName('Pessoa').AsString, FieldByName('CommissionPercent').AsFloat);
Next;
end;
finally
Free;
end;
end;
end.
|
////////////////////////////////////////////////////////////////////////////
// PaxCompiler
// Site: http://www.paxcompiler.com
// Author: Alexander Baranovsky (paxscript@gmail.com)
// ========================================================================
// Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved.
// Code Version: 4.2
// ========================================================================
// Unit: PAXCOMP_GC.pas
// ========================================================================
////////////////////////////////////////////////////////////////////////////
{$I PaxCompiler.def}
{$O-}
unit PAXCOMP_GC;
interface
uses {$I uses.def}
SysUtils,
Classes,
PAXCOMP_TYPES,
PAXCOMP_SYS;
const
MAX_OBJECTS: Integer = 1024;
type
TGC = class;
TGC_Object = class(TPersistent)
private
fRefCount: Integer;
public
constructor Create;
function AddRef: Integer;
function __toString: String; virtual;
function GetGC: TGC; virtual; abstract;
property RefCount: Integer read fRefCount write fRefCount;
end;
PGC_Object = ^TGC_Object;
TGC = class(TTypedList)
private
GC_Ref: TPtrList;
Bound: Integer;
function GetRecord(I: Integer): TGC_Object;
public
constructor Create;
destructor Destroy; override;
procedure Clear; override;
procedure ClearRef;
procedure ClearObjects;
function AddObject(X: TGC_Object): Integer;
function AddReference(X: TGC_Object): Integer;
procedure Remove(X: TGC_Object);
procedure Collect;
procedure Mark;
property Records[I: Integer]: TGC_Object read GetRecord; default;
end;
procedure GC_Assign(Dest: PGC_Object; Source: TGC_Object);
implementation
procedure GC_Assign(Dest: PGC_Object; Source: TGC_Object);
var
GC: TGC;
begin
if Source = nil then
begin
if Dest = nil then
Exit;
if Dest^ = nil then
Exit;
GC := Dest^.GetGC;
Dec(Dest^.fRefCount);
if Dest^.fRefCount = 0 then
GC.Remove(Dest^);
Exit;
end;
GC := Source.GetGC;
Inc(Source.fRefCount);
if Dest^ <> nil then
begin
Dec(Dest^.fRefCount);
if Dest^.fRefCount = 0 then
GC.Remove(Dest^);
end;
Dest^ := Source;
end;
// TGC_Object ------------------------------------------------------------------
constructor TGC_Object.Create;
begin
inherited;
fRefCount := 1;
end;
function TGC_Object.__toString: String;
begin
result := '';
end;
function TGC_Object.AddRef: Integer;
begin
Inc(fRefCount);
Result := fRefCount;
end;
// TGC -------------------------------------------------------------------------
constructor TGC.Create;
begin
GC_Ref := TPtrList.Create;
Bound := 0;
inherited;
end;
destructor TGC.Destroy;
begin
Clear;
inherited;
GC_Ref.Free;
end;
procedure TGC.ClearRef;
var
I, K: Integer;
begin
K := GC_Ref.Count;
if K = 0 then
Exit;
for I := K - 1 downto 0 do
{$IFDEF ARC}
GC_Ref[I] := nil;
{$ELSE}
TObject(GC_Ref[I]).Free;
{$ENDIF}
GC_Ref.Clear;
end;
procedure TGC.Clear;
var
I: Integer;
begin
ClearRef;
for I := Count - 1 downto 0 do
{$IFDEF ARC}
L[I] := nil;
{$ELSE}
TObject(L[I]).Free;
{$ENDIF}
L.Clear;
Bound := 0;
end;
function TGC.GetRecord(I: Integer): TGC_Object;
begin
result := TGC_Object(L[I]);
end;
function TGC.AddObject(X: TGC_Object): Integer;
begin
result := L.IndexOf(X);
if result >= 0 then
Exit;
L.Add(X);
if L.Count = MAX_OBJECTS then
Collect;
result := L.Count;
end;
function TGC.AddReference(X: TGC_Object): Integer;
begin
result := GC_Ref.Add(X);
end;
procedure TGC.Remove(X: TGC_Object);
begin
L.Remove(X);
X.Free;
end;
procedure TGC.Collect;
var
I: Integer;
X: TGC_Object;
begin
for I := Count - 1 downto Bound do
begin
X := Records[I];
if X.RefCount <= 0 then
begin
L.Delete(I);
X.Free;
end;
end;
end;
procedure TGC.ClearObjects;
var
I: Integer;
X: TGC_Object;
begin
ClearRef;
for I := Count - 1 downto Bound do
begin
X := Records[I];
L.Delete(I);
X.Free;
end;
end;
procedure TGC.Mark;
begin
Bound := Count;
end;
end.
|
unit MainFrm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
OpenSSL.DSAUtils;
type
TMainForm = class(TForm)
btnSign: TButton;
btnVerify: TButton;
memSign: TMemo;
memSrc: TMemo;
pnlBottom: TPanel;
splTop: TSplitter;
procedure btnSignClick(Sender: TObject);
procedure btnVerifyClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FDSA: TDSAUtil;
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
uses
OpenSSL.Core;
{ TMainForm }
procedure TMainForm.btnSignClick(Sender: TObject);
var
R: TMemoryStream;
S: TStream;
D: TBytes;
begin
S := TStringStream.Create(memSrc.Text);
try
R := TMemoryStream.Create;
try
FDSA.PrivateSign(S, R);
SetLength(D, R.Size);
Move(R.Memory^, Pointer(D)^, R.Size);
D := Base64Encode(D);
R.Position := 0;
R.Size := Length(D);
Move(Pointer(D)^, R.Memory^, R.Size);
memSign.Lines.LoadFromStream(R);
finally
R.Free;
end;
finally
S.Free;
end;
end;
procedure TMainForm.btnVerifyClick(Sender: TObject);
var
R: TMemoryStream;
S: TStream;
D: TBytes;
begin
S := TStringStream.Create(memSrc.Text);
try
R := TMemoryStream.Create;
try
memSign.Lines.SaveToStream(R);
SetLength(D, R.Size);
Move(R.Memory^, Pointer(D)^, R.Size);
D := Base64Decode(D);
R.Position := 0;
R.Size := Length(D);
Move(Pointer(D)^, R.Memory^, R.Size);
Caption := BoolToStr(FDSA.PublicVerify(S, R), True);
finally
R.Free;
end;
finally
S.Free;
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
FDSA := TDSAUtil.Create;
FDSA.PublicKey.LoadFromFile('..\TestData\dsa_pub.pem');
FDSA.PrivateKey.LoadFromFile('..\TestData\dsa_priv.pem');
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
FreeAndNil(FDSA);
end;
end.
|
namespace Maps;
interface
uses
UIKit;
type
SearchResultsViewController = public class(UIViewController)
private
public
method init: id; override;
method viewDidLoad; override;
method didReceiveMemoryWarning; override;
property tableView: weak UITableView;
end;
implementation
method SearchResultsViewController.init: id;
begin
self := inherited init;
if assigned(self) then begin
// Custom initialization
end;
result := self;
end;
method SearchResultsViewController.viewDidLoad;
begin
inherited viewDidLoad;
// Do any additional setup after loading the view.
end;
method SearchResultsViewController.didReceiveMemoryWarning;
begin
inherited didReceiveMemoryWarning;
// Dispose of any resources that can be recreated.
end;
end.
|
//------------------------------------------------------------------------------
//InterSend UNIT
//------------------------------------------------------------------------------
// What it does-
// Contains any routines that involve sending information out from the
// inter server.
//
// Changes -
// May 22nd, 2007 - RaX - Created Header.
// June 28th, 2008 - Tsusai - Updated GetPacketLength to PacketDB.GetLength
// in various calls
//
//------------------------------------------------------------------------------
unit InterSend;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{RTL/VCL}
Classes,
{Project}
{3rd Party}
IdContext
;
Procedure InterSendWarpReplyToZone(
AClient : TIdContext;
CharacterID : LongWord;
ReturnIPCard : LongWord;
ReturnPort : Word;
MapName : String;
X : Word;
Y : Word
);
Procedure InterSendGMCommandToZone(
AClient : TIdContext;
const
GMID : LongWord;
const
CharacterID : LongWord;
const
ZoneID : LongWord;
const
CommandSeparator : TStringList;
const
TargetAID: LongWord = 0;
const
TargetCID: LongWord = 0
);
procedure InterSendGMCommandReplyToZone(
AClient : TIdContext;
const
CID : LongWord;
const
Error : TStringList
);
procedure InterParseGMCommand(
const
AClient : TIdContext;
const
GMID : LongWord;
const
CharaID : LongWord;
const
AZoneID : LongWord;
const
CommandString : String
);
procedure InterSendFriendRequest(
AClient : TIdContext;
const ReqAID, ReqID : LongWord;
const ReqName : String;
const TargetChar : LongWord
);
procedure InterSendFriendRequestReply(
AClient : TIdContext;
const OrigID : LongWord;
const AccID : LongWord;
const CharID : LongWord;
const CharName : String;
const Reply : Byte
);
procedure InterSendFriendOnlineStatus(
AClient : TIdContext;
const AID : LongWord;
const CID : LongWord;
const TargetAID : LongWord;
const TargetCID : LongWord;
const ZoneID : LongWord;
const Offline : Byte
);
procedure InterSendFriendStatusReply(
AClient : TIdContext;
const AID : LongWord;
const CID : LongWord;
const TargetID : LongWord;
const Offline : Byte
);
procedure InterSendMailNotify(
AClient : TIdContext;
const CharID : LongWord;
const MailID : LongWord;
const Sender : String;
const Title : String
);
procedure InterSendInstanceMapResult(
AClient : TIdContext;
const CharID : LongWord;
const ScriptID : LongWord;
const Flag : Byte;
const MapName : String
);
procedure InterSendCreateInstance(
AClient : TIdContext;
const ZoneID : LongWord;
const CharID : LongWord;
const ScriptID : LongWord;
const Identifier : String;
const MapName : String
);
implementation
uses
{RTL/VCL}
SysUtils,
{Project}
//none
PacketTypes,
Globals,
GMCommands,
BufferIO,
Main,
Character,
TCPServerRoutines,
GameConstants
{3rd Party}
//none
;
(*- Procedure -----------------------------------------------------------------*
InterSendGMCommandToZone
--------------------------------------------------------------------------------
Overview:
--
Sends the GM command to all connected zone servers.
{[2007/05/19] CR - TODO:
(open to anyone more knowledgable of this routine than I am!)
- Parameters are not yet explicitly var/const/in/out }
--
Revisions:
--
(Format: [yyyy/mm/dd] <Author> - <Comment>)
[2007/03/19] RaX - Created Header.
[2007/05/19] CR - Altered header, indent and style changes. Extracted a local
procedure to construct the packet ($2206), and slight optimizations made.
Used ClientList and ZoneServerLink properties for clarity.
*-----------------------------------------------------------------------------*)
Procedure InterSendGMCommandToZone(
AClient : TIdContext;
const
GMID : LongWord;
const
CharacterID : LongWord;
const
ZoneID : LongWord;
const
CommandSeparator : TStringList;
const
TargetAID: LongWord = 0;
const
TargetCID: LongWord = 0
);
Var
ABuffer : TBuffer;
CommandID : Integer;
Size : Cardinal;
(*- Local Procedure .................*
WritePacket2206
--
[2007/05/19] CR - Extracted from main body. Speedup: Using a local variable
to store the CommandSeparator length to avoid 2 extra function calls.
*...................................*)
procedure WritePacket2206;
var
BufferIndex : Integer;
CSLength : Integer;
Index : Integer;
begin
WriteBufferWord(0, $2206,ABuffer);
WriteBufferWord(4, CommandID, ABuffer);
WriteBufferLongWord(6, GMID, ABuffer);
WriteBufferLongWord(10, CharacterID, ABuffer);
WriteBufferLongWord(14, ZoneID, ABuffer);
WriteBufferLongWord(18, TargetAID, ABuffer);
WriteBufferLongWord(22, TargetCID, ABuffer);
WriteBufferWord(26, CommandSeparator.Count - 1, ABuffer);
BufferIndex := 28;//Where we are currently in the buffer.
//We then write the Command's arguments to the buffer.
for Index := 1 to CommandSeparator.Count - 1 do
begin
CSLength := Length(CommandSeparator[Index]);
WriteBufferWord(BufferIndex, CSLength, ABuffer);
Inc(BufferIndex, 2);
WriteBufferString(
BufferIndex,
CommandSeparator[Index],
CSLength,
ABuffer
);
Inc(BufferIndex, CSLength);
end;
Size := BufferIndex + 1;
WriteBufferWord(2, Size, ABuffer);
end;(* WritePacket2206
*...................................*)
Begin
with MainProc.InterServer do
begin
//Get the name of the command, remove the first character which is #
//Get the command ID to which the Command name is associated.
CommandID := Commands.GetCommandID(
Commands.GetCommandName(CommandSeparator[0])
);
//Test if valid gm command.
if (CommandID >= 0) then
begin
//start writing packet 2206 (see Notes/GM Command Packets.txt)
WritePacket2206;
SendBuffer(AClient, ABuffer, Size);
end;
end;
End; (* Proc TInterServer.InterSendGMCommandToZone
*-----------------------------------------------------------------------------*)
//------------------------------------------------------------------------------
//InterSendWarpReplyToZone PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Tells the zone server to approve the character's warp.
//
// Changes -
// April 26th, 2007 - RaX - Created.
//
//------------------------------------------------------------------------------
Procedure InterSendWarpReplyToZone(
AClient : TIdContext;
CharacterID : LongWord;
ReturnIPCard : LongWord;
ReturnPort : Word;
MapName : String;
X : Word;
Y : Word
);
var
Size : Word;
MapNameSize : Word;
ABuffer : TBuffer;
begin
MapNameSize := Length(MapName);
Size := MapNameSize + 20;
//<id>,<size>,<charaid>,<ip>,<port>,<x>,<y>,<mapnamesize><mapname>
WriteBufferWord(0, $2209, ABuffer);
WriteBufferWord(2, Size, ABuffer);
WriteBufferLongWord(4, CharacterID, ABuffer);
WriteBufferLongWord(8, ReturnIPCard, ABuffer);
WriteBufferWord(12, ReturnPort, ABuffer);
WriteBufferWord(14, X, ABuffer);
WriteBufferWord(16, Y, ABuffer);
WriteBufferword(18, MapNameSize, ABuffer);
WriteBufferString(20, MapName, MapNameSize, ABuffer);
SendBuffer(AClient, ABuffer, Size);
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//InterSendGMCommandReplyToZone PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Send command result to client
//
// Changes -
// [2007/08/09] Aeomin - Create.
//------------------------------------------------------------------------------
procedure InterSendGMCommandReplyToZone(
AClient : TIdContext;
const
CID : LongWord;
const
Error : TStringList
);
var
ABuffer : TBuffer;
BufferIndex : Integer;
CSLength : Integer;
Index : Integer;
begin
if Error.Count > 0 then
begin
WriteBufferWord(0, $2207, ABuffer);
WriteBufferLongWord(4, CID, ABuffer);
WriteBufferWord(8, Error.Count, ABuffer);
BufferIndex := 10;
for Index := 0 to Error.Count - 1 do
begin
CSLength := Length(Error[Index]);
WriteBufferWord(BufferIndex, CSLength, ABuffer);
Inc(BufferIndex, 2);
WriteBufferString(
BufferIndex,
Error[Index],
CSLength,
ABuffer
);
Inc(BufferIndex, CSLength);
end;
WriteBufferWord(2, BufferIndex + 1, ABuffer);
SendBuffer(AClient, ABuffer, BufferIndex + 1);
end;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//InterParseGMCommand PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// parse then send command result to client (Moved from RecvGMCommand)
// AZoneID should be the zone where commad result send to
//
// Changes -
// [2007/08/13] Aeomin - Create, Moved from RecvGMCommand.
//------------------------------------------------------------------------------
procedure InterParseGMCommand(
const
AClient : TIdContext;
const
GMID : LongWord;
const
CharaID : LongWord;
const
AZoneID : LongWord;
const
CommandString : String
);
var
CommandID : Word;
CommandSeparator : TStringList;
Index : Integer;
ListClient : TIdContext;
ACharacter : TCharacter;
ZoneID : Integer;
LoopIndex : Integer;
ZoneLink : TZoneServerLink;
Position : Integer;
Error : TStringList;
begin
CommandID := MainProc.InterServer.Commands.GetCommandID(
MainProc.InterServer.Commands.GetCommandName(CommandString)
);
CommandSeparator := TStringList.Create;
Error := TStringList.Create;
try
//Let's flag it!
if MainProc.InterServer.Commands.GetCommandNoBreak(CommandID) then
begin
Position := Pos(' ', CommandString);
if Position > 0 then
begin
CommandSeparator.Add(Copy(CommandString, 1, Position - 1));
CommandSeparator.Add(Copy(CommandString, Position + 1, StrLen(PChar(CommandString)) - Cardinal(Position)));
end else
begin
CommandSeparator.Add(CommandString);
end;
end else
begin
CommandSeparator.Delimiter := ',';
CommandSeparator.DelimitedText := CommandString;
end;
//Get command type
case MainProc.InterServer.Commands.GetCommandType(CommandID) of
//Send to ALL zones!
TYPE_ALLPLAYERS,
TYPE_BROADCAST: begin
//after getting the command information, we get ready to send it to the
//other zones.
for Index := (MainProc.InterServer.ClientList.Count - 1) downto 0 do
begin
if Assigned(MainProc.InterServer.ZoneServerLink[Index]) then
begin
ListClient := MainProc.InterServer.ClientList[Index];
InterSendGMCommandToZone(ListClient, GMID, CharaID, AZoneID, CommandSeparator);
end;
end;
end;
//Send back to orignal Zone
TYPE_RETURNBACK: begin
InterSendGMCommandToZone(AClient, GMID, CharaID, AZoneID, CommandSeparator);
end;
//We are controling other player
TYPE_TARGETCHAR: begin
with TZoneServerLink(AClient.Data).DatabaseLink do
begin
//At least 2 parameters required
if CommandSeparator.Count >= 2 then
begin
ACharacter := TCharacter.Create(AClient);
ACharacter.Name := CommandSeparator[1];
Character.Load(ACharacter);
ZoneID := Map.GetZoneID(ACharacter.Map);
Index := -1;
for LoopIndex := (MainProc.InterServer.ClientList.Count - 1) downto 0 do
begin
ZoneLink := MainProc.InterServer.ZoneServerLink[LoopIndex];
if (ZoneLink <> NIL) AND
(ZoneLink.Info.ZoneID = Cardinal(ZoneID)) then
begin
Index := LoopIndex;
Break;
end;
end;
if Index > -1 then
begin
//Same thing, but 2 extra parameters to store target character
InterSendGMCommandToZone(MainProc.InterServer.ClientList[Index], GMID, CharaID, AZoneID, CommandSeparator, ACharacter.AccountID, ACharacter.ID);
end else
begin
Error.Add('Character ''' + CommandSeparator[1] + ''' not found!');
InterSendGMCommandReplyToZone(AClient, CharaID, Error);
end;
ACharacter.Free;
end else
begin
Error.Add('Syntax Help:');
Error.Add(MainProc.InterServer.Commands.GetSyntax(CommandID));
InterSendGMCommandReplyToZone(AClient, CharaID, Error);
end;
end;
end;
//Map based control, ex. Kill all players in prontera
TYPE_TARGETMAP: begin
with TZoneServerLink(AClient.Data).DatabaseLink do
begin
if CommandSeparator.Count >= 2 then
begin
ZoneID := Map.GetZoneID(CommandSeparator[1]);
if ZoneID > -1 then
begin
Index := -1;
for LoopIndex := 0 to (MainProc.InterServer.ClientList.Count - 1) do
begin
ZoneLink := MainProc.InterServer.ZoneServerLink[LoopIndex];
if (ZoneLink <> NIL) AND
(ZoneLink.Info.ZoneID = Cardinal(ZoneID)) then
begin
Index := LoopIndex;
Break;
end;
end;
if Index > -1 then
begin
InterSendGMCommandToZone(MainProc.InterServer.ClientList[Index], GMID, CharaID, AZoneID, CommandSeparator);
end;
end else
begin
Error.Add('Map name ''' + CommandSeparator[1] + ''' not found!');
InterSendGMCommandReplyToZone(AClient, CharaID, Error);
end;
end else
begin
Error.Add('Syntax Help:');
Error.Add(MainProc.InterServer.Commands.GetSyntax(CommandID));
InterSendGMCommandReplyToZone(AClient, CharaID, Error);
end;
end;
end;
end;
finally
CommandSeparator.Free;
Error.Free;
end;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//InterSendFirendRequest PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Send add friend request to target zone
//--
// Pre:
// TODO
// Post:
// TODO
//--
// Changes -
// [2007/12/7] Aeomin - Created.
//------------------------------------------------------------------------------
procedure InterSendFriendRequest(
AClient : TIdContext;
const ReqAID, ReqID : LongWord;
const ReqName : String;
const TargetChar : LongWord
);
var
OutBuffer : TBuffer;
begin
WriteBufferWord(0, $2216, OutBuffer);
WriteBufferLongWord(2, ReqAID, OutBuffer);
WriteBufferLongWord(6, ReqID, OutBuffer);
WriteBufferLongWord(10, TargetChar, OutBuffer);
WriteBufferString(14, ReqName, NAME_LENGTH, OutBuffer);
SendBuffer(AClient, OutBuffer, PacketDB.GetLength($2216));
end;{InterSendFirendRequest}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//InterSendFirendRequest PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Send reply to zone
//--
// Pre:
// TODO
// Post:
// TODO
//--
// Changes -
// [2007/12/08] Aeomin - Created.
//------------------------------------------------------------------------------
procedure InterSendFriendRequestReply(
AClient : TIdContext;
const OrigID : LongWord;
const AccID : LongWord;
const CharID : LongWord;
const CharName : String;
const Reply : Byte
);
var
OutBuffer : TBuffer;
begin
// YEs using same packet...
WriteBufferWord(0, $2217, OutBuffer);
WriteBufferLongWord(2, OrigID, OutBuffer);
WriteBufferLongWord(6, AccID, OutBuffer);
WriteBufferLongWord(10, CharID, OutBuffer);
WriteBufferByte(14, Reply, OutBuffer);
WriteBufferString(15, CharName, NAME_LENGTH, OutBuffer);
SendBuffer(AClient, OutBuffer, PacketDB.GetLength($2217));
end;{InterSendFriendRequestReply}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//InterSendFriendOnlineStatus PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Send status update to target zone.
//--
// Pre:
// TODO
// Post:
// TODO
//--
// Changes -
// [2007/12/??] - Aeomin - Created
//------------------------------------------------------------------------------
procedure InterSendFriendOnlineStatus(
AClient : TIdContext;
const AID : LongWord;
const CID : LongWord;
const TargetAID : LongWord;
const TargetCID : LongWord;
const ZoneID : LongWord;
const Offline : Byte
);
var
OutBuffer : TBuffer;
begin
WriteBufferWord(0, $2219, OutBuffer);
WriteBufferLongWord(2, AID, OutBuffer);
WriteBufferLongWord(6, CID, OutBuffer);
WriteBufferLongWord(10, TargetAID, OutBuffer);
WriteBufferLongWord(14, TargetCID, OutBuffer);
WriteBufferLongWord(18, ZoneID, OutBuffer);
WriteBufferByte(22, Offline, OutBuffer);
SendBuffer(AClient, OutBuffer, PacketDB.GetLength($2219));
end;{InterSendFriendOnlineStatus}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//InterSendFriendStatusReply PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Send status back to origin zone.
//--
// Pre:
// TODO
// Post:
// TODO
//--
// Changes -
// [2007/12/??] - Aeomin - Created
//------------------------------------------------------------------------------
procedure InterSendFriendStatusReply(
AClient : TIdContext;
const AID : LongWord;
const CID : LongWord;
const TargetID : LongWord;
const Offline : Byte
);
var
OutBuffer : TBuffer;
begin
WriteBufferWord(0, $2221, OutBuffer);
WriteBufferLongWord(2, AID, OutBuffer);
WriteBufferLongWord(6, CID, OutBuffer);
WriteBufferLongWord(10, TargetID, OutBuffer);
WriteBufferByte(14, Offline, OutBuffer);
SendBuffer(AClient, OutBuffer, PacketDB.GetLength($2221));
end;{InterSendFriendStatusReply}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//InterSendMailNotify PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Send new mail notify to zone
//--
// Pre:
// TODO
// Post:
// TODO
//--
// Changes -
// [2008/08/11] Aeomin - Created
//------------------------------------------------------------------------------
procedure InterSendMailNotify(
AClient : TIdContext;
const CharID : LongWord;
const MailID : LongWord;
const Sender : String;
const Title : String
);
var
OutBuffer : TBuffer;
begin
WriteBufferWord(0, $2223, OutBuffer);
WriteBufferLongWord(2,CharID, OutBuffer);
WriteBufferLongWord(6,MailID, OutBuffer);
WriteBufferString(10,Sender,NAME_LENGTH, OutBuffer);
WriteBufferString(10+NAME_LENGTH, Title, 40, OutBuffer);
SendBuffer(AClient, OutBuffer, PacketDB.GetLength($2223));
end;{InterSendMailNotify}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//InterSendInstanceMapResult PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Send back results, fail if flag = 1
//
// Changes -
// [2008/12/06] Aeomin - Created
//------------------------------------------------------------------------------
procedure InterSendInstanceMapResult(
AClient : TIdContext;
const CharID : LongWord;
const ScriptID : LongWord;
const Flag : Byte;
const MapName : String
);
var
OutBuffer : TBuffer;
Len : Byte;
begin
Len := Length(MapName);
if Len > 0 then
begin
WriteBufferWord(0, $2225, OutBuffer);
WriteBufferWord(2, Len + 13, OutBuffer);
WriteBufferLongWord(4, CharID, OutBuffer);
WriteBufferLongWord(8, ScriptID, OutBuffer);
WriteBufferByte(12, Flag, OutBuffer);
WriteBufferString(13, MapName, Len, OutBuffer);
SendBuffer(AClient, OutBuffer, Len + 13);
end;
end;{nterSendInstanceMapResult}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//InterSendCreateInstance PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Tell zone server to instance map ..NOW!
//
// Changes -
// [2008/12/07] Aeomin - Created
//------------------------------------------------------------------------------
procedure InterSendCreateInstance(
AClient : TIdContext;
const ZoneID : LongWord;
const CharID : LongWord;
const ScriptID : LongWord;
const Identifier : String;
const MapName : String
);
var
OutBuffer : TBuffer;
Len : Byte;
begin
Len := Length(Identifier);
if Len > 0 then
begin
WriteBufferWord(0, $2227, OutBuffer);
WriteBufferWord(2, Len + 32, OutBuffer);
WriteBufferLongWord(4, ZoneID, OutBuffer);
WriteBufferLongWord(8, CharID, OutBuffer);
WriteBufferLongWord(12, ScriptID, OutBuffer);
WriteBufferString(16, MapName, 16, OutBuffer);
WriteBufferString(32, Identifier, Len, OutBuffer);
SendBuffer(AClient, OutBuffer, Len + 32);
end;
end;{InterSendCreateInstance}
//------------------------------------------------------------------------------
end.
|
{$I-,Q-,R-,S-}
{39■ Escaleras Finlandia 2001
Una empresa se dedica a la construcción de escaleras con escalones
simples (un escalón simple sólo tiene un peldaĄo o una unidad de
altura). La empresa tiene mucha demanda y recibe todo tipo de
solicitudes de escaleras, las solicitudes se hacen informando el largo
y la altura que desean cubrir con una escalera. Un cliente va a
realizar la solicitud y la empresa le muestra todas las posibles
formas que puede tener la escalera para que el usuario seleccione
la que desee.
Los ingenieros de la empresa están trabajando en la búsqueda de todas
estas formas y necesitan saber cuántas existen. Para estos ingenieros
la longitud de la escalera es el número de piezas usadas en la propia
escalera, cada pieza tiene una unidad de longitud. Una pieza puede
avanzar de forma horizontal o de forma vertical, en la forma vertical
sube un peldaĄo el cual será simple por lo que no habrá un escalón con
dos unidades de altura.
Ejemplo, para una logitud n=4 existen 8 formas las cuales son:
╔ ═══ ═══ ╔
║ ║
═══ ═══ ═══ ═══ ═══ ╔ ═══
(1) (4) ║
═══
╔ ╔ ═══ ═══ ═══ (7)
║ ║
═══ ═══ ═══ (5) ╔
(2) ║
╔ ═══ ╔ ═══ ═══
╔ ═══ ║ ║
║ ╔ ═══
═══ ═══ ║ (8)
(3) (6)
Elabore un programa que determine el número de escaleras que se pueden
construir de longitud n, (1<=n<=50).
Entrada
El archivo de entrada contiene un simple valor que representa a n.
Salida
El archivo de salida deberá contener el número de escaleras que se
pueden construir de longitud n.
┌───────────────────┐ ┌──────────────────┐
│ Ejemplo de entrada│ │ Ejemplo de salida│
├───────────────────┤ ├──────────────────┤
│ 4 │ │ 8 │
└───────────────────┘ └──────────────────┘
}
const
max = 51;
var
fe,fs : text;
n,i : byte;
tab,res : array[0..max] of int64;
procedure open;
begin
assign(fe,'fin039.in'); reset(fe);
assign(fs,'fin039.out'); rewrite(fs);
readln(fe,n);
close(fe);
end;
procedure work;
begin
tab[1]:=2; res[0]:=0; res[1]:=1;
for i:=2 to n do
begin
res[i]:=res[i-1] + res[i-2];
tab[i]:=(tab[i-1] * 2) - res[i-1];
end;
end;
procedure closer;
begin
writeln(fs,tab[n]);
close(fs);
end;
begin
open;
work;
closer;
end. |
unit uVSConst;
{违标常量定义}
interface
uses
SysUtils;
const
{$Region '定义违标参数'}
//运行记录头定义
CommonRec_Head_KeHuo = 10003; //客货
CommonRec_Head_CheCi = 10004; //车次
CommonRec_Head_TotalWeight=10005; //总重;
CommonRec_Head_LiangShu = 10006; //辆数
CommonRec_Head_LocalType = 10007; //车型
CommonRec_Head_LocalID = 10008; //车号
CommonRec_Head_Factory = 10009; //软件厂家
Custom_Head_ZongZai = 10010; //是否重载
Custom_Head_ZuHe = 10011; //是否组合列车
//记录事件类型定义
CommonRec_Event_Column = 20000; //事件变化
CommonRec_Event_BaoZha = 20001; //机车抱闸
CommonRec_Event_PingDiaoChange = 35333; //平调信号变化
CommonRec_Event_SignalChange = 35329; //机车信号变化
CommonRec_Event_XingHaoTuBian = 35332; //信号突变
CommonRec_Event_GLBTuBian = 34563; //公里标突变
CommonRec_Event_TrainPosForward = 34306;//车位向前
CommonRec_Event_TrainPosBack = 34307; //车位向后
CommonRec_Event_TrainPosReset = 34309; //车位对中
CommonRec_Event_CuDuan = 34321; //出段
CommonRec_Event_RuDuan = 34322; //入段
CommonRec_Event_EnsureGreenLight = 34433;//绿/绿黄确认
CommonRec_Event_Pos = 34332; //定标键
CommonRec_Event_Verify = 35904; //IC卡验证码
CommonRec_Event_PushIC = 34356; //插入IC卡
CommonRec_Event_PopIC = 34357; //拔出IC卡
CommonRec_Event_ClearReveal = 35849; //清除揭示
CommonRec_Event_KongZhuan = 34591; //转对空转
CommonRec_Event_KongZhuanEnd = 34592; //空转结束;
CommonRec_Event_RevealQuery = 35846; //揭示查询
CommonRec_Event_InputReveal = 33537; //输入揭示
CommonRec_Event_MInputReveal = 33538; //手工揭示输入
CommonRec_Event_ReInputReveal = 33539; //揭示重新输入
CommonRec_Event_CeXian = 34317; //侧线号输入
CommonRec_Event_DuiBiao = 34305; //开车对标
CommonRec_Event_EnterStation = 34575; //进站
CommonRec_Event_SectionSignal = 34577; //区间过机(过信号机)
CommonRec_Event_InOutStation = 34656; //进出站(过信号机)
CommonRec_Event_SpeedChange = 35585; //速度变化
CommonRec_Event_RotaChange = 35586; //转速变化
CommonRec_Event_GanYChange = 35590; //管压变化
CommonRec_Event_SpeedLmtChange = 35591; //限速变化
CommonRec_Event_GangYChange = 35600; //缸压变化
CommonRec_Event_LSXSStart = 35843; //临时限速开始
CommonRec_Event_LSXSEnd = 35844; //临时限速结束
CommonRec_Event_LeaveStation = 34576; //出站
CommonRec_Event_StartTrain = 34605; //起车
CommonRec_Event_ZiTing = 34580; //自停停车
CommonRec_Event_StopInRect = 34583; //区间停车
CommonRec_Event_StartInRect = 34587; //区间开车
CommonRec_Event_StopInJiangJi = 34579; //降级停车
CommonRec_Event_StopInStation = 34584; //站内停车
CommonRec_Event_StopOutSignal = 34585; //机外停车
CommonRec_Event_StartInStation = 34588; //站内开车
CommonRec_Event_StartInJiangJi = 34586; //降级开车
CommonRec_Event_GuoJiJiaoZheng = 34567; //过机校正
CommonRec_Event_JinRuJiangJi = 45104; //进入降级
CommonRec_Event_FangLiuStart = 34571; //防溜报警开始
CommonRec_Event_FangLiuEnd = 34572; //防溜报警结束
CommonRec_Event_JinJiBrake = 35073; //紧急制动
CommonRec_Event_ChangYongBrake = 35074;//常用制动
CommonRec_Event_XieZai = 35075; //卸载动作
CommonRec_Event_Diaoche = 34318; //进入调车
CommonRec_Event_DiaocheJS = 34319; //退出调车
CommonRec_Event_DiaoCheStart = 34590; //调车开车
CommonRec_Event_DiaoCheStop = 34582; //调车停车
CommonRec_Event_JKStateChange = 33237; //监控状态变化
CommonRec_Event_PingDiaoStart = 50001; //自定义平调开始
CommonRec_Event_PingDiaoStop = 50002; //自定义平调开始
CommonRec_Event_UnlockSucceed = 34310; //解锁成功(解锁键)
CommonRec_Event_GuoFX = 34424; //过分相
CommonRec_Event_YDJS = 34464; //引导解锁成功
CommonRec_Event_TDYDJS = 34465; //特定引导解锁
CommonRec_Event_KBJS = 34466; //靠标解锁成功
CommonRec_Event_FQZX = 34470; //防侵正线解锁
CommonRec_Event_LPJS = 34472; //路票解锁成功
CommonRec_Event_LSLPJS = 34373; //临时路票解锁
CommonRec_Event_LZJS = 34474; //绿证解锁成功
CommonRec_Event_LSLZJS = 34475; //临时绿证解锁
CommonRec_Event_JSCG = 34310; //解锁成功
Commonrec_Event_GDWMTGQR = 34476; //股道无码通过确认
Commonrec_Event_GDWMKCQR = 34477; //股道无码开车确认
CommonRec_Event_TSQR = 34479; //特殊发码确认
//自定义事件
Custom_Event_Revert = 39001; //返转
Custom_Event_Drop = 39002; //开始下降
Custom_Event_Rise = 39003; //开始上升
Custom_Event_DropValue = 39004; //达到下降量
Custom_Event_RiseValue = 39005; //达到上升量
Custom_Event_ReachValue= 39006; //达到指定值
Custom_Event_DropFromValue = 39007; //从指定值开始下降
Custom_Event_DropToValue = 39008; //下降到指定值
Custom_Event_RiseFromValue = 39009; //从指定值开始上升
Custom_Event_RiseToValue = 39010; //上升到指定值
//自定义VALUE
Custom_Value_CFTime = 999901; //冲风时间
Custom_Value_StandardPressure = 999902; //标压
Custom_Value_BrakeDistance = 999903; //带闸距离
//记录变动类行定义
CommonRec_Column_GuanYa = 30001; //管压;
CommonRec_Column_Sudu = 30002; //速度;
CommonRec_Column_WorkZero = 30003; //工况零位;
CommonRec_Column_HandPos = 30004; //前后;
CommonRec_Column_WorkDrag = 30005; //手柄位置;
CommonRec_Column_DTEvent = 30006; //事件发生时间;
CommonRec_Column_Distance = 30007; //信号机距离;
CommonRec_Column_LampSign = 30008; //信号灯;
CommonRec_Column_GangYa = 30009; //缸压;
CommonRec_Column_SpeedLimit= 30010; //限速;
CommonRec_Column_Coord = 30011; //公里标;
CommonRec_Column_Other = 30012; //其它字段;
CommonRec_Column_StartStation=30013; //起始站;
CommonRec_Column_EndStation = 30014; //起始站;
CommonRec_Column_JGPressure = 30015; //均缸
CommonRec_Column_LampNumber = 30017; //信号机编号
CommonRec_Column_Rotate = 30018; //柴速
CommonRec_Column_Acceleration = 30019; //加速度
CommonRec_Column_ZT= 30022; //监控状态;
File_Headinfo_dtBegin = 5001; //文件开始
File_Headinfo_Factory = 5002; //厂家标志
File_Headinfo_KeHuo = 5003; //本补客货
File_Headinfo_CheCi = 5004; //车次
File_Headinfo_TotalWeight = 5005;//总重
File_Headinfo_DataJL = 5006; //数据交路
File_Headinfo_JLH = 5007; //监控交路
File_Headinfo_Driver = 5008; //司机号
File_Headinfo_SubDriver = 5009; //副司机号
File_Headinfo_LiangShu = 5010; //辆数
File_Headinfo_JiChang = 5011; //计长
File_Headinfo_ZZhong = 5012; //载重
File_Headinfo_TrainNo = 5013; //机车号
File_Headinfo_TrainType = 5014; //机车类型
File_Headinfo_LkjID = 5015; //监控装置号
File_Headinfo_StartStation = 5016;//车站号
{$endRegion '定义违标参数'}
{$region '定义系统常量'}
SYSTEM_STANDARDPRESSURE = 1000000;
SYSTEM_STANDARDPRESSURE_HUO = 500; //货车标准压力
SYSTEM_STANDARDPRESSURE_XING = 600; //行包标准压力
SYSTEM_STANDARDPRESSURE_KE = 600; //客车标准压力
{$endregion '定义系统常量'}
{$REGION '集合定义'}
CommonRec_Column_VscMatched = 30019; //自定义常量 用在比较表达式固定返回Matched
CommonRec_Column_VscUnMatch = 30020; //自定义常量 用在比较表达式固定返回UnMatch
{$ENDREGION '集合定义'}
{$region '异常消息定义'}
WM_USER = 1024; //0X0400
WM_ERROR_GETVALUE = WM_USER + 1;
{$endregion '异常消息定义'}
{$region 'Html转义定义'}
VS_AND = '&'; // & , AND
VS_OR = '|'; // | , OR
VS_L = '('; // ( , 左括号
VS_R = ')'; // ) , 右括号
VS_N = '>'; // > ,这里为指向下一个 ,用于循序表达式
{$endregion 'Html转义定义'}
type
{$region '枚举定义'}
{违标条件枚举}
TVSCState = (vscAccept {接受状态},vscMatching,vscMatched{匹配状态},vscUnMatch{不匹配状态});
{操作符枚举}
TVSDataType = (vsdtAccept{第一次接受的数据},vsdtMatcing{第一次匹配中的数据},vsdtLast{上一条数据});
{操作符枚举}
TVSOperator = (vspMore{大于},vspLess{小于},vspEqual{等于},vspNoMore{不大于},
vspNoLess{不小于},vspNoEqual{不等于},vspLeftLike{左侧等:以左侧开头以问号指定字符},
vspLeftNotLike{左侧不等},vspChaZhi{差值});
{顺序枚举}
TVSOrder = (vsoArc{上升},vsoDesc{下降});
{数据返回类型}
TVSReturnType = (vsrBegin{范围开始},vsrEnd{范围结束},vsrMatched{匹配记录});
{取值位置}
TVSPositionType = (vsptCrest{波峰},vsptTrough{波谷});
{坡道类型}
TVSSlopeType = (stUp{上坡},stDown{下坡});
{制动机试验类型}
TBrakeTestType = (bttNotDone{未做},bbtLessTime{试验时间不足},bbtLeak{泄漏量超标});
{$endregion '枚举定义'}
{$REGION '结构定义'}
//车次信息
RCheCiInfo = record
strCheCi : string; //车次
dZaiZong : Double; //载重
bZZaiLieChe : Boolean; //重载
bZuHe : Boolean; //组合列车
end;
TCheCiInfo = array of RCheCiInfo;
PCheCiInfo = ^RCheCiInfo;
//坡度信息
RSlopeInfo = record
nBeginPos : Integer; //开始公里标
nEndPos : Integer; //结束公里标
nStation : Integer; //车站号
nJiaoLu : Integer ; //交路号
nUpDownType : Integer; //上下行,0上行、1下行
nSlopeType : Integer; //上下坡,0上坡、1下坡
end;
TSlopeInfo = array of RSlopeInfo;
//试闸点信息
RSZDInfo = record
nBeginPos : Integer; //开始公里标
nEndPos : Integer; //结束公里标
nStation : Integer; //车站号
nJiaoLu : Integer ; //交路号
nUpDownType : Integer; //上下行,0上行、1下行
end;
TSZDInfo = array of RSZDInfo;
//配置信息结构
RConfigInfo = record
dAcceleration : Double; //加速度
dSlipAcceperation : Double; //滑行加速度门限
nSampleSpeed : Integer; //计算加速度采样速度差
nBrakeDistance : Integer; //带闸距离
nStandardPressure : Integer; //标压
bZZaiLieChe : Boolean; //重载列车
bTwentyThousand : Boolean; //两万吨列车
SlopeInfo : TSlopeInfo; //坡道配置
SZDInfo : TSZDInfo; //试闸点信息
nCFTime50 : Integer; //减压50kpa冲风时间
nCFTime70 : Integer; //减压70kpa冲风时间
nCFTime100 : Integer; //减压100kpa冲风时间
nCFTime170 : Integer; //减压170kpa冲风时间
nPFTime50 : Integer; //减压50kpa排风时间
nPFTime70 : Integer; //减压70kpa排风时间
nPFTime100 : Integer; //减压100kpa排风时间
nPFTime170 : Integer; //减压170kpa排风时间
nBrakePressure : Integer; //制动时管压最低值
end;
RRulesInfo = record
strName : string; //规则名称
strDescription : string; //规则描述
strJudgeCondition : string; //判定条件
end;
TRulesInfo = array of RRulesInfo;
RRecordFmt = record
ID: integer; //序号
Disp: string; //事件描述
Time: TDateTime; //时间
glb: string; //公里标
xhj: string; //信号机
nDistance: integer; //距离
nGuanYa: Integer; //管压
nGangYa: Integer; //缸压
nJG1: Integer; //均缸1
nJG2: Integer; //均缸2
nSignal: Integer; //机车信号
nSignalType: Integer; //信号机类型
nSignalNo: Integer; //信号机编号
nHandle: Integer; //手柄状态
nRota: Integer; //柴速
nSpeed: Integer; //速度
nSpeed_lmt: Integer; //限速
lsxs: Integer; //临时限速
strOther: string; //其它
Shuoming: string; //说明
JKZT : Integer; //记录信号所处的监控状态;监控=1,平调=2,调监=3
end;
TRecordFmt = array of RRecordFmt;
//////////////////////////////////////////////////////////////////////////////
///乘务员作业时间
///内含时间为0时代表取不出来
//////////////////////////////////////////////////////////////////////////////
ROperationTime = record
//入库时间
inhousetime : TDateTime;
//出勤车次接车时间
jctime : TDateTime;
//出库时间
outhousetime : TDateTime;
//退勤车次到站时间
tqarrivetime : TDateTime;
//退勤车次开点
tqdat : TDateTime;
//计划退勤时间
jhtqtime : TDateTime;
end;
{$ENDREGION '结构定义'}
{$REGION 'DLL函数定义'}
function NewFmtFile(aPath, OrgFileName, FmtFileName: string): integer; stdcall; external 'fmtFile.dll';
procedure Fmttotable(var tablefilename,fmtfilename,curpath: PChar;userid:Byte); stdcall; external 'testdll.dll';
{$ENDREGION 'DLL函数定义'}
//二分法查找信号机
function IsExistInt(TArray: array of Integer;LowIndex,HighIndex,Value : Integer):Integer;
//组合日期时间
function CombineDateTime(dtDate,dtTime: TDateTime): TDateTime;
implementation
function CombineDateTime(dtDate,dtTime: TDateTime): TDateTime;
begin
Result := 0;
ReplaceDate(Result, dtDate);
ReplaceTime(Result, dtTime);
end;
function IsExistInt(TArray: array of Integer;LowIndex,HighIndex,Value : Integer):Integer;
var
TmpIndex : Integer;
begin
TmpIndex := (LowIndex + HighIndex) div 2;
if TArray[TmpIndex] = Value then
Result := TmpIndex
else
begin
if TArray[TmpIndex] < Value then
begin
if (TmpIndex + 1) > HighIndex then
Result := -1
else
Result := IsExistInt(TArray,TmpIndex + 1,HighIndex,Value);
end
else
begin
if (TmpIndex - 1) < LowIndex then
Result := -1
else
Result := IsExistInt(TArray,LowIndex,TmpIndex - 1,Value);
end;
end;
end;
end.
|
unit SDL2_SimpleGUI_StdWgts;
{:< The Standard Widgets Unit}
{ Simple GUI is a generic SDL2/Pascal GUI library by Matthias J. Molski,
get more infos here:
https://github.com/Free-Pascal-meets-SDL-Website/SimpleGUI.
It is based upon LK GUI by Lachlan Kingsford for SDL 1.2/Free Pascal,
get it here: https://sourceforge.net/projects/lkgui.
Written permission to re-license the library has been granted to me by the
original author.
Copyright (c) 2016-2020 Matthias J. Molski
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE. }
interface
uses
SDL2, SDL2_TTF, Math, SDL2_SimpleGUI_Base, SDL2_SimpleGUI_Element, SDL2_SimpleGUI_Canvas;
type
{ TGUI_Button }
{: Generic Button Class }
TGUI_Button = class(TGUI_Canvas)
public
{: Render the button }
procedure Render; override;
{: Constructor for the button }
constructor Create;
{: Destructor for the button }
destructor Destroy; override;
{: Control mouse entry procedure }
procedure ctrl_MouseEnter; override;
{: Control mouse entry procedure }
procedure ctrl_MouseExit; override;
protected
private
end;
{ TGUI_CheckBox }
{: Generic Checkbox Class. Click to change its value.
Can also act as a radio button by changing the ExcGroup to be less then 0
(and the same as the other now radio buttons). It only looks through one
level of parent for siblings of a CheckBox type. }
TGUI_CheckBox = class(TGUI_Canvas)
public
{: Checkbox Constructor }
constructor Create;
{: Checkbox Destructor }
destructor Destroy; override;
{: Set the value of the checkbox - true (Checked) or false (Unchecked) }
procedure SetValue(NewValue: Boolean); virtual;
{: Returns the value of the checkbox - true (Checked) or false (Unchecked)
}
function GetValue: Boolean; virtual;
{: Render the checkbox }
procedure Render; override;
{: Sets the Exclusive Group. If this is 0 (default) then the box operates
as a normal checkbox. If it is non-zero then it operates as a radio button
with all of the other checkboxes in the same Exclusive Group }
procedure SetExcGroup(NewExcGroup: Word);
{: Returns the Exclusive Group }
function GetExcGroup: Word;
{: Control Mouse Click Handler }
procedure ctrl_MouseClick(X, Y: Word; Button: UInt8); override;
{: Called when box is checked - should be overwritten by decendent
controls }
procedure ctrl_BoxChecked; virtual;
{: Called when box is unchecked - should be overwritten by decendent
controls }
procedure ctrl_BoxUnchecked; virtual;
{: Called when box is checked - should be overwritten by the actual
controls }
procedure BoxChecked; virtual;
{: Called when box is unchecked - should be overwritten by the actual
controls }
procedure BoxUnchecked; virtual;
protected
Value: Boolean;
ExcGroup: Word;
private
end;
{ TGUI_Label }
{: Generic Label Class }
TGUI_Label = class(TGUI_Canvas)
public
{: Label Constructor }
constructor Create;
{: Label Destructor }
destructor Destroy; override;
{: Render label }
procedure Render; override;
{: Set the Text Alignment }
procedure SetTextA(NewTextA: tTextAlign);
{: Get the Text Alignment }
function GetTextA: tTextAlign;
{: Set the Texts Vertical Alignment }
procedure SetVertA(NewVertA: tVertAlign);
{: Return the Texts Vertical Alignment }
function GetVertA: tVertAlign;
protected
TextA: tTextAlign;
VertA: tVertAlign;
end;
{ TGUI_ScrollBar }
{: Generic Scrollbar Class }
TGUI_ScrollBar = class(TGUI_Canvas)
public
{: Scrollbar Constructor }
constructor Create;
{: Scrollbar Destructor }
destructor Destroy; override;
{: Render scrollbar }
procedure Render; override;
{: Sets minimum value of scrollbar }
procedure SetMin(NewMinVal: Integer);
{: Returns the minimum value of scrollbar }
function GetMin: Integer;
{: Sets maximum value of scrollbar }
procedure SetMax(NewMaxVal: Integer);
{: Returns maximum value of scrollbar }
function GetMax: Integer;
{: Sets the value of the scrollbar }
procedure SetValue(NewValue: Integer);
{: Returns the current value of scrollbar }
function GetValue: Integer;
{: Sets whether the scrollbar is horizontal or vertical }
procedure SetDir(NewDir: TDirection);
{: Returns whether the scrollbar is horizontal or vertical }
function GetDir: TDirection;
{: Sets whether the scrollbar automatically aligns itself to the right of
its parent (for a vertical bar) or the bottom of its parent (for a
horizontal bar). }
procedure SetAutoAlign(NewValue: Boolean);
{: Returns the whether the scrollbar automatically aligns itself. }
function GetAutoAlign: Boolean;
{: Sets whether the scrollbar accounts for a second scroll bar in the
opposite direction hence leaving the bottom right corner free }
procedure SetAutoAlignBoth(NewValue: Boolean);
{: Returns autoalignboth }
function GetAutoAlignBoth: Boolean;
{: Called when parents size changes }
procedure ParentSizeCallback(NewW, NewH: Word); override;
{: Should be only called by parent control - Controls Mouse Down Handler }
procedure ctrl_MouseDown(X, Y: Word; Button: UInt8); override;
{: Should be only called by parent control - Controls Mouse Up Handler }
procedure ctrl_MouseUp(X, Y: Word; Button: UInt8); override;
{: Should be only called by control - Controls Value Changes Handler }
procedure ctrl_ValueChanged(NewValue: Integer); virtual;
{: Should be only called by parent control - SDL Event Handler }
procedure ctrl_SDLPassthrough(e: PSDL_Event); override;
{: Called when value of scroll bar has changed - should be overwritten
by child controls }
procedure ValueChanged(NewValue: Integer); virtual;
protected
MinVal, MaxVal, Value: Integer;
InitX, InitY: Word;
Dir: TDirection;
Moving: Boolean;
Autoalign, Autoalignboth: Boolean;
private
end;
{ TGUI_TextBox }
{: Generic Testbox Class. It could probably still be classified as unfinished
owing to the fact that its cursor is still a caret('^'), clicks don't move
the cursor and it sticks to showing the left side of its contents }
TGUI_TextBox = class(TGUI_Canvas)
public
constructor Create;
destructor Destroy; override;
procedure Render; override;
procedure ctrl_Selected; override;
procedure ctrl_LostSelected; override;
procedure ctrl_KeyDown(KeySym: TSDL_KeySym); override;
procedure ctrl_KeyUp(KeySym: TSDL_KeySym); override;
procedure ctrl_TextInput(TextIn: TSDLTextInputArray); override;
procedure KeyDown(KeySym: TSDL_KeySym); override;
procedure KeyUp(KeySym: TSDL_KeySym); override;
procedure ctrl_TextChanged(); virtual;
procedure TextChanged; virtual;
procedure SetText(InText: string);
function GetText: string;
protected
Cursor: Integer;
StrText: string;
IsSelected: Boolean;
procedure MoveCursor(Amt: Integer);
procedure CursorInsert(Character: TSDLTextInputArray);
procedure CursorBackspace;
procedure CursorDelete;
procedure CursorHome;
procedure CursorEnd;
private
end;
{ TGUI_Image }
{: Generic Image Class based upon SDL_Texture. Memory management? }
TGUI_Image = class(TGUI_Canvas)
public
{: Constructor for Surface Widget. }
constructor Create;
{: Destructor for Surface Widget. }
destructor Destroy; override;
{: Allows for a surface to be transformed into texture after Renderer known
to GUI element. }
procedure ChildAddedCallback; override;
{: Sets the source texture to draw from. }
procedure SetSource(NewSrcTexture: PSDL_Texture);
{: Sets the source surface to draw from. Is converted into a texture. }
procedure SetSource(NewSrcSurface: PSDL_Surface); overload;
{: Returns the current source surface. }
function GetSource: PSDL_Texture;
{: Sets the rectangle from where to draw from on the source surface. }
procedure SetSrcRect(NewRect: TSDL_Rect); virtual;
{: Returns the current source surface rectangle to draw from. }
function GetSrcRect: TSDL_Rect; virtual;
{: Sets whether or not the surface takes the full size of the source
surface or uses the bounding rectangle.}
procedure SetFullSrc(NewFullSrc: Boolean);
{: Returns whether or not the surface takes the full size of the source
surface or uses the bounding rectangle.}
function GetFullSrc: Boolean;
{: Sets if SrcTexture (SDL_Texture) is free'd automatically.
- set to True if SetSource() is a SDL_Surface
- set to False if SetSource() is a SDL_Texture
- you may change it afterwards }
procedure SetFreeAutomatically(NewFreeStatus: Boolean);
{: Returns the current free setting for the Image texture. }
function GetFreeAutomatically: Boolean;
{: Renders the widget }
procedure Render; override;
protected
{: This surface is a helper to store a surface which is set by SetSource()
until AddChild() is called, because just then the Renderer is known. After
that is not used anymore and also not free'd. }
StoredSurface: PSDL_Surface;
{: This is the image represented as a SDL2 texture. }
SrcTexture: PSDL_Texture;
SrcRect: TSDL_Rect;
DstRect: TSDL_Rect;
FullSrc: Boolean;
IsFreed: Boolean;
private
end;
{ TGUI_Listbox_Item }
{: Linked list of items in the Listbox or Dropbox. }
TGUI_Listbox_Item = class
public
{: Next item in list. }
Next: TGUI_Listbox_Item;
{: Previous item in list. }
Prev: TGUI_Listbox_Item;
NullFirst: Boolean;
{: Returns the final item in the list. }
function Last: TGUI_Listbox_Item;
{: Returns the first item in the list. }
function First: TGUI_Listbox_Item;
{: Returns a string version of the item - could be changed by child
classes to return something different. Essentially, this is the bit
that is displayed. }
function GetStr: string; virtual;
{: Sets the string to display. }
procedure SetStr(NewString: string); virtual;
{: Returns the index of this item. }
function GetIndex: Integer;
{: Sets the index of this item. }
procedure SetIndex(NewIndex: Integer);
{: Adds a new listbox_item with the test NewText and index NewIndex. }
procedure AddItem(NewStr: string; NewIndex: Integer);
{: Makes this the final item in the Linked list. }
procedure PushToLast;
{: Initialises Linked List. }
constructor Create;
{: Destructor of Item. }
destructor Destroy; override;
{: Returns the item bearing the index number. Returns nil if there is
no such item. }
function ReturnItem(ItemIndex: Integer): TGUI_listbox_item;
{: Sets whether the item is selected. If so, it will then unselect all
other items in the list.}
procedure SetSelected(NewSel: Boolean);
{: Returns whether the item is selected}
function GetSelected: Boolean;
{: Returns the currently selected item }
function GetSelectedItem: TGUI_Listbox_item;
{: Dumps the contents of the Linked list to the console. For debugging
purposes. }
procedure Dump;
function GetCount: Word;
protected
IndexNo: Integer;
Caption: string;
Selected: Boolean;
end;
{ TGUI_Listbox }
{: Widget that displays a listbox }
TGUI_Listbox = class(TGUI_Canvas)
public
{: Listbox constructor }
constructor Create;
{: Listbox destructor - will probably never be called }
destructor Destroy; override;
{: Returns list of items }
function GetItems: TGUI_Listbox_Item;
{: Renders the widget }
procedure Render; override;
{: Called when the font changes }
procedure ctrl_FontChanged; override;
{: Called when the control is resized }
procedure ctrl_Resize; override;
{: Called when the control recieves a keypress }
procedure ctrl_KeyDown(KeySym: TSDL_KeySym); override;
{: Called when the listbox is clicked}
procedure MouseDown(X, Y: Word; Button: UInt8); override;
{: Should be overwritten by children. Will be called when the selection
is changed }
procedure ctrl_NewSelection(Selection: TGUI_Listbox_Item); virtual;
{: Will be called when the selection is changed }
procedure NewSelection(Selection: TGUI_Listbox_Item); virtual;
{: Returns the currently selected item }
function GetSelectedItem: TGUI_Listbox_Item;
protected
Items: TGUI_Listbox_Item;
ListCount: Word;
ItemsToShow: Word;
Scrollbar: TGUI_Scrollbar;
private
end;
implementation
uses
SysUtils, SDL2_SimpleGUI;
//*********************************************************
//TGUI_Button
//*********************************************************
procedure TGUI_Button.Render;
begin
if ButtonStates[1] then
CurFillColor := ActiveColor
else
CurFillColor := BackColor;
inherited;
RenderText(GetCaption, Width div 2, (GetHeight - TTF_FontHeight(Font)) div 2,
Align_Center);
end;
constructor TGUI_Button.Create;
begin
inherited Create;
SetBorderStyle(BS_Single);
end;
destructor TGUI_Button.Destroy;
begin
inherited Destroy;
end;
procedure TGUI_Button.ctrl_MouseEnter();
begin
inherited;
CurBorderColor := ForeColor;
end;
procedure TGUI_Button.ctrl_MouseExit();
begin
inherited;
CurBorderColor := BorderColor;
end;
//*********************************************************
//TGUI_Checkbox
//*********************************************************
constructor TGUI_CheckBox.Create;
begin
inherited Create;
SetFillStyle(FS_None);
ExcGroup := 0;
end;
destructor TGUI_CheckBox.Destroy;
begin
inherited Destroy;
end;
procedure TGUI_CheckBox.SetValue(NewValue: Boolean);
begin
if Value <> newvalue then
begin
Value := newvalue;
if NewValue then
ctrl_BoxChecked
else
ctrl_BoxUnchecked;
end;
end;
function TGUI_CheckBox.GetValue: Boolean;
begin
getvalue := Value;
end;
procedure TGUI_CheckBox.Render;
var
r: TSDL_Rect;
begin
with r do
begin
w := 20;
h := 20;
x := GetAbsLeft + 3;
y := GetAbsTop + 3;
end;
if GetMouseEntered then
RenderFilledRect(@r, GUI_SelectedColor)
else
RenderFilledRect(@r, backcolor);
RenderRect(@r, CurBorderColor);
with r do
begin
w := 11;
h := 11;
x := GetAbsLeft + 8;
y := GetAbsTop + 8;
end;
if Value then
RenderFilledRect(@r, forecolor);
RenderText(GetCaption, 30, 5, Align_Left);
end;
procedure TGUI_CheckBox.ctrl_MouseClick(X, Y: Word; Button: UInt8);
var
Next: TGUI_Element_LL;
Data: TGUI_Checkbox;
begin
if ExcGroup = 0 then
// Do this if its just a checkbox
begin
if Value then
begin
SetValue(False);
end
else
begin
SetValue(True);
end;
end
else
// But do this if its an option box
begin
if not (Value) then
begin
SetValue(True);
// Traverse siblings to tell relevant siblings to be unselected
Next := Parent.GetChildren.Next;
while Assigned(Next) do
begin
if Next.Data is TGUI_Checkbox then
begin
Data := Next.Data as TGUI_Checkbox;
if Next.Data <> Self then
if Data.GetExcGroup = ExcGroup then
Data.SetValue(False);
end;
Next := Next.Next;
end;
end;
end;
end;
procedure TGUI_CheckBox.ctrl_BoxChecked();
begin
BoxChecked;
end;
procedure TGUI_CheckBox.ctrl_BoxUnchecked();
begin
BoxUnChecked;
end;
procedure TGUI_CheckBox.BoxChecked();
begin
end;
procedure TGUI_CheckBox.BoxUnchecked();
begin
end;
procedure TGUI_CheckBox.SetExcGroup(NewExcGroup: Word);
begin
ExcGroup := NewExcGroup;
end;
function TGUI_CheckBox.GetExcGroup: Word;
begin
GetExcGroup := ExcGroup;
end;
//*********************************************************
//TGUI_Label
//*********************************************************
constructor TGUI_Label.Create;
begin
inherited Create;
SetFillStyle(FS_None);
SetSelectable(False);
SetTextA(Align_Left);
SetVertA(VAlign_Top);
end;
destructor TGUI_Label.Destroy;
begin
inherited Destroy;
end;
procedure TGUI_Label.Render;
var
LeftPoint, TopPoint: Word;
begin
case TextA of
Align_Left:
LeftPoint := 0;
Align_Right:
LeftPoint := GetWidth;
Align_Center:
LeftPoint := GetWidth div 2;
end;
case VertA of
VAlign_Top:
TopPoint := 0;
VAlign_Bottom:
TopPoint := GetHeight - TTF_FontHeight(Font);
VAlign_Center:
TopPoint := (GetHeight - TTF_FontHeight(Font)) div 2;
end;
RenderText(GetCaption, LeftPoint, TopPoint, TextA);
end;
procedure TGUI_Label.SetTextA(NewTextA: tTextAlign);
begin
TextA := NewTextA;
end;
function TGUI_Label.GetTextA: tTextAlign;
begin
GetTextA := TextA;
end;
procedure TGUI_Label.SetVertA(NewVertA: tVertAlign);
begin
VertA := NewVertA;
end;
function TGUI_Label.GetVertA: tVertAlign;
begin
GetVertA := VertA;
end;
//*********************************************************
//TGUI_Scrollbar
//*********************************************************
constructor TGUI_ScrollBar.Create;
begin
inherited Create;
SetFillStyle(FS_None);
SetMin(0);
SetMax(100); // SetValue(50); [Why this comment?]
end;
destructor TGUI_ScrollBar.Destroy;
begin
inherited Destroy;
end;
procedure TGUI_ScrollBar.Render;
var
r: TSDL_Rect;
begin
case GetDir of
Dir_Horizontal:
begin
RenderLine(GetAbsLeft, GetAbsTop + GetHeight div 2, GetAbsLeft +
GetWidth - 1, GetAbsTop + GetHeight div 2, BorderColor);
with r do
begin
w := GUI_ScrollbarSize;
h := GUI_ScrollbarSize;
x := GetAbsLeft + floor((Value * (GetWidth - w - 2)) / (MaxVal - MinVal)
);
y := GetAbsTop + (GetHeight - h) div 2;
end;
end;
Dir_Vertical:
begin
RenderLine(GetAbsLeft + GetWidth div 2, GetAbsTop, GetAbsLeft +
GetWidth div 2, GetAbsTop + GetHeight, BorderColor);
with r do
begin
w := GUI_ScrollbarSize;
h := GUI_ScrollbarSize;
y := GetAbsTop + floor((Value * (GetHeight - h - 1)) / (MaxVal - MinVal)
);
x := GetAbsLeft + (GetWidth - w) div 2;
end;
end;
end;
if GetMouseEntered or Moving then
RenderFilledRect(@r, GUI_SelectedColor)
else
RenderFilledRect(@r, BackColor);
RenderRect(@r, CurBorderColor);
end;
procedure TGUI_ScrollBar.SetMin(NewMinVal: Integer);
begin
MinVal := NewMinVal;
end;
function TGUI_ScrollBar.GetMin: Integer;
begin
GetMin := MinVal;
end;
procedure TGUI_ScrollBar.SetMax(NewMaxVal: Integer);
begin
MaxVal := NewMaxVal;
end;
function TGUI_ScrollBar.GetMax: Integer;
begin
GetMax := MaxVal;
end;
procedure TGUI_ScrollBar.SetValue(NewValue: Integer);
begin
Value := NewValue;
ctrl_ValueChanged(NewValue);
end;
function TGUI_ScrollBar.GetValue: Integer;
begin
Result := Value;
end;
procedure TGUI_ScrollBar.SetDir(NewDir: TDirection);
begin
Dir := NewDir;
end;
function TGUI_ScrollBar.GetDir: TDirection;
begin
GetDir := Dir;
end;
procedure TGUI_ScrollBar.SetAutoAlign(NewValue: Boolean);
begin
Autoalign := NewValue;
if AutoAlign then
if Parent <> nil then
ParentSizeCallback(Parent.GetWidth, Parent.GetHeight);
end;
function TGUI_ScrollBar.GetAutoAlign: Boolean;
begin
GetAutoAlign := AutoAlign;
end;
procedure TGUI_ScrollBar.SetAutoAlignBoth(NewValue: Boolean);
begin
AutoAlignBoth := NewValue;
if AutoAlignBoth then
if Parent <> nil then
ParentSizeCallback(Parent.GetWidth, Parent.GetHeight);
end;
function TGUI_ScrollBar.GetAutoAlignBoth: Boolean;
begin
GetAutoAlignBoth := AutoAlignBoth;
end;
procedure TGUI_ScrollBar.ParentSizeCallback(NewW, NewH: Word);
begin
if AutoAlign then
begin
case Dir of
Dir_Horizontal:
begin
SetLeft(2);
SetWidth(NewW - ifthen(AutoAlignBoth, Gui_ScrollbarSize) - 4);
SetTop(NewH - Gui_ScrollBarSize - 4);
SetHeight(Gui_ScrollBarSize + 1);
end;
Dir_Vertical:
begin
SetTop(2);
SetHeight(NewH - ifthen(AutoAlignBoth, Gui_ScrollbarSize) - 4);
SetLeft(NewW - Gui_ScrollBarSize - 4);
SetWidth(Gui_ScrollBarSize + 1);
end;
end;
end;
end;
procedure TGUI_ScrollBar.ctrl_MouseDown(X, Y: Word; Button: UInt8);
var
NewVal: Integer;
begin
inherited;
if Button = 1 then
begin
case Dir of
Dir_Horizontal:
begin
NewVal := (X * (MaxVal - MinVal)) div Width;
InitX := GetAbsLeft;
end;
Dir_Vertical:
begin
NewVal := (Y * (MaxVal - MinVal)) div Height;
InitY := GetAbsTop;
end;
end;
NewVal := Max(MinVal, NewVal);
NewVal := Min(MaxVal, NewVal);
SetValue(NewVal);
Moving := True;
end;
end;
procedure TGUI_ScrollBar.ctrl_MouseUp(X, Y: Word; Button: UInt8);
begin
inherited;
if Button = 1 then
Moving := False;
end;
procedure TGUI_ScrollBar.ctrl_SDLPassthrough(e: PSDL_Event);
var
NewVal, X, Y: Integer;
begin
inherited;
case e^.type_ of
SDL_MOUSEBUTTONUP:
begin
if Moving then
if e^.button.button = 1 then
Moving := False;
end;
SDL_MOUSEMOTION:
if Moving then
begin
X := e^.motion.x - InitX;
y := e^.motion.y - InitY;
case Dir of
Dir_Horizontal:
begin
NewVal := (X * (MaxVal - MinVal)) div (GetWidth - 6);
end;
Dir_Vertical:
begin
NewVal := (Y * (MaxVal - MinVal)) div (GetHeight - 6);
end;
end;
NewVal := Max(MinVal, NewVal);
NewVal := Min(MaxVal, NewVal);
SetValue(NewVal);
end;
end;
end;
procedure TGUI_ScrollBar.ctrl_ValueChanged(NewValue: Integer);
begin
ValueChanged(NewValue);
end;
procedure TGUI_ScrollBar.ValueChanged(NewValue: Integer);
begin
end;
//*********************************************************
//TGUI_TextBox
//*********************************************************
constructor TGUI_TextBox.Create;
begin
inherited Create;
SetBackColor(GUI_DefaultTextBackColor);
SetBorderStyle(BS_Single);
Cursor := 0;
StrText := '';
IsSelected := False;
end;
destructor TGUI_TextBox.Destroy;
begin
inherited Destroy;
end;
procedure TGUI_TextBox.Render;
var
TextToRender: string;
ActiveToRender: string;
begin
inherited;
ActiveToRender := '';
begin
if CurSelected then
begin
ActiveToRender := GetText;
ActiveToRender := LeftStr(GetText, Cursor) + '^' + RightStr(GetText,
Length(GetText) - Cursor);
TextToRender := ActiveToRender; // optimise block? (re-str.)
end
else
if GetText = '' then
TextToRender := GetCaption
else
TextToRender := GetText;
end;
RenderText(TextToRender, 5, (GetHeight - TTF_FontHeight(Font)) div 2,
Align_Left);
end;
procedure TGUI_TextBox.ctrl_Selected;
begin
CurFillColor := GUI_SelectedColor;
IsSelected := True;
Cursor := Length(StrText);
SDL_StartTextInput;
end;
procedure TGUI_TextBox.ctrl_LostSelected;
begin
CurFillColor := BackColor;
IsSelected := False;
SDL_StopTextInput;
end;
procedure TGUI_TextBox.ctrl_KeyDown(KeySym: TSDL_KeySym);
begin
inherited;
case KeySym.Sym of
SDLK_LEFT:
begin
MoveCursor(-1);
end;
SDLK_RIGHT:
begin
MoveCursor(1);
end;
SDLK_BACKSPACE:
begin
CursorBackspace;
end;
SDLK_DELETE:
begin
CursorDelete;
end;
SDLK_HOME:
begin
CursorHome;
end;
SDLK_END:
begin
CursorEnd;
end;
{ TODO : new feat.: exit on ENTER; doesn't work as expected, why? }
//SDLK_RETURN:
//begin
// ctrl_LostSelected;
//end;
end;
end;
procedure TGUI_TextBox.ctrl_KeyUp(KeySym: TSDL_KeySym);
begin
end;
procedure TGUI_TextBox.ctrl_TextInput(TextIn: TSDLTextInputArray);
begin
inherited;
CursorInsert(TextIn);
MoveCursor(1);
end;
procedure TGUI_TextBox.KeyDown(KeySym: TSDL_KeySym);
begin
end;
procedure TGUI_TextBox.KeyUp(KeySym: TSDL_KeySym);
begin
end;
procedure TGUI_TextBox.ctrl_TextChanged();
begin
end;
procedure TGUI_TextBox.TextChanged;
begin
end;
procedure TGUI_TextBox.SetText(InText: string);
begin
StrText := InText;
end;
function TGUI_TextBox.GetText: string;
begin
Result := StrText;
end;
procedure TGUI_TextBox.MoveCursor(Amt: Integer);
begin
Cursor := Cursor + amt;
if cursor < 0 then
cursor := 0;
if cursor > length(GetText) then
cursor := length(GetText);
end;
procedure TGUI_TextBox.CursorInsert(Character: TSDLTextInputArray);
begin
StrText := LeftStr(GetText, Cursor) + Character + RightStr(GetText, Length(
GetText) - Cursor);
end;
procedure TGUI_TextBox.CursorBackspace;
begin
if cursor <> 0 then
begin
StrText := LeftStr(GetText, Cursor - 1) + RightStr(GetText, Length(
GetText) - Cursor);
MoveCursor(-1);
end;
end;
procedure TGUI_TextBox.CursorDelete;
begin
if cursor <> length(GetText) then
begin
StrText := LeftStr(GetText, Cursor) + RightStr(GetText, Length(GetText) -
Cursor - 1);
end;
end;
procedure TGUI_TextBox.CursorHome;
begin
Cursor := 0;
end;
procedure TGUI_TextBox.CursorEnd;
begin
Cursor := Length(GetText);
end;
//*********************************************************
//TGUI_Image
//*********************************************************
constructor TGUI_Image.Create;
begin
inherited Create;
SetFillStyle(FS_None);
SetFullSrc(True);
SetFreeAutomatically(False);
end;
destructor TGUI_Image.Destroy;
begin
inherited Destroy;
if GetFreeAutomatically then
SDL_DestroyTexture(SrcTexture);
end;
procedure TGUI_Image.ChildAddedCallback;
begin
inherited;
if Assigned(StoredSurface) then
SrcTexture := SDL_CreateTextureFromSurface(Renderer, StoredSurface);
end;
procedure TGUI_Image.SetSource(NewSrcTexture: PSDL_Texture);
begin
SrcTexture := NewSrcTexture;
end;
procedure TGUI_Image.SetSource(NewSrcSurface: PSDL_Surface);
begin
StoredSurface := NewSrcSurface;
SetFreeAutomatically(True);
end;
function TGUI_Image.GetSource: PSDL_Texture;
begin
GetSource := SrcTexture;
end;
procedure TGUI_Image.SetSrcRect(NewRect: TSDL_Rect);
begin
SrcRect := NewRect;
end;
function TGUI_Image.GetSrcRect: TSDL_Rect;
begin
GetSrcRect := SrcRect;
end;
procedure TGUI_Image.SetFullSrc(NewFullSrc: Boolean);
begin
FullSrc := NewFullSrc;
end;
function TGUI_Image.GetFullSrc: Boolean;
begin
GetFullSrc := FullSrc;
end;
procedure TGUI_Image.SetFreeAutomatically(NewFreeStatus: Boolean);
begin
IsFreed := NewFreeStatus;
end;
function TGUI_Image.GetFreeAutomatically: Boolean;
begin
Result := IsFreed;
end;
procedure TGUI_Image.Render;
begin
inherited Render;
if Assigned(SrcTexture) then
begin
DstRect.x := GetAbsLeft;
DstRect.y := GetAbsTop;
DstRect.w := GetWidth;
DstRect.h := GetHeight;
if FullSrc then
SDL_RenderCopy(Renderer, SrcTexture, nil, @DstRect)
else
SDL_RenderCopy(Renderer, SrcTexture, @SrcRect, @DstRect);
end;
end;
//*********************************************************
//TGUI_Listbox_Item
//*********************************************************
function TGUI_Listbox_Item.Last: TGUI_Listbox_Item;
begin
if Next <> nil then
Last := Next.Last
else
Last := Self;
end;
function TGUI_Listbox_Item.First: TGUI_Listbox_Item;
begin
if Prev <> nil then
First := Next.Prev
else
First := Self;
end;
function TGUI_Listbox_Item.GetSelectedItem: TGUI_Listbox_item;
var
NextItem: TGUI_Listbox_item;
begin
NextItem := First;
while (NextItem <> nil) and not (NextItem.GetSelected) do
NextItem := NextItem.Next;
GetSelectedItem := NextItem;
end;
function TGUI_Listbox_Item.GetStr: string;
begin
GetStr := Caption;
end;
procedure TGUI_Listbox_Item.SetStr(NewString: string);
begin
Caption := NewString;
end;
function TGUI_Listbox_Item.GetIndex: Integer;
begin
GetIndex := IndexNo;
end;
procedure TGUI_Listbox_Item.SetIndex(NewIndex: Integer);
begin
IndexNo := NewIndex;
end;
procedure TGUI_Listbox_Item.AddItem(NewStr: string; NewIndex: Integer);
var
NewPrev: TGUI_Listbox_Item;
begin
NewPrev := Last;
Last.Next := TGUI_Listbox_Item.Create;
Last.Next := nil;
Last.Prev := NewPrev;
Last.SetIndex(NewIndex);
Last.SetStr(NewStr);
end;
procedure TGUI_Listbox_Item.Dump;
begin
Write(GetStr, '(', GetIndex, ')');
if Next <> nil then
begin
Write('->');
Next.dump;
end
else
Writeln;
end;
constructor TGUI_Listbox_Item.Create;
begin
IndexNo := 0;
end;
destructor TGUI_Listbox_Item.Destroy;
begin
if Assigned(Next) then
FreeAndNil(Next);
inherited Destroy;
end;
function TGUI_Listbox_Item.ReturnItem(ItemIndex: Integer): TGUI_listbox_item;
begin
if IndexNo = ItemIndex then
ReturnItem := Self
else
if Next <> nil then
ReturnItem := Next.ReturnItem(ItemIndex)
else
ReturnItem := nil;
end;
procedure TGUI_Listbox_Item.PushToLast;
begin
if Next <> nil then
begin
Prev.Next := Next;
Next.Prev := Prev;
Prev := Last;
Prev.Next := Self;
Next := nil;
end;
end;
function TGUI_Listbox_Item.GetCount: Word;
begin
if Assigned(Next) then
GetCount := Next.GetCount + 1
else
GetCount := 1;
end;
procedure TGUI_Listbox_Item.SetSelected(NewSel: Boolean);
var
NextItem: TGUI_Listbox_Item;
begin
Selected := NewSel;
if NewSel then
begin
NextItem := Next;
while NextItem <> nil do
begin
NextItem.SetSelected(False);
NextItem := NextItem.Next;
end;
NextItem := Prev;
while NextItem <> nil do
begin
NextItem.SetSelected(False);
NextItem := NextItem.Prev;
end;
end;
end;
function TGUI_Listbox_Item.GetSelected: Boolean;
begin
GetSelected := Selected;
end;
//*********************************************************
//TGUI_Listbox
//*********************************************************
constructor TGUI_Listbox.Create;
begin
inherited Create;
SetBorderStyle(BS_Single);
SetSelectable(True);
Items := TGUI_Listbox_Item.Create;
Items.NullFirst := True;
Scrollbar := TGUI_Scrollbar.Create;
with Scrollbar do
begin
SetMin(0);
SetDir(DIR_VERTICAL);
SetAutoAlign(True);
end;
AddChild(Scrollbar);
end;
destructor TGUI_Listbox.Destroy;
begin
FreeAndNil(Items);
inherited Destroy;
end;
function TGUI_Listbox.GetItems: TGUI_Listbox_Item;
begin
Result := Items;
end;
procedure TGUI_Listbox.ctrl_FontChanged;
begin
inherited;
if FontLineSkip <> 0 then
begin
ItemsToShow := (GetHeight div FontLineSkip);
end
else
ItemsToShow := 0;
end;
procedure TGUI_Listbox.ctrl_Resize;
begin
inherited;
if FontLineSkip <> 0 then
begin
ItemsToShow := (GetHeight div FontLineSkip);
end
else
ItemsToShow := 0;
end;
procedure TGUI_Listbox.Render;
var
NewCount: Word;
i: Word;
Next: TGUI_Listbox_Item;
Rect: TSDL_Rect;
begin
if CurSelected then
CurBorderColor := GUI_DefaultForeColor
else
CurBorderColor := BorderColor;
inherited;
NewCount := Items.GetCount;
if NewCount <> ListCount then
begin
ListCount := NewCount;
if ItemsToShow <= NewCount then
begin
Scrollbar.Setmax(NewCount - ItemsToShow - 1);
Scrollbar.SetVisible(True);
end
else
begin
Scrollbar.SetVisible(False);
end;
end;
i := 0;
Next := GetItems.Next;
while (i < Scrollbar.GetValue) and (Next <> nil) do
begin
Next := Next.Next;
Inc(i);
end;
i := 0;
while (i < ItemsToShow) and (Next <> nil) do
begin
if Next.GetSelected then
begin
with Rect do
begin
x := GetAbsLeft + 1;
w := getwidth - 2;
y := GetAbsTop + i * FontLineSkip + 1;
h := FontLineSkip - 2;
end;
if CurSelected then
RenderFilledRect(@Rect, GUI_SelectedColor)
else
RenderFilledRect(@Rect, GUI_DefaultTextBackColor);
end;
RenderText(Next.Caption, 3, i * FontLineSkip, Align_Left);
Next := Next.Next;
Inc(i);
end;
end;
procedure TGUI_Listbox.ctrl_KeyDown(KeySym: TSDL_KeySym);
var
CurItem: TGUI_Listbox_Item;
begin
CurItem := GetItems.GetSelectedItem;
case KeySym.Sym of
SDLK_UP:
begin
if CurItem.Prev <> nil then
begin
if not CurItem.Prev.NullFirst then
begin
CurItem.Prev.SetSelected(True);
ctrl_NewSelection(CurItem.Prev);
end;
end;
end;
SDLK_DOWN:
begin
if CurItem.Next <> nil then
CurItem.Next.SetSelected(True);
ctrl_NewSelection(CurItem.Next);
end;
end;
end;
procedure TGUI_Listbox.MouseDown(X, Y: Word; Button: UInt8);
var
ItemNo: Word;
i: Integer;
Next: TGUI_Listbox_Item;
begin
inherited;
ItemNo := y div FontLineSkip;
if Button = 1 then
begin
i := 0;
Next := GetItems.Next;
while (i < Scrollbar.GetValue) and (Next <> nil) do
begin
Next := Next.Next;
Inc(i);
end;
i := 0;
while (i < ItemNo) and (Next <> nil) do
begin
Next := Next.Next;
Inc(i);
end;
end;
if Next <> nil then
begin
Next.setselected(True);
ctrl_NewSelection(Next);
end;
end;
procedure TGUI_Listbox.ctrl_NewSelection(Selection: TGUI_Listbox_Item);
begin
NewSelection(Selection);
end;
procedure TGUI_Listbox.NewSelection(Selection: TGUI_Listbox_Item);
begin
end;
function TGUI_Listbox.GetSelectedItem: TGUI_Listbox_Item;
begin
GetSelectedItem := GetItems.GetSelectedItem;
end;
begin
end.
|
PROGRAM XmasFire;
(* Check if the number is uneven*)
FUNCTION CheckForOdd(i : INTEGER) : BOOLEAN;
BEGIN
IF (i MOD 2 <> 0) AND ( i <> 0) THEN CheckForOdd := True ELSE CheckForOdd := False;
END;
(* Recursive *)
FUNCTION XFire(len : Integer) : INTEGER;
VAR count : INTEGER;
BEGIN
count := 0;
IF CheckForOdd(len) THEN
BEGIN
IF len < 3 THEN
count := count + 3
ELSE
BEGIN
count := count + (len - 3) * 2 ;
count := count + XFire(len-2);
END;
XFire := count;
END
ELSE
BEGIN
Write('Wrong Input!');
XFire := 0;
END;
END;
(* Iterative *)
FUNCTION XFire_iterative(len : INTEGER) : INTEGER;
VAR count, temp: INTEGER;
BEGIN
IF CheckForOdd(len) THEN
BEGIN
count := 0;
temp := len;
WHILE temp > 1 DO
BEGIN
count := count + 1;
temp := temp - 2;
END;
XFire_iterative := 3 + ((len-3) * count);
END
ELSE
BEGIN
Write('Wrong Input!');
XFire_iterative := 0;
END;
END;
VAR word : String;
BEGIN
WriteLn(chr(205),chr(205),chr(185),' Fire on XMas Tree ',chr(204),chr(205),chr(205));
word := '1234';
WriteLn('Ways for ',word,': ',XFire(length(word)));
WriteLn('Ways for ',word,' Iterative: ',XFire_iterative(length(word)));
word := '123';
WriteLn('Ways for ',word,': ',XFire(length(word)));
WriteLn('Ways for ',word,' Iterative: ',XFire_iterative(length(word)));
word := '12345';
WriteLn('Ways for ',word,': ',XFire(length(word)));
WriteLn('Ways for ',word,' Iterative: ',XFire_iterative(length(word)));
word := '1234567';
WriteLn('Ways for ',word,': ',XFire(length(word)));
WriteLn('Ways for ',word,' Iterative: ',XFire_iterative(length(word)));
word := '123456789';
WriteLn('Ways for ',word,': ',XFire(length(word)));
WriteLn('Ways for ',word,' Iterative: ',XFire_iterative(length(word)));
word := '12345678901';
WriteLn('Ways for ',word,': ',XFire(length(word)));
WriteLn('Ways for ',word,' Iterative: ',XFire_iterative(length(word)));
word := '1234567890123';
WriteLn('Ways for ',word,': ',XFire(length(word)));
WriteLn('Ways for ',word,' Iterative: ',XFire_iterative(length(word)));
END. |
unit MulOpTest;
interface
uses
DUnitX.TestFramework,
uEnums,
uIntXLibTypes,
uIntX,
uConstants;
type
[TestFixture]
TMulOpTest = class(TObject)
public
[Setup]
procedure Setup;
[Test]
procedure PureIntX();
[Test]
procedure PureIntXSign();
[Test]
procedure IntAndIntX();
[Test]
procedure Zero();
[Test]
procedure Big();
[Test]
procedure Big2();
[Test]
procedure Big3();
[Test]
procedure Performance();
end;
implementation
procedure TMulOpTest.Setup;
begin
TIntX.GlobalSettings.MultiplyMode := TMultiplyMode.mmClassic;
end;
[Test]
procedure TMulOpTest.PureIntX();
begin
Assert.IsTrue(TIntX.Create(3) * TIntX.Create(5) = TIntX.Create(15));
end;
[Test]
procedure TMulOpTest.PureIntXSign();
begin
Assert.IsTrue(TIntX.Create(-3) * TIntX.Create(5) = TIntX.Create(-15));
end;
[Test]
procedure TMulOpTest.IntAndIntX();
begin
Assert.IsTrue(TIntX.Create(3) * 5 = 15);
end;
[Test]
procedure TMulOpTest.Zero();
begin
Assert.IsTrue(0 * TIntX.Create(3) = 0);
end;
[Test]
procedure TMulOpTest.Big();
var
temp1, temp2, tempRes: TIntXLibUInt32Array;
int1, int2, intRes: TIntX;
begin
SetLength(temp1, 2);
temp1[0] := 1;
temp1[1] := 1;
SetLength(temp2, 2);
temp2[0] := 1;
temp2[1] := 1;
SetLength(tempRes, 3);
tempRes[0] := 1;
tempRes[1] := 2;
tempRes[2] := 1;
int1 := TIntX.Create(temp1, False);
int2 := TIntX.Create(temp2, False);
intRes := TIntX.Create(tempRes, False);
Assert.IsTrue(int1 * int2 = intRes);
end;
[Test]
procedure TMulOpTest.Big2();
var
temp1, temp2, tempRes: TIntXLibUInt32Array;
int1, int2, intRes: TIntX;
begin
SetLength(temp1, 2);
temp1[0] := 1;
temp1[1] := 1;
SetLength(temp2, 1);
temp2[0] := 2;
SetLength(tempRes, 2);
tempRes[0] := 2;
tempRes[1] := 2;
int1 := TIntX.Create(temp1, False);
int2 := TIntX.Create(temp2, False);
intRes := TIntX.Create(tempRes, False);
Assert.IsTrue(intRes = int1 * int2);
Assert.IsTrue(intRes = int2 * int1);
end;
[Test]
procedure TMulOpTest.Big3();
var
temp1, temp2, tempRes: TIntXLibUInt32Array;
int1, int2, intRes: TIntX;
begin
SetLength(temp1, 2);
temp1[0] := TConstants.MaxUInt32Value;
temp1[1] := TConstants.MaxUInt32Value;
SetLength(temp2, 2);
temp2[0] := TConstants.MaxUInt32Value;
temp2[1] := TConstants.MaxUInt32Value;
SetLength(tempRes, 4);
tempRes[0] := 1;
tempRes[1] := 0;
tempRes[2] := TConstants.MaxUInt32Value - 1;
tempRes[3] := TConstants.MaxUInt32Value;
int1 := TIntX.Create(temp1, False);
int2 := TIntX.Create(temp2, False);
intRes := TIntX.Create(tempRes, False);
Assert.IsTrue(int1 * int2 = intRes);
end;
[Test]
procedure TMulOpTest.Performance();
var
i: Integer;
temp1: TIntXLibUInt32Array;
IntX, intX2: TIntX;
begin
SetLength(temp1, 2);
temp1[0] := 0;
temp1[1] := 1;
IntX := TIntX.Create(temp1, False);
intX2 := IntX;
i := 0;
while i <= Pred(1000) do
begin
intX2 := intX2 * IntX;
Inc(i);
end;
end;
initialization
TDUnitX.RegisterTestFixture(TMulOpTest);
end.
|
//******************************************************************************
// Пакет для редактирования записи
// из таблицы Z_Current - зарплатные текущие выплаты
// Параметры: AOwner - компонент от которого создается форма для редактирования
// DB_Handle - база для подключения
// AZControlFormStyle - тип формы: редактрирование, удаление, добавление, просмотр
// AID - если добавление, то RMoving, иначе ID_Current
//******************************************************************************
unit Current_Ctrl_MainForm_Mas;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, ExtCtrls, cxMaskEdit, cxDropDownEdit,
cxCalendar, cxTextEdit, cxButtonEdit, cxContainer, cxEdit, cxLabel,
cxControls, cxGroupBox, StdCtrls, cxButtons, Registry,
PackageLoad, DB, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, IBase,
ZTypes, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, GlobalSpr,
cxDBEdit, cxSpinEdit, cxMemo, Dates, cxCalc, FIBQuery, pFIBQuery,
pFIBStoredProc, gr_uMessage, ActnList, gr_uCommonConsts,
cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxDBData, cxGridTableView, cxGridLevel, cxClasses,
cxGridCustomView, cxGridCustomTableView, cxGridDBTableView, cxGrid, Unit_NumericConsts,
dxStatusBar, Menus, gr_uCommonProc, cxGridBandedTableView,
cxGridDBBandedTableView, ZProc, gr_dmCommonStyles, cxCheckBox, gr_Stud_Group_DM,
gr_uCommonLoader, gr_uWaitForm, RxMemDS;
type
TFgrCurrentCtrlMas = class(TForm)
YesBtn: TcxButton;
CancelBtn: TcxButton;
PrikazBox: TcxGroupBox;
EditPrikaz: TcxMaskEdit;
LabelPrikaz: TcxLabel;
LabelPeriod: TcxLabel;
MonthesList: TcxComboBox;
YearSpinEdit: TcxSpinEdit;
LabelSumma: TcxLabel;
EditSumma: TcxMaskEdit;
Bevel2: TBevel;
ActionList1: TActionList;
Action1: TAction;
cxStyleRepository1: TcxStyleRepository;
GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
BoxChild: TcxGroupBox;
EditSmeta: TcxButtonEdit;
LabelSmeta: TcxLabel;
LabelSmetaName: TcxLabel;
LabelVidOpl: TcxLabel;
EditVidOpl: TcxButtonEdit;
LabelVidOplName: TcxLabel;
dxStatusBar1: TdxStatusBar;
CheckBoxMonthFinish: TcxCheckBox;
Action3: TAction;
procedure CancelBtnClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Action1Execute(Sender: TObject);
procedure EditVidOplExit(Sender: TObject);
procedure EditSmetaExit(Sender: TObject);
procedure MonthesListExit(Sender: TObject);
procedure EditSmetaPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure EditVidOplPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure RestoreFromBuffer(Sender:TObject);
procedure Action2Execute(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure Action3Execute(Sender: TObject);
private
FRes:variant;
StylesDM:TStylesDM;
CParam :TParamGG;
procedure WResult(const Value: Variant);
function RResult: Variant;
procedure Update_Mas_Payment();
procedure Delete_Mas_Payment;
public
Pcfs:TZControlFormStyle;
PId_VidOpl:LongWord;
PId_Smeta:LongWord;
PId_Man:LongWord;
PIdStud:int64;
PIdCurrent:int64;
PParameter:TZCurrentParameters;
PLanguageIndex:Byte;
PKodSetup:integer;
Constructor Create(BParam:TParamGG);reintroduce;
function DeleteRecord(Db_Handle:TISC_DB_HANDLE;Id:integer):boolean;
function PrepareData(Db_Handle:TISC_DB_HANDLE):boolean;
property Res:Variant read RResult write WResult;
end;
function ViewCurrentCtrlMas(BParam:TParamGG):Variant;stdcall;
exports ViewCurrentCtrlMas;
implementation
uses Math;
{$R *.dfm}
function ViewCurrentCtrlMas(BParam:TParamGG):Variant;stdcall;
var Form:TFgrCurrentCtrlMas;
begin
Form:=TFgrCurrentCtrlMas.Create(BParam);
if BParam.Mode='A' then
begin
result := Form.PrepareData(DM.DB.Handle);
if Result<>False then
begin
Form.ShowModal;
Result :=Form.RResult;
end
else Result:=NULL;
end
else if BParam.Mode='U'
then Form.Update_Mas_Payment
else if BParam.Mode='D'
then Form.Delete_Mas_Payment;
Form.Destroy;
end;
function TFgrCurrentCtrlMas.DeleteRecord(Db_Handle:TISC_DB_HANDLE;Id:integer):boolean;
var PLanguageIndex:byte;
begin
{Result:=False;
PLanguageIndex := IndexLanguage;
if grShowMessage(Caption_Delete[PLanguageIndex],
DeleteRecordQuestion_Text[PLanguageIndex],mtConfirmation,[mbYes,mbCancel])=mrYes then
begin
//DM := TDM.Create(self);
with DM do
try
Result:=True;
DB.Handle:=Db_Handle;
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='GR_CURRENT_D';
StProc.Prepare;
StProc.ParamByName('ID_CURRENT').AsInteger:=Id;
StProc.ExecProc;
StProc.Transaction.Commit;
except
on E:Exception do
begin
grShowMessage(ECaption[PlanguageIndex],e.Message,mtError,[mbOK]);
StProc.Transaction.Rollback;
Result:=False;
end;
end;
DM.Destroy;
end; }
end;
constructor TFgrCurrentCtrlMas.Create(BParam:TParamGG);
begin
inherited Create(BParam.owner);
PLanguageIndex:= IndexLanguage;
//******************************************************************************
EditSumma.Properties.EditMask := '[-]?\d\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d? (['+grSystemDecimalSeparator+']\d\d?)?';
//******************************************************************************
LabelSumma.Caption := LabelSumma_Caption[PLanguageIndex];
LabelVidOpl.Caption := LabelVidOpl_Caption[PLanguageIndex];
LabelSmeta.Caption := LabelSmeta_Caption[PLanguageIndex];
//LabelManMoving.Caption := LabelStudentMoving_Caption[PLanguageIndex];
LabelPeriod.Caption := LabelPeriod_Caption[PLanguageIndex];
LabelPrikaz.Caption := LabelPrikaz_Caption[PLanguageIndex];
CheckBoxMonthFinish.Properties.Caption := LabelMonthFinish_Caption[PLanguageIndex];
CParam:=BParam;
MonthesList.Properties.Items.Text := MonthesList_Text[PLanguageIndex];
YesBtn.Caption := YesBtn_Caption[PLanguageIndex];
YesBtn.Hint := YesBtn.Caption;
CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex];
CancelBtn.Hint := CancelBtn.Caption+' (Esc)';
//******************************************************************************
//dxStatusBar1.Panels[0].Text := 'F9 - '+ToBuffer_Caption[PLanguageIndex];
dxStatusBar1.Panels[0].Text := 'F10 - '+YesBtn.Caption;
dxStatusBar1.Panels[1].Text := 'Esc - '+CancelBtn.Caption;
end;
function TFgrCurrentCtrlMas.PrepareData(Db_Handle:TISC_DB_HANDLE):boolean;
var CurrKodSetup:integer;
FieldValue:Variant;
begin
Result:=False;
CurrKodSetup := ValueFieldZSetup(Db_Handle,'GR_KOD_SETUP');
MonthesList.ItemIndex := YearMonthFromKodSetup(CurrKodSetup,False)-1;
YearSpinEdit.Value := YearMonthFromKodSetup(CurrKodSetup);
PKodSetup := CurrKodSetup;
FieldValue := ValueFieldZSetup(Db_Handle,'GR_DEFAULT_SMETA');
if not VarIsNULL(FieldValue) then
begin
EditSmeta.Text := VarToStr(FieldValue);
EditSmetaExit(self);
end;
Result:=True;
end;
procedure TFgrCurrentCtrlMas.CancelBtnClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TFgrCurrentCtrlMas.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
//DM.Free;
end;
procedure TFgrCurrentCtrlMas.Action1Execute(Sender: TObject);
var wf:TForm;
ID_CURRENT,ID_GR_MASS_PAYMENT:variant;
Stream: TMemoryStream;
t:integer;
begin
if EditSumma.Text='' then
begin
grShowMessage(ECaption[PLanguageIndex],ESummaInput_Text[PLanguageIndex],mtInformation,[mbOK]);
EditSumma.SetFocus;
Exit;
end;
if PId_VidOpl=0 then
begin
grShowMessage(ECaption[PLanguageIndex],EVidOplInput_Text[PLanguageIndex],mtInformation,[mbOK]);
EditVidOpl.SetFocus;
Exit;
end;
if PId_Smeta=0 then
begin
grShowMessage(ECaption[PLanguageIndex],ESmetaInput_Text[PLanguageIndex],mtInformation,[mbOK]);
EditSmeta.SetFocus;
Exit;
end;
with DM do
begin
wf:=gr_uWaitForm.ShowWaitForm(self,wfSelectData);
TcxMemo(CParam.PMemo).Lines.Clear;
TcxMemo(CParam.PMemo).Lines.Append('Старт '+DateToStr(Now)+' в '+TimeToStr(Now));
try
StProcTransaction.StartTransaction;
StProc2.StoredProcName:='GR_MASS_PAYMENT_I'; //history of payment
StProc2.Prepare;
StProc2.ParamByName('KOD_SETUP').AsInteger := PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1);
StProc2.ParamByName('END_MONTH').AsString := IfThen(CheckBoxMonthFinish.Checked,'T','F');
StProc2.ParamByName('SUMMA').AsCurrency := StrToFloat(EditSumma.Text);
StProc2.ParamByName('PRIKAZ').AsString := EditPrikaz.Text;
StProc2.ParamByName('ID_VIDOPL').AsInteger := PId_VidOpl;
StProc2.ParamByName('ID_SMETA').AsInt64 := PId_Smeta;
StProc2.ParamByName('TYPE_MASS_PAYMENT').AsString := 'P';
StProc2.ExecProc;
ID_GR_MASS_PAYMENT := StProc2.ParamByName('ID_GR_MASS_PAYMENT').AsInt64;
StProcTransaction.Commit;
WResult(ID_GR_MASS_PAYMENT);
except
TcxMemo(CParam.PMemo).Lines.Append('Помилка: неможливо додати масовоу поточну виплату');
TcxMemo(CParam.PMemo).Lines.Append('Операцію відмінено');
StProcTransaction.Rollback;
CloseWaitForm(wf);
exit;
end;
TcxGridDBTableView(CParam.PGrid).Controller.GoToFirst;
For t:=0 to TcxGridDBTableView(CParam.PGrid).DataController.RowCount-1 do
begin
if TcxGridDBTableView(CParam.PGrid).DataController.Controller.FocusedRecord.Values[0]=Checked then
begin
try
DSetMoving.Close;
DSetMoving.SQLs.SelectSQL.Text := 'SELECT * FROM GR_CN_DT_STUD_INF_S_BY_STUD_KS('+
RxMemoryData1['ID_STUD']+',NULL)';
DSetMoving.Open;
StProcTransaction.StartTransaction;
StProc.StoredProcName:='GR_CURRENT_I';
StProc.Prepare;
StProc.ParamByName('KOD_SETUP').AsInteger := PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1);
StProc.ParamByName('KOD_SETUP_O1').AsVariant := NULL;
StProc.ParamByName('KOD_SETUP_O2').AsVariant := NULL;
StProc.ParamByName('ID_MAN').AsVariant := NULL;
StProc.ParamByName('SUMMA').AsCurrency := StrToFloat(EditSumma.Text);
StProc.ParamByName('ID_CATEGORY').AsVariant := DSetMoving['ID_KAT_STUD'];
StProc.ParamByName('ID_POST').AsVariant := NULL;
StProc.ParamByName('ID_DEPARTMENT').AsVariant := NULL;
StProc.ParamByName('ID_SMETA').AsInt64 := PId_Smeta;
StProc.ParamByName('ID_ACCOUNT').AsVariant := NULL;
StProc.ParamByName('ID_STUD_INF').AsInt64 := DSetMoving['ID_STUD_INF'];
StProc.ParamByName('ID_STUD').AsVariant := NULL;
StProc.ParamByName('TAX_TEXT').AsVariant := NULL;
StProc.ParamByName('P_OLD').AsString := 'F';
StProc.ParamByName('ID_VIDOPL').AsInteger := PId_VidOpl;
StProc.ParamByName('PRIKAZ').AsString := EditPrikaz.Text;
StProc.ParamByName('NOW_PAY').AsString := CheckBoxMonthFinish.EditValue;
StProc.ExecProc;
ID_CURRENT:= StProc.ParamByName('ID_CURRENT').AsVariant;
StProc3.StoredProcName:='GR_MASS_PAYMENT_MAN_I';
StProc3.Prepare;
StProc3.ParamByName('ID_GR_MASS_PAYMENT').AsInt64 := ID_GR_MASS_PAYMENT;
StProc3.ParamByName('ID_MAN').AsInt64 := RxMemoryData1['ID_MAN'];
StProc3.ParamByName('ID_STUD').AsInt64 := RxMemoryData1['ID_STUD'];
StProc3.ParamByName('ID_VIPL').AsInt64 := StrToInt64(VarToStr(ID_CURRENT));
StProc3.ExecProc;
StProcTransaction.Commit;
except
TcxMemo(CParam.PMemo).Lines.Append('Помилка: неможливе додання людини - '+RxMemoryData1['FIO']);
ID_CURRENT:=NULL;
StProcTransaction.Rollback;
end;
if ID_CURRENT<>null then
try
StProcTransaction.StartTransaction;
StProcImport.StoredProcName:='GR_CURRENT_PERESECH';
StProcImport.Prepare;
StProcImport.ParamByName('ID').AsInt64 := StrToInt64(VarToStr(ID_CURRENT)); //IFThen(isNull(ResCurr),0,ResCurr;
StProcImport.ExecProc;
if StProcImport.ParamByName('RES').AsInteger=1 then TcxMemo(CParam.PMemo).Lines.Append('Попередження: пересічення термінів - '+RxMemoryData1['FIO']);
StProcTransaction.Commit;
except
StProcTransaction.Rollback;
TcxMemo(CParam.PMemo).Lines.Append('Попередження: помилка перевірення пересічення термінів - '+RxMemoryData1['FIO']);
end;
ID_CURRENT:=Null;
end;
TcxGridDBTableView(CParam.PGrid).Controller.GotoNext(True,True);
end;
CloseWaitForm(wf);
TcxMemo(CParam.PMemo).Lines.Append('Операцію завершено '+DateToStr(Now)+' в '+TimeToStr(Now));
try
Stream:=TMemoryStream.Create;
TcxMemo(CParam.PMemo).Lines.SaveToStream(Stream);
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='GR_MASS_PAYMENT_U'; //добавление отчета
StProc.Prepare;
StProc.ParamByName('ID_GR_MASS_PAYMENT').AsInt64 := ID_GR_MASS_PAYMENT;
StProc.ParamByName('OTCHET').LoadFromStream(Stream);
StProc.ExecProc;
StProc.Transaction.Commit;
except
StProc.Transaction.Rollback;
TcxMemo(CParam.PMemo).Lines.Append('Неможливо додати доповідь');
end;
Stream.Free;
end;
ModalResult:=mrYes;
end;
procedure TFgrCurrentCtrlMas.Update_Mas_Payment;
var t,CurrKodSetup:integer;
ID_CURRENT:variant;
wf:TForm;
Stream:TMemoryStream;
begin
with DM do
begin
CurrKodSetup := DM.DSetEditPayment['KOD_SETUP']; //ValueFieldZSetup(Db_Handle,'GR_KOD_SETUP');
MonthesList.ItemIndex := YearMonthFromKodSetup(CurrKodSetup,False)-1;
YearSpinEdit.Value := YearMonthFromKodSetup(CurrKodSetup);
EditSumma.Text:= FloatToStr(DSetEditPayment['SUMMA']);
PId_Smeta:= DSetEditPayment['ID_SMETA'];
PId_VidOpl:= DSetEditPayment['ID_VIDOPL'];
EditPrikaz.Text:= DSetEditPayment['PRIKAZ'];
if DSetEditPayment['END_MONTH']='Так'
then CheckBoxMonthFinish.EditValue:='T'
else if DSetEditPayment['END_MONTH']='Ні'
then CheckBoxMonthFinish.EditValue:='F';
end;
wf:=gr_uWaitForm.ShowWaitForm(self,wfSelectData);
TcxMemo(CParam.PMemo).Lines.Append('Оновлення масової виплати '+DateToStr(Now)+' в '+TimeToStr(Now));
TcxGridDBTableView(CParam.PGrid).Controller.GoToFirst;
For t:=0 to TcxGridDBTableView(CParam.PGrid).DataController.RowCount-1 do
with DM do
begin
if (TcxGridDBTableView(CParam.PGrid).DataController.Controller.FocusedRecord.Values[0]=Checked)
and (TcxGridDBTableView(CParam.PGrid).DataController.Controller.FocusedRecord.Values[9]<>CheckedColor)
then
try
DSetMoving.Close;
DSetMoving.SQLs.SelectSQL.Text := 'SELECT * FROM GR_CN_DT_STUD_INF_S_BY_STUD_KS('+
RxMemoryData1['ID_STUD']+',NULL)';
DSetMoving.Open;
StProcTransaction.StartTransaction;
StProc.StoredProcName:='GR_CURRENT_I';
StProc.Prepare;
StProc.ParamByName('KOD_SETUP').AsInteger := PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1);
StProc.ParamByName('KOD_SETUP_O1').AsVariant := NULL;
StProc.ParamByName('KOD_SETUP_O2').AsVariant := NULL;
StProc.ParamByName('ID_MAN').AsVariant := NULL;
StProc.ParamByName('SUMMA').AsCurrency := StrToFloat(EditSumma.Text);
StProc.ParamByName('ID_CATEGORY').AsVariant := DSetMoving['ID_KAT_STUD'];
StProc.ParamByName('ID_POST').AsVariant := NULL;
StProc.ParamByName('ID_DEPARTMENT').AsVariant := NULL;
StProc.ParamByName('ID_SMETA').AsInt64 := PId_Smeta;
StProc.ParamByName('ID_ACCOUNT').AsVariant := NULL;
StProc.ParamByName('ID_STUD_INF').AsInt64 := DSetMoving['ID_STUD_INF'];
StProc.ParamByName('ID_STUD').AsVariant := NULL;
StProc.ParamByName('TAX_TEXT').AsVariant := NULL;
StProc.ParamByName('P_OLD').AsString := 'F';
StProc.ParamByName('ID_VIDOPL').AsInteger := PId_VidOpl;
StProc.ParamByName('PRIKAZ').AsString := EditPrikaz.Text;
StProc.ParamByName('NOW_PAY').AsString := CheckBoxMonthFinish.EditValue;
StProc.ExecProc;
ID_CURRENT:= StProc.ParamByName('ID_CURRENT').AsVariant;
StProc3.StoredProcName:='GR_MASS_PAYMENT_MAN_I';
StProc3.Prepare;
StProc3.ParamByName('ID_GR_MASS_PAYMENT').AsInt64 := DSetEditPayment['ID_GR_MASS_PAYMENT'];
StProc3.ParamByName('ID_MAN').AsInt64 := RxMemoryData1['ID_MAN'];
StProc3.ParamByName('ID_STUD').AsInt64 := RxMemoryData1['ID_STUD'];
StProc3.ParamByName('ID_VIPL').AsInt64 := StrToInt64(VarToStr(ID_CURRENT));
StProc3.ExecProc;
StProcTransaction.Commit;
if ID_CURRENT<>null then
try
StProcTransaction.StartTransaction;
StProcImport.StoredProcName:='GR_CURRENT_PERESECH';
StProcImport.Prepare;
StProcImport.ParamByName('ID').AsInt64 := StrToInt64(VarToStr(ID_CURRENT)); //IFThen(isNull(ResCurr),0,ResCurr;
StProcImport.ExecProc;
if StProcImport.ParamByName('RES').AsInteger=1 then TcxMemo(CParam.PMemo).Lines.Append('Попередження: пересічення термінів - '+RxMemoryData1['FIO']);
StProcTransaction.Commit;
except
StProcTransaction.Rollback;
TcxMemo(CParam.PMemo).Lines.Append('Попередження: помилка перевірення пересічення термінів - '+RxMemoryData1['FIO']);
end;
ID_CURRENT:=Null;
RxMemoryData1.Edit;
RxMemoryData1['CHECKBOXCOLOR']:=CheckedColor;
RxMemoryData1.Post;
except
TcxMemo(CParam.PMemo).Lines.Append('Попередження: помилка перевірення пересічення термінів - '+RxMemoryData1['FIO']);
StProcTransaction.Rollback;
end;
TcxGridDBTableView(CParam.PGrid).Controller.GoToNext(True,True);
end;
TcxMemo(CParam.PMemo).Lines.Append('Операцію завершено '+DateToStr(Now)+' в '+TimeToStr(Now));
with DM do
try
Stream:=TMemoryStream.Create;
TcxMemo(CParam.PMemo).Lines.SaveToStream(Stream);
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='GR_MASS_PAYMENT_U'; //добавление отчета
StProc.Prepare;
StProc.ParamByName('ID_GR_MASS_PAYMENT').AsInt64 := DSetEditPayment['ID_GR_MASS_PAYMENT'];
StProc.ParamByName('OTCHET').LoadFromStream(Stream);
StProc.ExecProc;
StProc.Transaction.Commit;
except
StProc.Transaction.Rollback;
TcxMemo(CParam.PMemo).Lines.Append('Неможливо додати доповідь');
end;
Stream.Free;
CloseWaitForm(wf);
end;
procedure TFgrCurrentCtrlMas.EditVidOplExit(Sender: TObject);
var Vo:variant;
begin
if EditVidOpl.Text<>'' then
begin
VO:=VoByKod(StrToInt(EditVidOpl.Text),
Date,
DM.DB.Handle,
ValueFieldZSetup(DM.DB.Handle,'GR_ID_SYSTEM'),
0);
if not VarIsNull(VO) then
begin
PId_VidOpl:=VO[0];
LabelVidOplName.Caption:=VarToStr(VO[2]);
end
else
EditVidOpl.SetFocus;
end;
end;
procedure TFgrCurrentCtrlMas.EditSmetaExit(Sender: TObject);
var Smeta:variant;
begin
if EditSmeta.Text<>'' then
begin
Smeta:=SmetaByKod(StrToInt(EditSmeta.Text),DM.DB.Handle);
if not VarIsNull(Smeta) then
begin
PId_Smeta:=Smeta[0];
LabelSmetaName.Caption:=VarToStr(Smeta[2]);
end
else
EditSmeta.SetFocus;
end
end;
procedure TFgrCurrentCtrlMas.MonthesListExit(Sender: TObject);
begin
if PKodSetup=PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1) then Exit
else PKodSetup:=PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1);
if DM.DSetMoving.Active then DM.DSetMoving.Close;
DM.DSetMoving.SQLs.SelectSQL.Text:='SELECT * FROM GR_CN_DT_STUD_INF_S_BY_STUD_KS('+
IntToStr(PIdStud)+','+IntToStr(PKodSetup)+') order by DATE_END';
DM.DSetMoving.Open;
DM.DSetMoving.Last;
end;
procedure TFgrCurrentCtrlMas.EditSmetaPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var Smeta:Variant;
begin
Smeta:=GetSmets(self,DM.DB.Handle,Date,psmSmet);
if VarArrayDimCount(Smeta)> 0 then
If Smeta[0]<>NULL then
begin
EditSmeta.Text := Smeta[3];
LabelSmetaName.Caption := Smeta[2];
PId_Smeta := Smeta[0];
end;
end;
procedure TFgrCurrentCtrlMas.EditVidOplPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var VidOpl:Variant;
begin
VidOPl:=LoadVidOpl(self,
DM.DB.Handle,
zfsModal,
0,
ValueFieldZSetup(DM.DB.Handle,'GR_ID_SYSTEM'));
if VarArrayDimCount(VidOpl)> 0 then
if VidOpl[0]<> NULL then
begin
EditVidOpl.Text := VidOpl[2];
LabelVidOplName.Caption := VidOpl[1];
PId_VidOpl := VidOpl[0];
end;
end;
procedure TFgrCurrentCtrlMas.RestoreFromBuffer(Sender:TObject);
var reg:TRegistry;
Kod:integer;
Key:string;
begin
{
Key := '\Software\Grant\GroupGrant\CurrentCtrl';
reg := TRegistry.Create;
reg.RootKey:=HKEY_CURRENT_USER;
if not reg.OpenKey(Key,False) then
begin
reg.free;
Exit;
end;
if reg.ReadString('IsBuffer')<>'1' then
begin
reg.Free;
exit;
end;
EditSmeta.Text := reg.ReadString('KodSmeta');
EditSmetaExit(sender);
EditVidOpl.Text := reg.ReadString('KodVidOpl');
EditVidOplExit(sender);
EditPrikaz.Text := reg.ReadString('Prikaz');
CheckBoxMonthFinish.EditValue := reg.ReadString('EndMonth');
EditSumma.Text:= reg.ReadString('Summa');
Kod := reg.ReadInteger('KodSetup');
if Kod>0 then
begin
MonthesList.ItemIndex := YearMonthFromKodSetup(Kod,False)-1;
YearSpinEdit.Value := YearMonthFromKodSetup(Kod);
end;
editSumma.SetFocus;
Reg.Free; }
end;
procedure TFgrCurrentCtrlMas.Action2Execute(Sender: TObject);
var reg: TRegistry;
Key:string;
begin
{ CancelBtn.SetFocus;
Key := '\Software\Grant\GroupGrant\CurrentCtrl';
reg:=TRegistry.Create;
try
reg.RootKey:=HKEY_CURRENT_USER;
reg.OpenKey(Key,True);
reg.WriteString('IsBuffer','1');
reg.WriteString('KodSmeta',EditSmeta.Text);
reg.WriteString('KodVidOpl',EditVidOpl.Text);
reg.WriteInteger('KodSetup',PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1));
reg.WriteString('Prikaz',EditPrikaz.Text);
reg.WriteString('EndMonth',CheckBoxMonthFinish.EditValue);
reg.WriteString('Summa',EditSumma.Text);
finally
reg.Free;
end; }
end;
procedure TFgrCurrentCtrlMas.FormShow(Sender: TObject);
begin
//RestoreFromBuffer(self);
FormResize(sender);
// F:=False;
end;
procedure TFgrCurrentCtrlMas.FormResize(Sender: TObject);
var i:integer;
begin
for i:=0 to dxStatusBar1.Panels.Count-1 do
dxStatusBar1.Panels[i].Width := Width div dxStatusBar1.Panels.Count;
end;
procedure TFgrCurrentCtrlMas.Action3Execute(Sender: TObject);
var F:boolean;
begin
if (CancelBtn.Focused=False) and (YesBtn.focused=False) and (CheckBoxMonthFinish.Focused=False) and
(YearSpinEdit.focused=False) and (MonthesList.focused=False) and (EditSumma.focused=False) and
(EditPrikaz.focused=False) and (EditVidOpl.focused=False) and (EditSmeta.focused=False)
then F:=True;
if CancelBtn.focused=true then close();
if YesBtn.focused=true then Action1.Execute;
if F=true then
begin
YesBtn.SetFocus;
F:=False;
exit;
end;
if CheckBoxMonthFinish.Focused=true then begin YesBtn.SetFocus; F:=True; exit; end;
if YearSpinEdit.focused=true then begin CheckBoxMonthFinish.SetFocus; exit; end;
if MonthesList.focused=true then begin YearSpinEdit.SetFocus; exit; end;
if EditSumma.focused=true then begin MonthesList.SetFocus; exit; end;
if EditPrikaz.focused=true then begin EditSumma.SetFocus; exit; end;
if EditVidOpl.focused=true then begin EditPrikaz.SetFocus; exit; end;
if EditSmeta.focused=true then begin EditVidOpl.SetFocus; exit; end;
if CancelBtn.focused=true then EditSmeta.SetFocus;
end;
function TFgrCurrentCtrlMas.RResult: Variant;
begin
result:=FRes;
end;
procedure TFgrCurrentCtrlMas.WResult(const Value: Variant);
begin
FRes:=Value;
end;
procedure TFgrCurrentCtrlMas.Delete_Mas_Payment;
var focus,t:integer;
Stream:TMemoryStream;
begin
if not DM.RxMemoryData1.Locate('CHECKBOX',UNCHECKED,[]) then
begin
TcxMemo(CParam.PMemo).Lines.Append('Помилка: неможливо видалити всіх');
exit;
end;
//TcxGridDBTableView(CParam.PGrid).DataController.DataSource:=nil;
//DM.RxMemoryData1.First;
TcxGridDBTableView(CParam.PGrid).Controller.GoToFirst;
For t:=0 to TcxGridDBTableView(CParam.PGrid).DataController.RowCount-1 do
begin
if DM.RxMemoryData1['CHECKBOX']=CHECKED then
begin
if DM.RxMemoryData1['CHECKBOXCOLOR']=CHECKEDCOLOR then
begin
TcxMemo(CParam.PMemo).Lines.Append('Видалиння '+DM.RxMemoryData1['FIO']);
with DM do
try
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='GR_MASS_PAYMENT_DDD';
StProc.Prepare;
StProc.ParamByName('ID_GR_MASS_PAYMENT').AsInt64 := DSetEditPayment['ID_GR_MASS_PAYMENT'];
StProc.ParamByName('ID_MAN_V').AsInt64 := RxMemoryData1['ID_MAN']; // TcxGridDBTableView(CParam.PGrid).Controller.SelectedRows[i].Values[7];
StProc.ParamByName('ID_STUD_V').AsInt64 := RxMemoryData1['ID_STUD']; // TcxGridDBTableView(CParam.PGrid).Controller.SelectedRows[i].Values[8];
StProc.ExecProc;
StProc.Transaction.Commit;
except
StProc.Transaction.rollback;
TcxMemo(CParam.PMemo).Lines.Append('Помилка: неможливо видалити - '+RxMemoryData1['FIO']);
exit;
end;
end;
DM.RxMemoryData1.Delete;
end
else
begin
focus:= DM.RxMemoryData1['ID_MAN'];
//DM.RxMemoryData1.Next;
TcxGridDBTableView(CParam.PGrid).Controller.GoToNext(True,True);
end
end;
with DM do
try
Stream:=TMemoryStream.Create;
TcxMemo(CParam.PMemo).Lines.SaveToStream(Stream);
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='GR_MASS_PAYMENT_U'; //добавление отчета при редактировании
StProc.Prepare;
StProc.ParamByName('ID_GR_MASS_PAYMENT').AsInt64 := DSetEditPayment['ID_GR_MASS_PAYMENT'];
StProc.ParamByName('OTCHET').LoadFromStream(Stream);
StProc.ExecProc;
StProc.Transaction.Commit;
except
StProc.Transaction.Rollback;
TcxMemo(CParam.PMemo).Lines.Append('Помилка: неможливо додати протокол видалення записів');
end;
Stream.Free;
TcxMemo(CParam.PMemo).Lines.Append('Операцію завершено '+DateToStr(Now)+' в '+TimeToStr(Now));
DM.RxMemoryData1.Locate('ID_MAN',focus,[]);
//TcxGridDBTableView(CParam.PGrid).DataController.DataSource:=DM.DSourceStudEdit;
end;
end.
|
unit dbiPickupDropRins;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf,
FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB, FireDAC.Phys.FBDef, Data.DB,
FireDAC.Comp.Client, FireDAC.VCLUI.Wait, FireDAC.Phys.IBBase, FireDAC.Comp.UI, FireDAC.Stan.Param, FireDAC.DatS,
FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet;
type
TdmPickupDropRins = class(TDataModule)
fdtPickupTypes: TFDTable;
fdqRecipesUtil: TFDQuery;
fdtDropTypes: TFDTable;
fdtRinsingTypes: TFDTable;
procedure fdcRecipesBeforeConnect(Sender: TObject);
procedure fdtPickupTypesBeforePost(DataSet: TDataSet);
procedure DataModuleCreate(Sender: TObject);
procedure fdtDropTypesBeforePost(DataSet: TDataSet);
procedure fdtRinsingTypesBeforePost(DataSet: TDataSet);
procedure fdtPickupTypesAfterOpen(DataSet: TDataSet);
procedure fdtDropTypesAfterOpen(DataSet: TDataSet);
procedure fdtRinsingTypesAfterOpen(DataSet: TDataSet);
procedure fdtPickupTypesNewRecord(DataSet: TDataSet);
procedure fdtDropTypesNewRecord(DataSet: TDataSet);
procedure fdtRinsingTypesNewRecord(DataSet: TDataSet);
private
lastPickupID, lastDropID, lastRinsingID: integer;
procedure duplicateSomethingType(pTblName: string; pTbl: TFDDataSet; pOldID, pNewID: integer);
public
procedure openTypes;
function DuplicateRecords(justOne: boolean; cdsFrom, cdsTo: TFDDataSet; skipField: string; useValue: variant): integer;
procedure duplicatePickupType(pOldID, pNewID: integer);
procedure duplicateDropType(pOldID, pNewID: integer);
procedure duplicateRinsingType(pOldID, pNewID: integer);
end;
var
dmPickupDropRins: TdmPickupDropRins;
k_maximumInclination_mm: integer = 1000; // 1m
k_topLevel_mm: integer = 5000; // 5m
k_RinsingDownLevel: integer = 500; // 50cm
k_mmXsecs_slow: integer = 70; // con inverter andiamo circa a 294mm/sec. in veloce e circa 70mm/sec. in lenta
k_mmXsecs_fast: integer = 294; // senza inverter: 41,6mm/sec. in lenta e 267mm/sec. in veloce
implementation uses forms, math, dialogs, uEtcXE, dbiRecipes;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TdmPickupDropRins.DataModuleCreate(Sender: TObject);
begin
k_maximumInclination_mm := puntoIni.readInteger('config', 'maximumInclination_mm', k_maximumInclination_mm);
k_topLevel_mm := puntoIni.readInteger('config', 'topLevel_mm', k_topLevel_mm);
k_RinsingDownLevel := puntoIni.readInteger('config', 'RinsingDownLevel', k_RinsingDownLevel);
k_mmXsecs_slow := puntoIni.readInteger('config', 'mmXsecs_slow', k_mmXsecs_slow);
k_mmXsecs_fast := puntoIni.readInteger('config', 'mmXsecs_fast', k_mmXsecs_fast);
end;
procedure TdmPickupDropRins.fdcRecipesBeforeConnect(Sender: TObject);
begin with Sender as TFDConnection do
begin
params.Values['database' ] := puntoIni.ReadString('gdb', 'recipes' , params.Values['database']);
params.Values['user_name'] := puntoIni.ReadString('gdb', 'recipes_user_name', params.Values['user_name']);
params.Values['password' ] := puntoIni.ReadString('gdb', 'recipes_password' , params.Values['password']);
end;
end;
function blip_maxIncl(dm, op_MM: integer): boolean;
begin
result := abs(dm - op_MM) > k_maximumInclination_mm
end;
function blip_maxLevel(dm, dm_top: integer): boolean;
begin
result := dm > dm_top
end;
function blip_totSecs(dm, op_MM, isFast: integer): real;
begin
result := max(dm, op_MM);
if isFast <> 0 then result := result / k_mmXsecs_fast else result := result / k_mmXsecs_slow
end;
procedure TdmPickupDropRins.fdtDropTypesAfterOpen(DataSet: TDataSet);
begin with Dataset do begin
last; lastDropID := fieldByName('ID').AsInteger;
end end;
procedure TdmPickupDropRins.fdtDropTypesBeforePost(DataSet: TDataSet);
var s: string;
begin
s := '';
// checking maximum inclination
if blip_maxIncl(dataSet.FieldByName('QUOTE_1_MM').asInteger, dataSet.FieldByName('QUOTE_1_OP_MM').asInteger) then
s := s + 'level 1 inclination exceeded' + #13;
if blip_maxIncl(dataSet.FieldByName('QUOTE_2_MM').asInteger, dataSet.FieldByName('QUOTE_2_OP_MM').asInteger) then
s := s + 'level 2 inclination exceeded' + #13;
if blip_maxIncl(dataSet.FieldByName('QUOTE_3_MM').asInteger, dataSet.FieldByName('QUOTE_3_OP_MM').asInteger) then
s := s + 'level 3 inclination exceeded' + #13;
// checking against top level / sequence
if blip_maxLevel(dataSet.FieldByName('QUOTE_1_MM').asInteger, k_topLevel_mm) then
s := s + 'level 1 too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_1_OP_MM').asInteger, k_topLevel_mm) then
s := s + 'level 1 operator side too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_2_MM').asInteger, dataSet.FieldByName('QUOTE_1_MM').asInteger) then
s := s + 'level 2 too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_2_OP_MM').asInteger, dataSet.FieldByName('QUOTE_1_OP_MM').asInteger) then
s := s + 'level 2 operator side too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_3_MM').asInteger, dataSet.FieldByName('QUOTE_2_MM').asInteger) then
s := s + 'level 3 too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_3_OP_MM').asInteger, dataSet.FieldByName('QUOTE_2_OP_MM').asInteger) then
s := s + 'level 3 operator side too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_4_MM').asInteger, dataSet.FieldByName('QUOTE_3_MM').asInteger) then
s := s + 'level "out of tank" too high' + #13;
if blip_maxLevel(0, dataSet.FieldByName('QUOTE_4_MM').asInteger) then
s := s + 'level "out of tank" too low' + #13;
if s <> '' then begin
showMessage(s); abort
end;
// calculating total time
dataSet.FieldByName('TOTAL_SECS').AsInteger := trunc(
dataSet.FieldByName('PAUSE_1_SECS').asInteger +
dataSet.FieldByName('PAUSE_2_SECS').asInteger +
dataSet.FieldByName('PAUSE_3_SECS').asInteger +
dataSet.FieldByName('PAUSE_4_SECS').asInteger +
blip_totSecs(k_topLevel_mm - dataSet.FieldByName('QUOTE_1_MM').asInteger, 0,
dataSet.FieldByName('SPEED_1_FAST').asInteger) +
blip_totSecs(dataSet.FieldByName('QUOTE_1_MM').asInteger - dataSet.FieldByName('QUOTE_2_MM').asInteger,
dataSet.FieldByName('QUOTE_1_OP_MM').asInteger - dataSet.FieldByName('QUOTE_2_OP_MM').asInteger,
dataSet.FieldByName('SPEED_2_FAST').asInteger) +
blip_totSecs(dataSet.FieldByName('QUOTE_2_MM').asInteger - dataSet.FieldByName('QUOTE_3_MM').asInteger,
dataSet.FieldByName('QUOTE_2_OP_MM').asInteger - dataSet.FieldByName('QUOTE_3_OP_MM').asInteger,
dataSet.FieldByName('SPEED_3_FAST').asInteger) +
blip_totSecs(dataSet.FieldByName('QUOTE_3_MM').asInteger - dataSet.FieldByName('QUOTE_4_MM').asInteger,
dataSet.FieldByName('QUOTE_3_OP_MM').asInteger - dataSet.FieldByName('QUOTE_4_MM').asInteger,
dataSet.FieldByName('SPEED_4_FAST').asInteger) +
blip_totSecs(dataSet.FieldByName('QUOTE_4_MM').asInteger, 0,
dataSet.FieldByName('SPEED_5_FAST').asInteger)
);
end;
procedure TdmPickupDropRins.fdtDropTypesNewRecord(DataSet: TDataSet);
begin inc(lastDropID);
with Dataset do begin
FieldByName('ID').AsInteger := lastDropID;
FieldByName('SPEED_1_FAST').AsInteger := 1; // true by default
FieldByName('SPEED_2_FAST').AsInteger := 1; // true by default
FieldByName('SPEED_3_FAST').AsInteger := 1; // true by default
FieldByName('SPEED_4_FAST').AsInteger := 1; // true by default
FieldByName('SPEED_5_FAST').AsInteger := 1; // true by default
end;
end;
procedure TdmPickupDropRins.fdtPickupTypesAfterOpen(DataSet: TDataSet);
begin with Dataset do begin
last; lastPickupID := fieldByName('ID').AsInteger;
end end;
procedure TdmPickupDropRins.fdtPickupTypesBeforePost(DataSet: TDataSet);
var s: string;
begin
s := '';
// checking maximum inclination
if blip_maxIncl(dataSet.FieldByName('QUOTE_2_MM').asInteger, dataSet.FieldByName('QUOTE_2_OP_MM').asInteger) then
s := s + 'level 1 inclination exceeded' + #13;
if blip_maxIncl(dataSet.FieldByName('QUOTE_3_MM').asInteger, dataSet.FieldByName('QUOTE_3_OP_MM').asInteger) then
s := s + 'level 2 inclination exceeded' + #13;
if blip_maxIncl(dataSet.FieldByName('QUOTE_4_MM').asInteger, dataSet.FieldByName('QUOTE_4_OP_MM').asInteger) then
s := s + 'level 3 inclination exceeded' + #13;
// checking against top level / sequence
if blip_maxLevel(dataSet.FieldByName('QUOTE_4_MM').asInteger, k_topLevel_mm) then
s := s + 'level 3 too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_4_OP_MM').asInteger, k_topLevel_mm) then
s := s + 'level 3 operator side too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_3_MM').asInteger, dataSet.FieldByName('QUOTE_4_MM').asInteger) then
s := s + 'level 2 too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_3_OP_MM').asInteger, dataSet.FieldByName('QUOTE_4_OP_MM').asInteger) then
s := s + 'level 2 operator side too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_2_MM').asInteger, dataSet.FieldByName('QUOTE_3_MM').asInteger) then
s := s + 'level 1 too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_2_OP_MM').asInteger, dataSet.FieldByName('QUOTE_3_OP_MM').asInteger) then
s := s + 'level 1 operator side too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_1_MM').asInteger, dataSet.FieldByName('QUOTE_2_MM').asInteger) then
s := s + 'level "out of tank" too high' + #13;
if blip_maxLevel(0, dataSet.FieldByName('QUOTE_1_MM').asInteger) then
s := s + 'level "out of tank" too low' + #13;
if s <> '' then begin
showMessage(s); abort
end;
// calculating total time
dataSet.FieldByName('TOTAL_SECS').AsInteger := trunc(
dataSet.FieldByName('PAUSE_1_SECS').asInteger +
dataSet.FieldByName('PAUSE_2_SECS').asInteger +
dataSet.FieldByName('PAUSE_3_SECS').asInteger +
dataSet.FieldByName('PAUSE_4_SECS').asInteger +
blip_totSecs(dataSet.FieldByName('QUOTE_1_MM').asInteger, 0, dataSet.FieldByName('SPEED_1_FAST').asInteger) +
blip_totSecs(dataSet.FieldByName('QUOTE_2_MM').asInteger - dataSet.FieldByName('QUOTE_1_MM').asInteger,
dataSet.FieldByName('QUOTE_2_OP_MM').asInteger - dataSet.FieldByName('QUOTE_1_MM').asInteger,
dataSet.FieldByName('SPEED_2_FAST').asInteger) +
blip_totSecs(dataSet.FieldByName('QUOTE_3_MM').asInteger - dataSet.FieldByName('QUOTE_2_MM').asInteger,
dataSet.FieldByName('QUOTE_3_OP_MM').asInteger - dataSet.FieldByName('QUOTE_2_OP_MM').asInteger,
dataSet.FieldByName('SPEED_3_FAST').asInteger) +
blip_totSecs(dataSet.FieldByName('QUOTE_4_MM').asInteger - dataSet.FieldByName('QUOTE_3_MM').asInteger,
dataSet.FieldByName('QUOTE_4_OP_MM').asInteger - dataSet.FieldByName('QUOTE_3_OP_MM').asInteger,
dataSet.FieldByName('SPEED_4_FAST').asInteger) +
blip_totSecs(k_topLevel_mm - dataSet.FieldByName('QUOTE_4_MM').asInteger, 0,
dataSet.FieldByName('SPEED_5_FAST').asInteger)
);
end;
procedure TdmPickupDropRins.fdtPickupTypesNewRecord(DataSet: TDataSet);
begin inc(lastPickupID);
with Dataset do begin
FieldByName('ID').AsInteger := lastPickupID;
FieldByName('SPEED_1_FAST').AsInteger := 1; // true by default
FieldByName('SPEED_2_FAST').AsInteger := 1; // true by default
FieldByName('SPEED_3_FAST').AsInteger := 1; // true by default
FieldByName('SPEED_4_FAST').AsInteger := 1; // true by default
FieldByName('SPEED_5_FAST').AsInteger := 1; // true by default
end;
end;
procedure TdmPickupDropRins.fdtRinsingTypesAfterOpen(DataSet: TDataSet);
begin with Dataset do begin
last; lastRinsingID := fieldByName('ID').AsInteger;
end end;
procedure TdmPickupDropRins.fdtRinsingTypesBeforePost(DataSet: TDataSet);
var s: string;
begin
s := '';
// checking maximum inclination
if blip_maxIncl(dataSet.FieldByName('QUOTE_2_MM').asInteger, dataSet.FieldByName('QUOTE_2_OP_MM').asInteger) then
s := s + 'level 1 inclination exceeded' + #13;
if blip_maxIncl(dataSet.FieldByName('QUOTE_3_MM').asInteger, dataSet.FieldByName('QUOTE_3_OP_MM').asInteger) then
s := s + 'level 2 inclination exceeded' + #13;
if blip_maxIncl(dataSet.FieldByName('QUOTE_4_MM').asInteger, dataSet.FieldByName('QUOTE_4_OP_MM').asInteger) then
s := s + 'level 3 inclination exceeded' + #13;
// checking against top level / sequence
if blip_maxLevel(dataSet.FieldByName('QUOTE_3_MM').asInteger, k_topLevel_mm) then
s := s + 'level 3 too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_3_OP_MM').asInteger, k_topLevel_mm) then
s := s + 'level 3 operator side too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_2_MM').asInteger, dataSet.FieldByName('QUOTE_3_MM').asInteger) then
s := s + 'level 2 too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_2_OP_MM').asInteger, dataSet.FieldByName('QUOTE_3_OP_MM').asInteger) then
s := s + 'level 2 operator side too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_4_MM').asInteger, dataSet.FieldByName('QUOTE_3_MM').asInteger) then
s := s + 'level 4 too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_4_OP_MM').asInteger, dataSet.FieldByName('QUOTE_3_OP_MM').asInteger) then
s := s + 'level 4 operator side too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_1_MM').asInteger, dataSet.FieldByName('QUOTE_2_MM').asInteger) then
s := s + 'level 1 too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_1_MM').asInteger, dataSet.FieldByName('QUOTE_2_OP_MM').asInteger) then
s := s + 'level 1 operator side too high' + #13;
if blip_maxLevel(dataSet.FieldByName('QUOTE_1_MM').asInteger, dataSet.FieldByName('QUOTE_2_MM').asInteger) then
s := s + 'level "out of tank" too high' + #13;
if blip_maxLevel(k_RinsingDownLevel, dataSet.FieldByName('QUOTE_1_MM').asInteger) then
s := s + 'level "out of tank" too low' + #13;
if s <> '' then begin
showMessage(s); abort
end;
// calculating total time
dataSet.FieldByName('TOTAL_SECS').AsInteger := trunc(
dataSet.FieldByName('PAUSE_1_SECS').asInteger +
dataSet.FieldByName('PAUSE_2_SECS').asInteger +
dataSet.FieldByName('PAUSE_3_SECS').asInteger +
dataSet.FieldByName('PAUSE_4_SECS').asInteger +
blip_totSecs(dataSet.FieldByName('QUOTE_1_MM').asInteger - k_RinsingDownLevel, 0,
dataSet.FieldByName('SPEED_1_FAST').asInteger) +
blip_totSecs(dataSet.FieldByName('QUOTE_2_MM').asInteger - dataSet.FieldByName('QUOTE_1_MM').asInteger,
dataSet.FieldByName('QUOTE_2_OP_MM').asInteger - dataSet.FieldByName('QUOTE_1_MM').asInteger,
dataSet.FieldByName('SPEED_2_FAST').asInteger) +
blip_totSecs(dataSet.FieldByName('QUOTE_3_MM').asInteger - dataSet.FieldByName('QUOTE_2_MM').asInteger,
dataSet.FieldByName('QUOTE_3_OP_MM').asInteger - dataSet.FieldByName('QUOTE_2_OP_MM').asInteger,
dataSet.FieldByName('SPEED_3_FAST').asInteger) +
blip_totSecs(dataSet.FieldByName('QUOTE_3_MM').asInteger - dataSet.FieldByName('QUOTE_4_MM').asInteger,
dataSet.FieldByName('QUOTE_3_OP_MM').asInteger - dataSet.FieldByName('QUOTE_4_OP_MM').asInteger,
dataSet.FieldByName('SPEED_4_FAST').asInteger) +
blip_totSecs(dataSet.FieldByName('QUOTE_4_MM').asInteger - k_RinsingDownLevel, 0,
dataSet.FieldByName('SPEED_5_FAST').asInteger)
);
end;
procedure TdmPickupDropRins.fdtRinsingTypesNewRecord(DataSet: TDataSet);
begin inc(lastRinsingID);
with Dataset do begin
FieldByName('ID').AsInteger := lastRinsingID;
FieldByName('SPEED_1_FAST').AsInteger := 1; // true by default
FieldByName('SPEED_2_FAST').AsInteger := 1; // true by default
FieldByName('SPEED_3_FAST').AsInteger := 1; // true by default
FieldByName('SPEED_4_FAST').AsInteger := 1; // true by default
FieldByName('SPEED_5_FAST').AsInteger := 1; // true by default
end;
end;
procedure TdmPickupDropRins.openTypes;
begin
fdtDropTypes .Active := true;
fdtPickupTypes .Active := true;
fdtRinsingTypes.Active := true;
end;
procedure TdmPickupDropRins.duplicateDropType(pOldID, pNewID: integer);
begin
duplicateSomethingType('DROPTYPES', fdtDropTypes, pOldID, pNewID);
end;
procedure TdmPickupDropRins.duplicatePickupType(pOldID, pNewID: integer);
begin
duplicateSomethingType('PICKUPTYPES', fdtPickupTypes, pOldID, pNewID);
end;
procedure TdmPickupDropRins.duplicateRinsingType(pOldID, pNewID: integer);
begin
duplicateSomethingType('RINSINGTYPES', fdtRinsingTypes, pOldID, pNewID);
end;
procedure TdmPickupDropRins.duplicateSomethingType(pTblName: string; pTbl: TFDDataSet; pOldID, pNewID: integer);
begin
with fdqRecipesUtil do
begin
close;
SQL.Text := format('select * from %s where ID = %d', [pTblName, pNewID]);
open;
if not EOF then
begin
showMessage(format('Duplicate pyckupType ERROR: new ID %d already exists', [pNewID])); exit
end;
close;
SQL.Text := format('select * from %s where ID = %d', [pTblName, pOldID]);
open;
if EOF then
begin
showMessage(format('Duplicate pyckupType ERROR: old ID %d not found', [pOldID])); exit
end;
end;
DuplicateRecords(true, fdqRecipesUtil, pTbl, 'ID', pNewID);
fdqRecipesUtil.Close
end;
function TdmPickupDropRins.DuplicateRecords(justOne: boolean; cdsFrom, cdsTo: TFDDataSet; skipField: string; useValue: variant): integer;
var i, k: integer; fldFrom, fldTo: TField;
function getFieldNamed(pFldName: string): integer;
var j: integer;
begin
result := -1; // not found
for j := 0 to cdsFrom.fieldDefs.count - 1 do begin
if compareText(cdsFrom.fieldDefs[j].Name, pFldName) = 0 then begin
result := j; exit
end;
end;
end;
procedure chkOrderRowId(sFld: string);
begin
if (compareText(sFld, 'ORDER_ID') = 0) or (compareText(sFld, 'ORDER_ROW') = 0) then begin
if trim(cdsFrom.FieldByName(sFld).AsString) = '' then begin
cdsTo.FieldByName(sFld).AsString := '-'
end;
end;
end;
begin
result := 0;
if cdsFrom.EOF then exit;
repeat
cdsTo.edit;
cdsTo.insert;
for i := 0 to cdsTo.fieldDefs.count - 1 do begin
if compareText(cdsTo.fieldDefs[i].name, skipField) = 0 then begin
cdsTo.fields[i].value := useValue;
end else begin
if (i < cdsFrom.fieldDefs.count) and (compareText(cdsTo.fieldDefs[i].name, cdsFrom.fieldDefs[i].name) = 0) then begin
k := i;
end else k := getFieldNamed(cdsTo.fieldDefs[i].Name);
if k >= 0 then begin
cdsTo.fields[i].Assign(cdsFrom.fields[k]); // chissą se la differenza di lunghezza in MATERIAL_ID manda tutto in vacca
// qui posso avere il problema dei campi ORDER_ID e ORDER_ROW vuoti ... mettere trattino
chkOrderRowId(cdsTo.fieldDefs[i].Name);
end; // else raise exception.Create(format('Field not found: %s', [cdsTo.fieldDefs[i].name]));
end;
end;
cdsTo.post; Application.ProcessMessages;
if not justOne then cdsFrom.next;
result := result + 1;
until justOne or cdsFrom.EOF;
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, Menus;
type
{ TForm1 }
TForm1 = class(TForm)
MainMenu1: TMainMenu;
FileButton: TMenuItem;
ThemesButton: TMenuItem;
MenuItem11: TMenuItem;
MenuItem12: TMenuItem;
MenuItem13: TMenuItem;
HelpButton: TMenuItem;
AboutButton: TMenuItem;
HelpButtonForm2: TMenuItem;
OpenButton: TMenuItem;
CloseButton: TMenuItem;
ModesButton: TMenuItem;
WindiwButton: TMenuItem;
FullScreenButton: TMenuItem;
languagesButton: TMenuItem;
RussianButton: TMenuItem;
EnglishButton: TMenuItem;
procedure AboutButtonClick(Sender: TObject);
procedure CloseButtonClick(Sender: TObject);
procedure EnglishButtonClick(Sender: TObject);
procedure FileButtonClick(Sender: TObject);
procedure FullScreenButtonClick(Sender: TObject);
procedure HelpButtonForm2Click(Sender: TObject);
procedure MenuItem11Click(Sender: TObject);
procedure MenuItem12Click(Sender: TObject);
procedure MenuItem13Click(Sender: TObject);
procedure OpenButtonClick(Sender: TObject);
procedure RussianButtonClick(Sender: TObject);
procedure WindiwButtonClick(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
uses Unit2, Unit3;
procedure TForm1.FileButtonClick(Sender: TObject);
begin
end;
procedure TForm1.FullScreenButtonClick(Sender: TObject);
begin
end;
procedure TForm1.HelpButtonForm2Click(Sender: TObject);
begin
Form3.Show;
end;
procedure TForm1.MenuItem11Click(Sender: TObject);
begin
end;
procedure TForm1.MenuItem12Click(Sender: TObject);
begin
end;
procedure TForm1.MenuItem13Click(Sender: TObject);
begin
end;
procedure TForm1.AboutButtonClick(Sender: TObject);
begin
Form2.Show;
end;
procedure TForm1.CloseButtonClick(Sender: TObject);
begin
end;
procedure TForm1.EnglishButtonClick(Sender: TObject);
begin
end;
procedure TForm1.OpenButtonClick(Sender: TObject);
begin
end;
procedure TForm1.RussianButtonClick(Sender: TObject);
begin
end;
procedure TForm1.WindiwButtonClick(Sender: TObject);
begin
end;
end.
|
// -------------------------------------------------------
//
// This file was generated using Parse::Easy v1.0 alpha.
//
// https://github.com/MahdiSafsafi/Parse-Easy
//
// DO NOT EDIT !!! ANY CHANGE MADE HERE WILL BE LOST !!!
//
// -------------------------------------------------------
unit ExpressionLexer;
interface
uses System.SysUtils, WinApi.Windows,
Parse.Easy.Lexer.CustomLexer;
type TExpressionLexer = class(TCustomLexer)
protected
procedure UserAction(Index: Integer); override;
public
class constructor Create;
function GetTokenName(Index: Integer): string; override;
end;
const
EOF = 0000;
LPAREN = 0001;
RPAREN = 0002;
PLUS = 0003;
MINUS = 0004;
STAR = 0005;
SLASH = 0006;
PERCENT = 0007;
COMMA = 0008;
EQUAL = 0009;
SEMICOLON = 0010;
COS = 0011;
SIN = 0012;
TAN = 0013;
MIN = 0014;
MAX = 0015;
TK_VAR = 0016;
CLEAR = 0017;
ECHO = 0018;
SQ_STRING = 0019;
DQ_STRING = 0020;
DIGIT = 0021;
FLOAT = 0022;
HEX = 0023;
ID = 0024;
COMMENT = 0025;
WS = 0026;
SECTION_DEFAULT = 0000;
implementation
{$R ExpressionLexer.RES}
{ TExpressionLexer }
class constructor TExpressionLexer.Create;
begin
Deserialize('EXPRESSIONLEXER');
end;
procedure TExpressionLexer.UserAction(Index: Integer);
begin
case Index of
0000:
begin
skip
end;
0001:
begin
skip
end;
end;
end;
function TExpressionLexer.GetTokenName(Index: Integer): string;
begin
case Index of
0000 : exit('EOF' );
0001 : exit('LPAREN' );
0002 : exit('RPAREN' );
0003 : exit('PLUS' );
0004 : exit('MINUS' );
0005 : exit('STAR' );
0006 : exit('SLASH' );
0007 : exit('PERCENT' );
0008 : exit('COMMA' );
0009 : exit('EQUAL' );
0010 : exit('SEMICOLON');
0011 : exit('COS' );
0012 : exit('SIN' );
0013 : exit('TAN' );
0014 : exit('MIN' );
0015 : exit('MAX' );
0016 : exit('TK_VAR' );
0017 : exit('CLEAR' );
0018 : exit('ECHO' );
0019 : exit('SQ_STRING');
0020 : exit('DQ_STRING');
0021 : exit('DIGIT' );
0022 : exit('FLOAT' );
0023 : exit('HEX' );
0024 : exit('ID' );
0025 : exit('COMMENT' );
0026 : exit('WS' );
end;
Result := 'Unkown' + IntToStr(Index);
end;
end.
|
{/*!
Provides COM helper functions.
\modified 2019-07-02 11:19am
\author Wuping Xin
*/}
namespace TsmPluginFx.Core;
uses
rtl;
type
VARIANT_BOOL = public Int16;
const
VARIANT_TRUE = $FFFF;
VARIANT_FALSE = $0000;
type
EOleSysError = public class(Exception)
private
fErrorCode: HRESULT;
fHelpContext: Integer;
public
constructor(const aMessage: String; aErrorCode: HRESULT; aHelpContext: Integer);
begin
var lMsg := aMessage;
fHelpContext := aHelpContext;
fErrorCode := aErrorCode;
if String.IsNullOrEmpty(lMsg) then begin
lMsg := SysErrorMessage(aErrorCode);
if String.IsNullOrEmpty(lMsg) then
lMsg := String.Format('Ole error {0:X8}', [aErrorCode]);
end;
inherited(lMsg);
end;
public
property ErrorCode: HRESULT read fErrorCode write fErrorCode;
property HelpContext: Integer read fHelpContext;
end;
method CreateComObject(const aClassID: String): IUnknown;
begin
var IID_IUnknown: GUID := guidOf(IUnknown);
var CLSID: GUID := new RemObjects.Elements.System.Guid(aClassID);
OleCheck(CoCreateInstance(
@CLSID,
nil,
DWORD(CLSCTX.CLSCTX_INPROC_SERVER or CLSCTX.CLSCTX_LOCAL_SERVER),
@IID_IUnknown,
(^LPVOID)(@result)));
end;
method OleError(aErrorCode: HRESULT);
begin
raise new EOleSysError(nil, aErrorCode, 0);
end;
method OleCheck(aHRESULT: HRESULT);
begin
if not Succeeded(aHRESULT) then
OleError(aHRESULT);
end;
method SysErrorMessage(aErrorCode: Cardinal; aModuleHandle: HLOCAL := 0): String;
begin
var lpBuffer: LPWSTR;
var lFlags: DWORD := FORMAT_MESSAGE_FROM_SYSTEM or FORMAT_MESSAGE_IGNORE_INSERTS or
FORMAT_MESSAGE_ARGUMENT_ARRAY or FORMAT_MESSAGE_ALLOCATE_BUFFER;
if aModuleHandle <> nil then
lFlags := lFlags or FORMAT_MESSAGE_FROM_HMODULE;
try
var lLen: DWORD := FormatMessage(
lFlags,
aModuleHandle,
aErrorCode,
0,
(LPWSTR)(@lpBuffer),
0,
nil);
while (lLen > 0) and ((lpBuffer[lLen - 1] <= #32) or (lpBuffer[lLen - 1] = '.')) do
dec(lLen);
result := String.FromPChar(lpBuffer, lLen);
finally
LocalFree(HLOCAL(lpBuffer^));
end;
end;
method Succeeded(aHRESULT: HRESULT): Boolean;
begin
result := aHRESULT and $80000000 = 0;
end;
method Failed(aHRESULT: HRESULT): Boolean;
begin
result := aHRESULT and $80000000 <> 0;
end;
method ResultCode(aHRESULT: HRESULT): Integer;
begin
result := aHRESULT and $0000FFFF;
end;
method ResultFacility(aHRESULT: HRESULT): Integer;
begin
result := (aHRESULT shr 16) and $00001FFF;
end;
method ResultSeverity(aHRESULT: HRESULT): Integer;
begin
result := aHRESULT shr 31;
end;
method MakeResult(aSeverity, aFacility, aCode: Integer): HRESULT;
begin
result := (aSeverity shl 31) or (aFacility shl 16) or aCode;
end;
method InterfaceConnect(const aSource: IUnknown; var IID: GUID; const aSink: IUnknown; var aConnection: DWORD);
begin
var lCP: IConnectionPoint;
var lCPC: IConnectionPointContainer := aSource as IConnectionPointContainer;
if Succeeded(lCPC.FindConnectionPoint(@IID, @lCP)) then
lCP.Advise(aSink, @aConnection);
end;
method InterfaceDisconnect(const aSource: IUnknown; var IID: GUID; aConnection: DWORD);
begin
var lCP: IConnectionPoint;
var lCPC: IConnectionPointContainer := aSource as IConnectionPointContainer;
if Succeeded(lCPC.FindConnectionPoint(@IID, (^IConnectionPoint)(@lCP))) then
lCP.Unadvise(aConnection);
end;
method StringToLPWSTR(aSource: not nullable String; aDestination: LPWSTR; aSize: DWORD): DWORD;
begin
if not assigned(aDestination) then exit (aSource.Length + 1);
var lChars: array of Char := aSource.ToCharArray;
var lSize: DWORD := Math.Min(aSize, aSource.Length + 1);
aDestination[lSize] := #0;
memcpy(aDestination, lChars, sizeOf(Char) * (lSize - 1));
exit lSize;
end;
end. |
unit CreateLogFile;
interface
uses
Classes, SysUtils, Math, StdCtrls,
Forms, Definitions;
Procedure SaveLogFile(UseCustomFilePath : Boolean;
CreateFileOnNotExist : Boolean);
Function GetComboBoxValue(Component : TComponent) : String;
Function GetListBoxValue(Component : TComponent) : TStringList;
Function GetEditValue(Component : TComponent) : String;
Function GetAutoRunValue : Boolean;
Function GetProgramStatus(var bRunStatus : Boolean) : Boolean;
Function GetCustomLogFilePath : String;
implementation
{$J+}
{===============================================================================
CHG12092013(MPT):Create portable log file unit
===============================================================================}
Procedure SaveLogFile(UseCustomFilePath : Boolean;
CreateFileOnNotExist : Boolean);
var
sDefaultLogFilePath, sCustomLogFilePath,
sLogFilePath, sDateTime : String;
_FileExists : Boolean;
tfLogFile : TextFile;
begin
sDefaultLogFilePath := GetCurrentDir + ExtractFileName(Application.ExeName) + '.log';
sCustomLogFilePath := GetCustomLogFilePath;
If UseCustomFilePath
then sLogFilePath := sDefaultLogFilePath
else sLogFilePath := sCustomLogFilePath;
_FileExists := FileExists(sLogFilePath);
If (_FileExists or
((not _FileExists) and
CreateFileOnNotExist))
then
begin
sDateTime := FormatDateTime(DateFormat, Date) + FormatDateTime(TimeFormat, Now);
AssignFile(tfLogFile, sLogFilePath);
Append(tfLogFile);
Write(sLineBreak + sDateTime);
end;
end;
{==============================================================================}
Function GetComboBoxValue(Component : TComponent) : String;
var
sComponentValue : String;
begin
sComponentValue := TComboBox(Component).Text;
Result := sComponentValue;
end;
{==============================================================================}
Function GetListBoxValue(Component : TComponent) : TStringList;
var
sComponentValue : String;
slSelectedValues : TStringList;
I : Integer;
begin
slSelectedValues := TStringList.Create;
For I:=0 to TListBox(Component).Items.Count do
begin
If TListBox(Component).Selected[I]
then
begin
sComponentValue := TListBox(Component).Items[I];
slSelectedValues.Append(sComponentValue);
end;
end;
Result := slSelectedValues;
end;
{==============================================================================}
Function GetEditValue(Component : TComponent) : String;
var
ComponentValue : String;
begin
ComponentValue := TEdit(Component).Text;
Result := ComponentValue;
end;
{==============================================================================}
Function GetAutoRunValue : Boolean;
var
sCurrentParam : String;
bAutoRun : Boolean;
I : Integer;
begin
bAutoRun := False;
For I:=0 to ParamCount do
begin
sCurrentParam := Uppercase(ParamStr(I));
If (sCurrentParam = 'AUTORUN')
then bAutoRun := True;
end;
Result := bAutoRun;
end;
{==========================================================}
Function GetProgramStatus(var bRunStatus : Boolean) : Boolean;
var
bRunYet : Boolean;
begin
bRunYet := bRunStatus;
If bRunStatus
then bRunYet := True;
Result := bRunYet;
end;
{==========================================================}
Function GetCustomLogFilePath : String;
var
sCustomLogFilePath, sParameterString : String;
I : Integer;
begin
For I:=0 to ParamCount do
begin
sParameterString := Uppercase(ParamStr(I));
If(Pos('LOGGING', sParameterString) > 0)
then
begin
Delete(sParameterString, 1, 8);
If not (Pos('.log', sParameterString) > 0)
then sCustomLogFilePath := sParameterString + ExtractFileName(Application.ExeName) + '.log'
else sCustomLogFilePath := sParameterString;
end;
end;
Result := sCustomLogFilepath;
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
A shader that passes control of the DoApply and DoUnApply
methods through published events. This component is
designed to make it a little easier to implement a
customized shader. Be sure to keep the shader balanced
by returning the OpenGL state to how you found it.
}
unit VXS.UserShader;
interface
uses
System.Classes,
VXS.Material, VXS.RenderContextInfo;
type
TOnDoApplyEvent = procedure (Sender : TObject; var rci : TVXRenderContextInfo) of Object;
TOnDoUnApplyEvent = procedure (Sender : TObject; Pass:Integer; var rci : TVXRenderContextInfo; var Continue : Boolean) of Object;
TVXUserShader = class(TVXShader)
private
FPass : Integer;
FOnDoApply : TOnDoApplyEvent;
FOnDoUnApply : TOnDoUnApplyEvent;
protected
procedure DoApply(var rci : TVXRenderContextInfo; Sender : TObject); override;
function DoUnApply(var rci : TVXRenderContextInfo) : Boolean; override;
published
property OnDoApply : TOnDoApplyEvent read FOnDoApply write FOnDoApply;
property OnDoUnApply : TOnDoUnApplyEvent read FOnDoUnApply write FOnDoUnApply;
property ShaderStyle;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------
// ------------------ TVXUserShader ------------------
// ------------------
// DoApply
//
procedure TVXUserShader.DoApply(var rci: TVXRenderContextInfo; Sender : TObject);
begin
FPass:=1;
if Assigned(FOnDoApply) and (not (csDesigning in ComponentState)) then
FOnDoApply(Self,rci);
end;
// DoUnApply
//
function TVXUserShader.DoUnApply(var rci: TVXRenderContextInfo): Boolean;
begin
Result:=False;
if Assigned(FOnDoUnApply) and (not (csDesigning in ComponentState)) then begin
FOnDoUnApply(Self,FPass,rci,Result);
Inc(FPass);
end;
end;
end.
|
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ExtCtrls, sButton, sLabel, sEdit,
sCheckBox, sListBox;
type
TFilterForm = class(TForm)
Open: TTimer;
FilterList: TsListBox;
FilterName: TsEdit;
sLabel1: TsLabel;
sLabel2: TsLabel;
sLabel3: TsLabel;
SaveFilter: TsButton;
AddFilter: TsButton;
DeleteFilter: TsButton;
FilterEnabled: TsCheckBox;
sLabel4: TsLabel;
sLabel5: TsLabel;
FilterOriginal: TsEdit;
FilterReplacement: TsEdit;
procedure AddFilterClick(Sender: TObject);
procedure OpenTimer(Sender: TObject);
procedure FormHide(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure DeleteFilterClick(Sender: TObject);
procedure SaveFilterClick(Sender: TObject);
procedure FilterListClick(Sender: TObject);
procedure loadFLTClick(Sender: TObject);
procedure saveFLTClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FilterForm: TFilterForm;
iFilterName, iFilterEnabled, iFilterOriginal, iFilterReplacement, iFilterType: TStringList;
implementation
{$R *.dfm}
procedure TFilterForm.AddFilterClick(Sender: TObject);
begin
FilterList.Items.Add('New Filter');
iFilterName.Add('New Filter');
iFilterEnabled.Add('false');
iFilterOriginal.Add('');
iFilterReplacement.Add('');
iFilterType.Add('received');
end;
procedure TFilterForm.OpenTimer(Sender: TObject);
var
i: Integer;
begin
i := FilterForm.AlphaBlendValue;
if i < 230 then begin
i := i + 5;
FilterForm.AlphaBlendValue := i;
end else begin
Open.Enabled := false;
end;
end;
procedure TFilterForm.FormHide(Sender: TObject);
begin
FilterForm.AlphaBlendValue := 0;
end;
procedure TFilterForm.FormShow(Sender: TObject);
begin
Open.Enabled := true;
end;
procedure TFilterForm.FormCreate(Sender: TObject);
begin
iFilterName := TStringList.Create();
iFilterEnabled := TStringList.Create();
iFilterOriginal := TStringList.Create();
iFilterReplacement := TStringList.Create();
iFilterType := TStringList.Create();
end;
procedure TFilterForm.DeleteFilterClick(Sender: TObject);
var
index: Integer;
begin
index := FilterList.ItemIndex;
FilterList.Items.Delete(index);
iFilterName.Delete(index);
iFilterEnabled.Delete(index);
iFilterOriginal.Delete(index);
iFilterReplacement.Delete(index);
end;
procedure TFilterForm.SaveFilterClick(Sender: TObject);
var
index: Integer;
begin
index := FilterList.ItemIndex;
if(index <> -1) then begin
iFilterName.Strings[index] := FilterName.Text;
if FilterEnabled.Checked then iFilterEnabled.Strings[index] := 'true' else iFilterEnabled.Strings[index] := 'true';
iFilterOriginal.Strings[index] := FilterOriginal.Text;
iFilterReplacement.Strings[index] := FilterReplacement.Text;
FilterList.Items.Strings[index] := FilterName.Text;
end else begin
ShowMessage('You need to select a filter if you want to edit it!');
end;
end;
procedure TFilterForm.FilterListClick(Sender: TObject);
var
index: Integer;
begin
index := FilterList.ItemIndex;
FilterName.Text := iFilterName.Strings[index];
if iFilterEnabled.Strings[index] = 'true' then FilterEnabled.Checked := true else FilterEnabled.Checked := false;
FilterOriginal.Text := iFilterOriginal.Strings[index];
FilterReplacement.Text := iFilterReplacement.Strings[index];
end;
procedure TFilterForm.loadFLTClick(Sender: TObject);
begin
ShowMessage('This list will be completed until the stable version(1.0)!');
end;
procedure TFilterForm.saveFLTClick(Sender: TObject);
begin
ShowMessage('This list will be completed until the stable version(1.0)!');
end;
end.
|
unit TestUUsuarioController;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, UUsuarioController, DBXJSON, UPessoasController, ConexaoBD,
Generics.Collections, UController, Classes, SysUtils, DBClient, UPessoasVo, UUsuarioVO,
DB, DBXCommon, SQLExpr;
type
// Test methods for class TUsuarioController
TestTUsuarioController = class(TTestCase)
strict private
FUsuarioController: TUsuarioController;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestConsultarPorId;
procedure TestConsultaPorIdNaoEncontrado;
end;
implementation
procedure TestTUsuarioController.SetUp;
begin
FUsuarioController := TUsuarioController.Create;
end;
procedure TestTUsuarioController.TearDown;
begin
FUsuarioController.Free;
FUsuarioController := nil;
end;
procedure TestTUsuarioController.TestConsultaPorIdNaoEncontrado;
var
ReturnValue: TUsuarioVO;
begin
ReturnValue := FUsuarioController.ConsultarPorId(100);
if(returnvalue <> nil) then
check(false,'Contador pesquisado com sucesso!')
else
check(true,'Contador nao encontrado!');
end;
procedure TestTUsuarioController.TestConsultarPorId;
var
ReturnValue: TUsuarioVO;
begin
ReturnValue := FUsuarioController.ConsultarPorId(1);
if(returnvalue <> nil) then
check(true,'Contador pesquisado com sucesso!')
else
check(true,'Contador nao encontrado!');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTUsuarioController.Suite);
end.
|
unit MainLib;
interface
uses
Windows, SysUtils, Classes, Controls, Forms,StdCtrls, ComCtrls, ExtCtrls,Tools,Graphics,Dialogs,
TooltipUtil,PerlRegEx,Messages,ShellAPi;
type
TMainForm = class(TForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
LogMemo: TMemo;
GroupBox1: TGroupBox;
ServerColor: TShape;
ServerState: TLabel;
btnStopStart: TButton;
btnClearLog: TButton;
btnInstallUnInstall: TButton;
TabSheet2: TTabSheet;
SQLBox: TScrollBox;
GroupBox2: TGroupBox;
Label1: TLabel;
cbbTaskNames: TComboBox;
btnLoad: TButton;
btnSave: TButton;
btnDelTask: TButton;
lbledtReadTime: TLabeledEdit;
btnAddSql: TButton;
TabSheet3: TTabSheet;
TabSheet4: TTabSheet;
Memo1: TMemo;
lbledtServer: TLabeledEdit;
cbbDataName: TComboBox;
Label2: TLabel;
lbledtPort: TLabeledEdit;
lbledtUserName: TLabeledEdit;
lbledtPassWord: TLabeledEdit;
cbbDataType: TComboBox;
Label3: TLabel;
btnLoadData: TButton;
btnSaveData: TButton;
btnData: TButton;
lbledtDataBase: TLabeledEdit;
tltpA: TToolTip;
Timer: TTimer;
Button1: TButton;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
procedure FormCreate(Sender: TObject);
procedure btnClearLogClick(Sender: TObject);
procedure btnAddSqlClick(Sender: TObject);
procedure Panel1Click(Sender: TObject);
procedure btnLoadDataClick(Sender: TObject);
procedure btnSaveDataClick(Sender: TObject);
procedure btnDataClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnLoadClick(Sender: TObject);
procedure btnDelTaskClick(Sender: TObject);
procedure cbbDataTypeChange(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure btnInstallUnInstallClick(Sender: TObject);
procedure btnStopStartClick(Sender: TObject);
procedure btnAccessPjClick(Sender: TObject);
procedure cbbTaskNamesChange(Sender: TObject);
procedure cbbDataNameChange(Sender: TObject);
private
{ Private declarations }
procedure btnDelClick(Sender: TObject);
public
{ Public declarations }
procedure LoadLogs;
procedure ReadLogs;
procedure InitServiceState;
function checkSqlTyep(sql:string):Boolean;//true,sql语句执行上一步中查询记录数次,false,执行1次
end;
var
MainForm: TMainForm;
ComputName:string; //计算机名
LinesCount :Integer; //读取到最新日志文件的第几行了.
HasReaded : Boolean;
implementation
{$R *.dfm}
procedure TMainForm.InitServiceState;
var
install,IsRunning : Boolean;
begin
if ComputName = '' then
ComputName := Tools.ComputerName;
install := Tools.ServiceInstalled(ComputName,'shService');
if not install then
begin
ServerColor.Brush.Color := clRed;
ServerState.Caption := '四和数据采集服务尚未安装!';
btnStopStart.Enabled := False;
btnInstallUnInstall.Enabled := True;
end
else
begin
IsRunning := Tools.ServiceRunning(ComputName,'shService');
if IsRunning then
begin
ServerColor.Brush.Color := clGreen;
ServerState.Caption := '四和数据采集服务运行中...';
btnStopStart.Enabled := True;
btnStopStart.Caption := '停止服务';
btnInstallUnInstall.Enabled := True;
btnInstallUnInstall.Caption := '卸载服务';
end
else
begin
ServerColor.Brush.Color := clPurple;
ServerState.Caption := '四和数据采集服务已停止!';
btnStopStart.Enabled := True;
btnStopStart.Caption := '启动服务';
btnInstallUnInstall.Enabled := True;
btnInstallUnInstall.Caption := '卸载服务'
end;
end;
end;
procedure TMainForm.btnDataClick(Sender: TObject);
begin
if cbbDataName.Items.IndexOf(cbbDataName.Text) > -1 then
begin
if Application.MessageBox('确定删除?删除后无法恢复!',
PChar(Application.Title), MB_OKCANCEL + MB_ICONQUESTION) = IDOK then
begin
DeleteFile(ExtractFileDir(PARAMSTR(0)) +'\data\' + cbbDataName.Text);
cbbDataName.Items.Delete(cbbDataName.Items.IndexOf(cbbDataName.Text));
cbbDataName.Text := '';
cbbDataType.Text := '';
lbledtServer.Text := '';
lbledtPort.Text := '';
lbledtUserName.Text := '';
lbledtPassWord.Text := '';
end;
end;
end;
procedure TMainForm.btnDelClick(Sender: TObject);
var
I,Count : Integer;
begin
(Sender as TButton).Parent.Parent.Free;
Count := SQLBox.ControlCount;
for I := 0 to Count - 1 do
begin
(SQLBox.Controls[I] as TSql).Top := I * 125 + 5;
(SQLBox.Controls[I] as TSql).bLable.Caption := '第 ' + InttoStr(I+1) + ' 步 ';
end;
end;
procedure TMainForm.btnDelTaskClick(Sender: TObject);
var
Count,I:Integer;
begin
if cbbTaskNames.Items.IndexOf(cbbTaskNames.Text) > -1 then
begin
if Application.MessageBox('确定删除?删除后无法恢复!',
PChar(Application.Title), MB_OKCANCEL + MB_ICONQUESTION) = IDOK then
begin
DeleteFile(ExtractFileDir(PARAMSTR(0)) +'\task\' + cbbTaskNames.Text);
cbbTaskNames.Items.Delete(cbbTaskNames.Items.IndexOf(cbbTaskNames.Text));
cbbTaskNames.Text := '';
lbledtReadTime.Text := '';
Count := SQLBox.ControlCount;
for I := 0 to Count - 1 do
begin
SQLBox.Controls[0].Free;
end;
end;
end;
end;
procedure TMainForm.btnInstallUnInstallClick(Sender: TObject);
begin
if btnInstallUnInstall.Caption = '安装服务' then
begin
Tools.RunDOS('AccessService.exe /install');
btnInstallUnInstall.Caption := '卸载服务';
end
else
begin
Tools.RunDOS('sc delete shService');
btnInstallUnInstall.Caption := '安装服务';
end;
InitServiceState;
end;
procedure TMainForm.btnLoadClick(Sender: TObject);
var
task : TTask;
I,Count:Integer;
Sql : TSql;
begin
if cbbTaskNames.Items.IndexOf(cbbTaskNames.Text) > -1 then
begin
Count := SQLBox.ControlCount;
for I := 0 to Count - 1 do
begin
SQLBox.Controls[0].Free;
end;
task := Tools.getTask(cbbTaskNames.Text);
lbledtReadTime.Text := InttoStr(task.time);
Count := task.sql.Count;
for I := 0 to Count - 1 do
begin
Sql := TSql.Create(Application,cbbDataName.Items,SQLBox);
Sql.btnDel.OnClick := btnDelClick;
Sql.SQL.Text := task.sql[I];
Sql.bLable.Caption := '第 ' + InttoStr(I+1) + ' 步 ';
Sql.DataSource.ItemIndex := Sql.DataSource.Items.IndexOf(task.data[I]);
end;
end;
end;
function TMainForm.checkSqlTyep(sql:string):Boolean;//true,sql语句执行上一步中查询记录数次,false,执行1次
var
RegEx : TPerlRegEx;
begin
RegEx := TPerlRegEx.Create(Application);
RegEx.RegEx := '.+:\w+';
RegEx.Subject := sql;
Result := RegEx.Match;
RegEx.Free;
end;
procedure TMainForm.btnLoadDataClick(Sender: TObject);
var
data : TDataSource;
begin
if cbbDataName.Items.IndexOf(cbbDataName.Text) > -1 then
begin
data := Tools.getData(cbbDataName.Text);
cbbDataType.ItemIndex := cbbDataType.Items.IndexOf(data.DataType);
lbledtServer.Text := data.Server;
lbledtPort.Text := data.Port;
lbledtUserName.Text := data.UserName;
lbledtPassWord.Text := data.PassWord;
lbledtDataBase.Text := data.DataBase;
data.Free;
if cbbDataType.Text = 'MySql' then
begin
lbledtServer.Enabled := True;
lbledtPort.Enabled := True;
lbledtDataBase.Enabled := True;
lbledtUserName.Enabled := True;
lbledtPassWord.Enabled := True;
end
else if cbbDataType.Text = 'Oracle' then
begin
lbledtServer.Enabled := True;
lbledtPort.Enabled := True;
lbledtDataBase.Enabled := False;
lbledtUserName.Enabled := True;
lbledtPassWord.Enabled := True;
end
else if cbbDataType.Text = 'Access' then
begin
lbledtServer.Enabled := True;
lbledtPort.Enabled := False;
lbledtDataBase.Enabled := True;
lbledtUserName.Enabled := False;
lbledtPassWord.Enabled := True;
end
else if cbbDataType.Text = 'SQLite' then
begin
lbledtServer.Enabled := True;
lbledtPort.Enabled := False;
lbledtDataBase.Enabled := True;
lbledtUserName.Enabled := False;
lbledtPassWord.Enabled := True;
end
end;
end;
procedure TMainForm.btnSaveClick(Sender: TObject);
var
task : TTask;
I,Count:LongInt;
SQL:TSql;
begin
if cbbTaskNames.Text = '' then
begin
tltpA.Popup(cbbTaskNames.Handle,ttInformationIcon,'警告','请输入任务名称');
Exit;
end;
if lbledtReadTime.Text = '' then
begin
tltpA.Popup(lbledtReadTime.Handle,ttInformationIcon,'警告','请输入执行周期');
Exit;
end;
if not TryStrToInt(lbledtReadTime.Text,I) then
begin
tltpA.Popup(lbledtReadTime.Handle,ttInformationIcon,'警告','执行周期必须是数字');
Exit;
end;
if SQLBox.ControlCount = 0 then
begin
tltpA.Popup(SQLBox.Handle,ttInformationIcon,'警告','至少要有一步!');
Exit;
end;
if checkSqlTyep((SQLBox.Controls[0] as TSql).SQL.Text) then
begin
tltpA.Popup((SQLBox.Controls[0] as TSql).SQL.Handle,ttInformationIcon,'警告','第一步中不能有 :参数 格式的参数!');
Exit;
end;
////验证第一步中不能有:参数
task := TTask.Create(Application);
task.name := cbbTaskNames.Text;
task.time := StrToInt(lbledtReadTime.Text);
Count := SQLBox.ControlCount;
for I := 0 to Count - 1 do
begin
SQL := Sqlbox.Controls[I] as TSql;
if (SQL.SQL.Text <> '') and (SQL.DataSource.Text <> '')then
begin
task.addSql(SQL);
end;
end;
Tools.saveTask(task);
if cbbTaskNames.Items.IndexOf(cbbTaskNames.Text) = -1 then
cbbTaskNames.Items.Add(cbbTaskNames.Text);
end;
procedure TMainForm.btnSaveDataClick(Sender: TObject);
var
data : TDataSource;
begin
if cbbDataName.Text = '' then
begin
tltpA.Popup(cbbDataName.Handle,ttInformationIcon,'警告','请输入数据源名');
Exit;
end;
if cbbDataType.Text = '' then
begin
tltpA.Popup(cbbDataType.Handle,ttInformationIcon,'警告','请选择数据源类型');
Exit;
end;
if lbledtServer.Enabled and (lbledtServer.Text = '') then
begin
tltpA.Popup(lbledtServer.Handle,ttInformationIcon,'警告','请选择服务器地址');
Exit;
end;
if lbledtUserName.Enabled and (lbledtUserName.Text = '') then
begin
tltpA.Popup(lbledtUserName.Handle,ttInformationIcon,'警告','请输入用户名');
Exit;
end;
if cbbDataName.Items.IndexOf(cbbDataName.Text) = -1 then
cbbDataName.Items.Add(cbbDataName.Text);
data := TDataSource.Create(Application);
data.DataName := cbbDataName.Text;
data.DataType := cbbDataType.Text;
data.Server := lbledtServer.Text;
data.Port := lbledtPort.Text;
data.UserName := lbledtUserName.Text;
data.DataBase := lbledtDataBase.Text;
data.PassWord := lbledtPassWord.Text;
Tools.saveData(data);
end;
procedure TMainForm.btnStopStartClick(Sender: TObject);
begin
if btnStopStart.Caption = '启动服务' then
begin
Tools.RunDOS('net start shService');
btnStopStart.Caption := '停止服务';
end
else
begin
Tools.RunDOS('net stop shService');
btnStopStart.Caption := '启动服务';
end;
InitServiceState;
end;
procedure TMainForm.cbbDataNameChange(Sender: TObject);
begin
if cbbDataName.Items.IndexOf(cbbDataName.Text) > -1 then
btnLoadDataClick(nil);
end;
procedure TMainForm.cbbDataTypeChange(Sender: TObject);
begin
if cbbDataType.Text = 'MySql' then
begin
lbledtServer.Enabled := True;
lbledtServer.Text := '';
lbledtPort.Enabled := True;
lbledtPort.Text := '';
lbledtDataBase.Enabled := True;
lbledtDataBase.Text := '';
lbledtUserName.Enabled := True;
lbledtUserName.Text := '';
lbledtPassWord.Enabled := True;
lbledtPassWord.Text := '';
end
else if cbbDataType.Text = 'Oracle' then
begin
lbledtServer.Enabled := True;
lbledtServer.Text := '';
lbledtPort.Enabled := True;
lbledtPort.Text := '';
lbledtDataBase.Enabled := False;
lbledtDataBase.Text := '';
lbledtUserName.Enabled := True;
lbledtUserName.Text := '';
lbledtPassWord.Enabled := True;
lbledtPassWord.Text := '';
end
else if cbbDataType.Text = 'Access' then
begin
lbledtServer.Enabled := True;
lbledtServer.Text := '';
lbledtPort.Enabled := False;
lbledtPort.Text := '';
lbledtDataBase.Enabled := True;
lbledtDataBase.Text := '';
lbledtUserName.Enabled := False;
lbledtUserName.Text := '';
lbledtPassWord.Enabled := True;
lbledtPassWord.Text := '';
end
else if cbbDataType.Text = 'SQLite' then
begin
lbledtServer.Enabled := True;
lbledtServer.Text := '';
lbledtPort.Enabled := False;
lbledtPort.Text := '';
lbledtDataBase.Enabled := True;
lbledtDataBase.Text := '';
lbledtUserName.Enabled := False;
lbledtUserName.Text := '';
lbledtPassWord.Enabled := True;
lbledtPassWord.Text := '';
end
end;
procedure TMainForm.cbbTaskNamesChange(Sender: TObject);
begin
if cbbTaskNames.Items.IndexOf(cbbTaskNames.Text) > -1 then
btnLoadClick(nil);
end;
procedure TMainForm.btnAccessPjClick(Sender: TObject);
begin
ShellExecute(Handle, nil, pchar('AccessPj.exe'), nil, pchar(ExtractFileDir(PARAMSTR(0))), SW_SHOW);
end;
procedure TMainForm.btnAddSqlClick(Sender: TObject);
var
Sql : TSql;
begin
Sql := TSql.Create(Application,cbbDataName.Items,SQLBox);
Sql.btnDel.OnClick := btnDelClick;
Sql.bLable.Caption := '第 ' + IntToStr(SQLBox.ControlCount) + ' 步';
end;
procedure TMainForm.btnClearLogClick(Sender: TObject);
var
Dir:string;
FileName:TStrings;
I:Integer;
begin
Dir := ExtractFileDir(PARAMSTR(0)) + '\logs\';
FileName := Tools.getAllFilesFromDir(Dir,'*');
LogMemo.Lines.Clear;
for I := 0 to FileName.Count - 1 do
DeleteFile(Dir + FileName[I]);
LinesCount := -1;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
if not DirectoryExists(ExtractFileDir(PARAMSTR(0)) + '\logs') then CreateDirectory(PChar(ExtractFilePath(ParamStr(0)) + '\logs'), nil);
if not DirectoryExists(ExtractFileDir(PARAMSTR(0)) + '\task') then CreateDirectory(PChar(ExtractFilePath(ParamStr(0)) + '\task'), nil);
if not DirectoryExists(ExtractFileDir(PARAMSTR(0)) + '\data') then CreateDirectory(PChar(ExtractFilePath(ParamStr(0)) + '\data'), nil);
InitServiceState;
LinesCount := -1;
LoadLogs;
cbbDataName.Items := Tools.getAllFilesFromDir(ExtractFileDir(PARAMSTR(0)) + '\data\','*');
cbbTaskNames.Items := Tools.getAllFilesFromDir(ExtractFileDir(PARAMSTR(0)) + '\task\','*');
HasReaded := False;
end;
procedure TMainForm.LoadLogs;
var
FileName,Logs : TStrings;
I:Integer;
Dir:string;
begin
Dir := ExtractFileDir(PARAMSTR(0)) + '\logs\';
FileName := Tools.getAllFilesFromDir(Dir,'*');
Logs := TStringList.Create;
for I := 0 to FileName.Count - 1 do
begin
LogMemo.Lines.Add('==================' + FileName[I] + '==================');
Logs.LoadFromFile(Dir + FileName[I]);
LogMemo.Lines.AddStrings(Logs);
if FileName[I] = FormatDateTime('yyyy-mm-dd', now) then
begin
LinesCount := Logs.Count;
end;
end;
Logs.Free;
end;
procedure TMainForm.ReadLogs;
var
Logs : TStrings;
I:Integer;
begin
Logs := TStringList.Create;
if not FileExists(ExtractFileDir(PARAMSTR(0)) + '\logs\' + FormatDateTime('yyyy-mm-dd', now)) then
Exit;
Logs.LoadFromFile(ExtractFileDir(PARAMSTR(0)) + '\logs\' + FormatDateTime('yyyy-mm-dd', now));
if LinesCount = -1 then
begin
LogMemo.Lines.AddStrings(Logs);
LinesCount := Logs.Count;
end
else
begin
if LinesCount < Logs.Count then
begin
for I := LinesCount - 1 to Logs.Count - 1 do
begin
LogMemo.Lines.Add(Logs[I]);
end;
LinesCount := I;
end
else if LinesCount > Logs.Count then
begin
LogMemo.Lines.AddStrings(Logs);
LinesCount := Logs.Count;
HasReaded := True;
end;
end;
end;
procedure TMainForm.Panel1Click(Sender: TObject);
begin
(Sender as TPanel).BorderStyle := bsSingle;
end;
procedure TMainForm.TimerTimer(Sender: TObject);
begin
ReadLogs;
if HasReaded then
begin
LogMemo.Perform(EM_LINESCROLL, 0, LogMemo.Lines.Count);
HasReaded := False;
end;
end;
end.
|
(*
Copyright 2016, MARS-Curiosity library
Home: https://github.com/andrea-magni/MARS
*)
unit MARS.Core.Utils;
{$I MARS.inc}
interface
uses
SysUtils, Classes, RTTI, SyncObjs, Web.HttpApp, REST.JSON
, MARS.Core.JSON
;
type
TFormParamFile = record
FieldName: string;
FileName: string;
Bytes: TBytes;
ContentType: string;
procedure Clear;
constructor CreateFromRequest(const ARequest: TWebRequest; const AFieldName: string); overload;
constructor CreateFromRequest(const ARequest: TWebRequest; const AFileIndex: Integer); overload;
constructor Create(const AFieldName: string; const AFileName: string; const ABytes: TBytes; const AContentType: string);
function ToString: string;
end;
TFormParam = record
FieldName: string;
Value: TValue;
function IsFile: Boolean;
function AsFile: TFormParamFile;
procedure Clear;
constructor CreateFromRequest(const ARequest: TWebRequest; const AFieldName: string); overload;
constructor CreateFromRequest(const ARequest: TWebRequest; const AFileIndex: Integer); overload;
constructor Create(const AFieldName: string; const AValue: TValue);
constructor CreateFile(const AFieldName: string; const AFileName: string; const ABytes: TBytes = nil; const AContentType: string = '');
function ToString: string;
end;
TDump = class
public
class procedure Request(const ARequest: TWebRequest; const AFileName: string); overload; virtual;
end;
function CreateCompactGuidStr: string;
function ObjectToJSON(const AObject: TObject;
const AOptions: TJsonOptions = [joDateIsUTC, joDateFormatISO8601]): TJSONObject; deprecated 'use MARS.Core.JSON.TJSONObject.ObjectToJSON';
function BooleanToTJSON(AValue: Boolean): TJSONValue;
function SmartConcat(const AArgs: array of string; const ADelimiter: string = ',';
const AAvoidDuplicateDelimiter: Boolean = True; const ATrim: Boolean = True;
const ACaseInsensitive: Boolean = True): string;
function EnsurePrefix(const AString, APrefix: string; const AIgnoreCase: Boolean = True): string;
function EnsureSuffix(const AString, ASuffix: string; const AIgnoreCase: Boolean = True): string;
function StringArrayToString(const AArray: TArray<string>; const ADelimiter: string = ','): string;
function StreamToJSONValue(const AStream: TStream; const AEncoding: TEncoding = nil): TJSONValue;
procedure JSONValueToStream(const AValue: TJSONValue; const ADestStream: TStream; const AEncoding: TEncoding = nil);
function StreamToString(const AStream: TStream; const AEncoding: TEncoding = nil): string;
procedure StringToStream(const AStream: TStream; const AString: string; const AEncoding: TEncoding = nil);
procedure CopyStream(ASourceStream, ADestStream: TStream;
AOverWriteDest: Boolean = True; AThenResetDestPosition: Boolean = True);
{$ifndef DelphiXE6_UP}
function DateToISO8601(const ADate: TDateTime; AInputIsUTC: Boolean = False): string;
function ISO8601ToDate(const AISODate: string; AReturnUTC: Boolean = False): TDateTime;
{$endif}
function DateToJSON(const ADate: TDateTime; AInputIsUTC: Boolean = False): string;
function JSONToDate(const ADate: string; AReturnUTC: Boolean = False): TDateTime;
function IsMask(const AString: string): Boolean;
function MatchesMask(const AString, AMask: string): Boolean;
function GuessTValueFromString(const AString: string): TValue;
procedure ZipStream(const ASource: TStream; const ADest: TStream);
procedure UnzipStream(const ASource: TStream; const ADest: TStream);
function StreamToBase64(const AStream: TStream): string;
procedure Base64ToStream(const ABase64: string; const ADestStream: TStream);
function StreamToBytes(const ASource: TStream): TBytes;
implementation
uses
TypInfo
{$ifndef DelphiXE6_UP}
, XSBuiltIns
{$endif}
, StrUtils, DateUtils, Masks, ZLib, Zip, NetEncoding
;
function StreamToBytes(const ASource: TStream): TBytes;
begin
SetLength(Result, ASource.Size);
ASource.Position := 0;
if ASource.Read(Result, ASource.Size) <> ASource.Size then
raise Exception.Create('Unable to copy all content to TBytes');
end;
procedure ZipStream(const ASource: TStream; const ADest: TStream);
var
LZipStream: TZCompressionStream;
begin
Assert(Assigned(ASource));
Assert(Assigned(ADest));
LZipStream := TZCompressionStream.Create(clDefault, ADest);
try
ASource.Position := 0;
LZipStream.CopyFrom(ASource, ASource.Size);
finally
LZipStream.Free;
end;
end;
procedure UnzipStream(const ASource: TStream; const ADest: TStream);
var
LZipStream: TZDecompressionStream;
begin
Assert(Assigned(ASource));
Assert(Assigned(ADest));
LZipStream := TZDecompressionStream.Create(ASource);
try
ASource.Position := 0;
ADest.CopyFrom(LZipStream, LZipStream.Size);
finally
LZipStream.Free;
end;
end;
function StreamToBase64(const AStream: TStream): string;
var
LBase64Stream: TStringStream;
begin
Assert(Assigned(AStream));
LBase64Stream := TStringStream.Create;
try
AStream.Position := 0;
TNetEncoding.Base64.Encode(AStream, LBase64Stream);
Result := LBase64Stream.DataString;
finally
LBase64Stream.Free;
end;
end;
procedure Base64ToStream(const ABase64: string; const ADestStream: TStream);
var
LBase64Stream: TStringStream;
begin
Assert(Assigned(ADestStream));
LBase64Stream := TStringStream.Create(ABase64);
try
LBase64Stream.Position := 0;
ADestStream.Size := 0;
TNetEncoding.Base64.Decode(LBase64Stream, ADestStream);
finally
LBase64Stream.Free;
end;
end;
function GuessTValueFromString(const AString: string): TValue;
var
LValueInteger: Integer;
LErrorCode: Integer;
LValueDouble: Double;
LValueBool: Boolean;
LValueInt64: Int64;
LValueDateTime: TDateTime;
begin
if AString = '' then
Result := TValue.Empty
else begin
Val(AString, LValueInteger, LErrorCode);
if LErrorCode = 0 then
Result := LValueInteger
else if TryStrToInt64(AString, LValueInt64) then
Result := LValueInt64
else if TryStrToFloat(AString, LValueDouble) then
Result := LValueDouble
else if TryStrToFloat(AString, LValueDouble, TFormatSettings.Create('en')) then
Result := LValueDouble
else if TryStrToBool(AString, LValueBool) then
Result := LValueBool
else if (AString.CountChar('-') >= 2)
and TryISO8601ToDate(AString.DeQuotedString('"'), LValueDateTime, False)
then
Result := LValueDateTime
else
Result := AString;
end;
end;
function StreamToString(const AStream: TStream; const AEncoding: TEncoding = nil): string;
var
LStreamReader: TStreamReader;
LEncoding: TEncoding;
begin
Result := '';
if not Assigned(AStream) then
Exit;
LEncoding := AEncoding;
if not Assigned(LEncoding) then
LEncoding := TEncoding.Default;
AStream.Position := 0;
LStreamReader := TStreamReader.Create(AStream, LEncoding);
try
Result := LStreamReader.ReadToEnd;
finally
LStreamReader.Free;
end;
end;
procedure StringToStream(const AStream: TStream; const AString: string; const AEncoding: TEncoding = nil);
var
LStreamWriter: TStreamWriter;
LEncoding: TEncoding;
begin
if not Assigned(AStream) then
Exit;
LEncoding := AEncoding;
if not Assigned(LEncoding) then
LEncoding := TEncoding.Default;
AStream.Position := 0;
AStream.Size := 0;
LStreamWriter := TStreamWriter.Create(AStream, LEncoding);
try
LStreamWriter.Write(AString);
finally
LStreamWriter.Free;
end;
end;
function IsMask(const AString: string): Boolean;
begin
Result := ContainsStr(AString, '*') // wildcard
or ContainsStr(AString, '?') // jolly
or (ContainsStr(AString, '[') and ContainsStr(AString, ']')); // range
end;
function MatchesMask(const AString, AMask: string): Boolean;
begin
Result := Masks.MatchesMask(AString, AMask);
end;
function DateToJSON(const ADate: TDateTime; AInputIsUTC: Boolean = False): string;
begin
Result := '';
if ADate <> 0 then
Result := DateToISO8601(ADate, AInputIsUTC);
end;
function JSONToDate(const ADate: string; AReturnUTC: Boolean = False): TDateTime;
begin
Result := 0.0;
if ADate<>'' then
Result := ISO8601ToDate(ADate, AReturnUTC);
end;
{$ifndef DelphiXE6_UP}
function DateToISO8601(const ADate: TDateTime; AInputIsUTC: Boolean = False): string;
begin
Result := DateTimeToXMLTime(ADate, not AInputIsUTC);
end;
function ISO8601ToDate(const AISODate: string; AReturnUTC: Boolean = False): TDateTime;
begin
Result := XMLTimeToDateTime(AISODate, AReturnUTC);
end;
{$endif}
procedure CopyStream(ASourceStream, ADestStream: TStream;
AOverWriteDest: Boolean = True; AThenResetDestPosition: Boolean = True);
begin
if AOverWriteDest then
ADestStream.Size := 0;
ADestStream.CopyFrom(ASourceStream, 0);
if AThenResetDestPosition then
ADestStream.Position := 0;
end;
function StreamToJSONValue(const AStream: TStream; const AEncoding: TEncoding): TJSONValue;
var
LStreamReader: TStreamReader;
LEncoding: TEncoding;
begin
LEncoding := AEncoding;
if not Assigned(LEncoding) then
LEncoding := TEncoding.Default;
AStream.Position := 0;
LStreamReader := TStreamReader.Create(AStream, LEncoding);
try
Result := TJSONObject.ParseJSONValue(LStreamReader.ReadToEnd);
finally
LStreamReader.Free;
end;
end;
procedure JSONValueToStream(const AValue: TJSONValue; const ADestStream: TStream; const AEncoding: TEncoding);
var
LStreamWriter: TStreamWriter;
LEncoding: TEncoding;
begin
LEncoding := AEncoding;
if not Assigned(LEncoding) then
LEncoding := TEncoding.Default;
LStreamWriter := TStreamWriter.Create(ADestStream, LEncoding);
try
LStreamWriter.Write(AValue.ToJSON);
finally
LStreamWriter.Free;
end;
end;
function StringArrayToString(const AArray: TArray<string>; const ADelimiter: string = ','): string;
begin
Result := SmartConcat(AArray, ADelimiter);
end;
function EnsurePrefix(const AString, APrefix: string; const AIgnoreCase: Boolean = True): string;
begin
Result := AString;
if Result <> '' then
begin
if (AIgnoreCase and not StartsText(APrefix, Result))
or not StartsStr(APrefix, Result) then
Result := APrefix + Result;
end;
end;
function EnsureSuffix(const AString, ASuffix: string; const AIgnoreCase: Boolean = True): string;
begin
Result := AString;
if Result <> '' then
begin
if (AIgnoreCase and not EndsText(ASuffix, Result))
or not EndsStr(ASuffix, Result) then
Result := Result + ASuffix;
end;
end;
function StripPrefix(const APrefix, AString: string): string;
begin
Result := AString;
if APrefix <> '' then
while StartsStr(APrefix, Result) do
Result := RightStr(Result, Length(Result) - Length(APrefix));
end;
function StripSuffix(const ASuffix, AString: string): string;
begin
Result := AString;
if ASuffix <> '' then
while EndsStr(ASuffix, Result) do
Result := LeftStr(Result, Length(Result) - Length(ASuffix));
end;
function SmartConcat(const AArgs: array of string; const ADelimiter: string = ',';
const AAvoidDuplicateDelimiter: Boolean = True; const ATrim: Boolean = True;
const ACaseInsensitive: Boolean = True): string;
var
LIndex: Integer;
LValue: string;
begin
Result := '';
for LIndex := 0 to Length(AArgs) - 1 do
begin
LValue := AArgs[LIndex];
if ATrim then
LValue := Trim(LValue);
if AAvoidDuplicateDelimiter then
LValue := StripPrefix(ADelimiter, StripSuffix(ADelimiter, LValue));
if (Result <> '') and (LValue <> '') then
Result := Result + ADelimiter;
Result := Result + LValue;
end;
end;
function BooleanToTJSON(AValue: Boolean): TJSONValue;
begin
if AValue then
Result := TJSONTrue.Create
else
Result := TJSONFalse.Create;
end;
function CreateCompactGuidStr: string;
var
I: Integer;
LBuffer: array[0..15] of Byte;
begin
CreateGUID(TGUID(LBuffer));
Result := '';
for I := 0 to 15 do
Result := Result + IntToHex(LBuffer[I], 2);
end;
function ObjectToJSON(const AObject: TObject; const AOptions: TJsonOptions): TJSONObject;
begin
Result := TJSONObject.ObjectToJSON(AObject, AOptions);
end;
{ TFormParamFile }
procedure TFormParamFile.Clear;
begin
FieldName := '';
FileName := '';
Bytes := [];
ContentType := '';
end;
constructor TFormParamFile.CreateFromRequest(const ARequest: TWebRequest; const AFieldName: string);
var
LIndex, LFileIndex: Integer;
LFile: TAbstractWebRequestFile;
begin
Clear;
LFileIndex := -1;
for LIndex := 0 to ARequest.Files.Count - 1 do
begin
LFile := ARequest.Files[LIndex];
if SameText(LFile.FieldName, AFieldName) then
begin
LFileIndex := LIndex;
Break;
end;
end;
CreateFromRequest(ARequest, LFileIndex);
end;
constructor TFormParamFile.Create(const AFieldName, AFileName: string;
const ABytes: TBytes; const AContentType: string);
begin
FieldName := AFieldName;
FileName := AFileName;
Bytes := ABytes;
ContentType := AContentType;
end;
constructor TFormParamFile.CreateFromRequest(const ARequest: TWebRequest;
const AFileIndex: Integer);
var
LFile: TAbstractWebRequestFile;
begin
Clear;
if (AFileIndex >= 0) and (AFileIndex < ARequest.Files.Count) then
begin
LFile := ARequest.Files[AFileIndex];
Create(LFile.FieldName, LFile.FileName, StreamToBytes(LFile.Stream), LFile.ContentType);
end;
end;
function TFormParamFile.ToString: string;
begin
Result := FieldName + '=' + SmartConcat([FileName, ContentType, Length(Bytes).ToString + ' bytes']);
end;
{ TFormParam }
function TFormParam.AsFile: TFormParamFile;
begin
Result := Value.AsType<TFormParamFile>;
end;
procedure TFormParam.Clear;
begin
FieldName := '';
Value := TValue.Empty;
end;
constructor TFormParam.Create(const AFieldName: string; const AValue: TValue);
begin
Clear;
FieldName := AFieldName;
Value := AValue;
end;
constructor TFormParam.CreateFile(const AFieldName, AFileName: string;
const ABytes: TBytes; const AContentType: string);
begin
Create(AFieldName
, TValue.From<TFormParamFile>(
TFormParamFile.Create(AFieldName, AFileName, ABytes, AContentType)
)
);
end;
constructor TFormParam.CreateFromRequest(const ARequest: TWebRequest;
const AFileIndex: Integer);
var
LValue: TFormParamFile;
begin
Clear;
LValue := TFormParamFile.CreateFromRequest(ARequest, AFileIndex);
Value := TValue.From<TFormParamFile>(LValue);
FieldName := LValue.FieldName;
end;
constructor TFormParam.CreateFromRequest(const ARequest: TWebRequest;
const AFieldName: string);
var
LIndex: Integer;
begin
Clear;
LIndex := ARequest.ContentFields.IndexOfName(AFieldName);
if LIndex <> -1 then
begin
FieldName := AFieldName;
Value := ARequest.ContentFields.ValueFromIndex[LIndex];
end
else
begin
FieldName := AFieldName;
Value := TValue.From<TFormParamFile>(
TFormParamFile.CreateFromRequest(ARequest, AFieldName)
);
end;
end;
function TFormParam.IsFile: Boolean;
begin
Result := Value.IsType<TFormParamFile>;
end;
function TFormParam.ToString: string;
begin
if IsFile then
Result := AsFile.ToString
else
Result := FieldName + '=' + Value.ToString;
end;
{ TDump }
class procedure TDump.Request(const ARequest: TWebRequest;
const AFileName: string);
var
LSS: TStringStream;
LHeaders: string;
LRawString: string;
{$ifdef Delphi10Berlin_UP}
LBytesStream: TBytesStream;
{$endif}
begin
try
try
LRawString := 'Content: ' + ARequest.Content;
except
{$IFDEF Delphi10Berlin_UP}
try
LRawString := TEncoding.UTF8.GetString(ARequest.RawContent);
except
try
LBytesStream := TBytesStream.Create(ARequest.RawContent);
try
LRawString := StreamToString(LBytesStream);
finally
LBytesStream.Free;
end;
except
LRawString := 'Unable to read content: ' + Length(ARequest.RawContent).ToString + ' bytes';
end;
end;
{$ELSE}
LRawString := ARequest.RawContent;
{$ENDIF}
end;
LHeaders := string.join(sLineBreak, [
'PathInfo: ' + ARequest.PathInfo
, 'Method: ' + ARequest.Method
, 'ProtocolVersion: ' + ARequest.ProtocolVersion
, 'Authorization: ' + ARequest.Authorization
, 'Accept: ' + ARequest.Accept
, 'ContentFields: ' + ARequest.ContentFields.CommaText
, 'CookieFields: ' + ARequest.CookieFields.CommaText
, 'QueryFields: ' + ARequest.QueryFields.CommaText
, 'ContentType: ' + ARequest.ContentType
, 'ContentEncoding: ' + ARequest.ContentEncoding
, 'ContentLength: ' + ARequest.ContentLength.ToString
, 'ContentVersion: ' + ARequest.ContentVersion
, 'RemoteAddr: ' + ARequest.RemoteAddr
, 'RemoteHost: ' + ARequest.RemoteHost
, 'RemoteIP: ' + ARequest.RemoteIP
]);
LSS := TStringStream.Create(LHeaders + sLineBreak + sLineBreak + LRawString);
try
LSS.SaveToFile(AFileName);
finally
LSS.Free;
end;
except on E:Exception do
begin
LSS := TStringStream.Create('Error: ' + E.ToString);
try
LSS.SaveToFile(AFileName);
finally
LSS.Free;
end;
end;
// no exceptions allowed outside here
end;
end;
end.
|
//**********************************************************************************************************************
// $Id: udSettings.pas,v 1.12 2006-09-13 14:38:06 dale Exp $
//----------------------------------------------------------------------------------------------------------------------
// DKLang Translation Editor
// Copyright ęDK Software, http://www.dk-soft.org/
//**********************************************************************************************************************
unit udSettings;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, TntSystem, TntWindows,
TntSysUtils, uTranEdPlugin, ConsVars,
DKLTranEdFrm, DKLang, StdCtrls, TntStdCtrls, ComCtrls, TntComCtrls,
VirtualTrees, ExtCtrls, TntExtCtrls;
type
TdSettings = class(TDKLTranEdForm)
bBrowseReposPath: TTntButton;
bCancel: TTntButton;
bHelp: TTntButton;
bInterfaceFont: TTntButton;
bOK: TTntButton;
bTableFont: TTntButton;
cbAutoAddStrings: TTntCheckBox;
cbIgnoreEncodingMismatch: TTntCheckBox;
cbRemovePrefix: TTntCheckBox;
dklcMain: TDKLanguageController;
eReposPath: TTntEdit;
gbInterface: TGroupBox;
gbRepository: TGroupBox;
lInterfaceFont: TTntLabel;
lRemovePrefix: TTntLabel;
lReposPath: TTntLabel;
lTableFont: TTntLabel;
pcMain: TTntPageControl;
tsGeneral: TTntTabSheet;
tsPlugins: TTntTabSheet;
tvPlugins: TVirtualStringTree;
procedure AdjustOKCancel(Sender: TObject);
procedure bBrowseReposPathClick(Sender: TObject);
procedure bInterfaceFontClick(Sender: TObject);
procedure bOKClick(Sender: TObject);
procedure bTableFontClick(Sender: TObject);
procedure tvPluginsBeforeItemErase(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; ItemRect: TRect; var ItemColor: TColor; var EraseAction: TItemEraseAction);
procedure tvPluginsExpanding(Sender: TBaseVirtualTree; Node: PVirtualNode; var Allowed: Boolean);
procedure tvPluginsGetCursor(Sender: TBaseVirtualTree; var Cursor: TCursor);
procedure tvPluginsGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer);
procedure tvPluginsGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString);
procedure tvPluginsInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
procedure tvPluginsMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure tvPluginsPaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType);
private
// Fonts
FInterfaceFont: WideString;
FTableFont: WideString;
// Plugin host object
FPluginHost: TPluginHost;
// Returns True if point p (client coordinates) is at hyperlink in tvPlugins
function PointAtPluginHyperlink(const p: TPoint; out Plugin: IDKLang_TranEd_Plugin): Boolean;
// Updates info about selected fonts
procedure UpdateFonts;
protected
procedure DoCreate; override;
procedure ExecuteInitialize; override;
end;
function EditSettings(APluginHost: TPluginHost): Boolean;
implementation
{$R *.dfm}
uses TntFileCtrl, ShellAPI, Main;
const
// tvPlugins column indices
IColIdx_Plugins_Name = 0;
IColIdx_Plugins_Value = 1;
// Number of plugin info entries
IPluginInfoEntryCount = 5;
// Plugin info entries indices
IPluginInfoEntryIdx_Version = 0;
IPluginInfoEntryIdx_Author = 1;
IPluginInfoEntryIdx_Copyright = 2;
IPluginInfoEntryIdx_Description = 3;
IPluginInfoEntryIdx_Website = 4;
function EditSettings(APluginHost: TPluginHost): Boolean;
begin
with TdSettings.Create(Application) do
try
FPluginHost := APluginHost;
Result := ExecuteModal;
finally
Free;
end;
end;
//===================================================================================================================
// TdSettings
//===================================================================================================================
procedure TdSettings.AdjustOKCancel(Sender: TObject);
begin
bOK.Enabled := True;
end;
procedure TdSettings.bBrowseReposPathClick(Sender: TObject);
var ws: WideString;
begin
ws := eReposPath.Text;
if WideSelectDirectory(DKLangConstW('SDlgTitle_SelReposPath'), '', ws) then eReposPath.Text := ws;
end;
procedure TdSettings.bInterfaceFontClick(Sender: TObject);
begin
if SelectFont(FInterfaceFont) then begin
UpdateFonts;
AdjustOKCancel(nil);
end;
end;
procedure TdSettings.bOKClick(Sender: TObject);
begin
// Repository
wsSetting_RepositoryDir := eReposPath.Text;
bSetting_ReposRemovePrefix := cbRemovePrefix.Checked;
bSetting_ReposAutoAdd := cbAutoAddStrings.Checked;
// Interface
wsSetting_InterfaceFont := FInterfaceFont;
wsSetting_TableFont := FTableFont;
// Misc
bSetting_IgnoreEncodingMismatch := cbIgnoreEncodingMismatch.Checked;
ModalResult := mrOK;
end;
procedure TdSettings.bTableFontClick(Sender: TObject);
begin
if SelectFont(FTableFont) then begin
UpdateFonts;
AdjustOKCancel(nil);
end;
end;
procedure TdSettings.DoCreate;
begin
inherited DoCreate;
// Initialize help context ID
HelpContext := IDH_iface_dlg_settings;
end;
procedure TdSettings.ExecuteInitialize;
begin
inherited ExecuteInitialize;
pcMain.ActivePageIndex := 0;
// Repository
eReposPath.Text := wsSetting_RepositoryDir;
cbRemovePrefix.Checked := bSetting_ReposRemovePrefix;
cbAutoAddStrings.Checked := bSetting_ReposAutoAdd;
// Interface
FInterfaceFont := wsSetting_InterfaceFont;
FTableFont := wsSetting_TableFont;
UpdateFonts;
// Misc
cbIgnoreEncodingMismatch.Checked := bSetting_IgnoreEncodingMismatch;
// Plugins
tvPlugins.RootNodeCount := FPluginHost.PluginEntryCount;
end;
function TdSettings.PointAtPluginHyperlink(const p: TPoint; out Plugin: IDKLang_TranEd_Plugin): Boolean;
var hi: THitInfo;
begin
tvPlugins.GetHitTestInfoAt(p.x, p.y, True, hi);
Result :=
(hi.HitNode<>nil) and (tvPlugins.NodeParent[hi.HitNode]<>nil) and (hi.HitColumn=IColIdx_Plugins_Value) and
(hiOnItemLabel in hi.HitPositions) and (hi.HitNode.Index=IPluginInfoEntryIdx_Website);
if Result then Plugin := FPluginHost[tvPlugins.NodeParent[hi.HitNode].Index].Plugin else Plugin := nil;
end;
procedure TdSettings.tvPluginsBeforeItemErase(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; ItemRect: TRect; var ItemColor: TColor; var EraseAction: TItemEraseAction);
begin
// Shade plugin rows
if Sender.NodeParent[Node]=nil then begin
EraseAction := eaColor;
ItemColor := CBack_LightShade;
end;
end;
procedure TdSettings.tvPluginsExpanding(Sender: TBaseVirtualTree; Node: PVirtualNode; var Allowed: Boolean);
begin
if Sender.ChildCount[Node]=0 then Sender.ChildCount[Node] := IPluginInfoEntryCount;
end;
procedure TdSettings.tvPluginsGetCursor(Sender: TBaseVirtualTree; var Cursor: TCursor);
var Plugin: IDKLang_TranEd_Plugin;
begin
if PointAtPluginHyperlink(Sender.ScreenToClient(Mouse.CursorPos), Plugin) then Cursor := crHandPoint;
end;
procedure TdSettings.tvPluginsGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer);
begin
if (Kind in [ikNormal, ikSelected]) and (Sender.NodeParent[Node]=nil) and (Column=IColIdx_Plugins_Name) then
ImageIndex := iiPlugin;
end;
procedure TdSettings.tvPluginsGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString);
var
cEntryIndex: Cardinal;
PE: TPluginEntry;
PI: IDKLang_TranEd_PluginInfo;
nParent: PVirtualNode;
begin
if TextType<>ttNormal then Exit;
nParent := Sender.NodeParent[Node];
if nParent=nil then cEntryIndex := Node.Index else cEntryIndex := nParent.Index;
PE := FPluginHost[cEntryIndex];
// Root node
if nParent=nil then
case Column of
IColIdx_Plugins_Name: CellText := PE.Plugin.Name;
IColIdx_Plugins_Value: CellText := PE.FileName;
end
// Child node
else
case Column of
IColIdx_Plugins_Name:
case Node.Index of
IPluginInfoEntryIdx_Version: CellText := DKLangConstW('SMsg_PluginVersion');
IPluginInfoEntryIdx_Author: CellText := DKLangConstW('SMsg_PluginAuthor');
IPluginInfoEntryIdx_Copyright: CellText := DKLangConstW('SMsg_PluginCopyright');
IPluginInfoEntryIdx_Description: CellText := DKLangConstW('SMsg_PluginDescription');
IPluginInfoEntryIdx_Website: CellText := DKLangConstW('SMsg_PluginWebsite');
end;
IColIdx_Plugins_Value:
if Supports(PE.Plugin, IDKLang_TranEd_PluginInfo, PI) then
case Node.Index of
IPluginInfoEntryIdx_Version: CellText := WideFormat('%s (%d)', [PI.InfoVersionText, PE.SubsystemVersion]);
IPluginInfoEntryIdx_Author: CellText := PI.InfoAuthor;
IPluginInfoEntryIdx_Copyright: CellText := PI.InfoCopyright;
IPluginInfoEntryIdx_Description: CellText := PI.InfoDescription;
IPluginInfoEntryIdx_Website: CellText := PI.InfoWebsiteURL;
end;
end;
end;
procedure TdSettings.tvPluginsInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
begin
// Mark the node as having children if there's extended plugin info
if (ParentNode=nil) and Supports(FPluginHost[Node.Index].Plugin, IDKLang_TranEd_PluginInfo) then
Include(InitialStates, ivsHasChildren);
end;
procedure TdSettings.tvPluginsMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var Plugin: IDKLang_TranEd_Plugin;
begin
// When plugin's URL clicked open it
if (Shift=[ssLeft]) and PointAtPluginHyperlink(Point(x, y), Plugin) then
Tnt_ShellExecuteW(
Application.Handle,
nil,
PWideChar((Plugin as IDKLang_TranEd_PluginInfo).InfoWebsiteURL),
nil,
nil,
SW_SHOWNORMAL);
end;
procedure TdSettings.tvPluginsPaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType);
begin
// Draw plugin names in bold
if Sender.NodeParent[Node]=nil then begin
if Column=IColIdx_Plugins_Name then TargetCanvas.Font.Style := [fsBold];
// Draw URLs as hyperlinks
end else
if (Column=IColIdx_Plugins_Value) and (Node.Index=IPluginInfoEntryIdx_Website) then begin
TargetCanvas.Font.Style := [fsUnderline];
if not (vsSelected in Node.States) then TargetCanvas.Font.Color := clHotLight;
end;
end;
procedure TdSettings.UpdateFonts;
procedure ShowFont(const wsFont: WideString; Lbl: TTntLabel);
begin
Lbl.Caption := GetFirstWord(wsFont, '/');
FontFromStr(Lbl.Font, wsFont);
end;
begin
ShowFont(FInterfaceFont, lInterfaceFont);
ShowFont(FTableFont, lTableFont);
end;
end.
|
unit SrvBpjsParallelU;
interface
uses System.Classes, OtlParallel;
type
SrvBpjsParallel = class
public
procedure bpjsAllPost(idxstr : string);
procedure bpjsAllPostNonParallel(idxstr : string);
procedure bpjsPendaftaranPost(idxstr : string);
procedure bpjsPendaftaranDel(idxstr : string);
procedure bpjsKunjunganPost(idxstr : string);
procedure bpjsObatPost(idxstr : string);
procedure bpjsObatPostTunggal(id : string);
procedure bpjsObatDel(id : string);
procedure bpjsTindakanPost(idxstr : string);
procedure bpjsTindakanDel(id : string);
constructor Create;
destructor Destroy;
end;
implementation
uses brPendaftaranU, brKunjunganU, brObatU, brTindakanU;
{ SrvParallel }
procedure SrvBpjsParallel.bpjsAllPost(idxstr: string);
begin
Parallel.Async(
procedure
var
srvDaftar : brPendaftaran;
srvKunjungan : brKunjungan;
srvObat : brObat;
srvTindakan : brTindakan;
begin
// daftar
srvDaftar := brPendaftaran.Create;
try
srvDaftar.postPendaftaran(idxstr);
finally
srvDaftar.Free;
//kunjungan
srvKunjungan := brKunjungan.Create;
try
srvKunjungan.postKunjungan(idxstr);
finally
srvKunjungan.Free;
//obat
srvObat := brObat.Create;
try
srvObat.postObat(idxstr);
finally
srvObat.Free;
//tindakan
srvTindakan := brTindakan.Create;
try
srvTindakan.postTindakan(idxstr);
finally
srvTindakan.Free;
end;
end;
end;
end;
end
);
end;
procedure SrvBpjsParallel.bpjsAllPostNonParallel(idxstr: string);
var
srvDaftar : brPendaftaran;
srvKunjungan : brKunjungan;
srvObat : brObat;
srvTindakan : brTindakan;
begin
// daftar
srvDaftar := brPendaftaran.Create;
try
srvDaftar.postPendaftaran(idxstr);
finally
srvDaftar.Free;
//kunjungan
srvKunjungan := brKunjungan.Create;
try
srvKunjungan.postKunjungan(idxstr);
finally
srvKunjungan.Free;
//obat
srvObat := brObat.Create;
try
srvObat.postObat(idxstr);
finally
srvObat.Free;
//tindakan
srvTindakan := brTindakan.Create;
try
srvTindakan.postTindakan(idxstr);
finally
srvTindakan.Free;
end;
end;
end;
end;
end;
procedure SrvBpjsParallel.bpjsKunjunganPost(idxstr: string);
begin
Parallel.Async(
procedure
var srv : brKunjungan;
begin
srv := brKunjungan.Create;
try
srv.postKunjungan(idxstr);
finally
srv.Free;
end;
end
);
end;
procedure SrvBpjsParallel.bpjsObatDel(id: string);
begin
Parallel.Async(
procedure
var srv : brObat;
begin
srv := brObat.Create;
try
srv.delObat(id);
finally
srv.Free;
end;
end
);
end;
procedure SrvBpjsParallel.bpjsObatPost(idxstr: string);
begin
Parallel.Async(
procedure
var srv : brObat;
begin
srv := brObat.Create;
try
srv.postObat(idxstr);
finally
srv.Free;
end;
end
);
end;
procedure SrvBpjsParallel.bpjsObatPostTunggal(id: string);
begin
Parallel.Async(
procedure
var srv : brObat;
begin
srv := brObat.Create;
try
srv.postObatTunggal(id);
finally
srv.Free;
end;
end
);
end;
procedure SrvBpjsParallel.bpjsPendaftaranDel(idxstr: string);
begin
Parallel.Async(
procedure
var srv : brPendaftaran;
begin
srv := brPendaftaran.Create;
try
srv.delPendaftaranX(idxstr);
finally
srv.Free;
end;
end
);
end;
procedure SrvBpjsParallel.bpjsPendaftaranPost(idxstr: string);
begin
Parallel.Async(
procedure
var srv : brPendaftaran;
begin
srv := brPendaftaran.Create;
try
srv.postPendaftaran(idxstr);
finally
srv.Free;
end;
end
);
end;
procedure SrvBpjsParallel.bpjsTindakanDel(id: string);
begin
Parallel.Async(
procedure
var srv : brTindakan;
begin
srv := brTindakan.Create;
try
srv.delTindakan(id);
finally
srv.Free;
end;
end
);
end;
procedure SrvBpjsParallel.bpjsTindakanPost(idxstr: string);
begin
Parallel.Async(
procedure
var srv : brTindakan;
begin
srv := brTindakan.Create;
try
srv.postTindakan(idxstr);
finally
srv.Free;
end;
end
);
end;
constructor SrvBpjsParallel.Create;
begin
inherited;
end;
destructor SrvBpjsParallel.Destroy;
begin
inherited;
end;
end.
|
unit frm_Script;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, HCSynEdit, SynEdit,
SynHighlighterPas, SynHighlighterJScript, SynCompletionProposal,
System.ImageList, Vcl.ImgList, Vcl.StdCtrls;
type
TProposalEvent = procedure(const AWord: string; const AInsertList, AItemList: TStrings) of object;
TfrmScript = class(TForm)
StatusBar: TStatusBar;
il: TImageList;
lbl1: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FProposal: TSynCompletionProposal; // 代码提示
FOnProposal: TProposalEvent;
FOnCodeCompletion: TCodeCompletionEvent;
FPascalSyn: TSynPasSyn; // Pascal高亮
//FJScript: TSynJScriptSyn; // JavaScript高亮
FSynEdit: THCSynEdit;
procedure ChangeHighlighter;
procedure DoEditStatusChange(Sender: TObject; Changes: TSynStatusChanges);
procedure DoProposal(Kind: SynCompletionType; Sender: TObject;
var CurrentInput: UnicodeString; var x, y: Integer; var CanExecute: Boolean);
procedure DoCodeCompletion(Sender: TObject; var Value: string;
Shift: TShiftState; Index: Integer; EndToken: Char);
public
{ Public declarations }
property SynEdit: THCSynEdit read FSynEdit;
property OnProposal: TProposalEvent read FOnProposal write FOnProposal;
property OnCodeCompletion: TCodeCompletionEvent read FOnCodeCompletion write FOnCodeCompletion;
end;
implementation
const
ModifiedStrs: array[boolean] of string = ('', 'Modified');
InsertModeStrs: array[boolean] of string = ('Overwrite', 'Insert');
{$R *.dfm}
procedure TfrmScript.ChangeHighlighter;
var
vHighlighterFile: string;
begin
vHighlighterFile := ExtractFilePath(ParamStr(0)) + FSynEdit.Highlighter.LanguageName + '.ini';
if FileExists(vHighlighterFile) then
FSynEdit.Highlighter.LoadFromFile(vHighlighterFile);
end;
procedure TfrmScript.DoCodeCompletion(Sender: TObject; var Value: string;
Shift: TShiftState; Index: Integer; EndToken: Char);
begin
if Assigned(FOnCodeCompletion) then
FOnCodeCompletion(FSynEdit, Value, Shift, Index, EndToken);
end;
procedure TfrmScript.DoEditStatusChange(Sender: TObject; Changes: TSynStatusChanges);
var
vCoord: TBufferCoord;
begin
if Changes * [scAll, scCaretX, scCaretY] <> [] then
begin
vCoord := FSynEdit.CaretXY;
Statusbar.Panels[0].Text := Format('%6d:%3d', [vCoord.Line, vCoord.Char]);
end;
if Changes * [scAll, scInsertMode, scReadOnly] <> [] then
begin
if FSynEdit.ReadOnly then
Statusbar.Panels[2].Text := 'ReadOnly'
else
Statusbar.Panels[2].Text := InsertModeStrs[FSynEdit.InsertMode];
end;
if Changes * [scAll, scModified] <> [] then
Statusbar.Panels[1].Text := ModifiedStrs[FSynEdit.Modified];
end;
procedure TfrmScript.DoProposal(Kind: SynCompletionType; Sender: TObject;
var CurrentInput: UnicodeString; var x, y: Integer; var CanExecute: Boolean);
var
vCurLine, vsLookup: string;
vCoorX, vCoorTemp, vParenCounter, vStartX, vSavePos: Integer;
vFoundMatch: Boolean;
begin
// 代码提示弹出时
if not Assigned(FOnProposal) then Exit;
vCurLine := FSynEdit.LineText;
vCoorX := FSynEdit.CaretX;
if vCoorX > length(vCurLine) then
vCoorX := length(vCurLine)
else
Dec(vCoorX);
vFoundMatch := False;
vCoorTemp := 0;
while (vCoorX > 0) and not(vFoundMatch) do
begin
if vCurLine[vCoorX] = '.' then
begin
//we have a valid open paren, lets see what the word before it is
vStartX := vCoorX;
while (vCoorX > 0) and not FSynEdit.IsIdentChar(vCurLine[vCoorX]) do
Dec(vCoorX);
if vCoorX > 0 then
begin
vSavePos := vCoorX;
While (vCoorX > 0) and FSynEdit.IsIdentChar(vCurLine[vCoorX]) do
Dec(vCoorX);
Inc(vCoorX);
vsLookup := Uppercase(Copy(vCurLine, vCoorX, vSavePos - vCoorX + 1));
vFoundMatch := True;
Break;
{vFoundMatch := FProposal.LookupList.IndexOf(vsLookup) > -1;
if vsLookup = 'SELF' then
begin
vFoundMatch := True;
Break;
end;
if not(vFoundMatch) then
begin
vCoorX := vStartX;
Dec(vCoorX);
end;}
end
else
begin
vsLookup := '.';
vFoundMatch := True;
Break;
end;
end
else
if vCurLine[vCoorX] = ',' then
begin
Inc(vCoorTemp);
Dec(vCoorX);
end
else
if vCurLine[vCoorX] = ')' then
begin
//We found a close, go till it's opening paren
vParenCounter := 1;
Dec(vCoorX);
while (vCoorX > 0) and (vParenCounter > 0) do
begin
if vCurLine[vCoorX] = ')' then
Inc(vParenCounter)
else
if vCurLine[vCoorX] = '(' then
Dec(vParenCounter);
Dec(vCoorX);
end;
if vCoorX > 0 then
Dec(vCoorX); //eat the open paren
end
else
if vCurLine[vCoorX] = '(' then
begin
//we have a valid open paren, lets see what the word before it is
vStartX := vCoorX;
while (vCoorX > 0) and not FSynEdit.IsIdentChar(vCurLine[vCoorX]) do
Dec(vCoorX);
if vCoorX > 0 then
begin
vSavePos := vCoorX;
While (vCoorX > 0) and FSynEdit.IsIdentChar(vCurLine[vCoorX]) do
Dec(vCoorX);
Inc(vCoorX);
vsLookup := Uppercase(Copy(vCurLine, vCoorX, vSavePos - vCoorX + 1));
vFoundMatch := True;
Break;
{vFoundMatch := LookupList.IndexOf(vsLookup) > -1;
if not(vFoundMatch) then
begin
vCoorX := vStartX;
Dec(vCoorX);
end;}
end;
end
else
Dec(vCoorX)
end;
CanExecute := vFoundMatch;
if CanExecute then
begin
TSynCompletionProposal(Sender).Form.CurrentIndex := vCoorTemp;
//if vsLookup <> TSynCompletionProposal(Sender).PreviousToken then
begin
FProposal.InsertList.Clear;
FProposal.ItemList.Clear;
FOnProposal(vsLookup, FProposal.InsertList, FProposal.ItemList);
end;
end
else
begin
FProposal.InsertList.Clear;
FProposal.ItemList.Clear;
end;
end;
procedure TfrmScript.FormCreate(Sender: TObject);
begin
FPascalSyn := TSynPasSyn.Create(nil);
//FJScript := TSynJScriptSyn.Create(nil);
FSynEdit := THCSynEdit.Create(nil);
FSynEdit.Gutter.ShowLineNumbers := True;
FSynEdit.Highlighter := FPascalSyn; // FJScript
FSynEdit.Highlighter.UseUserSettings(2);
//FSynEdit.Highlighter.SaveToFile('c:\a.ini');
ChangeHighlighter;
FSynEdit.Text := FPascalSyn.SampleSource;
FSynEdit.OnStatusChange := DoEditStatusChange;
FSynEdit.Align := alClient;
FSynEdit.Parent := Self;
FProposal := TSynCompletionProposal.Create(nil);
FProposal.Editor := FSynEdit;
FProposal.Title := '代码提示:';
FProposal.TimerInterval := 200;
FProposal.ShortCut := VK_SHIFT or VK_SPACE;
FProposal.ClSelect := $00A56D53;
FProposal.Font.Name := 'Tahoma';
FProposal.Width := 600;
FProposal.Images := il;
FProposal.ItemHeight := 16;
FProposal.Columns.Add.ColumnWidth := 16; // 图标
FProposal.Columns.Add.ColumnWidth := 80; // 修饰词 如 var procedure functon property等
//FProposal.Margin := 4;
FProposal.Options := FProposal.Options + [scoUseInsertList, scoUsePrettyText, scoUseBuiltInTimer];
FProposal.OnExecute := DoProposal;
FProposal.OnCodeCompletion := DoCodeCompletion;
end;
procedure TfrmScript.FormDestroy(Sender: TObject);
begin
FreeAndNil(FSynEdit);
FreeAndNil(FProposal);
FreeAndNil(FPascalSyn);
//FreeAndNil(FJScript);
end;
procedure TfrmScript.FormShow(Sender: TObject);
begin
DoEditStatusChange(Self, [scAll]);
end;
end.
|
unit FormStepsLibImages;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts,
FMX.ListBox, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Objects,
System.ImageList, FMX.ImgList, KrDnceUtilTypes, System.Generics.Collections;
type
TImgImport = class(TObject)
public
FileName: string;
ColourCnt: Integer;
Colours: array[0..3] of TAlphaColor;
ColourMap: array[0..3] of SmallInt;
CanImport: Boolean;
Mapping: array[0..79, 0..49] of SmallInt;
ImportView,
MapView: TBitmap;
constructor Create;
destructor Destroy; override;
end;
TStepsLibImagesForm = class(TForm)
ToolBar1: TToolBar;
Button2: TButton;
ListBox1: TListBox;
Footer: TToolBar;
OpenDialog1: TOpenDialog;
ImageList1: TImageList;
Button5: TButton;
Button1: TButton;
Panel1: TPanel;
Image1: TImage;
CheckBox1: TCheckBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
ComboBox1: TComboBox;
ComboBox2: TComboBox;
ComboBox3: TComboBox;
ComboBox4: TComboBox;
Rectangle1: TRectangle;
Rectangle2: TRectangle;
Rectangle3: TRectangle;
Rectangle4: TRectangle;
Button3: TButton;
Button4: TButton;
Button6: TButton;
Button7: TButton;
Rectangle5: TRectangle;
Rectangle6: TRectangle;
Rectangle7: TRectangle;
Rectangle8: TRectangle;
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure ListBox1Change(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FImportImgs: TList<TImgImport>;
FFixed: Boolean;
FCombos: array[0..3] of TComboBox;
FSrcRects,
FDstRects: array[0..3] of TRectangle;
FSelectedImage: Integer;
procedure DoDisplayImage(const AImage: Integer);
procedure DoUpdateImageView(const AImage: Integer);
procedure DoRebuildMapView(const AImage: Integer);
procedure DoRemapImageColour(const AImage: Integer;
const AColour: TAlphaColor; const AMap: Integer);
function ColourForMap(const AMap: Integer;
const ADefault: TAlphaColor): TAlphaColor;
function GetImageCount: Integer;
public
procedure Clear;
procedure AddImage(const AFileName: string; ABitmap: TBitmap);
procedure ImageToScreen(const AImage: Integer; var AScreen: TC64Screen);
function ShowAddImages(const AFixed: Boolean = False): TModalResult;
property ImageCount: Integer read GetImageCount;
end;
var
StepsLibImagesForm: TStepsLibImagesForm;
implementation
{$R *.fmx}
uses
System.IOUtils, KrDnceGraphTypes, DModStepsLibMain;
{ TImgImport }
constructor TImgImport.Create;
var
x,
y: Integer;
begin
ImportView:= TBitmap.Create;
ImportView.Width:= 80;
ImportView.Height:= 50;
MapView:= TBitmap.Create;
MapView.Width:= 80;
MapView.Height:= 50;
for x:= 0 to 79 do
for y:= 0 to 49 do
Mapping[x, y]:= -1;
end;
destructor TImgImport.Destroy;
begin
MapView.Free;
ImportView.Free;
inherited;
end;
{ TStepsBuildImagesForm }
procedure TStepsLibImagesForm.AddImage(const AFileName: string;
ABitmap: TBitmap);
var
b1: TBitmap;
l: TListBoxItem;
img: TImgImport;
i,
x,
y: Integer;
rd: TBitmapData;
p: TAlphaColor;
f: Boolean;
begin
img:= TImgImport.Create;
img.FileName:= AFileName;
img.CanImport:= False;
for i:= 0 to 3 do
img.ColourMap[i]:= -1;
FImportImgs.Add(img);
b1:= ABitmap.CreateThumbnail(32, 32);
ImageListAdd(ImageList1, b1);
b1.Free;
l:= TListBoxItem.Create(ListBox1);
l.ItemData.Text:= AFileName;
l.ImageIndex:= FImportImgs.Count - 1;
l.Tag:= FImportImgs.Count - 1;
l.Parent:= ListBox1;
if ((ABitmap.Width mod 40) <> 0)
or (ABitmap.Width < 80) then
Exit;
if ((ABitmap.Height mod 25) <> 0)
or (ABitmap.Height < 50) then
Exit;
i:= Trunc(ABitmap.Width / 80);
if Trunc(ABitmap.Height / 50) <> i then
Exit;
b1:= ABitmap.CreateThumbnail(80, 50);
img.ImportView.CopyFromBitmap(b1);
img.MapView.CopyFromBitmap(b1);
b1.Free;
img.ColourCnt:= 0;
if img.ImportView.Map(TMapAccess.Read, rd) then
try
for x:= 0 to img.ImportView.Width - 1 do
begin
for y:= 0 to img.ImportView.Height - 1 do
begin
p:= rd.GetPixel(x, y);
if TAlphaColorRec(p).A <> $FF then
begin
img.ColourCnt:= -1;
Break;
end;
f:= False;
for i:= 0 to img.ColourCnt - 1 do
if img.Colours[i] = p then
begin
f:= True;
Break;
end;
if f then
Continue;
Inc(img.ColourCnt);
if img.ColourCnt > 4 then
Break;
img.Colours[img.ColourCnt - 1]:= p;
end;
if (img.ColourCnt < 0)
or (img.ColourCnt > 4) then
Break;
end;
finally
img.ImportView.Unmap(rd);
end;
if (img.ColourCnt < 0)
or (img.ColourCnt > 4) then
Exit;
img.CanImport:= True;
end;
procedure TStepsLibImagesForm.Button2Click(Sender: TObject);
var
i: Integer;
b: TBitmap;
begin
if OpenDialog1.Execute then
begin
for i:= 0 to OpenDialog1.Files.Count - 1 do
begin
b:= TBitmap.CreateFromFile(OpenDialog1.Files[i]);
try
AddImage(TPath.GetFileName(OpenDialog1.Files[i]), b);
finally
b.Free;
end;
end;
if not Assigned(ListBox1.Selected) then
ListBox1.SelectRange(ListBox1.ListItems[0], ListBox1.ListItems[0]);
end;
end;
procedure TStepsLibImagesForm.Button3Click(Sender: TObject);
var
i,
m: Integer;
p: TAlphaColor;
begin
i:= TButton(Sender).Tag;
if (FSelectedImage > -1)
and (FCombos[i].Enabled) then
begin
p:= FImportImgs[FSelectedImage].Colours[i];
m:= FImportImgs[FSelectedImage].ColourMap[i];
for i:= 0 to FImportImgs.Count - 1 do
if i <> FSelectedImage then
begin
DoRemapImageColour(i, p, m);
DoRebuildMapView(i);
end;
end;
end;
procedure TStepsLibImagesForm.Clear;
var
i: Integer;
img: TImgImport;
begin
FSelectedImage:= -1;
ImageList1.Source.Clear;
ImageList1.Destination.Clear;
ImageList1.ClearCache;
ListBox1.Items.Clear;
for i:= FImportImgs.Count - 1 downto 0 do
begin
img:= FImportImgs[i];
FImportImgs.Delete(i);
img.Free;
end;
for i:= 0 to 3 do
FCombos[i].ItemIndex:= 0;
end;
function TStepsLibImagesForm.ColourForMap(const AMap: Integer;
const ADefault: TAlphaColor): TAlphaColor;
begin
Result:= ADefault;
case AMap of
0:
Result:= TC64FrameClrs.Bkgrd0;
1:
Result:= TC64FrameClrs.Multi1;
2:
Result:= TC64FrameClrs.Multi2;
3:
Result:= TC64FrameClrs.Frgrd3;
end;
end;
procedure TStepsLibImagesForm.ComboBox1Change(Sender: TObject);
var
c: TComboBox;
begin
c:= TComboBox(Sender);
if (FSelectedImage > -1)
and (c.Enabled) then
begin
FImportImgs[FSelectedImage].ColourMap[c.Tag]:= c.ItemIndex - 1;
FDstRects[c.Tag].Fill.Color:= ColourForMap(c.ItemIndex - 1,
FImportImgs[FSelectedImage].Colours[c.Tag]);
DoRebuildMapView(FSelectedImage);
DoUpdateImageView(FSelectedImage);
end;
end;
procedure TStepsLibImagesForm.DoDisplayImage(const AImage: Integer);
var
i: Integer;
img: TImgImport;
begin
FSelectedImage:= AImage;
DoUpdateImageView(AImage);
img:= FImportImgs.Items[AImage];
CheckBox1.IsChecked:= img.CanImport;
for i:= 0 to 3 do
if i > (img.ColourCnt - 1) then
begin
FCombos[i].Enabled:= False;
FCombos[i].ItemIndex:= 0;
FSrcRects[i].Fill.Color:= TAlphaColorRec.Null;
FDstRects[i].Fill.Color:= TAlphaColorRec.Null;
end
else
begin
FCombos[i].Enabled:= True;
FCombos[i].ItemIndex:= img.ColourMap[i] + 1;
FSrcRects[i].Fill.Color:= img.Colours[i];
FDstRects[i].Fill.Color:= ColourForMap(img.ColourMap[i],
img.Colours[i]);
end;
end;
procedure TStepsLibImagesForm.DoRebuildMapView(const AImage: Integer);
var
x,
y,
i,
m: Integer;
p: TAlphaColor;
rd,
wd: TBitmapData;
img: TImgImport;
begin
img:= FImportImgs[AImage];
if img.ImportView.Map(TMapAccess.Read, rd) then
try
if img.MapView.Map(TMapAccess.Write, wd) then
try
for x:= 0 to img.ImportView.Width - 1 do
for y:= 0 to img.ImportView.Height - 1 do
begin
p:= rd.GetPixel(x, y);
m:= -1;
for i:= 0 to img.ColourCnt - 1 do
if img.Colours[i] = p then
begin
m:= i;
Break;
end;
if m > -1 then
m:= img.ColourMap[m];
img.Mapping[x, y]:= m;
p:= ColourForMap(m, p);
wd.SetPixel(x, y, p);
end;
finally
FImportImgs[AImage].MapView.Unmap(wd);
end;
finally
FImportImgs[AImage].ImportView.Unmap(rd);
end;
end;
procedure TStepsLibImagesForm.DoRemapImageColour(const AImage: Integer;
const AColour: TAlphaColor; const AMap: Integer);
var
i: Integer;
img: TImgImport;
begin
img:= FImportImgs[AImage];
for i:= 0 to img.ColourCnt - 1 do
if img.Colours[i] = AColour then
begin
img.ColourMap[i]:= AMap;
Break;
end;
end;
procedure TStepsLibImagesForm.DoUpdateImageView(const AImage: Integer);
begin
Image1.Bitmap.Width:= 320;
Image1.Bitmap.Height:= 200;
if FImportImgs.Items[AImage].CanImport then
begin
Image1.Bitmap.Canvas.BeginScene;
try
Image1.Bitmap.Canvas.DrawBitmap(FImportImgs.Items[AImage].MapView,
RectF(0, 0, 80, 50), RectF(0, 0, 320, 200), 1);
finally
Image1.Bitmap.Canvas.EndScene;
end;
end
else
Image1.Bitmap.Clear(TAlphaColorRec.Crimson);
end;
procedure TStepsLibImagesForm.FormCreate(Sender: TObject);
begin
FSelectedImage:= -1;
FImportImgs:= TList<TImgImport>.Create;
FCombos[0]:= ComboBox1;
FCombos[1]:= ComboBox2;
FCombos[2]:= ComboBox3;
FCombos[3]:= ComboBox4;
FSrcRects[0]:= Rectangle1;
FSrcRects[1]:= Rectangle2;
FSrcRects[2]:= Rectangle3;
FSrcRects[3]:= Rectangle4;
FDstRects[0]:= Rectangle5;
FDstRects[1]:= Rectangle6;
FDstRects[2]:= Rectangle7;
FDstRects[3]:= Rectangle8;
end;
procedure TStepsLibImagesForm.FormDestroy(Sender: TObject);
begin
Clear;
FImportImgs.Free;
end;
function TStepsLibImagesForm.GetImageCount: Integer;
begin
Result:= FImportImgs.Count;
end;
procedure TStepsLibImagesForm.ImageToScreen(const AImage: Integer;
var AScreen: TC64Screen);
var
i,
x,
y: Integer;
img: TImgImport;
c: TC64Colours;
begin
img:= FImportImgs[AImage];
if not img.CanImport then
raise Exception.Create('Invalid image!');
for i:= 0 to img.ColourCnt - 1 do
if img.ColourMap[i] < 0 then
raise Exception.Create('Incomplete mapping!');
for x:= 0 to 39 do
for y:= 0 to 24 do
begin
c[0]:= TC64Colour(img.Mapping[x * 2, y * 2]);
c[1]:= TC64Colour(img.Mapping[x * 2 + 1, y * 2]);
c[2]:= TC64Colour(img.Mapping[x * 2, y * 2 + 1]);
c[3]:= TC64Colour(img.Mapping[x * 2 + 1, y * 2 + 1]);
AScreen[y * 40 + x]:= C64ColorsToIndex(c);
end;
end;
procedure TStepsLibImagesForm.ListBox1Change(Sender: TObject);
begin
if Assigned(ListBox1.Selected) then
begin
Panel1.Visible:= True;
DoDisplayImage(ListBox1.Selected.Tag);
end;
end;
function TStepsLibImagesForm.ShowAddImages(
const AFixed: Boolean): TModalResult;
begin
FFixed:= AFixed;
if not FFixed then
Clear
else
ListBox1.SelectRange(ListBox1.ListItems[0], ListBox1.ListItems[0]);
Button2.Enabled:= not FFixed;
Result:= ShowModal;
end;
end.
|
unit glButton;
interface
uses
{$IFDEF VER230} WinAPI.Windows, WinAPI.Messages {$ELSE} Windows, Messages
{$ENDIF}, SysUtils, Classes, Controls, Graphics, glCustomObject,
PNGimage, glButtonPattern;
type
TglButton = class(TglCustomObject)
private
fViewState: byte;
fLeave, fEnter, fDown: TPicture;
function isEmpty(var value: TPicture): boolean;
protected
procedure Paint; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseEnter(var Msg: TMessage); message cm_mouseEnter;
procedure MouseLeave(var Msg: TMessage); message cm_mouseLeave;
procedure SetLeaveImage(value: TPicture); virtual;
procedure SetEnterImage(value: TPicture); virtual;
procedure SetDownImage(value: TPicture); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AssignPattern(value: TglButtonPattern);
published
property ImageLeave: TPicture read fLeave
write SetLeaveImage;
property ImageEnter: TPicture read fEnter write SetEnterImage;
property ImageDown: TPicture read fDown write SetDownImage;
property OnMouseEnter;
property OnMouseLeave;
end;
procedure Register;
implementation
const
vsLeave = 0;
vsEnter = 1;
vsDown = 2;
procedure Register;
begin
RegisterComponents('Golden Line', [TglButton]);
end;
procedure TglButton.AssignPattern(value: TglButtonPattern);
begin
fDown.Assign(value.ImageDown);
fLeave.Assign(value.ImageLeave);
fEnter.Assign(value.ImageEnter);
Invalidate;
end;
constructor TglButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fLeave := TPicture.Create;
fEnter := TPicture.Create;
fDown := TPicture.Create;
end;
destructor TglButton.Destroy;
begin
inherited Destroy;
fDown.Free;
fEnter.Free;
fLeave.Free;
end;
function TglButton.isEmpty(var value: TPicture): boolean;
var
m: TMemoryStream;
begin
m := TMemoryStream.Create;
value.Graphic.SaveToStream(m);
if m.Size > 0 then
result := false
else
result := true;
FreeAndNil(m);
end;
procedure TglButton.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited;
fViewState := vsDown;
repaint;
end;
procedure TglButton.MouseEnter(var Msg: TMessage);
begin
fViewState := vsEnter;
repaint;
end;
procedure TglButton.MouseLeave(var Msg: TMessage);
begin
fViewState := vsLeave;
repaint;
end;
procedure TglButton.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited;
repaint;
end;
procedure TglButton.Paint;
begin
case fViewState of
0:
Canvas.Draw(0, 0, fLeave.Graphic);
1:
begin
if Assigned(fEnter.Graphic) then
Canvas.Draw(0, 0, fEnter.Graphic)
else
Canvas.Draw(0, 0, fLeave.Graphic);
end;
2:
begin
if Assigned(fDown.Graphic) then
Canvas.Draw(0, 0, fDown.Graphic)
else if Assigned(fEnter.Graphic) then
Canvas.Draw(0, 0, fEnter.Graphic)
else
Canvas.Draw(0, 0, fLeave.Graphic);
end;
end;
inherited;
end;
procedure TglButton.SetDownImage(value: TPicture);
begin
fDown.Assign(value);
Invalidate;
end;
procedure TglButton.SetEnterImage(value: TPicture);
begin
fEnter.Assign(value);
Invalidate;
end;
procedure TglButton.SetLeaveImage(value: TPicture);
begin
fLeave.Assign(value);
Invalidate;
end;
end.
|
unit OperatingSystem;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
TOperatingSystem = class
private
FArchitecture: Integer;
FProductName: String;
public
constructor Create();
property Architecture: Integer read FArchitecture;
property ProductName: String read FProductName;
end;
implementation
uses
{$IFDEF WINDOWS}
uWin32_ComputerSystem, uWin32_OperatingSystem;
{$ENDIF}
{$IFDEF LINUX}
BaseUnix;
{$ENDIF}
constructor TOperatingSystem.Create();
{$IFDEF LINUX}
var
LinuxKernelInfo: UtsName;
begin
FpUname(LinuxKernelInfo);
if (
(LinuxKernelInfo.Machine = 'amd64') or
(LinuxKernelInfo.Machine = 'x86_64')
) then
FArchitecture := 64
else if (
(LinuxKernelInfo.Machine = 'i386') or
(LinuxKernelInfo.Machine = 'i486') or
(LinuxKernelInfo.Machine = 'i586') or
(LinuxKernelInfo.Machine = 'i686')
) then
FArchitecture := 32
else
FArchitecture := 0;
FProductName := LinuxKernelInfo.Sysname + ' ' + LinuxKernelInfo.Release;
end;
{$ENDIF}
{$IFDEF WINDOWS}
var
Arch: String;
Version: TStringList;
Win32_ComputerSystem: TWin32_ComputerSystem;
Win32_OperatingSystem: TWin32_OperatingSystem;
begin
FArchitecture := 0;
Win32_OperatingSystem:= TWin32_OperatingSystem.Create;
Version := TStringList.Create;
Version.Delimiter := '.';
Version.DelimitedText := Win32_OperatingSystem.Version;
if (StrToInt(Version.Strings[0]) >= 6) then
begin
// Windows Vista and newer
Arch := Win32_OperatingSystem.OSArchitecture;
if (Pos('64', Arch) > 0) then
FArchitecture := 64
else // TODO Review
FArchitecture := 32;
end
else
begin
// Windows XP and earlier
Win32_ComputerSystem := TWin32_ComputerSystem.Create;
if (Pos('64', Win32_ComputerSystem.SystemType) > 0) then
FArchitecture := 64
else // TODO Review
FArchitecture := 32;
end;
FProductName := Win32_OperatingSystem.Caption;
end;
{$ENDIF}
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.IDE.ProjectTreeManager;
//an attempt to hack into the IDE project tree.
//since the IDE does not provide any api to do this
//we are drilling into the IDE internals.. messy.
interface
uses
System.Rtti,
Spring.Collections,
Spring.Container,
System.Classes,
Vcl.Controls,
WinApi.Messages,
DPM.Core.Types,
DPM.Core.Options.Search,
DPM.Core.Dependency.Interfaces,
DPM.Core.Project.Interfaces,
DPM.Core.Configuration.Interfaces,
DPM.IDE.Logger,
DPM.IDE.VSTProxy,
DPM.IDE.ProjectTree.Containers,
DPM.IDE.Options;
type
IDPMProjectTreeManager = interface
['{F0BA2907-E337-4591-8E16-FB684AE2E19B}']
procedure EndLoading();
procedure ProjectLoaded(const fileName : string);
procedure ProjectClosed(const fileName : string);
procedure ProjectGroupClosed;
end;
const
WM_PROJECTLOADED = WM_USER + $1234;
type
TDPMProjectTreeManager = class(TInterfacedObject,IDPMProjectTreeManager)
private
FContainer : TContainer;
FLogger : IDPMIDELogger;
FOptions : IDPMIDEOptions;
FWindowHandle : THandle;
FTimerRunning : boolean;
FProjectTreeInstance : TControl;
FVSTProxy : TVirtualStringTreeProxy;
FSearchOptions : TSearchOptions;
FProjectLoadList : IQueue<string>;
FDPMImageIndex : integer;
FPlatformImageIndexes : array[TDPMPlatform] of integer;
//TODO : Invalidate cache when projects close.
FNodeCache : IDictionary<TProjectTreeContainer, PVirtualNode>;
//procedure DumpInterfaces(AClass: TClass);
protected
procedure ProjectLoaded(const fileName : string);
procedure ProjectClosed(const fileName : string);
procedure EndLoading;
procedure ProjectGroupClosed;
procedure WndProc(var msg: TMessage);
function EnsureProjectTree : boolean;
function TryGetContainerTreeNode(const container : TProjectTreeContainer; out containerNode : PVirtualNode) : boolean;
procedure AddChildContainer(const parentContainer, childContainer : TProjectTreeContainer);
procedure AddSiblingContainer(const existingContainer, siblingContainer : TProjectTreeContainer);
function GetProjects : IList<TProjectTreeContainer>;
function FindProjectNode(const fileName : string) : TProjectTreeContainer;
function FindTargetPlatformContainer(const projectContainer : TProjectTreeContainer) : TProjectTreeContainer;
function FindDPMContainer(const projectContainer : TProjectTreeContainer) : TProjectTreeContainer;
procedure ConfigureProjectDPMNode(const projectContainer : TProjectTreeContainer; const projectFile : string; const config : IConfiguration);
procedure UpdateProjectDPMPackages(const targetPlatformsContainer : TProjectTreeContainer; const dpmContainer : TProjectTreeContainer; const projectFile : string; const projectEditor : IProjectEditor);
procedure DoProjectLoaded(const projectFile : string);
procedure DoDumpClass(const typ : TRttiInstanceType);
procedure DumpClass(const obj : TClass);
public
constructor Create(const container : TContainer; const logger : IDPMIDELogger; const options : IDPMIDEOptions);
destructor Destroy;override;
end;
implementation
uses
ToolsApi,
System.TypInfo,
System.SysUtils,
WinApi.Windows,
Vcl.ImgList,
Vcl.Graphics,
Vcl.Forms,
{$IF CompilerVersion >= 35.0}
Vcl.ImageCollection,
Vcl.VirtualImageList,
{$IFEND}
DPM.Core.Constants,
DPM.Core.Logging,
DPM.Core.Options.Common,
DPM.Core.Configuration.Manager,
DPM.Core.Project.Editor,
DPM.IDE.Constants,
DPM.IDE.Utils,
DPM.IDE.Types;
const
cCategoryContainerClass = 'Containers.TStdContainerCategory';
{ TProjectTreeManager }
procedure TDPMProjectTreeManager.AddChildContainer(const parentContainer, childContainer: TProjectTreeContainer);
var
parentNode, childNode : PVirtualNode;
nodeData : PNodeData;
begin
if TryGetContainerTreeNode(parentContainer, parentNode) then
begin
childNode := FVSTProxy.AddChildNode(parentNode);
nodeData := FVSTProxy.GetNodeData(childNode);
nodeData.GraphLocation := childContainer.GraphLocation;
nodeData.GraphData := childContainer.GraphData;
end;
end;
procedure TDPMProjectTreeManager.AddSiblingContainer(const existingContainer, siblingContainer: TProjectTreeContainer);
var
parentNode : PVirtualNode;
childNode : PVirtualNode;
nodeData : PNodeData;
begin
if not TryGetContainerTreeNode(existingContainer, parentNode) then
raise Exception.Create('Unable to find node for project container');
childNode := FVSTProxy.InsertNode(parentNode, TVTNodeAttachMode.amInsertAfter);
nodeData := FVSTProxy.GetNodeData(childNode);
nodeData.GraphLocation := siblingContainer.GraphLocation;
nodeData.GraphData := siblingContainer.GraphData;
end;
procedure TDPMProjectTreeManager.ConfigureProjectDPMNode(const projectContainer: TProjectTreeContainer; const projectFile : string; const config : IConfiguration);
var
dpmContainer : TProjectTreeContainer;
targetPlatformContainer : TProjectTreeContainer;
projectEditor : IProjectEditor;
projectNode : PVirtualNode;
begin
projectEditor := TProjectEditor.Create(FLogger as ILogger, config, IDECompilerVersion);
targetPlatformContainer := FindTargetPlatformContainer(projectContainer);
if targetPlatformContainer = nil then
begin
//the container might not exists yet if the project node was never expanded.
//so we expand and collapse the project node to force it to be created.
projectNode := FNodeCache[projectContainer];
if projectNode <> nil then
begin
FVSTProxy.SetExpanded(projectNode,true);
FVSTProxy.SetExpanded(projectNode,false);
end;
targetPlatformContainer := FindTargetPlatformContainer(projectContainer);
if targetPlatformContainer = nil then
exit;
end;
// DumpClass(targetPlatformContainer.ClassType);
//first see if we have allready added dpm to the project
dpmContainer := FindDPMContainer(projectContainer);
if dpmContainer = nil then
begin
//not found so we need to add it.
try
dpmContainer := TProjectTreeContainer.CreateNewContainer(projectContainer, cDPMPackages, cDPMContainer);
dpmContainer.ImageIndex := FDPMImageIndex;
targetPlatformContainer := FindTargetPlatformContainer(projectContainer);
Assert(targetPlatformContainer <> nil);
//add it to the tree
AddSiblingContainer(targetPlatformContainer, dpmContainer);
//this is important.. add it to the model, without this the dpm node disappears if the IDE rebuilds the tree
projectContainer.Children.Insert(2, dpmContainer); // 0=build config, 1=target platforms
except
on e : Exception do
begin
FLogger.Error(e.Message);
OutputDebugString(PChar(e.Message));
exit;
end;
end;
end;
Application.ProcessMessages;
UpdateProjectDPMPackages(targetPlatformContainer, dpmContainer, projectFile, projectEditor);
end;
constructor TDPMProjectTreeManager.Create(const container : TContainer;const logger : IDPMIDELogger; const options : IDPMIDEOptions);
begin
FContainer := container;
FLogger := logger;
FOptions := options;
FProjectLoadList := TCollections.CreateQueue<string>;
FWindowHandle := AllocateHWnd(WndProc);
//can't find it here as it's too early as our expert is loaded before the project manager is loaded.
FProjectTreeInstance := nil;
FVSTProxy := nil;
FSearchOptions := TSearchOptions.Create;
// This ensures that the default config file is uses if a project one doesn't exist.
FSearchOptions.ApplyCommon(TCommonOptions.Default);
FNodeCache := TCollections.CreateDictionary<TProjectTreeContainer, PVirtualNode>();
end;
destructor TDPMProjectTreeManager.Destroy;
begin
FLogger := nil;
FVSTProxy.Free;
DeallocateHWnd(FWindowHandle);
FSearchOptions.Free;
inherited;
end;
function TDPMProjectTreeManager.EnsureProjectTree : boolean;
var
// i: Integer;
platform : TDPMPlatform;
{$IF CompilerVersion >= 35.0}
imageCollection : TImageCollection;
imageList : TVirtualImageList;
{$ELSE}
bitmap : TBitmap;
imageList : TCustomImageList;
{$IFEND}
begin
if FVSTProxy <> nil then
exit(true);
result := false;
if FVSTProxy = nil then
begin
//control name and class discovered via IDE Explorer https://www.davidghoyle.co.uk/WordPress - need to check it's the same for each new IDE version
FProjectTreeInstance := FindIDEControl('TVirtualStringTree', 'ProjectTree2');
if FProjectTreeInstance <> nil then
begin
FVSTProxy := TVirtualStringTreeProxy.Create(FProjectTreeInstance, FLogger);
{$IF CompilerVersion < 35.0}
imageList := FVSTProxy.Images;
{$ELSE}
imageList := TVirtualImageList(FVSTProxy.Images);
{$IFEND}
for platform := Low(TDPMPlatform) to High(TDPMPlatform) do
FPlatformImageIndexes[platform] := -1;
Result := true;
{$IF CompilerVersion < 35.0}
//10.4 and earlier
bitmap := TBitmap.Create;
try
bitmap.LoadFromResourceName(HInstance, 'DPMLOGOBMP_16');
FDPMImageIndex := imageList.AddMasked(bitmap, clFuchsia);
bitmap.LoadFromResourceName(HInstance, 'PLATFORM_WIN32');
FPlatformImageIndexes[TDPMPlatform.Win32] := imageList.AddMasked(bitmap, clFuchsia);
bitmap.LoadFromResourceName(HInstance, 'PLATFORM_WIN32'); //same for win32/64
FPlatformImageIndexes[TDPMPlatform.Win64] := imageList.AddMasked(bitmap, clFuchsia);
bitmap.LoadFromResourceName(HInstance, 'PLATFORM_MACOS');
FPlatformImageIndexes[TDPMPlatform.OSX32] := imageList.AddMasked(bitmap, clFuchsia);
FPlatformImageIndexes[TDPMPlatform.OSX64] := FPlatformImageIndexes[TDPMPlatform.OSX32];
bitmap.LoadFromResourceName(HInstance, 'PLATFORM_ANDRIOD');
FPlatformImageIndexes[TDPMPlatform.AndroidArm32] := imageList.AddMasked(bitmap, clFuchsia);
FPlatformImageIndexes[TDPMPlatform.AndroidArm64] := FPlatformImageIndexes[TDPMPlatform.AndroidArm32];
FPlatformImageIndexes[TDPMPlatform.AndroidIntel32] := FPlatformImageIndexes[TDPMPlatform.AndroidArm32];
FPlatformImageIndexes[TDPMPlatform.AndroidIntel64] := FPlatformImageIndexes[TDPMPlatform.AndroidArm32];
bitmap.LoadFromResourceName(HInstance, 'PLATFORM_IOS');
FPlatformImageIndexes[TDPMPlatform.iOS32] := imageList.AddMasked(bitmap, clFuchsia);
FPlatformImageIndexes[TDPMPlatform.iOS64] := FPlatformImageIndexes[TDPMPlatform.iOS32];
bitmap.LoadFromResourceName(HInstance, 'PLATFORM_LINUX');
FPlatformImageIndexes[TDPMPlatform.LinuxIntel32] := imageList.AddMasked(bitmap, clFuchsia);
FPlatformImageIndexes[TDPMPlatform.LinuxIntel64] := FPlatformImageIndexes[TDPMPlatform.LinuxIntel32];
FPlatformImageIndexes[TDPMPlatform.LinuxArm32] := FPlatformImageIndexes[TDPMPlatform.LinuxIntel32];
FPlatformImageIndexes[TDPMPlatform.LinuxArm64] := FPlatformImageIndexes[TDPMPlatform.LinuxIntel32];
finally
bitmap.Free;
end;
{$ELSE}
//11.x and later uses an imagecollection so it's easy to lookup the built in images and use those.
//just need to add our logo image to the collection and then the image list.
imageCollection := TImageCollection(TVirtualImageList(imageList).ImageCollection);
imageCollection.Add('DPM\DPMLOGO', HInstance, 'DPMLOGO', ['_16','_24','_32']);
imageList.Add('DPM\DPMLOGO','DPM\DPMLOGO');
//TODO : This sometimes doesn't work and we end up with the wrong icon. Only seems to happen'
// when loading large project groups.
FDPMImageIndex := imageList.GetIndexByName('DPM\DPMLOGO');
FPlatformImageIndexes[TDPMPlatform.Win32] := imageList.GetIndexByName('Platforms\PlatformWindows');
FPlatformImageIndexes[TDPMPlatform.Win64] := FPlatformImageIndexes[TDPMPlatform.Win32];
FPlatformImageIndexes[TDPMPlatform.OSX32] := imageList.GetIndexByName('Platforms\PlatformMacOS');
FPlatformImageIndexes[TDPMPlatform.OSX64] := FPlatformImageIndexes[TDPMPlatform.OSX32];
FPlatformImageIndexes[TDPMPlatform.AndroidArm32] := imageList.GetIndexByName('Platforms\PlatformAndroid');
FPlatformImageIndexes[TDPMPlatform.AndroidArm64] := FPlatformImageIndexes[TDPMPlatform.AndroidArm32];
FPlatformImageIndexes[TDPMPlatform.AndroidIntel32] := FPlatformImageIndexes[TDPMPlatform.AndroidArm32];
FPlatformImageIndexes[TDPMPlatform.AndroidIntel64] := FPlatformImageIndexes[TDPMPlatform.AndroidArm32];
FPlatformImageIndexes[TDPMPlatform.iOS32] := imageList.GetIndexByName('Platforms\PlatformiOS');
FPlatformImageIndexes[TDPMPlatform.iOS64] := FPlatformImageIndexes[TDPMPlatform.iOS32];
FPlatformImageIndexes[TDPMPlatform.LinuxIntel32] := imageList.GetIndexByName('Platforms\PlatformLinux');
FPlatformImageIndexes[TDPMPlatform.LinuxIntel64] := FPlatformImageIndexes[TDPMPlatform.LinuxIntel32];
FPlatformImageIndexes[TDPMPlatform.LinuxArm32] := FPlatformImageIndexes[TDPMPlatform.LinuxIntel32];
FPlatformImageIndexes[TDPMPlatform.LinuxArm64] := FPlatformImageIndexes[TDPMPlatform.LinuxIntel32];
{$IFEND}
end;
end;
end;
function TDPMProjectTreeManager.FindDPMContainer(const projectContainer: TProjectTreeContainer): TProjectTreeContainer;
var
childContainer : TProjectTreeContainer;
children : IInterfaceList;
i : integer;
begin
children := projectContainer.Children;
for i := 0 to children.Count -1 do
begin
childContainer := TProjectTreeContainer(children[i] as TObject);
if SameText(childContainer.DisplayName, cDPMPackages ) then
exit(childContainer);
end;
result := nil;
end;
function TDPMProjectTreeManager.FindProjectNode(const fileName: string): TProjectTreeContainer;
var
displayName : string;
rootNode, projectNode : PVirtualNode;
nodeData: PNodeData;
container : TProjectTreeContainer;
project : ICustomProjectGroupProject;
// graphLocation : IInterface;
// graphData : IInterface;
begin
result := nil;
displayName := ChangeFileExt(ExtractFileName(fileName),'');
rootNode := FVSTProxy.GetFirstVisibleNode;
if Assigned(rootNode) then
begin
projectNode := FVSTProxy.GetFirstChild(rootNode);
while projectNode <> nil do
begin
nodeData := FVSTProxy.GetNodeData(projectNode);
//DumpClass((nodeData.GraphLocation as TObject).ClassType);
container := TProjectTreeContainer(nodeData.GraphLocation as TObject);
if Assigned(container) then
begin
project := container.Project;
if project <> nil then
begin
if SameText(container.FileName, fileName) then
begin
// graphLocation := container.GraphLocation;
// graphData := container.GraphData;
//take this opportunity to cache the node.
FNodeCache[container] := projectNode;
exit(container);
end;
end;
end;
projectNode := FVSTProxy.GetNextSibling(projectNode);
end;
end;
end;
function TDPMProjectTreeManager.FindTargetPlatformContainer(const projectContainer: TProjectTreeContainer): TProjectTreeContainer;
var
childContainer : TProjectTreeContainer;
children : IInterfaceList;
i : integer;
begin
result := nil;
children := projectContainer.Children;
if children = nil then
begin
FLogger.Debug('projectContainer children Empty for ' + projectContainer.DisplayName);
exit;
end;
for i := 0 to children.Count -1 do
begin
childContainer := TProjectTreeContainer(children[i] as TObject);
if SameText(childContainer.ClassName, 'TBasePlatformContainer') then //class name comes from rtti inspection
exit(childContainer);
end;
end;
function TDPMProjectTreeManager.GetProjects: IList<TProjectTreeContainer>;
var
rootNode, projectNode: Pointer;
nodeData: PNodeData;
proxy : TProjectTreeContainer;
begin
//
Assert(EnsureProjectTree);
result := TCollections.CreateList<TProjectTreeContainer>();
rootNode := FVSTProxy.GetFirstVisibleNode;
if Assigned(rootNode) then
begin
projectNode := FVSTProxy.GetFirstChild(rootNode);
while projectNode <> nil do
begin
nodeData := FVSTProxy.GetNodeData(projectNode);
proxy := TProjectTreeContainer(nodeData.GraphLocation as TObject);
//FLogger.Debug('Project Container ' + proxy.DisplayName);
if Assigned(proxy) then
result.Add(proxy);
//DumpClass(proxy.ClassType);
projectNode := FVSTProxy.GetNextSibling(projectNode);
end;
end;
end;
procedure TDPMProjectTreeManager.EndLoading;
begin
if not FOptions.AddDPMToProjectTree then
exit;
//kick off a timer that will eventually sort out the nodes. - see WndProc
PostMessage(FWindowHandle, WM_PROJECTLOADED, 0,0);
end;
procedure TDPMProjectTreeManager.ProjectClosed(const fileName: string);
//var
// projectContainer : TProjectTreeContainer;
begin
//not ideal.. but not sure it will be a problem.. we don't really need the nodes
//after it's all setup. When we add packages etc, that triggers a project reload
//so the tree is built again.
FNodeCache.Clear;
// this doesn't work, the container's project is already gone when we get here so FindProjectNode fails.
// projectContainer := FindProjectNode(fileName);
// if projectContainer <> nil then
// begin
// if FNodeCache.ContainsKey(projectContainer) then
// FNodeCache.Remove(projectContainer);
// end;
end;
procedure TDPMProjectTreeManager.ProjectLoaded(const fileName: string);
begin
if not FOptions.AddDPMToProjectTree then
exit;
//The project tree nodes do not seem to have been added at this stage
//just enqueue the project, and we'll deal with it when all projects are loaded.
FProjectLoadList.Enqueue(fileName);
end;
procedure TDPMProjectTreeManager.ProjectGroupClosed;
begin
FNodeCache.Clear;
end;
function TDPMProjectTreeManager.TryGetContainerTreeNode(const container: TProjectTreeContainer; out containerNode: PVirtualNode): boolean;
var
node : PVirtualNode;
nodeData : PNodeData;
begin
containerNode := nil;
result := false;
if FNodeCache.TryGetValue(container, containerNode) then
exit(true);
node := FVSTProxy.GetFirstNode;
while node <> nil do
begin
nodeData := FVSTProxy.GetNodeData(node);
if container = (nodeData.GraphLocation as TObject) then
begin
containerNode := node;
FNodeCache[container] := containerNode;
exit(true);
end
else
begin
if nodeData.GraphLocation <> nil then
FNodeCache[TProjectTreeContainer(nodeData.GraphLocation as TObject)] := node;
end;
node := FVSTProxy.GetNextNode(node);
end;
end;
procedure TDPMProjectTreeManager.UpdateProjectDPMPackages(const targetPlatformsContainer : TProjectTreeContainer; const dpmContainer: TProjectTreeContainer; const projectFile : string; const projectEditor : IProjectEditor);
var
projectGroup : IOTAProjectGroup;
project : IOTAProject;
sConfigFile : string;
pf : TDPMPlatform;
dpmNode : PVirtualNode;
dpmChildren : IInterfaceList;
platformSortedList : TStringList;
i : integer;
platformPackageReferences : IPackageReference;
function FindProject : IOTAProject;
var
j : integer;
begin
result := nil;
for j := 0 to projectGroup.ProjectCount -1 do
begin
if SameText(projectGroup.Projects[j].FileName, projectFile) then
exit(projectGroup.Projects[j]);
end;
end;
//TODO: Figure out image indexes for platforms.
function DPMPlatformImageIndex(const pf : TDPMPlatform) : integer;
begin
result := FPlatformImageIndexes[pf];
//
// case pf of
// TDPMPlatform.UnknownPlatform: ;
// TDPMPlatform.Win32: result := FPlatformImageIndexes[pf];
// TDPMPlatform.Win64: result := 94;
// TDPMPlatform.WinArm32: ;
// TDPMPlatform.WinArm64: ;
// TDPMPlatform.OSX32: result := 91;
// TDPMPlatform.OSX64: result := 91;
// TDPMPlatform.AndroidArm32: result := 95;
// TDPMPlatform.AndroidArm64: result := 95;
// TDPMPlatform.AndroidIntel32: ;
// TDPMPlatform.AndroidIntel64: ;
// TDPMPlatform.iOS32: result := 96;
// TDPMPlatform.iOS64: result := 93;
// TDPMPlatform.LinuxIntel32: result := 92;
// TDPMPlatform.LinuxIntel64: result := 92;
// TDPMPlatform.LinuxArm32: ;
// TDPMPlatform.LinuxArm64: ;
// end;
end;
procedure AddPlatform(const pf : TDPMPlatform; const PackageReferences : IPackageReference);
var
platformContainer : TProjectTreeContainer;
packageRef : IPackageReference;
procedure AddPackage(const parentContainer : TProjectTreeContainer; const packageReference : IPackageReference; const children : IInterfaceList);
var
packageRefContainer : TProjectTreeContainer;
depRef : IPackageReference;
begin
packageRefContainer := TProjectTreeContainer.CreateNewContainer(parentContainer, packageReference.ToIdVersionString,cDPMContainer);
packageRefContainer.ImageIndex := -1;
AddChildContainer(parentContainer, packageRefContainer);
children.Add(packageRefContainer);
if packageReference.HasDependencies then
begin
packageRefContainer.Children := TInterfaceList.Create;
for depRef in packageReference.Dependencies do
begin
AddPackage(packageRefContainer, depRef, packageRefContainer.Children);
end;
end;
end;
begin
platformContainer := TProjectTreeContainer.CreateNewContainer(dpmContainer, DPMPlatformToDisplayString(pf),cDPMContainer);
platformContainer.ImageIndex := DPMPlatformImageIndex(pf);
AddChildContainer(dpmContainer, platformContainer);
dpmChildren.Add(platformContainer);
if PackageReferences.HasDependencies then
begin
platformContainer.Children := TInterfaceList.Create;
//using for loop rather the enumerator for per reasons.
for packageRef in PackageReferences.Dependencies do
begin
if packageRef.Platform <> pf then
continue;
AddPackage(platformContainer, packageRef, platformContainer.Children);
end;
end;
end;
begin
Assert(dpmContainer <> nil);
projectGroup := (BorlandIDEServices as IOTAModuleServices).MainProjectGroup;
//projectGroup.FindProject doesn't work! so we do it ourselves.
project := FindProject;
if project = nil then
exit;
dpmChildren := dpmContainer.Children;
//Clear dpm node before doing this
if dpmChildren <> nil then
begin
dpmChildren.Clear;
if TryGetContainerTreeNode(dpmContainer, dpmNode) then
FVSTProxy.DeleteChildren(dpmContainer);
end
else
begin
//the container classes don't create the list, so we must.
dpmChildren := TInterfaceList.Create;
dpmContainer.Children := dpmChildren;
end;
//if there is a project specific config file then that is what we should use.
sConfigFile := IncludeTrailingPathDelimiter(ExtractFilePath(project.FileName)) + cDPMConfigFileName;
if FileExists(sConfigFile) then
FSearchOptions.ConfigFile := sConfigFile;
if projectEditor.LoadProject(projectFile) then
begin
platformSortedList := TStringList.Create;
platformSortedList.Sorted := true;
try
for pf in projectEditor.Platforms do
platformSortedList.AddObject(DPMPlatformToString(pf), TObjecT(Ord(pf)));
for i := 0 to platformSortedList.Count -1 do
begin
pf := TDPMPlatform(Integer(platformSortedList.Objects[i]));
platformPackageReferences := projectEditor.GetPackageReferences(pf);
if platformPackageReferences <> nil then
AddPlatform(pf, platformPackageReferences);
end;
finally
platformSortedList.Free;
end;
// FLogger.Debug('Target platform : ' + DPMPlatformToString(pf));
// Application.ProcessMessages;
end;
end;
procedure TDPMProjectTreeManager.DoDumpClass(const typ: TRttiInstanceType);
var
Field : TRttiField;
Prop: TRttiProperty;
IndexProp : TRttiIndexedProperty;
intfType : TRttiInterfaceType;
method : TRttiMethod;
sMethod : string;
begin
OutputDebugString(PChar(''));
OutputDebugString(PChar('class ' + Typ.Name +' = class(' + Typ.MetaclassType.ClassParent.ClassName + ')'));
for intfType in Typ.GetImplementedInterfaces do
begin
OutputDebugString(PChar(' implements interface ' + intfType.Name + ' [' + intfType.GUID.ToString + ']'));
end;
OutputDebugString(PChar(''));
for Field in Typ.GetDeclaredFields do
begin
OutputDebugString(PChar(' ' + Field.Name + ' : ' + Field.FieldType.Name));
end;
OutputDebugString(PChar(''));
for Prop in Typ.GetDeclaredProperties do
begin
OutputDebugString(PChar(' property ' + Prop.Name + ' : ' + prop.PropertyType.Name));
if prop.PropertyType is TRttiInterfaceType then
begin
intfType := prop.PropertyType as TRttiInterfaceType;
OutputDebugString(PChar('interface ' + intfType.Name + ' [' + intfType.GUID.ToString + ']'));
end;
end;
for IndexProp in Typ.GetDeclaredIndexedProperties do
begin
OutputDebugString(PChar(' property ' + IndexProp.Name + '[] : ' + IndexProp.PropertyType.Name));
end;
OutputDebugString(PChar(''));
for method in Typ.GetDeclaredMethods do
begin
sMethod := method.Name;
if method.ReturnType <> nil then
sMethod := ' function ' + sMethod + ' : ' + method.ReturnType.Name
else if method.IsConstructor then
sMethod := ' constructor ' + sMethod
else if method.IsDestructor then
sMethod := ' destructor ' + sMethod
else
sMethod := ' procedure ' + sMethod;
OutputDebugString(PChar(sMethod));
end;
end;
procedure TDPMProjectTreeManager.DoProjectLoaded(const projectFile : string);
var
projectContainer : TProjectTreeContainer;
configurationManager : IConfigurationManager;
config : IConfiguration;
begin
//load our dpm configuration
configurationManager := FContainer.Resolve<IConfigurationManager>;
config := configurationManager.LoadConfig(FSearchOptions.ConfigFile);
EnsureProjectTree;
projectContainer := FindProjectNode(projectFile);
if projectContainer <> nil then
ConfigureProjectDPMNode(projectContainer, projectFile, config)
else
FLogger.Debug('project container not found for ' + projectfile);
end;
procedure TDPMProjectTreeManager.DumpClass(const obj: TClass);
var
Ctx: TRttiContext;
typ : TRttiInstanceType;
begin
if not (obj.ClassParent = TObject) then
DumpClass(obj.ClassParent);
Typ := Ctx.GetType(obj).AsInstance;
DoDumpClass(typ);
end;
//procedure TDPMProjectTreeManager.DumpInterfaces(AClass: TClass);
//var
// i : integer;
// InterfaceTable: PInterfaceTable;
// InterfaceEntry: PInterfaceEntry;
//begin
// while Assigned(AClass) do
// begin
// InterfaceTable := AClass.GetInterfaceTable;
// if Assigned(InterfaceTable) then
// begin
// OutputDebugString(PChar('Implemented interfaces in ' + AClass.ClassName));
// for i := 0 to InterfaceTable.EntryCount-1 do
// begin
// InterfaceEntry := @InterfaceTable.Entries[i];
//
// OutputDebugString(PChar(Format('%d. GUID = %s offest = %s',[i, GUIDToString(InterfaceEntry.IID), IntToHex(InterfaceEntry.IOffset,2)])));
// end;
// end;
// AClass := AClass.ClassParent;
// end;
// writeln;
//end;
procedure TDPMProjectTreeManager.WndProc(var msg: TMessage);
var
project : string;
begin
case msg.Msg of
WM_PROJECTLOADED :
begin
if FTimerRunning then
begin
KillTimer(FWindowHandle, 1);
FTimerRunning := false;
end;
//if we try too early, the tree might not exist yet
//or the images are not added to the list and we get the
//wrong image indexes for the platforms.
SetTimer(FWindowHandle, 1, 500, nil);
FTimerRunning := true;
msg.Result := 1;
end;
WM_TIMER :
begin
if msg.WParam = 1 then
begin
//sometimes the tree isn't actually available when we get here.
//in that case we'll just let the timer continue and try again later.
if EnsureProjectTree then
begin
//stop the timer.
FTimerRunning := false;
KillTimer(FWindowHandle, 1);
FVSTProxy.BeginUpdate;
try
while FProjectLoadList.TryDequeue(project) do
begin
DoProjectLoaded(project);
end;
finally
FVSTProxy.EndUpdate;
end;
end;
msg.Result := 1;
end;
end
else
Msg.Result := DefWindowProc(FWindowHandle, Msg.Msg, Msg.wParam, Msg.lParam);
end;
end;
end.
|
unit BmpToDIB;
interface
uses
Windows;
function WIDTHBYTES(bits : DWORD) : DWORD;
function DIBNumColors( lpbi : PBITMAPINFOHEADER ) : WORD;
function PaletteSize( lpbi : PBITMAPINFOHEADER ) : WORD;
function BitmapToDIB(hBitmap : HBITMAP; hPal : HPALETTE) : THandle;
implementation
function WIDTHBYTES(bits : DWORD) : DWORD;
begin
WIDTHBYTES := ((((bits) + 31) div 32) * 4);
end;
function DIBNumColors( lpbi : PBITMAPINFOHEADER ) : WORD;
var
wBitCount : WORD;
dwClrUsed : DWORD;
begin
dwClrUsed := lpbi^.biClrUsed;
if (dwClrUsed <> 0) then
begin
DIBNumColors := dwClrUsed;
exit;
end;
wBitCount := lpbi^.biBitCount;
case wBitCount of
1: DIBNumColors := 2;
4: DIBNumColors := 16;
8: DIBNumColors := 256;
else
DIBNumColors := 0;
end;
end;
function PaletteSize( lpbi : PBITMAPINFOHEADER ) : WORD;
begin
PaletteSize := ( DIBNumColors( lpbi ) * SizeOf( RGBQUAD ) );
end;
function BitmapToDIB(hBitmap : HBITMAP; hPal : HPALETTE) : THandle;
var
bm : BITMAP; // bitmap structure
bi : BITMAPINFOHEADER; // bitmap header
lpbi : PBITMAPINFOHEADER; // pointer to BITMAPINFOHEADER
dwLen : DWORD; // size of memory block
hDIB, h : THandle; // handle to DIB, temp handle
hDC : Windows.HDC; // handle to DC
biBits : WORD; // bits per pixel
begin
// check if bitmap handle is valid
if (hBitmap = 0) then
begin
BitmapToDIB := 0;
exit;
end;
// fill in BITMAP structure, return NULL if it didn't work
if (GetObject(hBitmap, SizeOf(bm), @bm) = 0) then
begin
BitmapToDIB := 0;
exit;
end;
// if no palette is specified, use default palette
if (hPal = 0) then
hPal := GetStockObject(DEFAULT_PALETTE);
// calculate bits per pixel
biBits := bm.bmPlanes * bm.bmBitsPixel;
// make sure bits per pixel is valid
if (biBits <= 1) then
biBits := 1
else if (biBits <= 4) then
biBits := 4
else if (biBits <= 8) then
biBits := 8
else // if greater than 8-bit, force to 24-bit
biBits := 24;
// initialize BITMAPINFOHEADER
bi.biSize := SizeOf(BITMAPINFOHEADER);
bi.biWidth := bm.bmWidth;
bi.biHeight := bm.bmHeight;
bi.biPlanes := 1;
bi.biBitCount := biBits;
bi.biCompression := BI_RGB;
bi.biSizeImage := 0;
bi.biXPelsPerMeter := 0;
bi.biYPelsPerMeter := 0;
bi.biClrUsed := 0;
bi.biClrImportant := 0;
// calculate size of memory block required to store BITMAPINFO
dwLen := bi.biSize + PaletteSize(@bi);
// get a DC
hDC := GetDC(0);
// select and realize our palette
hPal := SelectPalette(hDC, hPal, FALSE);
RealizePalette(hDC);
// alloc memory block to store our bitmap
hDIB := GlobalAlloc(GHND, dwLen);
// if we couldn't get memory block
if (hDIB = 0) then
begin
// clean up and return NULL
SelectPalette(hDC, hPal, TRUE);
RealizePalette(hDC);
ReleaseDC(0, hDC);
BitmapToDIB := 0;
exit;
end;
// lock memory and get pointer to it
lpbi := GlobalLock(hDIB);
/// use our bitmap info. to fill BITMAPINFOHEADER
lpbi^ := bi;
// call GetDIBits with a NULL lpBits param, so it will calculate the
// biSizeImage field for us
GetDIBits(hDC, hBitmap, 0, bi.biHeight, NIL, PBITMAPINFO(lpbi)^, DIB_RGB_COLORS);
// get the info. returned by GetDIBits and unlock memory block
bi := lpbi^;
GlobalUnlock(hDIB);
// if the driver did not fill in the biSizeImage field, make one up
if (bi.biSizeImage = 0) then
bi.biSizeImage := WIDTHBYTES(bm.bmWidth * biBits) * bm.bmHeight;
// realloc the buffer big enough to hold all the bits
dwLen := bi.biSize + PaletteSize(@bi) + bi.biSizeImage;
h := GlobalReAlloc(hDIB, dwLen, 0);
if (h <> 0) then
hDIB := h
else
begin
// clean up and return NULL
GlobalFree(hDIB);
SelectPalette(hDC, hPal, TRUE);
RealizePalette(hDC);
ReleaseDC(0, hDC);
BitmapToDIB := 0;
exit;
end;
// lock memory block and get pointer to it */
lpbi := GlobalLock(hDIB);
// call GetDIBits with a NON-NULL lpBits param, and actualy get the
// bits this time
if (GetDIBits(hDC, hBitmap, 0, bi.biHeight, (PCHAR(lpbi) + lpbi^.biSize + PaletteSize(lpbi)), PBITMAPINFO(lpbi)^, DIB_RGB_COLORS) = 0) then
begin
// clean up and return NULL
GlobalUnlock(hDIB);
SelectPalette(hDC, hPal, TRUE);
RealizePalette(hDC);
ReleaseDC(0, hDC);
BitmapToDIB := 0;
exit;
end;
bi := lpbi^;
// clean up
GlobalUnlock(hDIB);
SelectPalette(hDC, hPal, TRUE);
RealizePalette(hDC);
ReleaseDC(0, hDC);
// return handle to the DIB
BitmapToDIB := hDIB;
end;
end.
|
unit HashAlgSHA256_U;
// Description: SHA-256 Hash (Wrapper for the SHA-256 Hashing Engine)
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Classes,
HashAlg_U,
HashValue_U,
HashAlgSHA256Engine_U;
type
THashAlgSHA256 = class(THashAlg)
private
shaXXXEngine: THashAlgSHA256Engine;
context: SHA256_CTX;
protected
{ Protected declarations }
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure Init(); override;
procedure Update(const input: array of byte; const inputLen: cardinal); override;
procedure Final(digest: THashValue); override;
function PrettyPrintHashValue(const theHashValue: THashValue): string; override;
published
{ Published declarations }
end;
procedure Register;
implementation
uses
SysUtils; // needed for fmOpenRead
procedure Register;
begin
RegisterComponents('Hash', [THashAlgSHA256]);
end;
constructor THashAlgSHA256.Create(AOwner: TComponent);
begin
inherited;
shaXXXEngine:= THashAlgSHA256Engine.Create();
fTitle := 'SHA-256';
fHashLength := 256;
fBlockLength := 512;
end;
destructor THashAlgSHA256.Destroy();
begin
// Nuke any existing context before freeing off the engine...
shaXXXEngine.SHA256Init(context);
shaXXXEngine.Free();
inherited;
end;
procedure THashAlgSHA256.Init();
begin
shaXXXEngine.SHA256Init(context);
end;
procedure THashAlgSHA256.Update(const input: array of byte; const inputLen: cardinal);
begin
shaXXXEngine.SHA256Update(context, input, inputLen);
end;
procedure THashAlgSHA256.Final(digest: THashValue);
begin
shaXXXEngine.SHA256Final(digest, context);
end;
function THashAlgSHA256.PrettyPrintHashValue(const theHashValue: THashValue): string;
var
retVal: string;
begin
retVal := inherited PrettyPrintHashValue(theHashValue);
insert(' ', retVal, 57);
insert(' ', retVal, 49);
insert(' ', retVal, 41);
insert(' ', retVal, 33);
insert(' ', retVal, 25);
insert(' ', retVal, 17);
insert(' ', retVal, 9);
Result := retVal;
end;
END.
|
unit UtilFunc;
interface
uses
windows,
messages,
CommDlg;
//
//--------------- Global Types, Constants and Variables ----------
//
const
IDM_EXIT = 200;
IDM_TEST = 201;
IDM_ABOUT = 202;
type
TTestProc = procedure(hWnd:HWND);
TNotifyMessage = procedure (var Msg:TMessage);
const
clrBlack = $000000;
clrMaroon = $000080;
clrGreen = $008000;
clrOlive = $008080;
clrNavy = $800000;
clrPurple = $800080;
clrTeal = $808000;
clrGray = $808080;
clrSilver = $C0C0C0;
clrRed = $0000FF;
clrLime = $00FF00;
clrYellow = $00FFFF;
clrBlue = $FF0000;
clrFuchsia = $FF00FF;
clrAqua = $FFFF00;
clrLtGray = $C0C0C0;
clrDkGray = $808080;
clrWhite = $FFFFFF;
//
//--------------- window support functions ------------------------
//
function GetExeName: string;
function MakeMainWindow(WndProc:TFNWndProc): HWND;
function MessageLoopNormal: integer;
function ChangeWindowPos(hWindow: HWND; x,y: integer):Boolean;
function ChangeWindowSize(hWindow: HWND; cx,cy: integer):Boolean;
function ChangeWindowZOrder(hWindow: HWND; hWndInsertAfter: HWND):Boolean;
function CenterWindow(hWindow: HWND): Boolean;
function EraseBkGnd(hWindow: HWND;Clr:COLORREF;DC: HDC):LRESULT;
procedure MakeInitMenu(hWindow: HWND);
procedure InitMenuCommand(var Msg: TMessage;OnTest:TTestProc);
function WindowInfo(sobject: string;hWindow: HWND): string;
function ClassInfo(hWindow:HWND):string;
procedure FindOtherInstance(classname: string);
//
//--------------- utility functions -------------------------------
//
function wsprintf1(Output,Format: PChar;pr1: integer): Integer; cdecl;
function wsprintf2(Output,Format: PChar;pr1,pr2: integer): Integer; cdecl;
function wsprintf3(Output,Format: PChar;pr1,pr2,pr3: integer): Integer; cdecl;
function wsprintf4(Output,Format: PChar;pr1,pr2,pr3,pr4: integer): Integer; cdecl;
function AIntToStr(value: integer):string;
function AIntToHex(value: Integer; digits: Integer): string;
function clrBtnFace: COLORREF;
function clrWindow: COLORREF;
function clrGrayText: COLORREF;
function SetDim(x,y,width,height: Integer):TRect;
function DoChooseFont(hOwner: HWND;var ALogFont: TLogFont; Flag: DWORD;
var Color: COLORREF): Boolean;
procedure DrawBitmap(DC:HDC;hBit:HBITMAP;x,y:integer);
implementation
//
//--------------- window support functions ------------------------
//
function GetLowDir(var Path: string): Boolean;
var
p,Len: integer;
begin
result := false;
p := Pos('\',Path);
if p <> 0 then begin
result := true;
Len := Length(Path)-p;
Path := Copy(Path,p+1,Len);
SetLength(Path,Len);
end;
end;
function GetExeName: string;
var
s,t: string;
buf: array[0..MAX_PATH] of Char;
Len: integer;
begin
Len := GetModuleFileName(0,buf,SizeOf(buf));
SetString(s,buf,Len);
t := s;
while GetLowDir(t) do s := t;
Len := Pos('.',s);
result := Copy(s,0,Len-1);
end;
function MakeMainWindow(WndProc:TFNWndProc): HWND;
var
wc: TWndClass;
hWindow: HWND;
s: string;
begin
s := GetExeName;
wc.lpszClassName := PChar(s);
wc.lpfnWndProc := WndProc;
wc.style := CS_VREDRAW or CS_HREDRAW;
wc.hInstance := hInstance;
wc.hIcon := LoadIcon(0,IDI_APPLICATION);
wc.hCursor := LoadCursor(0,IDC_ARROW);
wc.hbrBackground := (COLOR_WINDOW+1);
wc.lpszMenuName := nil;
wc.cbClsExtra := 0;
wc.cbWndExtra := 0;
RegisterClass( wc );
hWindow := CreateWindowEx(WS_EX_CONTROLPARENT or WS_EX_WINDOWEDGE,
PChar(s),
PChar(s),
WS_VISIBLE or WS_OVERLAPPEDWINDOW,
200,100,
300,200,
0,
0,
hInstance,
nil);
ShowWindow(hWindow,CmdShow);
UpDateWindow(hWindow);
result := hWindow;
end;
function MessageLoopNormal: integer;
var
Msg: TMsg;
begin
while GetMessage(Msg, 0, 0, 0) do begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
result := Msg.wParam;
end;
function ChangeWindowPos(hWindow: HWND; x,y: integer):Boolean;
begin
result := SetWindowPos(hWindow,0,x,y,0,0,SWP_NOSIZE or SWP_NOZORDER);
end;
function ChangeWindowSize(hWindow: HWND; cx,cy: integer):Boolean;
begin
result := SetWindowPos(hWindow,0,0,0,cx,cy,SWP_NOMOVE or SWP_NOZORDER);
end;
function ChangeWindowZOrder(hWindow: HWND; hWndInsertAfter: HWND):Boolean;
begin
result := SetWindowPos(hWindow,hWndInsertAfter,0,0,0,0,SWP_NOSIZE or SWP_NOMOVE);
end;
function CenterWindow(hWindow: HWND): Boolean;
var
r:TRect;
CSX,CSY,w,h: integer;
begin
CSX := GetSystemMetrics(SM_CXSCREEN);
CSY := GetSystemMetrics(SM_CYSCREEN);
GetWindowRect(hWindow,r);
w := r.Right-r.Left;
h := r.Bottom-r.Top;
result := ChangeWindowPos(hWindow,(CSX-w) div 2, (CSY-h) div 2);
end;
function EraseBkGnd(hWindow: HWND;Clr:COLORREF;DC: HDC):LRESULT;
var
hBr: hBrush;
r: TRect;
begin
hBr := CreateSolidBrush(Clr);
GetClientRect(hWindow,r);
FillRect(DC,r,hBr);
DeleteObject(hBr);
result := 1;
end;
procedure MakeInitMenu(hWindow: HWND);
var
hM, hMp: HMENU;
begin
hM := CreateMenu;
hMp := CreateMenu;
AppendMenu(hMp,MF_STRING,IDM_EXIT, 'E&xit');
AppendMenu(hM,MF_POPUP,hMp,'&File');
AppendMenu(hM, MF_STRING, IDM_TEST, '&Test!');
hMp := CreateMenu;
AppendMenu(hMp,MF_STRING,IDM_ABOUT, '&About..');
AppendMenu(hM,MF_POPUP,hMp,'&Help');
SetMenu(hWindow,hM);
end;
procedure InitMenuCommand(var Msg: TMessage;OnTest:TTestProc);
var
hWindow: HWND;
s: string;
begin
hWindow := Msg.Msg;
if Msg.WParamHi=0 then // Menu=0,Accel=1,NotifyCode=Control
case Msg.WParamLo of
IDM_EXIT: DestroyWindow(hWindow);
IDM_TEST: OnTest(hWindow);
IDM_ABOUT:begin
s := 'OBJECT PASCAL API PROGRAM '+#13#13+
' By Delphian Inc.,'+#13#13+
' Created by Delphi 3 '+#13#13;
MessageBox(hWindow,PChar(s),'About ...',MB_OK);
end;
end;
end;
function WindowInfo(sobject: string;hWindow: HWND): string;
var
s: string;
c: array[0..50] of Char;
begin
GetWindowText(hWindow,c,50);
s := 'WindowInfo of '+sobject+#13#13;
s := s+'TEXT = '+ string(c)+#13;
s := s+'HANDLE = $'+ AIntToHex(hWindow,8)+#13;
s := s+'EXSTYLE = $'+ AIntToHex(GetWindowLong(hWindow,GWL_EXSTYLE),8)+#13;
s := s+'STYLE = $' + AIntToHex(GetWindowLong(hWindow,GWL_STYLE),8)+#13;
s := s+'WNDPROC = $' + AIntToHex(GetWindowLong(hWindow,GWL_WNDPROC),8)+#13;
s := s+'HINSTANCE = $'+ AIntToHex(GetWindowLong(hWindow,GWL_HINSTANCE),8)+#13;
s := s+'HWNDPARENT = $'+ AIntToHex(GetWindowLong(hWindow,GWL_HWNDPARENT),8)+#13;
s := s+'ID = '+ AIntToStr(GetWindowLong(hWindow,GWL_ID));
result := s;
end;
function ClassInfo(hWindow:HWND):string;
var
WC: TWndClass;
c: array[0..50] of Char;
s: string;
i: integer;
w: word;
begin
GetClassName(hWindow,c,50);
GetClassInfo(hInstance,c,WC);
s := 'ClassInfo of '+ string(c)+#13#13+
'Style = $'+ AIntToHex(WC.Style,8)+#13+
'WndProc = $' + AIntToHex(integer(WC.lpfnWndProc),8)+#13+
'hInstance = $' + AIntToHex(WC.hInstance,8)+#13+
'ClsExtra = ' + AIntToStr(WC.cbClsExtra)+' byte'#13;
if WC.cbClsExtra > 0 then begin
s := s+' ClsExtraData = ';
for i := 0 to (WC.cbClsExtra div 2) -1 do begin
w := GetClassWord(hWindow,i);
s := s+AIntToHex(LOBYTE(w),1)+AIntToHex(HIBYTE(w),1);
end;
s := s+#13;
end;
s := s+'WndExtra = ' + AIntToStr(WC.cbWndExtra)+' byte'#13;
if WC.cbWndExtra > 0 then begin
s := s+' WndExtraData = ';
for i := 0 to (WC.cbWndExtra div 2) -1 do begin
w := GetWindowWord(hWindow,i);
s := s+AIntToHex(LOBYTE(w),1)+AIntToHex(HIBYTE(w),1);
end;
s := s+#13;
end;
s := s+ 'hIcon = $' + AIntToHex(WC.hIcon,8)+#13+
'hBrush = $' + AIntToHex(WC.hbrBackground,8)+#13+
'MenuName = ' + string(WC.lpszMenuName);
result := s;
end;
var
cn: string = '';
function FindOtherWndProc(hWindow: HWND; lData: LPARAM):BOOL; stdcall;
var
c: array[0..100] of Char;
begin
GetClassName(hWindow,c,100);
if string(c) = cn then begin
PInteger(LData)^ := hWindow;
result := false;
end else begin
PInteger(LData)^ := 0;
result := true;
end;
end;
procedure FindOtherInstance(classname: string);
var
FindWnd: HWND;
begin
cn := classname;
EnumWindows(@FindOtherWndProc,LPARAM(@FindWnd));
if FindWnd <> 0 then begin
MessageBox(0, 'このアプリケーションは既に起動されています',
'おしらせ',MB_ICONINFORMATION or MB_OK);
ShowWindow(FindWnd,SW_RESTORE);
SetForegroundWindow(FindWnd);
Halt(0);
end;
end;
//
//--------------- utility functions -------------------------------
//
function wsprintf1; external 'user32.dll' name 'wsprintfA';
function wsprintf2; external 'user32.dll' name 'wsprintfA';
function wsprintf3; external 'user32.dll' name 'wsprintfA';
function wsprintf4; external 'user32.dll' name 'wsprintfA';
function AIntToStr(value: integer):string;
var
i: integer;
pBuf: PChar;
begin
GetMem(pBuf,20);
i := wsprintf1(pBuf,'%d',value);
SetString(result,pBuf,i);
FreeMem(pBuf);
end;
function AIntToHex(value: Integer; digits: Integer): string;
var
i: integer;
s: string;
pBuf: PChar;
begin
GetMem(pBuf,20);
i := wsprintf1(pBuf,'%d',digits);
SetString(s,pBuf,i);
s := '%.'+s+'X';
i := wsprintf1(pBuf,PChar(s),value);
SetString(result,pBuf,i);
FreeMem(pBuf);
end;
function clrBtnFace: COLORREF;
begin
result := GetSysColor(COLOR_BTNFACE);
end;
function clrWindow: COLORREF;
begin
result := GetSysColor(COLOR_WINDOW);
end;
function clrGrayText: COLORREF;
begin
result := GetSysColor(COLOR_GRAYTEXT);
end;
function SetDim(x,y,width,height: Integer):TRect;
begin
SetRect(result,x,y,width,height);
end;
function DoChooseFont(hOwner: HWND;var ALogFont: TLogFont; Flag: DWORD;
var Color: COLORREF): Boolean;
var
cf: TChooseFont;
begin
FillChar(cf,SizeOf(cf),0);
with cf do begin
lStructSize := SizeOf(cf);
hWndOwner := hOwner;
lpLogFont := @ALogFont;
if Flag = 0 then
Flags := CF_BOTH or CF_EFFECTS
else
Flags := Flag;
rgbColors := Color;
if ALogFont.lfFaceName[0]<>#0 then Flags := Flags or CF_INITTOLOGFONTSTRUCT;
end;
if ChooseFont(cf) then begin
result := true;
Color := cf.rgbColors;
end else result := false;
end;
procedure DrawBitmap(DC:HDC;hBit:HBITMAP;x,y:integer);
var
memDC: HDC;
bm: TBitmap;
begin
GetObject(hBit,SizeOf(bm),@bm);
memDC := CreateCompatibleDC(DC);
SelectObject(memDC, hBit);
BitBlt(DC,x,y,bm.bmWidth,bm.bmHeight,memDC,0,0,SRCCOPY);
DeleteDC(memDC);
end;
end. |
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: CrackDecl.pas,v 1.9 2007/02/05 22:21:13 clootie Exp $
*----------------------------------------------------------------------------*)
{$I DirectX.inc}
unit CrackDecl;
interface
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2000 Microsoft Corporation. All Rights Reserved.
//
// File: crackdecl.h
// Content: Used to access vertex data using Declarations or FVFs
//
//////////////////////////////////////////////////////////////////////////////
uses
Windows, DXTypes, Direct3D9, D3DX9;
type
PFVFDeclaration = ^TFVFDeclaration;
//----------------------------------------------------------------------------
// CD3DXCrackDecl
//----------------------------------------------------------------------------
CD3DXCrackDecl = class
protected
//just a pointer to the Decl! No data stored!
{CONST} pElements: PFVFDeclaration; // PD3DVertexElement9;
dwNumElements: DWORD;
//still need the stream pointer though
//and the strides
pStream: array[0..15] of PByte;
dwStride: array[0..15] of DWORD;
public
constructor Create;
function SetDeclaration(const pDecl: PD3DVertexElement9): HRESULT;
function SetStreamSource(Stream: LongWord; pData: Pointer; Stride: LongWord): HRESULT;
// Get
function GetVertexStride(Stream: LongWord): LongWord;{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF}
function GetFields(const pElement: PD3DVertexElement9): LongWord;//{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF}
function GetVertex(Stream: LongWord; Index: LongWord): PByte;{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF}
function GetElementPointer(const Element: PD3DVertexElement9; Index: LongWord): PByte;{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF}
function GetSemanticElement(Usage: TD3DDeclUsage; UsageIndex: LongWord): {CONST} PD3DVertexElement9;{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF}
//simple function that gives part of the decl back
function GetIndexElement(Index: LongWord): {CONST} PD3DVertexElement9;{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF}
// Encode/Decode
procedure Decode(const pElem: PD3DVertexElement9; Index: LongWord; pData: PSingle; cData: LongWord);
procedure Encode(const pElem: PD3DVertexElement9; Index: LongWord; const pDataArray: PSingle; cData: LongWord);
procedure DecodeSemantic(Usage: TD3DDeclUsage; UsageIndex, VertexIndex: LongWord; pData: PSingle; cData: LongWord);{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF}
procedure EncodeSemantic(Usage: TD3DDeclUsage; UsageIndex, VertexIndex: LongWord; pData: PSingle; cData: LongWord);{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF}
property Elements: PFVFDeclaration read pElements;
property NumElements: DWORD read dwNumElements;
property GetElements: PFVFDeclaration read pElements; // C++ compatibility
property GetNumElements: DWORD read dwNumElements; // C++ compatibility
function DeclUsageToString(usage: TD3DDeclUsage): {CONST} PWideChar;
end;
function GetDeclElement(pDecl: {const} PD3DVertexElement9; Usage: TD3DDeclUsage; UsageIndex: Byte): {const} PD3DVertexElement9;{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF}
procedure AppendDeclElement(pNew: {const} PD3DVertexElement9; const pDecl: TFVFDeclaration);//{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF}
implementation
{ CD3DXCrackDecl }
constructor CD3DXCrackDecl.Create;
var
i: LongWord;
begin
for i := 0 to 15 do dwStride[i] := 0;
end;
procedure CD3DXCrackDecl.DecodeSemantic(Usage: TD3DDeclUsage;
UsageIndex, VertexIndex: LongWord; pData: PSingle; cData: LongWord);
begin
Decode(GetSemanticElement(Usage, UsageIndex), VertexIndex, pData, cData);
end;
procedure CD3DXCrackDecl.EncodeSemantic(Usage: TD3DDeclUsage;
UsageIndex, VertexIndex: LongWord; pData: PSingle; cData: LongWord);
begin
Encode(GetSemanticElement(Usage, UsageIndex), VertexIndex, pData, cData);
end;
function CD3DXCrackDecl.GetElementPointer(
const Element: PD3DVertexElement9; Index: LongWord): PByte;
begin
Result:= PByte(PtrInt(GetVertex(Element.Stream, Index)) + Element.Offset);
end;
const
x_rgcbFields: array [TD3DDeclType] of Byte = (
1, // D3DDECLTYPE_FLOAT1, // 1D float expanded to (value, 0., 0., 1.)
2, // D3DDECLTYPE_FLOAT2, // 2D float expanded to (value, value, 0., 1.)
3, // D3DDECLTYPE_FLOAT3, / 3D float expanded to (value, value, value, 1.)
4, // D3DDECLTYPE_FLOAT4, / 4D float
4, // D3DDECLTYPE_D3DCOLOR, // 4D packed unsigned bytes mapped to 0. to 1. range
// // Input is in D3DCOLOR format (ARGB) expanded to (R, G, B, A)
4, // D3DDECLTYPE_UBYTE4, // 4D unsigned byte
2, // D3DDECLTYPE_SHORT2, // 2D signed short expanded to (value, value, 0., 1.)
4, // D3DDECLTYPE_SHORT4 // 4D signed short
4, // D3DDECLTYPE_UBYTE4N, // Each of 4 bytes is normalized by dividing to 255.0
2, // D3DDECLTYPE_SHORT2N, // 2D signed short normalized (v[0]/32767.0,v[1]/32767.0,0,1)
4, // D3DDECLTYPE_SHORT4N, // 4D signed short normalized (v[0]/32767.0,v[1]/32767.0,v[2]/32767.0,v[3]/32767.0)
2, // D3DDECLTYPE_USHORT2N, // 2D unsigned short normalized (v[0]/65535.0,v[1]/65535.0,0,1)
4, // D3DDECLTYPE_USHORT4N, // 4D unsigned short normalized (v[0]/65535.0,v[1]/65535.0,v[2]/65535.0,v[3]/65535.0)
3, // D3DDECLTYPE_UDEC3, // 3D unsigned 10 10 10 format expanded to (value, value, value, 1)
3, // D3DDECLTYPE_DEC3N, // 3D signed 10 10 10 format normalized and expanded to (v[0]/511.0, v[1]/511.0, v[2]/511.0, 1)
2, // D3DDECLTYPE_FLOAT16_2, // 2D 16 bit float expanded to (value, value, 0, 1 )
4, // D3DDECLTYPE_FLOAT16_4, // 4D 16 bit float
0 // D3DDECLTYPE_UNKNOWN, // Unknown
);
function CD3DXCrackDecl.GetFields(const pElement: PD3DVertexElement9): LongWord;
begin
if (pElement^._Type <= D3DDECLTYPE_FLOAT16_4)
then Result:= x_rgcbFields[pElement._Type]
else Result:= 0;
end;
function CD3DXCrackDecl.GetIndexElement(
Index: LongWord): PD3DVertexElement9;
begin
if (Index < dwNumElements)
then Result:= @pElements[Index]
else Result:= nil;
end;
function CD3DXCrackDecl.GetSemanticElement(Usage: TD3DDeclUsage;
UsageIndex: LongWord): PD3DVertexElement9;
var
pPlace: PD3DVertexElement9;
begin
pPlace := @pElements[0];
while (pPlace.Stream <> $ff) do
begin
if (pPlace.Usage = Usage) and
(pPlace.UsageIndex = UsageIndex) then
begin
Result:= pPlace;
Exit;
end else
Inc(pPlace);
end;
Result:= nil;
end;
function CD3DXCrackDecl.GetVertex(Stream, Index: LongWord): PByte;
begin
Result:= PByte(PtrUInt(pStream[Stream]) + dwStride[Stream] * Index);
end;
function CD3DXCrackDecl.GetVertexStride(Stream: LongWord): LongWord;
begin
Result:= dwStride[Stream];
end;
function CD3DXCrackDecl.SetDeclaration(const pDecl: PD3DVertexElement9): HRESULT;
begin
pElements := PFVFDeclaration(pDecl);
dwNumElements := D3DXGetDeclLength(pDecl);
Result:= S_OK;
end;
function CD3DXCrackDecl.SetStreamSource(Stream: LongWord; pData: Pointer;
Stride: LongWord): HRESULT;
begin
pStream[Stream] := pData;
if (Stride = 0)
then dwStride[Stream] := D3DXGetDeclVertexSize(@pElements[0], Stream)
else dwStride[Stream] := Stride;
Result:= S_OK;
end;
function BIdenticalDecls(const pDecl1, pDecl2: PD3DVertexElement9): Boolean;{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF}
var
pCurSrc, pCurDest: PD3DVertexElement9;
begin
pCurSrc := pDecl1;
pCurDest := pDecl2;
while (pCurSrc.Stream <> $ff) and (pCurDest.Stream <> $ff) do
begin
if (pCurDest.Stream <> pCurSrc.Stream)
and (pCurDest.Offset <> pCurSrc.Offset)
or (pCurDest._Type <> pCurSrc._Type)
or (pCurDest.Method <> pCurSrc.Method)
or (pCurDest.Usage <> pCurSrc.Usage)
or (pCurDest.UsageIndex <> pCurSrc.UsageIndex)
then Break;
Inc(pCurSrc);
Inc(pCurDest);
end;
// it is the same decl if reached the end at the same time on both decls
Result:= (pCurSrc.Stream = $ff) and (pCurDest.Stream = $ff);
end;
procedure CopyDecls(pDest, pSrc: PD3DVertexElement9);{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF}
begin
while (pSrc.Stream <> $ff) do
begin
CopyMemory(pDest, pSrc, SizeOf(TD3DVertexElement9));
Inc(pSrc);
Inc(pDest);
end;
CopyMemory(pDest, pSrc, SizeOf(TD3DVertexElement9));
end;
const
x_rgcbTypeSizes: array [TD3DDeclType] of Byte = (
4, // D3DDECLTYPE_FLOAT1, // 1D float expanded to (value, 0., 0., 1.)
8, // D3DDECLTYPE_FLOAT2, // 2D float expanded to (value, value, 0., 1.)
12, // D3DDECLTYPE_FLOAT3, / 3D float expanded to (value, value, value, 1.)
16, // D3DDECLTYPE_FLOAT4, / 4D float
4, // D3DDECLTYPE_D3DCOLOR, // 4D packed unsigned bytes mapped to 0. to 1. range
// // Input is in D3DCOLOR format (ARGB) expanded to (R, G, B, A)
4, // D3DDECLTYPE_UBYTE4, // 4D unsigned byte
4, // D3DDECLTYPE_SHORT2, // 2D signed short expanded to (value, value, 0., 1.)
8, // D3DDECLTYPE_SHORT4 // 4D signed short
4, // D3DDECLTYPE_UBYTE4N, // Each of 4 bytes is normalized by dividing to 255.0
4, // D3DDECLTYPE_SHORT2N, // 2D signed short normalized (v[0]/32767.0,v[1]/32767.0,0,1)
8, // D3DDECLTYPE_SHORT4N, // 4D signed short normalized (v[0]/32767.0,v[1]/32767.0,v[2]/32767.0,v[3]/32767.0)
4, // D3DDECLTYPE_USHORT2N, // 2D unsigned short normalized (v[0]/65535.0,v[1]/65535.0,0,1)
8, // D3DDECLTYPE_USHORT4N, // 4D unsigned short normalized (v[0]/65535.0,v[1]/65535.0,v[2]/65535.0,v[3]/65535.0)
4, // D3DDECLTYPE_UDEC3, // 3D unsigned 10 10 10 format expanded to (value, value, value, 1)
4, // D3DDECLTYPE_DEC3N, // 3D signed 10 10 10 format normalized and expanded to (v[0]/511.0, v[1]/511.0, v[2]/511.0, 1)
4, // D3DDECLTYPE_FLOAT16_2, // 2D 16 bit float expanded to (value, value, 0, 1 )
8, // D3DDECLTYPE_FLOAT16_4, // 4D 16 bit float
0 // D3DDECLTYPE_UNUSED, // Unused
);
function GetDeclElement(pDecl: {const} PD3DVertexElement9; Usage: TD3DDeclUsage; UsageIndex: Byte): {const} PD3DVertexElement9;{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF}
begin
while (pDecl.Stream <> $ff) do
begin
if (pDecl.Usage = Usage) and (pDecl.UsageIndex = UsageIndex) then
begin
Result:= pDecl;
Exit;
end;
Inc(pDecl);
end;
Result:= nil;
end;
procedure RemoveDeclElement(Usage: TD3DDeclUsage; UsageIndex: Byte; const pDecl: TFVFDeclaration);{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF}
var
pCur: PD3DVertexElement9;
pPrev: PD3DVertexElement9;
cbElementSize: Byte;
begin
pCur := @pDecl[0];
while (pCur.Stream <> $ff) do
begin
if (pCur.Usage = Usage) and (pCur.UsageIndex = UsageIndex) then
begin
Break;
end;
Inc(pCur);
end;
//. if we found one to remove, then remove it
if (pCur.Stream <> $ff) then
begin
cbElementSize := x_rgcbTypeSizes[pCur._Type];
pPrev := pCur;
Inc(pCur);
while (pCur.Stream <> $ff) do
begin
CopyMemory(pPrev, pCur, SizeOf(TD3DVertexElement9));
pPrev.Offset := pPrev.Offset - cbElementSize;
Inc(pPrev);
Inc(pCur);
end;
// copy the end of stream down one
CopyMemory(pPrev, pCur, SizeOf(TD3DVertexElement9));
end;
end;
// NOTE: size checking of array should happen OUTSIDE this function!
procedure AppendDeclElement(pNew: {const} PD3DVertexElement9; const pDecl: TFVFDeclaration);//{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF}
var
pCur: PD3DVertexElement9;
cbOffset: Byte;
begin
pCur := @pDecl[0];
cbOffset := 0;
while (pCur.Stream <> $ff) do
begin
Inc(cbOffset, x_rgcbTypeSizes[pCur._Type]);
Inc(pCur);
end;
// NOTE: size checking of array should happen OUTSIDE this function!
// assert(pCur - pDecl + 1 < MAX_FVF_DECL_SIZE);
Assert((PtrInt(pCur) - PtrInt(@pDecl)) div SizeOf(TD3DVertexElement9) + 1 < MAX_FVF_DECL_SIZE);
// move the end of the stream down one
CopyMemory(Pointer(PtrInt(pCur)+SizeOf(TD3DVertexElement9)), pCur, SizeOf(TD3DVertexElement9));
// copy the new element in and update the offset
CopyMemory(pCur, pNew, SizeOf(TD3DVertexElement9));
pCur.Offset := cbOffset;
end;
// NOTE: size checking of array should happen OUTSIDE this function!
procedure InsertDeclElement(iInsertBefore: LongWord; pNew: {const} PD3DVertexElement9; const pDecl: TFVFDeclaration);{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF}
var
pCur: PD3DVertexElement9;
cbOffset: Byte;
cbNewOffset: Byte;
TempElement1: TD3DVertexElement9;
TempElement2: TD3DVertexElement9;
iCur: LongWord;
begin
pCur := @pDecl[0];
cbOffset := 0;
iCur := 0;
while (pCur.Stream <> $ff) and (iCur < iInsertBefore) do
begin
Inc(cbOffset, x_rgcbTypeSizes[pCur._Type]);
Inc(pCur);
Inc(iCur);
end;
// NOTE: size checking of array should happen OUTSIDE this function!
// assert(pCur - pDecl + 1 < MAX_FVF_DECL_SIZE);
Assert((PtrInt(pCur) - PtrInt(@pDecl)) div SizeOf(TD3DVertexElement9) + 1 < MAX_FVF_DECL_SIZE);
// if we hit the end, just append
if (pCur.Stream = $ff) then
begin
// move the end of the stream down one
CopyMemory(Pointer(PtrInt(pCur)+SizeOf(TD3DVertexElement9)), pCur, SizeOf(TD3DVertexElement9));
// copy the new element in and update the offset
CopyMemory(pCur, pNew, SizeOf(TD3DVertexElement9));
pCur.Offset := cbOffset;
end else // insert in the middle
begin
// save off the offset for the new decl
cbNewOffset := cbOffset;
// calculate the offset for the first element shifted up
Inc(cbOffset, x_rgcbTypeSizes[pNew._Type]);
// save off the first item to move, data so that we can copy the new element in
CopyMemory(@TempElement1, pCur, SizeOf(TD3DVertexElement9));
// copy the new element in
CopyMemory(pCur, pNew, SizeOf(TD3DVertexElement9));
pCur.Offset := cbNewOffset;
// advance pCur one because we effectively did an iteration of the loop adding the new element
Inc(pCur);
while (pCur.Stream <> $ff) do
begin
// save off the current element
CopyMemory(@TempElement2, pCur, SizeOf(TD3DVertexElement9));
// update the current element with the previous's value which was stored in TempElement1
CopyMemory(pCur, @TempElement1, SizeOf(TD3DVertexElement9));
// move the current element's value into TempElement1 for the next iteration
CopyMemory(@TempElement1, @TempElement2, SizeOf(TD3DVertexElement9));
pCur.Offset := cbOffset;
Inc(cbOffset, x_rgcbTypeSizes[pCur._Type]);
Inc(pCur);
end;
// now we exited one element, need to move the end back one and copy in the last element
// move the end element back one
CopyMemory(Pointer(PtrInt(pCur)+SizeOf(TD3DVertexElement9)), pCur, SizeOf(TD3DVertexElement9));
// copy the prev element's data out of the temp and into the last element
CopyMemory(pCur, @TempElement1, SizeOf(TD3DVertexElement9));
pCur.Offset := cbOffset;
end;
end;
procedure CD3DXCrackDecl.Decode(const pElem: PD3DVertexElement9;
Index: LongWord; pData: PSingle; cData: LongWord);
type
PSingleArray = ^TSingleArray;
TSingleArray = array[0..3] of Single;
PByteArray = ^TByteArray;
TByteArray = array[0..3] of Byte;
PSmallintArray = ^TSmallintArray;
TSmallintArray = array[0..3] of Smallint;
PWordArray = ^TWordArray;
TWordArray = array[0..3] of Word;
var
Data: array[0..3] of Single;
pElement: Pointer;
nX, nY, nZ, nW: Smallint;
nXl, nYl, nZl: Longint;
i: Integer;
begin
if Assigned(pElem) then
begin
pElement := GetElementPointer(pElem,index);
case pElem._Type of
D3DDECLTYPE_FLOAT1:
begin
Data[0] := PSingleArray(pElement)[0];
Data[1] := 0.0;
Data[2] := 0.0;
Data[3] := 1.0;
end;
D3DDECLTYPE_FLOAT2:
begin
Data[0] := PSingleArray(pElement)[0];
Data[1] := PSingleArray(pElement)[1];
Data[2] := 0.0;
Data[3] := 1.0;
end;
D3DDECLTYPE_FLOAT3:
begin
Data[0] := PSingleArray(pElement)[0];
Data[1] := PSingleArray(pElement)[1];
Data[2] := PSingleArray(pElement)[2];
Data[3] := 1.0;
end;
D3DDECLTYPE_FLOAT4:
begin
Data[0] := PSingleArray(pElement)[0];
Data[1] := PSingleArray(pElement)[1];
Data[2] := PSingleArray(pElement)[2];
Data[3] := PSingleArray(pElement)[3];
end;
D3DDECLTYPE_D3DCOLOR:
begin
Data[0] := (1.0 / 255.0) * Byte(PD3DColor(pElement)^ shr 16);
Data[1] := (1.0 / 255.0) * Byte(PD3DColor(pElement)^ shr 8);
Data[2] := (1.0 / 255.0) * Byte(PD3DColor(pElement)^ shr 0);
Data[3] := (1.0 / 255.0) * Byte(PD3DColor(pElement)^ shr 24);
end;
D3DDECLTYPE_UBYTE4:
begin
Data[0] := PByteArray(pElement)[0];
Data[1] := PByteArray(pElement)[1];
Data[2] := PByteArray(pElement)[2];
Data[3] := PByteArray(pElement)[3];
end;
D3DDECLTYPE_SHORT2:
begin
Data[0] := PSmallintArray(pElement)[0];
Data[1] := PSmallintArray(pElement)[1];
Data[2] := 0.0;
Data[3] := 1.0;
end;
D3DDECLTYPE_SHORT4:
begin
Data[0] := PSmallintArray(pElement)[0];
Data[1] := PSmallintArray(pElement)[1];
Data[2] := PSmallintArray(pElement)[2];
Data[3] := PSmallintArray(pElement)[3];
end;
D3DDECLTYPE_UBYTE4N:
begin
Data[0] := (1.0 / 255.0) * PByteArray(pElement)[0];
Data[1] := (1.0 / 255.0) * PByteArray(pElement)[1];
Data[2] := (1.0 / 255.0) * PByteArray(pElement)[2];
Data[3] := (1.0 / 255.0) * PByteArray(pElement)[3];
end;
D3DDECLTYPE_SHORT2N:
begin
nX := PSmallintArray(pElement)[0];
nY := PSmallintArray(pElement)[1];
if (-32768 = Integer(nX)) then Inc(nX); // nX += (-32768 == nX);
if (-32768 = Integer(nY)) then Inc(nY); // nY += (-32768 == nY);
Data[0] := (1.0 / 32767.0) * nX;
Data[1] := (1.0 / 32767.0) * nY;
Data[2] := 0.0;
Data[3] := 1.0;
end;
D3DDECLTYPE_SHORT4N:
begin
nX := PSmallintArray(pElement)[0];
nY := PSmallintArray(pElement)[1];
nZ := PSmallintArray(pElement)[2];
nW := PSmallintArray(pElement)[3];
if (-32768 = Integer(nX)) then Inc(nX); // nX += (-32768 == nX);
if (-32768 = Integer(nY)) then Inc(nY); // nY += (-32768 == nY);
if (-32768 = Integer(nZ)) then Inc(nZ); // nZ += (-32768 == nZ);
if (-32768 = Integer(nW)) then Inc(nW); // nW += (-32768 == nW);
Data[0] := (1.0 / 32767.0) * nX;
Data[1] := (1.0 / 32767.0) * nY;
Data[2] := (1.0 / 32767.0) * nZ;
Data[3] := (1.0 / 32767.0) * nW;
end;
D3DDECLTYPE_USHORT2N:
begin
Data[0] := (1.0 / 65535.0) * PWordArray(pElement)[0];
Data[1] := (1.0 / 65535.0) * PWordArray(pElement)[1];
Data[2] := 0.0;
Data[3] := 1.0;
end;
D3DDECLTYPE_USHORT4N:
begin
Data[0] := (1.0 / 65535.0) * PWordArray(pElement)[0];
Data[1] := (1.0 / 65535.0) * PWordArray(pElement)[1];
Data[2] := (1.0 / 65535.0) * PWordArray(pElement)[2];
Data[3] := (1.0 / 65535.0) * PWordArray(pElement)[3];
end;
D3DDECLTYPE_UDEC3:
begin
Data[0] := (PLongword(pElement)^ shr 0) and $3ff;
Data[1] := (PLongword(pElement)^ shr 10) and $3ff;
Data[2] := (PLongword(pElement)^ shr 20) and $3ff;
Data[3] := 1.0;
end;
D3DDECLTYPE_DEC3N:
begin
nXl := (PLongint(pElement)^ shl 22) shr 22;
nYl := (PLongint(pElement)^ shl 12) shr 22;
nZl := (PLongint(pElement)^ shl 2) shr 22;
if (-512 = nXl) then Inc(nXl); // nX += (-512 == nX);
if (-512 = nYl) then Inc(nYl); // nY += (-512 == nY);
if (-512 = nZl) then Inc(nZl); // nZ += (-512 == nZ);
Data[0] := (1.0 / 511.0) * nXl;
Data[1] := (1.0 / 511.0) * nYl;
Data[2] := (1.0 / 511.0) * nZl;
Data[3] := 1.0;
end;
D3DDECLTYPE_FLOAT16_2:
begin
D3DXFloat16To32Array(@Data, PD3DXFloat16(pElement), 2);
Data[2] := 0.0;
Data[3] := 1.0;
end;
D3DDECLTYPE_FLOAT16_4:
D3DXFloat16To32Array(@Data, PD3DXFloat16(pElement), 4);
end;
end else
begin
Data[0] := 0.0;
Data[1] := 0.0;
Data[2] := 0.0;
Data[3] := 1.0;
end;
if (cData > 4) then cData := 4;
for i := 0 to cData - 1 do PSingleArray(pData)[i] := Data[i];
end;
procedure CD3DXCrackDecl.Encode(const pElem: PD3DVertexElement9;
Index: LongWord; const pDataArray: PSingle; cData: LongWord);
type
PSingleArray = ^TSingleArray;
TSingleArray = array[0..3] of Single;
PByteArray = ^TByteArray;
TByteArray = array[0..3] of Byte;
PSmallintArray = ^TSmallintArray;
TSmallintArray = array[0..3] of Smallint;
PWordArray = ^TWordArray;
TWordArray = array[0..3] of Word;
var
i: LongWord;
Data: array[0..3] of Single;
pData: PSingleArray;
pElement: Pointer;
begin
pData:= PSingleArray(pDataArray);
// Set default values
Data[0] := 0.0; Data[1] := 0.0; Data[2] := 0.0; Data[3] := 1.0;
if(cData > 4) then cData := 4;
case pElem._Type of
D3DDECLTYPE_D3DCOLOR,
D3DDECLTYPE_UBYTE4N,
D3DDECLTYPE_USHORT2N,
D3DDECLTYPE_USHORT4N:
begin
for i:= 0 to cData - 1 do
begin
if (0.0 > pData[i]) then Data[i] := 0.0 else
if (1.0 < pData[i]) then Data[i] := 1.0 else
Data[i]:= pData[i];
end;
end;
D3DDECLTYPE_SHORT2N,
D3DDECLTYPE_SHORT4N,
D3DDECLTYPE_DEC3N:
begin
for i:= 0 to cData - 1 do
begin
if (-1.0 > pData[i]) then Data[i] := -1.0 else
if ( 1.0 < pData[i]) then Data[i] := 1.0 else
Data[i]:= pData[i];
end;
end;
D3DDECLTYPE_UBYTE4,
D3DDECLTYPE_UDEC3:
begin
for i:= 0 to cData - 1 do
begin
if (0.0 > pData[i]) then Data[i] := 0.0 else
Data[i]:= pData[i];
end;
end;
else
for i:= 0 to cData - 1 do
Data[i] := pData[i];
end;
if Assigned(pElem) then
begin
pElement := GetElementPointer(pElem, index);
case pElem._Type of
D3DDECLTYPE_FLOAT1:
PSingleArray(pElement)[0] := Data[0];
D3DDECLTYPE_FLOAT2:
begin
PSingleArray(pElement)[0] := Data[0];
PSingleArray(pElement)[1] := Data[1];
end;
D3DDECLTYPE_FLOAT3:
begin
PSingleArray(pElement)[0] := Data[0];
PSingleArray(pElement)[1] := Data[1];
PSingleArray(pElement)[2] := Data[2];
end;
D3DDECLTYPE_FLOAT4:
begin
PSingleArray(pElement)[0] := Data[0];
PSingleArray(pElement)[1] := Data[1];
PSingleArray(pElement)[2] := Data[2];
PSingleArray(pElement)[3] := Data[3];
end;
D3DDECLTYPE_D3DCOLOR:
begin
PD3DColor(pElement)^ :=
((Trunc(Data[0] * 255.0 + 0.5) and $ff) shl 16) or
((Trunc(Data[1] * 255.0 + 0.5) and $ff) shl 8) or
((Trunc(Data[2] * 255.0 + 0.5) and $ff) shl 0) or
((Trunc(Data[3] * 255.0 + 0.5) and $ff) shl 24);
end;
D3DDECLTYPE_UBYTE4:
begin
PByteArray(pElement)[0] := Trunc(Data[0] + 0.5);
PByteArray(pElement)[1] := Trunc(Data[1] + 0.5);
PByteArray(pElement)[2] := Trunc(Data[2] + 0.5);
PByteArray(pElement)[3] := Trunc(Data[3] + 0.5);
end;
D3DDECLTYPE_SHORT2:
begin
PSmallintArray(pElement)[0] := Trunc(Data[0] + 0.5);
PSmallintArray(pElement)[1] := Trunc(Data[1] + 0.5);
end;
D3DDECLTYPE_SHORT4:
begin
PSmallintArray(pElement)[0] := Trunc(Data[0] + 0.5);
PSmallintArray(pElement)[1] := Trunc(Data[1] + 0.5);
PSmallintArray(pElement)[2] := Trunc(Data[2] + 0.5);
PSmallintArray(pElement)[3] := Trunc(Data[3] + 0.5);
end;
D3DDECLTYPE_UBYTE4N:
begin
PByteArray(pElement)[0] := Trunc(Data[0] * 255.0 + 0.5);
PByteArray(pElement)[1] := Trunc(Data[1] * 255.0 + 0.5);
PByteArray(pElement)[2] := Trunc(Data[2] * 255.0 + 0.5);
PByteArray(pElement)[3] := Trunc(Data[3] * 255.0 + 0.5);
end;
D3DDECLTYPE_SHORT2N:
begin
PSmallintArray(pElement)[0] := Trunc(Data[0] * 32767.0 + 0.5);
PSmallintArray(pElement)[1] := Trunc(Data[1] * 32767.0 + 0.5);
end;
D3DDECLTYPE_SHORT4N:
begin
PSmallintArray(pElement)[0] := Trunc(Data[0] * 32767.0 + 0.5);
PSmallintArray(pElement)[1] := Trunc(Data[1] * 32767.0 + 0.5);
PSmallintArray(pElement)[2] := Trunc(Data[2] * 32767.0 + 0.5);
PSmallintArray(pElement)[3] := Trunc(Data[3] * 32767.0 + 0.5);
end;
D3DDECLTYPE_USHORT2N:
begin
PWordArray(pElement)[0] := Trunc(Data[0] * 65535.0 + 0.5);
PWordArray(pElement)[1] := Trunc(Data[1] * 65535.0 + 0.5);
end;
D3DDECLTYPE_USHORT4N:
begin
PWordArray(pElement)[0] := Trunc(Data[0] * 65535.0 + 0.5);
PWordArray(pElement)[1] := Trunc(Data[1] * 65535.0 + 0.5);
PWordArray(pElement)[2] := Trunc(Data[2] * 65535.0 + 0.5);
PWordArray(pElement)[3] := Trunc(Data[3] * 65535.0 + 0.5);
end;
D3DDECLTYPE_UDEC3:
begin
PLongint(pElement)^ :=
((Trunc(Data[0] + 0.5) and $3ff) shl 0) or
((Trunc(Data[1] + 0.5) and $3ff) shl 10) or
((Trunc(Data[2] + 0.5) and $3ff) shl 20);
end;
D3DDECLTYPE_DEC3N:
begin
PLongint(pElement)^ :=
((Trunc(Data[0]*511.0 + 0.5) and $3ff) shl 0) or
((Trunc(Data[1]*511.0 + 0.5) and $3ff) shl 10) or
((Trunc(Data[2]*511.0 + 0.5) and $3ff) shl 20);
end;
D3DDECLTYPE_FLOAT16_2:
D3DXFloat32To16Array(PD3DXFloat16(pElement), @Data, 2);
D3DDECLTYPE_FLOAT16_4:
D3DXFloat32To16Array(PD3DXFloat16(pElement), @Data, 4);
end;
end;
end;
const
MAXD3DDECLUSAGE = D3DDECLUSAGE_SAMPLE; //todo: Temporary (while headers still not fixed) - June SDK
const
x_szDeclStrings: array [TD3DDeclUsage] of PWideChar = (
'D3DDECLUSAGE_POSITION',
'D3DDECLUSAGE_BLENDWEIGHT',
'D3DDECLUSAGE_BLENDINDICES',
'D3DDECLUSAGE_NORMAL',
'D3DDECLUSAGE_PSIZE',
'D3DDECLUSAGE_TEXCOORD',
'D3DDECLUSAGE_TANGENT',
'D3DDECLUSAGE_BINORMAL',
'D3DDECLUSAGE_TESSFACTOR',
'D3DDECLUSAGE_POSITIONT',
'D3DDECLUSAGE_COLOR',
'D3DDECLUSAGE_FOG',
'D3DDECLUSAGE_DEPTH',
'D3DDECLUSAGE_SAMPLE'
// 'UNKNOWN'
);
x_szDeclStrings_Unknown{: PWideChar} = 'UNKNOWN';
function CD3DXCrackDecl.DeclUsageToString(usage: TD3DDeclUsage): PWideChar;
begin
if (usage >= D3DDECLUSAGE_POSITION) and (usage <= MAXD3DDECLUSAGE)
then Result:= x_szDeclStrings[usage]
else Result:= x_szDeclStrings_Unknown; // x_szDeclStrings[MAXD3DDECLUSAGE+1];
end;
end.
|
(**
This module contains simple types for use in the application.
@Author David Hoyle
@Version 1.0
@Date 17 Feb 2018
**)
Unit JVTGTypes;
Interface
Type
(** A record to describe repository and module information. **)
TJVTGRepoData = Record
FOLDGitRepoPath : String;
FNEWGitRepoPath : String;
FModulePath : String;
FModuleName : String;
Constructor Create(Const strOldGitRepoPath, strNewGitRepoPath, strModulePath, strModuleName: String);
End;
Implementation
{ TJVTGRepoData }
(**
A constructor for the TJVTGRepoData record.
@precon None.
@postcon Initialises the the record.
@param strOldGitRepoPath as a String as a constant
@param strNewGitRepoPath as a String as a constant
@param strModulePath as a String as a constant
@param strModuleName as a String as a constant
**)
Constructor TJVTGRepoData.Create(Const strOldGitRepoPath, strNewGitRepoPath, strModulePath,
strModuleName: String);
Begin
FOLDGitRepoPath := strOldGitRepoPath;
FNEWGitRepoPath := strNewGitRepoPath;
FModulePath := strModulePath;
FModuleName := strModuleName;
End;
End.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmColumns
Purpose : Saves column information and details from a listview to the registry
Date : 02-11-1999
Author : Ryan J. Mills
Version : 1.92
================================================================================}
unit rmColumns;
interface
{$I CompilerDefines.INC}
uses
Classes, ComCtrls, dialogs;
type
TrmColumnTypes = (ctString, ctDateTime, ctInteger, ctFloat);
TrmListColumns = class;
TrmListColumn = class(TCollectionItem)
private
FAlignment: TAlignment;
FAutoSize: Boolean;
FCaption: string;
FMaxWidth: TWidth;
FMinWidth: TWidth;
FImageIndex: Integer;
FWidth: TWidth;
FColumnType:TrmColumnTypes;
fVisible: Boolean;
FTag: integer;
function IsWidthStored: Boolean;
procedure SetAlignment(Value: TAlignment);
procedure SetAutoSize(Value: Boolean);
procedure SetCaption(const Value: string);
procedure SetImageIndex(Value: Integer);
procedure SetMaxWidth(Value: TWidth);
procedure SetMinWidth(Value: TWidth);
procedure SetWidth(Value: TWidth);
function GetWidth:TWidth;
procedure SetVisible(const Value: Boolean);
procedure SetColumnIndex(const Value: integer);
function GetColumnIndex: integer;
protected
function GetDisplayName: string; override;
public
constructor Create(Collection: TCollection); override;
procedure Assign(Source: TPersistent); override;
published
property Alignment: TAlignment read FAlignment write SetAlignment default taLeftJustify;
property AutoSize: Boolean read FAutoSize write SetAutoSize default False;
property Caption: string read FCaption write SetCaption;
property ColumnType : TrmColumnTypes read fColumnType write fColumnType;
property ImageIndex: Integer read FImageIndex write SetImageIndex default -1;
property MaxWidth: TWidth read FMaxWidth write SetMaxWidth default 0;
property MinWidth: TWidth read FMinWidth write SetMinWidth default 0;
property Width: TWidth read GetWidth write SetWidth stored IsWidthStored default 50;
property Visible: Boolean read fVisible write SetVisible default true;
property Tag: integer read FTag write fTag default -1;
property ColumnIndex: integer read GetColumnIndex write SetColumnIndex;
end;
TrmListColumns = class(TCollection)
private
FOwner : TComponent;
function GetItem(Index: Integer): TrmListColumn;
procedure SetItem(Index: Integer; Value: TrmListColumn);
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner:TComponent);
function Add: TrmListColumn;
property Items[Index: Integer]: TrmListColumn read GetItem write SetItem; default;
end;
TrmColumns = class(TComponent)
private
{ Private declarations }
FVersionID : Integer;
FColumns : TrmListColumns;
FSortColumn : integer;
FSortDsc : boolean;
procedure SetListColumns(Value: TrmListColumns);
procedure SetSortColumn(const Value: integer);
procedure SetSortDsc(const Value: boolean);
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure SaveToFile(FileName:string; Binary:Boolean);
procedure LoadFromFile(FileName:String; Binary:Boolean);
procedure SaveToReg(Key, Value:string; Binary:Boolean);
procedure LoadFromReg(key, Value:string; Binary:Boolean);
procedure SetListViewCols(lvObject:TListView);
procedure GetListViewCols(lvObject:TListView);
published
{ Published declarations }
property SortColumn : integer read fSortColumn write SetSortColumn;
property SortDsc : boolean read FSortDsc write SetSortDsc;
property Columns: TrmListColumns read FColumns write SetListColumns;
property VersionID:integer read FVersionID write FVersionID;
end;
implementation
Uses SysUtils, Registry;
{ TrmListColumn }
constructor TrmListColumn.Create(Collection: TCollection);
begin
inherited Create(Collection);
FWidth := 50;
FAlignment := taLeftJustify;
FImageIndex := -1;
fVisible := true;
FTag := -1;
end;
procedure TrmListColumn.SetCaption(const Value: string);
begin
if FCaption <> Value then
begin
FCaption := Value;
end;
end;
function TrmListColumn.GetWidth: TWidth;
begin
Result := FWidth;
end;
function TrmListColumn.IsWidthStored: Boolean;
begin
Result := not FAutoSize;
end;
procedure TrmListColumn.SetWidth(Value: TWidth);
begin
if FWidth <> Value then
begin
FWidth := Value;
end;
end;
procedure TrmListColumn.SetAlignment(Value: TAlignment);
begin
if FAlignment <> Value then
begin
FAlignment := Value;
end;
end;
procedure TrmListColumn.SetAutoSize(Value: Boolean);
begin
if FAutoSize <> Value then
begin
FAutoSize := Value;
end;
end;
procedure TrmListColumn.SetImageIndex(Value: Integer);
begin
if FImageIndex <> Value then
begin
FImageIndex := Value;
end;
end;
procedure TrmListColumn.SetMaxWidth(Value: TWidth);
begin
if FMaxWidth <> Value then
begin
FMaxWidth := Value;
end;
end;
procedure TrmListColumn.SetMinWidth(Value: TWidth);
begin
if FMinWidth <> Value then
begin
FMinWidth := Value;
end;
end;
procedure TrmListColumn.Assign(Source: TPersistent);
var
Column: TrmListColumn;
begin
if Source is TrmListColumn then
begin
Column := TrmListColumn(Source);
Alignment := Column.Alignment;
AutoSize := Column.AutoSize;
Caption := Column.Caption;
ImageIndex := Column.ImageIndex;
MaxWidth := Column.MaxWidth;
MinWidth := Column.MinWidth;
Width := Column.Width;
ColumnType := Column.ColumnType;
Tag := Column.Tag;
end
else inherited Assign(Source);
end;
function TrmListColumn.GetDisplayName: string;
begin
Result := Caption;
if Result = '' then Result := inherited GetDisplayName;
end;
procedure TrmListColumn.SetVisible(const Value: Boolean);
begin
if fVisible <> value then
begin
fVisible := Value;
end;
end;
procedure TrmListColumn.SetColumnIndex(const Value: integer);
begin
Self.Index := value;
end;
function TrmListColumn.GetColumnIndex: integer;
begin
result := Self.Index;
end;
{ TrmListColumns }
function TrmListColumns.GetItem(Index: Integer): TrmListColumn;
begin
Result := TrmListColumn(inherited GetItem(Index));
end;
procedure TrmListColumns.SetItem(Index: Integer; Value: TrmListColumn);
begin
inherited SetItem(Index, Value);
end;
function TrmListColumns.Add: TrmListColumn;
begin
Result := TrmListColumn(inherited Add);
end;
function TrmListColumns.GetOwner: TPersistent;
begin
Result := FOwner;
end;
constructor TrmListColumns.Create(AOwner: TComponent);
begin
inherited Create(TrmListColumn);
FOwner := AOwner;
end;
{ TrmColumns }
constructor TrmColumns.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FColumns := TrmListColumns.create(self);
end;
destructor TrmColumns.Destroy;
begin
FColumns.free;
inherited;
end;
procedure TrmColumns.SetListViewCols(lvObject: TListView);
var
index : integer;
begin
lvObject.Columns.BeginUpdate;
try
lvObject.Columns.Clear;
index := 0;
While index < Columns.Count do
begin
if Columns[index].visible then
with lvObject.Columns.Add do
begin
Alignment := Columns[index].Alignment;
AutoSize := Columns[index].AutoSize;
Caption := Columns[index].Caption;
ImageIndex := Columns[index].ImageIndex;
MaxWidth := Columns[index].MaxWidth;
MinWidth := Columns[index].MinWidth;
Width := Columns[index].Width;
Tag := Columns[index].Tag;
end;
inc(index);
end;
finally
lvObject.Columns.EndUpdate;
end;
end;
procedure TrmColumns.GetListViewCols(lvObject: TListView);
var
index : integer;
begin
Columns.Clear;
index := 0;
While index < lvObject.Columns.Count do
begin
Columns.Add;
with Columns[index] do
begin
Alignment := lvObject.Columns[index].Alignment;
AutoSize := lvObject.Columns[index].AutoSize;
Caption := lvObject.Columns[index].Caption;
ImageIndex := lvObject.Columns[index].ImageIndex;
MaxWidth := lvObject.Columns[index].MaxWidth;
MinWidth := lvObject.Columns[index].MinWidth;
Width := lvObject.Columns[index].Width;
Tag := lvObject.Columns[index].Tag;
end;
inc(index);
end;
end;
procedure TrmColumns.LoadFromFile(FileName: String; Binary: Boolean);
var
StrmIn, TempStrm : TStream;
TmpCols : TrmColumns;
begin
TmpCols := TrmColumns.Create(nil);
try
StrmIn := TFileStream.Create(fileName,fmOpenRead);
try
if Binary then
StrmIn.ReadComponent(TmpCols)
else
begin
TempStrm := TMemoryStream.Create;
try
ObjectTextToBinary(StrmIn,TempStrm);
TempStrm.Position := 0;
TempStrm.ReadComponent(TmpCols);
finally
TempStrm.Free;
end;
end;
finally
StrmIn.Free;
end;
Self.Assign(TmpCols);
finally
TmpCols.free;
end;
end;
procedure TrmColumns.LoadFromReg(key, value: string; Binary: Boolean);
var
StrmIn, TempStrm : TStream;
TmpCols : TrmColumns;
Reg : TRegistry;
Buf : Pointer;
BufSize : integer;
begin
BufSize := -1;
StrmIn := TMemoryStream.Create;
try
Reg := TRegistry.Create;
try
if reg.OpenKey(key,false) then
begin
if Reg.ValueExists(Value) then
begin
BufSize := Reg.GetDataSize(Value);
if BufSize > -1 then
begin
GetMem(Buf,BufSize);
try
Reg.ReadBinaryData(Value,Buf^,BufSize);
StrmIn.WriteBuffer(Buf^,BufSize);
finally
FreeMem(Buf,BufSize);
end;
end;
end;
Reg.CloseKey;
end;
finally
Reg.CloseKey;
Reg.free;
end;
if BufSize > -1 then
begin
StrmIn.Position := 0;
TmpCols := TrmColumns.Create(nil);
try
if Binary then
StrmIn.ReadComponent(TmpCols)
else
begin
TempStrm := TMemoryStream.Create;
try
ObjectTextToBinary(StrmIn,TempStrm);
TempStrm.Position := 0;
TempStrm.ReadComponent(TmpCols);
finally
TempStrm.Free;
end;
end;
Self.Assign(TmpCols);
finally
TmpCols.free;
end;
end;
finally
StrmIn.Free;
end;
end;
procedure TrmColumns.SaveToFile(FileName: string; Binary: Boolean);
var
StrmOut, TempStrm : TStream;
Name : string;
begin
Name := Self.Name;
Self.Name := '';
StrmOut := TFileStream.Create(fileName,fmCreate);
try
if Binary then
StrmOut.WriteComponent(Self)
else
begin
TempStrm := TMemoryStream.Create;
try
TempStrm.WriteComponent(Self);
TempStrm.Position := 0;
ObjectBinaryToText(TempStrm,StrmOut);
finally
TempStrm.Free;
end;
end;
finally
StrmOut.Free;
end;
Self.Name := Name;
end;
procedure TrmColumns.SaveToReg(Key, Value: string; Binary: Boolean);
var
StrmOut, TempStrm : TStream;
Name : string;
reg : TRegistry;
Buf : pointer;
begin
Name := Self.Name;
Self.Name := '';
StrmOut := TMemoryStream.Create;
try
if Binary then
StrmOut.WriteComponent(Self)
else
begin
TempStrm := TMemoryStream.Create;
try
TempStrm.WriteComponent(Self);
TempStrm.Position := 0;
ObjectBinaryToText(TempStrm,StrmOut);
finally
TempStrm.Free;
end;
end;
Reg := TRegistry.Create;
try
GetMem(buf,StrmOut.Size);
try
StrmOut.Position := 0;
StrmOut.ReadBuffer(Buf^,StrmOut.Size);
if reg.OpenKey(key,true) then
begin
Reg.WriteBinaryData(Value,Buf^,StrmOut.Size);
Reg.CloseKey;
end;
finally
FreeMem(Buf,StrmOut.Size);
end;
finally
Reg.CloseKey;
Reg.free;
end;
finally
StrmOut.Free;
end;
Self.Name := Name;
end;
procedure TrmColumns.SetListColumns(Value: TrmListColumns);
begin
FColumns.Assign(Value);
end;
procedure TrmColumns.Assign(Source: TPersistent);
begin
if source is TrmColumns then
begin
VersionID := TrmColumns(Source).VersionID;
SortColumn := TrmColumns(Source).SortColumn;
SortDsc := TrmColumns(Source).SortDsc;
Columns.assign(TrmColumns(Source).Columns);
end
else
inherited assign(source);
end;
procedure TrmColumns.SetSortColumn(const Value: integer);
begin
fSortColumn := Value;
end;
procedure TrmColumns.SetSortDsc(const Value: boolean);
begin
FSortDsc := Value;
end;
end.
|
PROGRAM Library(input, output) ;
CONST
MaxLength = 40 ;
TYPE
StringType = PACKED ARRAY[1..MaxLength] OF char ;
KeyType = (Title, Subject, Author) ;
BookPtrType = ^BookType ;
BookType =
RECORD
Field : ARRAY[KeyType] OF StringType ;
Next : ARRAY[KeyType] OF BookPtrType ;
END ;
BookPtrArrayType = ARRAY[KeyType] OF BookPtrType ;
VAR
FirstBookPtr : BookPtrArrayType ; (* Points to the first books
depending on the key *)
Inserted, Deleted : Boolean ;
SubjectChanged : Boolean ;
BookTitle : StringType ;
BookSubject : StringType ;
Key : KeyType ;
choice, keychoice : Integer ;
Quit : Boolean ;
PROCEDURE InsertBook (VAR PrevbookPtr, ThisBookPtr : BookPtrType; Key : KeyType) ;
(*Inserts a book in the list, given the pointers to the books before and after*)
VAR
TempBookPtr : BookPtrType ;
BEGIN
TempBookPtr := PrevBookPtr ;
PrevBookPtr := ThisBookPtr ;
ThisBookPtr^.Next[Key] := TempBookPtr ;
END ;
FUNCTION BookExists(TitlePtr : BookPtrType; BookTitle : StringType) : Boolean ;
(* Check if book is in the list, given the title *)
VAR
Found : Boolean ;
BEGIN
Found := false ;
WHILE ((TitlePtr <> NIL) AND (NOT Found)) DO
BEGIN
IF (TitlePtr^.Field[Title] = BookTitle) THEN
Found := true
ELSE
TitlePtr := TitlePtr^.Next[Title] ;
END ;
BookExists := Found ;
END ;
FUNCTION CreateNode : BookPtrType ;
(* Creates space for a new book, and returns a pointer to the new book*)
VAR
BookPtr : BookPtrType ;
Key : KeyType ;
BEGIN
New (BookPtr) ;
writeln (' ' ) ; writeln ('Input Book Information :') ; readln ;
FOR Key := Title TO Author DO
BEGIN
write (Key, ': ') ;
readln (BookPtr^.Field[Key]) ;
BookPtr^.Next[Key] := NIL ;
END ;
CreateNode := BookPtr ;
writeln ;
END ;
PROCEDURE LinkNode (VAR FirstBookPtr : BookPtrArraytype; Key : KeyType; VAR BookPtr : BookPtrType) ;
(* Checks where in a list to insert a book, and inserts it *)
VAR
NextBookPtr : BookPtrType ;
Inserted : Boolean ;
BEGIN
IF (FirstBookPtr[Key]^.Field[Key] > BookPtr^.Field[Key]) THEN
InsertBook (FirstBookPtr[Key], BookPtr, Key)
ELSE
BEGIN
Inserted := false ;
NextBookPtr := FirstBookPtr[Key] ;
WHILE ((NextBookPtr^.Next[Key] <> NIL) AND (NOT Inserted)) DO
BEGIN
WITH NextBookPtr^ DO
BEGIN
IF (Next[Key]^.Field[Key] > BookPtr^.Field[Key]) THEN
BEGIN
InsertBook (Next[Key], BookPtr, Key) ;
Inserted := true ;
END
ELSE
NextBookPtr := Next[Key] ;
END ;
END ;
IF (NOT Inserted) THEN
NextBookPtr^.Next[Key] := BookPtr ;
END ;
END ;
PROCEDURE DeLinkNode (VAR FirstBookPtr : BookPtrArrayType; Key : KeyType; InputTitle : StringType; VAR BookPtr : BookPtrType) ;
(* Removes a book from a list, and returns a pointer to this book*)
VAR
NextBookPtr : BookPtrType ;
BEGIN
IF (FirstBookPtr[Key]^.Field[Title] = InputTitle) THEN
BEGIN
BookPtr := FirstBookPtr[Key] ;
FirstBookPtr[Key] := FirstBookPtr[Key]^.Next[Key] ;
END
ELSE
BEGIN
NextBookPtr := FirstBookPtr[Key] ;
WHILE (NextBookPtr^.Next[Key]^.Field[Title] <> InputTitle) DO
NextBookPtr := NextBookPtr^.Next[Key] ;
WITH NextBookPtr^ DO
BEGIN
BookPtr := Next[Key] ;
Next[Key] := Next[Key]^.Next[Key] ;
END ;
END ;
END ;
PROCEDURE Insert(VAR FirstBookPtr : BookPtrArrayType; VAR Inserted : Boolean) ;
VAR
Key : KeyType ;
NewBookPtr : BookPtrType ;
BEGIN
Inserted := False ;
NewBookPtr := CreateNode ;
IF NOT(BookExists(FirstBookPtr[Title], NewBookPtr^.Field[Title])) THEN
BEGIN
IF (FirstBookPtr[Title] = NIL) THEN
FOR Key := Title TO Author DO
FirstBookPtr[Key] := NewBookPtr
ELSE
BEGIN
FOR Key := Title TO Author DO
LinkNode(FirstBookPtr, Key, NewBookPtr) ;
END ;
Inserted := true ;
END
ELSE
Dispose (NewBookPtr) ;
END ;
PROCEDURE Delete(VAR FirstBookPtr : BookPtrArrayType; InputTitle : StringType; VAR Deleted : Boolean) ;
VAR
Key : KeyType ;
OldBookPtr : BookPtrType ;
BEGIN
Deleted := False ;
IF (BookExists(FirstBookPtr[Title], InputTitle)) THEN
BEGIN
FOR Key := Title TO Author DO
DeLinkNode (FirstBookPtr, Key, InputTitle, OldBookPtr) ;
Dispose (OldBookPtr) ;
Deleted := True ;
END ;
END ;
PROCEDURE ListByKey (FirstBookPtr : BookPtrArrayType; Key : KeyType ) ;
VAR
Count : integer ;
PrintKey : KeyType ;
NextBookPtr : BookPtrType ;
BEGIN
Count := 0 ;
NextBookPtr := FirstBookPtr[Key] ;
writeln (' ') ; writeln ('KEY :', Key) ; writeln (' ') ;
WHILE (NextBookPtr <> NIL) DO
BEGIN
Count := Count + 1 ;
writeln ('Book', Count, ' : Primary key = ', NextBookPtr^.Field[Key]) ;
writeln ;
FOR PrintKey := Title TO Author DO
writeln (PrintKey, ' : ', NextBookPtr^.Field[PrintKey]) ;
NextBookPtr := NextBookPtr^.Next[Key] ;
writeln (' ') ;
END ;
END ;
PROCEDURE ChangeSubject(VAR FirstBookPtr : BookPtrArrayType; InputTitle, NewSubject : StringType; VAR SubjectChanged : Boolean) ;
VAR
InputBookPtr : BookPtrType ;
BEGIN
InputBookPtr := NIL ;
SubjectChanged := false ;
IF BookExists(FirstBookPtr[Title], InputTitle) THEN
BEGIN
DeLinkNode (FirstBookPtr, Subject, InputTitle, InputBookPtr) ;
InputBookPtr^.Field[Subject] := NewSubject ;
InputBookPtr^.Next[Subject] := NIL ;
IF (FirstBookPtr[Subject] = NIL) THEN
FirstBookPtr[Subject] := InputBookPtr
ELSE
LinkNode (FirstBookPtr, Subject, InputBookPtr) ;
SubjectChanged := true ;
END ;
END ;
(* MAIN PROGRAM *)
BEGIN
Quit := false ;
Inserted := false ;
Deleted := false ;
SubjectChanged := false ;
FOR Key := Title TO Author DO
FirstBookPtr[Key] := NIL ;
WHILE (NOT Quit) DO
BEGIN
writeln ('MENU : 1 = Insert, 2 = Delete, 3 = List By Key, 4 = Change Subject, 5 = Quit') ;
write ('What is your choice? ') ;
read (choice) ;
IF NOT((choice < 1) OR (choice > 5)) THEN
BEGIN
CASE choice OF
1 : BEGIN
Insert (FirstBookPtr, Inserted) ;
IF (NOT Inserted) THEN
BEGIN
writeln ;
writeln ('Book is already in Library.') ;
END ;
END ;
2 : BEGIN
writeln (' ') ; write ('Title of book to be deleted?') ;
readln ;
readln (BookTitle) ;
Delete (FirstBookPtr, BookTitle, Deleted) ;
writeln ;
IF (NOT Deleted) THEN
writeln ('Book is not in Library.') ;
END ;
3 : BEGIN
writeln (' '); write ('Which list do you want (1 = Title, 2 = Subject, 3 = Author? ') ;
readln (keychoice) ;
IF NOT((keychoice < 1) OR (keychoice > 3)) THEN
BEGIN
CASE keychoice OF
1 : ListByKey (FirstBookPtr, Title) ;
2 : ListByKey (FirstBookPtr, Subject) ;
3 : ListByKey (FirstBookPtr, Author) ;
END ;
END ;
END ;
4 : BEGIN
writeln (' '); write ('Title of book? ') ;
readln ;
read (BookTitle) ;
writeln (' '); write ('New Subject for book? ') ;
readln ;
read (BookSubject) ;
ChangeSubject (FirstBookPtr, BookTitle, BookSubject, SubjectChanged) ;
writeln (' ') ;
IF NOT(SubjectChanged) THEN
writeln ('Book is not in Library') ;
END ;
5 : BEGIN
ListByKey (FirstBookPtr, Title) ;
Quit := true ;
END ;
END;
END ;
writeln ;
END ;
END.
|
unit ibSHServicesAPIFrm;
interface
uses
SHDesignIntf, SHEvents, ibSHDesignIntf, ibSHDriverIntf, ibSHComponentFrm,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ToolWin, ExtCtrls, ActnList, ImgList, SynEdit,
pSHSynEdit, StdCtrls, Buttons, AppEvnts, Menus;
type
TibSHServicesAPIForm = class(TibBTComponentForm)
ImageList1: TImageList;
Panel1: TPanel;
pSHSynEdit1: TpSHSynEdit;
Panel2: TPanel;
pSHSynEdit2: TpSHSynEdit;
Splitter1: TSplitter;
Panel3: TPanel;
ComboBox1: TComboBox;
Panel6: TPanel;
Label2: TLabel;
Label3: TLabel;
ComboBox2: TComboBox;
ComboBox3: TComboBox;
PopupMenuMessage: TPopupMenu;
pmiHideMessage: TMenuItem;
PopupMenu1: TPopupMenu;
GetDatabaseNameFromRegistrator1: TMenuItem;
GetDatabaseNameFromNavigator1: TMenuItem;
Label1: TLabel;
procedure ComboBox1Enter(Sender: TObject);
procedure pmiHideMessageClick(Sender: TObject);
procedure Panel3Resize(Sender: TObject);
procedure Panel6Resize(Sender: TObject);
private
{ Private declarations }
FServiceIntf: IibSHService;
function GetSaveFile: string;
function GetBackupSourceFile: string;
function GetBackupDestFile: string;
function GetRestoreSourceFile: string;
function GetRestoreDestFile: string;
procedure SetDatabaseNameNav;
procedure SetDatabaseNameReg;
procedure ShowDatabaseNameWindow;
procedure HideDatabaseNameWindow;
procedure ShowBackupRestoreWindow;
procedure HideBackupRestoreWindow;
procedure GutterDrawNotify(Sender: TObject; ALine: Integer; var ImageIndex: Integer);
procedure OnTextNotify(Sender: TObject; const Text: String);
protected
procedure RegisterEditors; override;
procedure EditorMsgVisible(AShow: Boolean = True); override;
{ ISHFileCommands }
function GetCanOpen: Boolean; override;
procedure Open; override;
{ ISHRunCommands }
function GetCanRun: Boolean; override;
function GetCanRefresh: Boolean; override;
procedure Run; override;
procedure Refresh; override;
function DoOnOptionsChanged: Boolean; override;
function GetCanDestroy: Boolean; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string); override;
destructor Destroy; override;
property Service: IibSHService read FServiceIntf;
end;
var
ibSHServicesAPIForm: TibSHServicesAPIForm;
implementation
uses
ibSHconsts, ibSHMessages;
{$R *.dfm}
{ TibSHServicesForm }
constructor TibSHServicesAPIForm.Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string);
begin
inherited Create(AOwner, AParent, AComponent, ACallString);
Supports(Component, IibSHService, FServiceIntf);
Editor := pSHSynEdit1;
Editor.Lines.Clear;
FocusedControl := Editor;
EditorMsg := pSHSynEdit2;
EditorMsg.Clear;
EditorMsg.OnGutterDraw := GutterDrawNotify;
EditorMsg.GutterDrawer.ImageList := ImageList1;
EditorMsg.GutterDrawer.Enabled := True;
RegisterEditors;
DoOnOptionsChanged;
HideDatabaseNameWindow;
HideBackupRestoreWindow;
EditorMsgVisible(False);
if Supports(Component, IibSHDatabaseStatistics) then ShowDatabaseNameWindow;
if Supports(Component, IibSHDatabaseValidation) then ShowDatabaseNameWindow;
if Supports(Component, IibSHDatabaseSweep) then ShowDatabaseNameWindow;
if Supports(Component, IibSHDatabaseMend) then ShowDatabaseNameWindow;
if Supports(Component, IibSHTransactionRecovery) then ShowDatabaseNameWindow;
if Supports(Component, IibSHDatabaseShutdown) then ShowDatabaseNameWindow;
if Supports(Component, IibSHDatabaseOnline) then ShowDatabaseNameWindow;
if Supports(Component, IibSHDatabaseBackup) then ShowBackupRestoreWindow;
if Supports(Component, IibSHDatabaseRestore) then ShowBackupRestoreWindow;
if Supports(Component, IibSHDatabaseProps) then ShowDatabaseNameWindow;
if Panel3.Visible then
begin
if FileExists(GetSaveFile) then
ComboBox1.Items.LoadFromFile(GetSaveFile);
end;
if Panel6.Visible then
begin
if Supports(Component, IibSHDatabaseBackup) then
begin
if FileExists(GetBackupSourceFile) then
ComboBox2.Items.LoadFromFile(GetBackupSourceFile);
if FileExists(GetBackupDestFile) then
ComboBox3.Items.LoadFromFile(GetBackupDestFile);
end;
if Supports(Component, IibSHDatabaseRestore) then
begin
if FileExists(GetRestoreSourceFile) then
ComboBox2.Items.LoadFromFile(GetRestoreSourceFile);
if FileExists(GetRestoreDestFile) then
ComboBox3.Items.LoadFromFile(GetRestoreDestFile);
end;
end;
ComboBox1.Text := SEnterYourDatabaseName;
if Supports(Component, IibSHDatabaseBackup) then
begin
ComboBox2.Text := SEnterYourDatabaseName;
ComboBox3.Text := SEnterYourBackupDatabaseName;
end;
if Supports(Component, IibSHDatabaseRestore) then
begin
ComboBox2.Text := SEnterYourBackupDatabaseName;
ComboBox3.Text := SEnterYourDatabaseName;
end;
SetDatabaseNameNav;
end;
destructor TibSHServicesAPIForm.Destroy;
begin
inherited Destroy;
end;
function TibSHServicesAPIForm.GetSaveFile: string;
begin
Result := Format('%s%s', [Service.BTCLServer.DataRootDirectory, SServicesFile]);
if not SysUtils.DirectoryExists(ExtractFilePath(Result)) then
ForceDirectories(ExtractFilePath(Result));
end;
function TibSHServicesAPIForm.GetBackupSourceFile: string;
begin
Result := Format('%s%s', [Service.BTCLServer.DataRootDirectory, SBackupSourceFile]);
if not SysUtils.DirectoryExists(ExtractFilePath(Result)) then
ForceDirectories(ExtractFilePath(Result));
end;
function TibSHServicesAPIForm.GetBackupDestFile: string;
begin
Result := Format('%s%s', [Service.BTCLServer.DataRootDirectory, SBackupDestinationFile]);
if not SysUtils.DirectoryExists(ExtractFilePath(Result)) then
ForceDirectories(ExtractFilePath(Result));
end;
function TibSHServicesAPIForm.GetRestoreSourceFile: string;
begin
Result := Format('%s%s', [Service.BTCLServer.DataRootDirectory, SRestoreSourceFile]);
if not SysUtils.DirectoryExists(ExtractFilePath(Result)) then
ForceDirectories(ExtractFilePath(Result));
end;
function TibSHServicesAPIForm.GetRestoreDestFile: string;
begin
Result := Format('%s%s', [Service.BTCLServer.DataRootDirectory, SRestoreDestinationFile]);
if not SysUtils.DirectoryExists(ExtractFilePath(Result)) then
ForceDirectories(ExtractFilePath(Result));
end;
procedure TibSHServicesAPIForm.SetDatabaseNameNav;
var
BTCLDatabase: IibSHDatabase;
S: string;
I: Integer;
begin
if Supports(Designer.CurrentDatabase, IibSHDatabase, BTCLDatabase) then
begin
S := BTCLDatabase.Database;
if not Supports(Component, IibSHDatabaseBackup) then
begin
I := ComboBox1.Items.IndexOf(S);
if I <> -1 then ComboBox1.Items.Delete(I);
ComboBox1.Items.Insert(0, S);
ComboBox1.ItemIndex := 0;
end else
begin
I := ComboBox2.Items.IndexOf(S);
if I <> -1 then ComboBox2.Items.Delete(I);
ComboBox2.Items.Insert(0, S);
ComboBox2.ItemIndex := 0;
end;
end;
end;
procedure TibSHServicesAPIForm.SetDatabaseNameReg;
var
BTCLDatabase: IibSHDatabase;
S: string;
I: Integer;
begin
if Supports(Designer.CurrentDatabase, IibSHDatabase, BTCLDatabase) then
begin
S := BTCLDatabase.Database;
if not Supports(Component, IibSHDatabaseBackup) then
begin
I := ComboBox1.Items.IndexOf(S);
if I <> -1 then ComboBox1.Items.Delete(I);
ComboBox1.Items.Insert(0, S);
ComboBox1.ItemIndex := 0;
end else
begin
I := ComboBox2.Items.IndexOf(S);
if I <> -1 then ComboBox2.Items.Delete(I);
ComboBox2.Items.Insert(0, S);
ComboBox2.ItemIndex := 0;
end;
end;
end;
{
Alias := ExtractFileName(AnsiReplaceText(FDatabase, '/', '\'));
if Pos('.', Alias) <> 0 then Alias := Copy(Alias, 1, Pos('.', Alias) - 1);
}
procedure TibSHServicesAPIForm.ShowDatabaseNameWindow;
begin
Panel3.Visible := True;
end;
procedure TibSHServicesAPIForm.HideDatabaseNameWindow;
begin
Panel3.Visible := False;
end;
procedure TibSHServicesAPIForm.ShowBackupRestoreWindow;
begin
Panel6.Visible := True;
end;
procedure TibSHServicesAPIForm.HideBackupRestoreWindow;
begin
Panel6.Visible := False;
end;
procedure TibSHServicesAPIForm.GutterDrawNotify(Sender: TObject; ALine: Integer;
var ImageIndex: Integer);
begin
if ALine = 0 then ImageIndex := 3;
end;
procedure TibSHServicesAPIForm.OnTextNotify(Sender: TObject; const Text: String);
begin
Component.Tag := Component.Tag + 1;
Editor.Lines.Add(Text);
Editor.CaretY := Pred(Editor.Lines.Count);
Application.ProcessMessages;
end;
procedure TibSHServicesAPIForm.RegisterEditors;
var
vEditorRegistrator: IibSHEditorRegistrator;
begin
if Supports(Designer.GetDemon(IibSHEditorRegistrator), IibSHEditorRegistrator, vEditorRegistrator) then
vEditorRegistrator.RegisterEditor(Editor, Service.BTCLServer, Service.BTCLDatabase);
end;
procedure TibSHServicesAPIForm.EditorMsgVisible(AShow: Boolean = True);
begin
Panel2.Visible := AShow;
Splitter1.Visible := AShow;
end;
function TibSHServicesAPIForm.GetCanOpen: Boolean;
begin
Result := Panel3.Visible or Panel6.Visible;
end;
procedure TibSHServicesAPIForm.Open;
var
OpenDialog: TOpenDialog;
begin
OpenDialog := TOpenDialog.Create(nil);
try
if Supports(Component, IibSHDatabaseRestore) then
OpenDialog.Filter := Format('%s', [SOpenDialogDatabaseBackupFilter])
else
OpenDialog.Filter := Format('%s', [SOpenDialogDatabaseFilter]);
if OpenDialog.Execute then
begin
if Supports(Component, IibSHBackupRestoreService) then
begin
if Supports(Component, IibSHDatabaseBackup) then
ComboBox2.Text := OpenDialog.FileName;
if Supports(Component, IibSHDatabaseRestore) then
ComboBox2.Text := OpenDialog.FileName;
end else
ComboBox1.Text := OpenDialog.FileName;
end;
finally
FreeAndNil(OpenDialog);
end;
end;
function TibSHServicesAPIForm.GetCanRun: Boolean;
var
ResultSource, ResultDest: Boolean;
begin
Result := True;
if Panel3.Visible then
begin
Result := Assigned(Service) and
not AnsiSameText(ComboBox1.Text, SEnterYourDatabaseName) and
(Length(ComboBox1.Text) > 0);
end;
if Panel6.Visible then
begin
ResultSource := (Assigned(Service) and
not AnsiSameText(ComboBox2.Text, SEnterYourDatabaseName) and
not AnsiSameText(ComboBox2.Text, SEnterYourBackupDatabaseName) and
(Length(ComboBox2.Text) > 0));
ResultDest := (Assigned(Service) and
not AnsiSameText(ComboBox3.Text, SEnterYourDatabaseName) and
not AnsiSameText(ComboBox3.Text, SEnterYourBackupDatabaseName) and
(Length(ComboBox3.Text) > 0));
Result := ResultSource and ResultDest;
end;
end;
function TibSHServicesAPIForm.GetCanRefresh: Boolean;
begin
Result := False;
end;
procedure TibSHServicesAPIForm.Run;
var
S1, S2, S3: string;
begin
if Assigned(Service) then
begin
Editor.Clear;
EditorMsgVisible(False);
S1 := ComboBox1.Text;
S2 := ComboBox2.Text;
S3 := ComboBox3.Text;
Service.DatabaseName := S1;
Service.OnTextNotify := OnTextNotify;
if Supports(Component, IibSHDatabaseBackup) or Supports(Component, IibSHDatabaseRestore) then
begin
(Component as IibSHBackupRestoreService).SourceFileList.CommaText := S2;
(Component as IibSHBackupRestoreService).DestinationFileList.CommaText := S3;
end;
Designer.UpdateActions;
Application.ProcessMessages;
if not Service.Execute then
begin
EditorMsgVisible;
Designer.TextToStrings(Service.ErrorText, EditorMsg.Lines, True);
end else
begin
if Panel3.Visible then
begin
if ComboBox1.Items.IndexOf(S1) <> -1 then
ComboBox1.Items.Delete(ComboBox1.Items.IndexOf(S1));
ComboBox1.Items.Insert(0, S1);
ComboBox1.ItemIndex := 0;
ComboBox1.Items.SaveToFile(GetSaveFile);
end;
if Panel6.Visible then
begin
if Supports(Component, IibSHDatabaseBackup) then
begin
if ComboBox2.Items.IndexOf(S2) <> -1 then
ComboBox2.Items.Delete(ComboBox2.Items.IndexOf(S2));
ComboBox2.Items.Insert(0, S2);
ComboBox2.ItemIndex := 0;
ComboBox2.Items.SaveToFile(GetBackupSourceFile);
if ComboBox3.Items.IndexOf(S3) <> -1 then
ComboBox3.Items.Delete(ComboBox3.Items.IndexOf(S3));
ComboBox3.Items.Insert(0, S3);
ComboBox3.ItemIndex := 0;
ComboBox3.Items.SaveToFile(GetBackupDestFile);
end;
if Supports(Component, IibSHDatabaseRestore) then
begin
if ComboBox2.Items.IndexOf(S2) <> -1 then
ComboBox2.Items.Delete(ComboBox2.Items.IndexOf(S2));
ComboBox2.Items.Insert(0, S2);
ComboBox2.ItemIndex := 0;
ComboBox2.Items.SaveToFile(GetRestoreSourceFile);
if ComboBox3.Items.IndexOf(S3) <> -1 then
ComboBox3.Items.Delete(ComboBox3.Items.IndexOf(S3));
ComboBox3.Items.Insert(0, S3);
ComboBox3.ItemIndex := 0;
ComboBox3.Items.SaveToFile(GetRestoreDestFile);
end;
end;
end;
end;
end;
procedure TibSHServicesAPIForm.Refresh;
begin
end;
function TibSHServicesAPIForm.DoOnOptionsChanged: Boolean;
begin
Result := inherited DoOnOptionsChanged;
if Result and Assigned(Editor) then
begin
Editor.ReadOnly := True;
Editor.Options := Editor.Options + [eoScrollPastEof];
Editor.Highlighter := nil;
// Принудительная установка фонта
Editor.Font.Charset := 1;
Editor.Font.Color := clWindowText;
Editor.Font.Height := -13;
Editor.Font.Name := 'Courier New';
Editor.Font.Pitch := fpDefault;
Editor.Font.Size := 10;
Editor.Font.Style := [];
end;
end;
function TibSHServicesAPIForm.GetCanDestroy: Boolean;
begin
Result := inherited GetCanDestroy;
//Service.DRVService.
end;
procedure TibSHServicesAPIForm.ComboBox1Enter(Sender: TObject);
begin
if Sender is TComboBox then
begin
if AnsiSameText(TComboBox(Sender).Text, SEnterYourDatabaseName) or
AnsiSameText(TComboBox(Sender).Text, SEnterYourBackupDatabaseName) then
begin
TComboBox(Sender).Text := ' ';
TComboBox(Sender).Text := EmptyStr;
TComboBox(Sender).Invalidate;
TComboBox(Sender).Repaint;
end;
end;
end;
procedure TibSHServicesAPIForm.pmiHideMessageClick(Sender: TObject);
begin
EditorMsgVisible(False);
end;
procedure TibSHServicesAPIForm.Panel3Resize(Sender: TObject);
begin
ComboBox1.Width := ComboBox1.Parent.ClientWidth - ComboBox1.Left * 2;
end;
procedure TibSHServicesAPIForm.Panel6Resize(Sender: TObject);
begin
ComboBox2.Width := ComboBox2.Parent.ClientWidth - ComboBox2.Left * 2;
ComboBox3.Width := ComboBox3.Parent.ClientWidth - ComboBox3.Left * 2;
end;
end.
|
Unit Signal;
{ * Signal: *
* *
* Esta unidad es la encargada de chequear si la tarea actual posee *
* alguna se¤al pendiente y ejecutar la se¤al correspondiente *
* de la se¤al se deve volver con un RET , como si fuese una *
* llamada CALL convenicional , si hay muchas signal esperando ser *
* atendidas son anidas y la ultima vuelve a la tarea que se estaba *
* ejecutando *
* Cada BIT de los flags de signal corresponde a un puntero dentro *
* del array de punteros signals[] *
* *
* Hay un total de 32 Signals posibles *
* *
* Copyright (c) 2003-2006 Matias Vara <matiasevara@gmail.com> *
* All Rights Reserved *
* *
* Versiones : *
* *
* 02 / 04 / 2005 : Es reescrita la mayor parte de la unidad *
* ?? - ?? - ?? : Version Inicial *
* *
**********************************************************************
}
interface
{DEFINE DEBUG}
{$I ../include/toro/procesos.inc}
{$I ../include/toro/signal.inc}
{$I ../include/head/irq.h}
{$I ../include/head/gdt.h}
{$I ../include/head/mm.h}
{$I ../include/head/idt.h}
{$I ../include/head/asm.h}
{$I ../include/head/scheduler.h}
{$I ../include/head/procesos.h}
{$I ../include/head/printk_.h}
implementation
{ * Empilar_Signal : *
* *
* new_ret : Nuevo punto de retorno *
* *
* Proceso que se encarga de anidar las se¤ales de un proceso *
* *
**************************************************************************
}
function enpilar_signal (new_ret : pointer ) : dword ;
var tmp , esp : ^dword ;
s : dword ;
begin
{ Puntero donde se encuentra la direcion de retorno }
tmp := Tarea_Actual^.ret_eip ;
{ la salvo }
s := tmp^ ;
{ nueva direccion de retorno }
tmp^ := longint(new_ret);
{ esp de retorno }
tmp := Tarea_Actual^.ret_esp ;
{ ahora devo decrementar para guardar el retorno anterior }
tmp^ -= 4;
esp := pointer(tmp^) ;
{ coloco en la pila de usuario el retorno anterior }
esp^ := s ;
exit(0);
end;
{ * Kernel_Signal_Handler : *
* *
* Manejador de las se¤ales del kernel , cuando un proceso no quiere *
* controlarlas el mismo el kernel lo hara , siempre se destruye al *
* proceso si recibe una se¤al no esperada no procesable *
* *
***********************************************************************
}
procedure kernel_signal_handler;
var tarea:pointer ;
begin
//printk('$d',[],[Tarea_Actual^.pid]);
printk('/nMuerte por Se¤al : %s \n',[dword(@Sig_name[tarea_actual^.terminacion][1])]);
Proceso_destruir (Tarea_Actual);
scheduling;
end;
{ * Signaling : *
* *
* Este proceso es el nucleo de las se¤ales , este es llamado cada vez *
* que se vuelve a ejecutar una tarea , y evalua que bit de signal esta*
* activo y de acuerdo a estos bit , ejecuta su hilo correspondiente , *
* *
***********************************************************************
}
procedure signaling;[public , alias : 'SIGNALING'];
var tmp , ret : dword ;
ret2 : word;
signal_handler , tarea: pointer ;
begin
{ Son rastreadas todas las signal }
for tmp:= 0 to 31 do
begin
{ Se esta aguardando por su ejecucion ? }
if Bit_Test(@Tarea_Actual^.flags_de_signal,tmp) then
begin
signal_handler := Tarea_actual^.signals[tmp];
{ Se baja el bit de pendiente }
bit_reset(@Tarea_Actual^.flags_de_signal,tmp);
case tmp of
Sig_Hijo : begin
Esperar_Hijo (Tarea_Actual,ret,ret2);
continue;
end;
Sig_Morir:begin
Tarea_Actual^.terminacion := Sig_Morir ;
Proceso_Destruir (Tarea_Actual) ;
{ Se replanifica }
Scheduling;
exit;
end;
Sig_Detener:begin
Proceso_Interrumpir (Tarea_Actual,Tq_Interrumpidas);
exit;
end;
Sig_Alarm:begin
Enpilar_signal (signal_handler);
Tarea_Actual^.signals[Sig_Alarm] := nil ;
end;
Sig_ili : begin
{ puede ser que el kernel deva ocuparse de la se¤al }
if signal_handler = nil then
begin
Tarea_actual^.terminacion := Sig_ili ;
kernel_signal_handler;
end;
end;
Sig_Segv : begin
{ puede ser que el kernel deva ocuparse de la se¤al }
if signal_handler = nil then
begin
Tarea_actual^.terminacion := Sig_Segv ;
kernel_signal_handler;
end;
end;
Sig_Dive : begin
{ puede ser que el kernel deva ocuparse de la se¤al }
if signal_handler = nil then
begin
Tarea_actual^.terminacion := Sig_Dive ;
kernel_signal_handler;
end;
end;
Sig_Fpue : begin
{ puede ser que el kernel deva ocuparse de la se¤al }
if signal_handler = nil then
begin
Tarea_actual^.terminacion := Sig_Fpue ;
kernel_signal_handler;
end;
end;
Sig_BrkPoint : begin
if signal_handler = nil then
begin
Tarea_Actual^.terminacion := Sig_brkpoint ;
kernel_signal_handler;
end;
end;
Sig_OverFlow : begin
if signal_handler = nil then
begin
Tarea_Actual^.terminacion := Sig_Overflow ;
kernel_signal_handler;
end;
end;
end;
{ la se¤al es procesada por el usuario }
Enpilar_Signal (signal_handler);
Tarea_Actual^.signals[tmp] := nil ;
end;
end;
end;
{ * Signal_Send : *
* *
* Tarea:Tarea a la que se le envia la se¤al *
* signal: Numero de se¤al *
* *
* Esta funcion envia una se¤al a la tarea indicada en TAREA , activando *
* el correspondiente BIT *
* Devolvera error si no hubiera un tratamiento para la se¤al *
* *
*************************************************************************
}
procedure signal_send(Tarea:p_tarea_struc;signal:word);[public , alias :'SIGNAL_SEND'];
begin
{ Zona critica }
cerrar;
if Tarea_Actual= nil then Panic ('/nImposible cargar toro , excepcion desconocida !!!!\n');
{ Ya se esta procesando otra signal }
if Bit_test(@tarea^.flags_de_signal,signal) then exit;
{ Se activa su bit }
Bit_Set(@Tarea^.flags_de_signal,signal);
abrir;
{$IFDEF DEBUG}
printk('/nSignal : %d /n --> Pid : %d /V Send\n',[signal,Tarea_actual^.pid],[]);
{$ENDIF}
end;
end.
|
unit Controllers.Tour;
interface
uses
Classes,
System.Generics.Collections;
type
TTourController = class
public
class procedure GetLevels( AList: TList<string> );
class procedure ListTours( const ALevel: String; AList: TList<string> );
class procedure GetTour( const ALevel, AName: String; AStream: TStream );
end;
implementation
{ TTourController }
uses
SysUtils,
System.IOUtils,
Modules.Configuration;
class procedure TTourController.GetLevels(AList: TList<string>);
var
LRoot : String;
LLevels: TArray<string>;
LLevel: string;
begin
if Assigned( AList ) then
begin
LRoot := Configuration.FolderName;
LLevels := TDirectory.GetDirectories(LRoot);
AList.Clear;
for LLevel in LLevels do
begin
AList.Add( ExtractFileName( LLevel ) );
end;
end;
end;
class procedure TTourController.GetTour(const ALevel, AName: String; AStream: TStream);
var
LPath: String;
LMemory: TMemoryStream;
begin
if Assigned( AStream ) then
begin
LPath := TPath.Combine(Configuration.FolderName, ALevel );
LMemory := TMemoryStream.Create;
try
LMemory.LoadFromFile(TPath.Combine(LPath, AName + '.gpx'));
LMemory.Position := 0;
AStream.CopyFrom(LMemory, LMemory.Size);
finally
LMemory.Free;
end;
end;
end;
class procedure TTourController.ListTours(const ALevel: String; AList: TList<string>);
var
LPath: String;
LFiles: TArray<string>;
LFile: String;
begin
if Assigned( AList ) then
begin
AList.Clear;
LPath := TPath.Combine(Configuration.FolderName, ALevel);
LFiles := TDirectory.GetFiles(LPath, '*.gpx');
for LFile in LFiles do
begin
AList.Add(TPath.GetFileNameWithoutExtension(LFile));
end;
end;
end;
end.
|
(* Players Field of View function *)
unit fov;
{$mode objfpc}{$H+}
interface
uses
map, globalutils;
(* Draw Bresenham lines in a circle *)
procedure drawLine(x1, y1, x2, y2: smallint; hiDef: byte);
(* Calculate circle around player *)
procedure fieldOfView(centreX, centreY, radius: smallint; hiDef: byte);
implementation
procedure drawLine(x1, y1, x2, y2: smallint; hiDef: byte);
var
i, deltax, deltay, numpixels, d, dinc1, dinc2, x, xinc1, xinc2, y,
yinc1, yinc2: smallint;
begin
(* Calculate delta X and delta Y for initialisation *)
deltax := abs(x2 - x1);
deltay := abs(y2 - y1);
(* Initialize all vars based on which is the independent variable *)
if deltax >= deltay then
begin
(* x is independent variable *)
numpixels := deltax + 1;
d := (2 * deltay) - deltax;
dinc1 := deltay shl 1;
dinc2 := (deltay - deltax) shl 1;
xinc1 := 1;
xinc2 := 1;
yinc1 := 0;
yinc2 := 1;
end
else
begin
(* y is independent variable *)
numpixels := deltay + 1;
d := (2 * deltax) - deltay;
dinc1 := deltax shl 1;
dinc2 := (deltax - deltay) shl 1;
xinc1 := 0;
xinc2 := 1;
yinc1 := 1;
yinc2 := 1;
end;
(* Make sure x and y move in the right directions *)
if x1 > x2 then
begin
xinc1 := -xinc1;
xinc2 := -xinc2;
end;
if y1 > y2 then
begin
yinc1 := -yinc1;
yinc2 := -yinc2;
end;
(* Start tracing line at *)
x := x1;
y := y1;
(* Draw the pixels *)
for i := 1 to numpixels do
begin
(* Check that we are not searching out of bounds of map *)
if (x >= 1) and (x <= globalutils.MAXCOLUMNS) and (y >= 1) and
(y <= globalutils.MAXROWS) then
begin
if (hiDef = 1) then
begin
map.drawTile(x, y, 1);
map.maparea[y][x].Visible := True;
map.maparea[y][x].Discovered := True;
if (map.maparea[y][x].Blocks = True) then
exit;
end
else
begin
map.drawTile(x, y, 0);
map.maparea[y][x].Visible := False;
map.maparea[y][x].Discovered := True;
if (map.maparea[y][x].Blocks = True) then
exit;
end;
end;
if d < 0 then
begin
d := d + dinc1;
x := x + xinc1;
y := y + yinc1;
end
else
begin
d := d + dinc2;
x := x + xinc2;
y := y + yinc2;
end;
end;
end;
procedure fieldOfView(centreX, centreY, radius: smallint; hiDef: byte);
var
d, x, y: smallint;
begin
d := 3 - (2 * radius);
x := 0;
y := radius;
while (x <= y) do
begin
drawLine(centreX, centreY, centreX + X, centreY + Y, hiDef);
drawLine(centreX, centreY, centreX + X, centreY - Y, hiDef);
drawLine(centreX, centreY, centreX - X, centreY + Y, hiDef);
drawLine(centreX, centreY, centreX - X, centreY - Y, hiDef);
drawLine(centreX, centreY, centreX + Y, centreY + X, hiDef);
drawLine(centreX, centreY, centreX + Y, centreY - X, hiDef);
drawLine(centreX, centreY, centreX - Y, centreY + X, hiDef);
drawLine(centreX, centreY, centreX - Y, centreY - X, hiDef);
(* cover the gaps in the circle *)
if (radius = 5) then
begin
drawLine(centreX, centreY, centreX + 3, centreY - 3, hiDef);
drawLine(centreX, centreY, centreX + 3, centreY + 3, hiDef);
drawLine(centreX, centreY, centreX - 3, centreY + 3, hiDef);
drawLine(centreX, centreY, centreX - 3, centreY - 3, hiDef);
end;
if (radius = 6) then
begin
drawLine(centreX, centreY, centreX + 4, centreY - 3, hiDef);
drawLine(centreX, centreY, centreX + 3, centreY - 4, hiDef);
drawLine(centreX, centreY, centreX - 4, centreY - 3, hiDef);
drawLine(centreX, centreY, centreX - 3, centreY - 4, hiDef);
drawLine(centreX, centreY, centreX + 4, centreY + 3, hiDef);
drawLine(centreX, centreY, centreX + 3, centreY + 4, hiDef);
drawLine(centreX, centreY, centreX - 4, centreY + 3, hiDef);
drawLine(centreX, centreY, centreX - 3, centreY + 4, hiDef);
end;
if (d < 0) then
d := d + (4 * x) + 6
else
begin
d := d + 4 * (x - y) + 10;
y := y - 1;
end;
Inc(x);
end;
end;
end.
|
unit NetWorkUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, ExtCtrls;
type
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
THabBtn = class(TGraphicControl)
private
FOnPaint: TNotifyEvent;
MouseExsist:Boolean;
BC:TColor;
FFlat:Boolean;
FPortNum:Byte;
FHabName:string;
FIcon:TIcon;
FIconProp:WORD;
procedure CMMouseEnter (var message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave (var message: TMessage); message CM_MOUSELEAVE;
procedure SetFFlat(const Value: Boolean);
procedure SetFIcon(const Value: TIcon);
procedure SetIconProp(const Value: Word);
procedure SetPortNum(const Value: Byte);
procedure SetHabName(const Value: string);
protected
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
property Canvas;
published
property Align;
property Anchors;
property Color;
property BorderColor: TColor read BC write BC;
property Constraints;
property Caption;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property Flat:Boolean read FFlat write SetFFlat default False;
property HabName:string read FHabName write SetHabName;
property Icon:TIcon read FIcon write SetFIcon;
property IconPropertis:Word read FIconProp write SetIconProp;
property ParentColor;
property ParentFont default False;
property ParentShowHint;
property PortNym:Byte read FPortNum write SetPortNum;
property PopupMenu;
property ShowHint;
property Visible;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnPaint: TNotifyEvent read FOnPaint write FOnPaint;
property OnStartDock;
property OnStartDrag;
end;
implementation
procedure THabBtn.CMMouseEnter(var message: TMessage);
begin
MouseExsist:=True;
Repaint;
end;
procedure THabBtn.CMMouseLeave(var message: TMessage);
begin
MouseExsist:=False;
Repaint;
end;
constructor THabBtn.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csReplicatable];
Width := 50;
Height := 50;
FIcon:=TIcon.Create;
FIcon.Width := 32;
FIcon.Height := 32;
FIconProp:=32;
FPortNum:=8;
MouseExsist:=False;
FHabName:='';
end;
procedure THabBtn.Paint;
var kl, kt, tl, tt:integer;
IconSiz:integer;
TR:TRect;
OldBkMode : integer;
begin
Canvas.Font:=Font;
if Icon.Handle = 0
then IconSiz:=0
else IconSiz:=FIconProp;
tl:=(Width - Canvas.TextWidth(Caption))div(2);
tt:=(Height - Canvas.TextHeight(Caption))div(2);
kl:=(Width - IconSiz)div(2);
kt:=(Height - IconSiz)div(2);
if (MouseExsist)and(not FFlat)
then begin
Canvas.Pen.Color:=Color;
Canvas.Brush.Color:=Color;
Canvas.RoundRect(0,0, Width, Height, 5, 5);
end;
if FFlat
then begin
Canvas.Pen.Color:=BC;
Canvas.Brush.Color:=Color;
kl:=kl+1;
kt:=kt+1;
Canvas.RoundRect(0,0, Width, Height, 5, 5);
end;
DrawIconEx(Canvas.Handle, kl, kt,FIcon.Handle, FIconProp, FIconProp, 0, 0, DI_NORMAL);
TR:=Rect(tl, tt, Canvas.ClipRect.Right, Canvas.ClipRect.Bottom);
OldBkMode := SetBkMode(Canvas.Handle,1);
DrawText(Canvas.Handle, PChar(Caption), Length(Caption), TR, 0);
SetBkMode(Canvas.Handle,OldBkMode);
end;
procedure THabBtn.SetFFlat(const Value: Boolean);
begin
FFlat := Value;
Repaint;
end;
procedure THabBtn.SetFIcon(const Value: TIcon);
begin
FIcon.Assign(Value);
Repaint;
end;
procedure THabBtn.SetHabName(const Value: string);
begin
FHabName := Value;
end;
procedure THabBtn.SetIconProp(const Value: Word);
begin
if FIconProp = Value
then exit;
FIconProp := Value;
end;
procedure THabBtn.SetPortNum(const Value: Byte);
begin
FPortNum := Value;
end;
end.
|
unit ExprMatching;
{
Parses expression and reading records.
Sometimes in places where we expect expression, a clarification is needed
and reading is added in one of various ways:
<ruby>側<rt>そば</rt></ruby>
側 [そば]
側(そば)
側・そば
Sometimes it's excessive (e.g. it was only a visual clue and we have this data
from another column), at other times important.
We also support multi-value splitting here, e.g.
側 [がわ、そば]
In case someone thinks several readings/writings are interchangeable, but only
to a limited extent. We do not support full-blown EDICT style kana-to-kanji
matching:
側、侧 [がわ(侧、側)、そば(側)] --- not supported
Usage:
SetInlineReadingPattern('your inline-reading regex'); //optionally
read := StripInlineReading(expr);
read := StripInlineReading(expr);
}
interface
uses UniStrUtils;
//Overrides default expression/reading separtor
procedure SetExpressionSeparator(const ASep: char);
procedure SetReadingSeparator(const ASep: char);
//Overrides default matching patterns with this regex. It must match all patterns
//and put expression into \k'expr' and reading into \k'read'
procedure SetExpressionPattern(const pattern: string);
procedure SetReadingPattern(const pattern: string);
//Matches ONE expression inplace, removing everything not matched. If reading
//was provided, it's returned in read.
procedure MatchExpression(var expr: string; out read: string);
procedure MatchReading(var expr: string);
type
TExpression = record
expr: string;
readings: TStringArray;
end;
PExpression = ^TExpressions;
TExpressions = array of TExpression;
//Splits the string with the appropriate separator and matches all items
//with MatchExpression/Reading.
function ParseExpressions(const expr: string): TExpressions; overload;
function ParseExpressions(const expr, read: string): TExpressions; overload;
type
TReading = record
read: string;
expressions: array of integer; //expression indexes
end;
PReading = ^TReading;
TReadings = array of TReading;
//Converts "kanji with attached kana" to "kana with attached kanji"
function ExpressionsToReadings(const expr: TExpressions): TReadings;
implementation
uses SysUtils, RegularExpressionsCore, RegexUtils;
var
ExpressionSeparator: char = '、';
ReadingSeparator: char = #00; //same as expression
//Default expression pattern
ptExpression: string = '(?J)(?|'
+'<ruby>(?''expr''[^<>]*)<rt>(?''read''[^<>]*)</rt></ruby>'+'|'
+'(?''expr''[^\[]*)\s*\[(?''read''[^\]]*)\]'+'|'
+'(?''expr''[^(]*)\s*((?''read''[^)]*))'+'|'
+'(?''expr''[^・]*)\s*・s*(?''read''.*)'
+'?)';
ptReading: string = '';
preExpression: TPerlRegEx = nil;
preReading: TPerlRegEx = nil;
procedure SetExpressionSeparator(const ASep: char);
begin
ExpressionSeparator := ASep;
end;
procedure SetReadingSeparator(const ASep: char);
begin
ReadingSeparator := ASep;
end;
procedure SetExpressionPattern(const pattern: string);
begin
ptExpression := pattern;
FreeAndNil(preExpression);
end;
procedure SetReadingPattern(const pattern: string);
begin
ptExpression := pattern;
FreeAndNil(preReading);
end;
procedure MatchExpression(var expr: string; out read: string);
var id: integer;
begin
read := '';
if ptExpression='' then exit;
if preExpression=nil then
preExpression := Regex(ptExpression);
preExpression.Subject := UTF8String(expr);
if not preExpression.Match then exit;
id := preExpression.NamedGroup('expr');
if id<0 then exit; //no expr group
expr := string(preExpression.Groups[id]);
id := preExpression.NamedGroup('read');
if id>=0 then
read := string(preExpression.Groups[id]);
end;
procedure MatchReading(var expr: string);
var id: integer;
begin
if ptReading='' then exit;
if preReading=nil then
preReading := Regex(ptReading);
preReading.Subject := UTF8String(expr);
if not preReading.Match then exit;
id := preReading.NamedGroup('expr');
if id<0 then exit;//no expr group
expr := string(preExpression.Groups[id]);
end;
function SplitReadings(const read: string): TStringArray;
begin
if ReadingSeparator=#00 then
Result := StrSplit(PChar(read), ExpressionSeparator)
else
Result := StrSplit(PChar(read), ReadingSeparator);
end;
function FindReading(const AReadings: TStringArray; const read: string): integer;
var i: integer;
begin
Result := -1;
for i := 0 to Length(AReadings)-1 do
if AReadings[i]=read then begin
Result := i;
break;
end;
end;
//Merges all readings used in expressions to a single list
function MergeReadings(const expr: TExpressions): TStringArray;
var i, j: integer;
begin
SetLength(Result, 0);
for i := 0 to Length(expr)-1 do
for j := 0 to Length(expr[i].readings)-1 do
if FindReading(Result, expr[i].readings[j])<0 then begin
SetLength(Result, Length(Result)+1);
Result[Length(Result)-1] := expr[i].readings[j];
end;
end;
function ParseExpressions(const expr: string): TExpressions;
var parts: TStringArray;
i: integer;
read: string;
begin
parts := StrSplit(PChar(expr), ExpressionSeparator);
SetLength(Result, Length(parts));
for i := 0 to Length(parts)-1 do begin
Result[i].expr := parts[i];
MatchExpression(Result[i].expr, read);
if read<>'' then
Result[i].readings := SplitReadings(read)
else
SetLength(Result[i].readings, 0);
end;
end;
function ParseExpressions(const expr, read: string): TExpressions;
var readings, r2: TStringArray;
i: integer;
begin
Result := ParseExpressions(expr);
readings := SplitReadings(read);
for i := 0 to Length(readings)-1 do
MatchReading(readings[i]);
//Copy common readings to expressions where no exact readings are given
for i := 0 to Length(Result)-1 do
if Result[i].readings=nil then
Result[i].readings := readings;
//Check that all the external readings are used or it's a warning
r2 := MergeReadings(Result);
for i := 0 to Length(r2)-1 do
if FindReading(readings, r2[i])<0 then
writeln(ErrOutput, 'Warning: reading '+r2[i]+' not assigned to any kanji in "'+expr+' : '+read+'"');
end;
function ExpressionsToReadings(const expr: TExpressions): TReadings;
var readings: TStringArray;
i, j: integer;
begin
readings := MergeReadings(expr);
SetLength(Result, Length(readings));
for i := 0 to Length(readings)-1 do begin
Result[i].read := readings[i];
SetLength(Result[i].expressions, 0);
for j := 0 to Length(expr)-1 do
if FindReading(expr[j].readings, readings[i])>=0 then begin
SetLength(Result[i].expressions, Length(Result[i].expressions)+1);
Result[i].expressions[Length(Result[i].expressions)-1] := j;
end;
if Length(Result[i].expressions)=Length(expr) then //all expressions matched
SetLength(Result[i].expressions, 0); //informal "all matched"
end;
end;
end.
|
{
Библиотека дополнительных утилит
Дополнительные процедуры и функции общего назначения
© Роман М. Мочалов, 1997-2001
E-mail: roman@sar.nnov.ru
}
unit ExtSysUtils;
interface
{$I EX.INC}
uses
SysUtils;
{ Перевод строки в верщественное число. При возникновении ошибки не
создает исключение, но присваивает результату значение по умолчанию. }
function StrToFloatDef(const S: string; Default: Extended): Extended;
{ Обработка сообщения исключительной ситуации (Exception): удаление
переносов строки, точки на конце строки. }
function ExceptionMsg(E: Exception): string;
{ Получение первого попавшегося параметра командной строки, который
равен указанной строке (PartialOK = True) или начинается на указанную
строку (PartialOK = False). }
function FindParam(const Param: string; PartialOK: Boolean; var Value: string): Boolean;
{ Определение наличия параметра командной строки. }
function ParamExists(const Param: string; PartialOK: Boolean): Boolean;
function ParamsExists(const Params: array of string; PartialOK, CheckAll: Boolean): Boolean;
{ Определение значения параметра. Возвращает строку, слудующую сразу за
указанныой строкой. Например, для строки -F значение параметра командной
строки -FExtUtils.pas будет равно ExtUtils.pas }
function GetParamValue(const Param: string): string;
function GetParamValueDef(const Param: string; const Default: string): string;
{ Вставка, удаление и перемещение элементов в произвольном массиве с
заданным размером Функции врзвращают False, если указаны неверные
индексы. }
function ArrayInsert(Items: Pointer; Count, ItemSize: Integer; Index: Integer; Item: Pointer): Boolean;
function ArrayDelete(Items: Pointer; Count, ItemSize: Integer; Index: Integer; Item: Pointer): Boolean;
function ArrayExchange(Items: Pointer; Count, ItemSize: Integer; Index1, Index2: Integer): Boolean;
function ArrayMove(Items: Pointer; Count, ItemSize: Integer; CurIndex, NewIndex: Integer): Boolean;
{ Освобождение памяти. Пред удалением проверяем указатель на nil. }
procedure FreeMemAndNil(var P; Size: Integer);
{$IFNDEF EX_D5_UP}
procedure FreeAndNil(var Obj);
{$ENDIF}
{ Заливка буфера указанным 4-байтовым значением. }
procedure FillDWord(var Dest; Count, Value: Integer); register;
implementation
uses
ExtStrUtils;
{ Перевод строки в верщественное число }
function StrToFloatDef(const S: string; Default: Extended): Extended;
begin
if not TextToFloat(PChar(S), Result, fvExtended) then Result := Default;
end;
{ Обработка сообщения исключительной ситуации }
function ExceptionMsg(E: Exception): string;
begin
Result := RemoveLineBreaks(TrimCharRight(E.Message, '.'));
end;
{ Поиск параметра }
function FindParam(const Param: string; PartialOK: Boolean; var Value: string): Boolean;
var
I, P: Integer;
begin
{ перебираем параметры командной строки }
for I := 1 to ParamCount do
begin
{ получаем параметр }
Value := ParamStr(I);
{ проверяем частичное совпадение }
if PartialOK then
begin
{ ищем в параметре искомый }
P := CasePos(Param, Value, False);
if P = 1 then
begin
{ параметр существует - выход }
Result := True;
Exit;
end;
end
else
{ сравниваем }
if AnsiCompareText(Param, Value) = 0 then
begin
{ параметр существует - выход }
Result := True;
Exit;
end;
end;
{ параметра нет }
Value := '';
Result := False;
end;
{ Определение наличия параметра командной строки }
function ParamExists(const Param: string; PartialOK: Boolean): Boolean;
var
Value: string;
begin
Result := FindParam(Param, PartialOK, Value);
end;
function ParamsExists(const Params: array of string; PartialOK, CheckAll: Boolean): Boolean;
var
I, Count: Integer;
begin
Count := 0;
{ перебираем параметры }
for I := Low(Params) to High(Params) do
if ParamExists(Params[I], PartialOK) then Inc(Count);
{ результат }
if CheckAll then
Result := Count = High(Params) - Low(Params) + 1
else
Result := Count > 0;
end;
{ Определение значения параметра }
function GetParamValue(const Param: string): string;
begin
Result := GetParamValueDef(Param, '');
end;
function GetParamValueDef(const Param: string; const Default: string): string;
var
Value: string;
begin
if FindParam(Param, True, Value) then
Result := Copy(Value, Length(Param) + 1, MaxInt)
else
Result := Default;
end;
{ Вставка, удаление и перемещение элементов в произвольном массиве с
заданным размером элеменнта }
function ArrayInsert(Items: Pointer; Count, ItemSize: Integer; Index: Integer; Item: Pointer): Boolean;
var
PI, PI1: PChar;
begin
{ проверяем индекс }
if (Index < 0) or (Index > Count) then
begin
Result := False;
Exit;
end;
{ указатели на элемент Index и следующий }
PI := PChar(Items) + Index * ItemSize;
PI1 := PChar(Items) + (Index + 1) * ItemSize;
{ вставляем }
if Index < Count then Move(PI^, PI1^, (Count - Index) * ItemSize);
if Item <> nil then Move(Item^, PI^, ItemSize);
{ элемент вставлен }
Result := True;
end;
function ArrayDelete(Items: Pointer; Count, ItemSize: Integer; Index: Integer; Item: Pointer): Boolean;
var
PI, PI1: PChar;
begin
{ проверяем индекс }
if (Index < 0) or (Index >= Count) then
begin
Result := False;
Exit;
end;
{ указатели на элемент Index и следующий }
PI := PChar(Items) + Index * ItemSize;
PI1 := PChar(Items) + (Index + 1) * ItemSize;
{ запоминаем элемент, удаляем }
if Item <> nil then Move(PI^, Item^, ItemSize);
if Index < Count then System.Move(PI1^, PI^, (Count - Index) * ItemSize);
{ элемент удален }
Result := True;
end;
function ArrayExchange(Items: Pointer; Count, ItemSize: Integer; Index1, Index2: Integer): Boolean;
var
PI1, PI2: Pointer;
Item: Pointer;
begin
Result := True;
{ не меняем элемент сам с собой }
if Index1 <> Index2 then
begin
{ проверяем индексы }
if (Index1 < 0) or (Index1 >= Count) or (Index2 < 0) or (Index2 >= Count) then
begin
Result := False;
Exit;
end;
{ буфер под элемент }
GetMem(Item, ItemSize);
try
{ указатели на элементы Index1 Index2 }
PI1 := PChar(Items) + Index1 * ItemSize;
PI2 := PChar(Items) + Index2 * ItemSize;
{ меняем местами }
Move(PI1^, Item^, ItemSize);
Move(PI2^, PI1^, ItemSize);
Move(Item^, PI2^, ItemSize);
finally
FreeMem(Item, ItemSize);
end;
end;
end;
function ArrayMove(Items: Pointer; Count, ItemSize: Integer; CurIndex, NewIndex: Integer): Boolean;
var
Item: Pointer;
begin
Result := True;
{ надо ли двигать элемент }
if CurIndex <> NewIndex then
begin
{ проверяем индексы }
if (NewIndex < 0) or (NewIndex >= Count) then
begin
Result := False;
Exit;
end;
{ буфер под элемент }
GetMem(Item, ItemSize);
try
{ передвигаем }
ArrayDelete(Items, Count, ItemSize, CurIndex, Item);
ArrayInsert(Items, Count, ItemSize, NewIndex, Item);
finally
FreeMem(Item, ItemSize);
end;
end;
end;
{ Освобождение памяти. Пред удалением проверяем указатель на nil. }
procedure FreeMemAndNil(var P; Size: Integer);
var
Mem: Pointer;
begin
Mem := Pointer(P);
Pointer(P) := nil;
if Mem <> nil then FreeMem(Mem, Size);
end;
{$IFNDEF EX_D5_UP}
procedure FreeAndNil(var Obj);
var
P: TObject;
begin
P := TObject(Obj);
TObject(Obj) := nil;
P.Free;
end;
{$ENDIF}
{ Заливка буфера указанным 4-байтовым значением }
procedure FillDWord(var Dest; Count, Value: Integer); register;
asm
XCHG EDX, ECX
PUSH EDI
MOV EDI, EAX
MOV EAX, EDX
REP STOSD
POP EDI
end;
end.
|
unit Demo.Histogram.MultipleSeries;
interface
uses
System.Classes, System.Variants, Demo.BaseFrame, cfs.GCharts;
type
TDemo_Histogram_MultipleSeries = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_Histogram_MultipleSeries.GenerateChart;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_HISTOGRAM_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Quarks'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Leptons'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Gauge Bosons'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Scalar Bosons')
]);
Chart.Data.AddRow([2/3, -1, 0, 0]);
Chart.Data.AddRow([2/3, -1, 0, null]);
Chart.Data.AddRow([2/3, -1, 0, null]);
Chart.Data.AddRow([-1/3, 0, 1, null]);
Chart.Data.AddRow([-1/3, 0, -1, null]);
Chart.Data.AddRow([-1/3, 0, null, null]);
Chart.Data.AddRow([-1/3, 0, null, null]);
// Options
Chart.Options.Title('Charges of subatomic particles');
Chart.Options.Legend('position', 'top');
Chart.Options.Legend('maxLines', 2);
Chart.Options.Colors(['#5C3292', '#1A8763', '#871B47', '#999999']);
Chart.Options.InterpolateNulls(false);
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="Chart1" style="width:100%;height:100%;"></div>');
GChartsFrame.DocumentGenerate('Chart1', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_Histogram_MultipleSeries);
end.
|
namespace GlHelper;
{$GLOBALS ON}
interface
uses
rtl,
{$IF ISLAND AND Windows}
//RemObjects.Elements.System,
{$ELSEIF TOFFEE}
Foundation,
{$ENDIF}
RemObjects.Elements.RTL,
OpenGL;
type
{$IF TOFFEE}
PGLChar = ^GLchar;
{$ENDIF}
Shader= public class
{$REGION 'Internal Declarations'}
private
FProgram: GLuint;
private
class method CreateShader(const AShaderPath: String; const AShaderType: GLenum): GLuint;
public
{ IShader }
method _GetHandle: GLuint;
method Use;
method GetUniformLocation(const AName: String): Integer;
{$ENDREGION 'Internal Declarations'}
public
{ Creates a shader.
Parameters:
AVertexShaderPath: path into the assets.zip file containing the vertex
shader (eg. 'shaders/MyShader.vs').
AFragmentShaderPath: path into the assets.zip file containing the
fragment shader (eg. 'shaders/MyShader.fs'). }
constructor (const AVertexShaderPath, AFragmentShaderPath: String);
finalizer ;
end;
{$IF DEBUG AND ISLAND}
method glErrorCheck;
{$ELSE}
method glErrorCheck; inline; empty;
{$ENDIF}
implementation
{$IF DEBUG AND ISLAND}
method glErrorCheck;
var
Error: GLenum;
begin
if assigned(glGetError) then
begin
Error := glGetError();
if (Error <> GL_NO_ERROR) then
begin
repeat until glGetError() = GL_NO_ERROR;
raise new Exception(String.format('OpenGL Error: {0}', [Error]));
end
end;
end;
{$ENDIF}
{$REGION 'Internal Declarations'}
class method Shader.CreateShader(const AShaderPath: String; const AShaderType: GLenum): GLuint;
var
Source: String;
// SourcePtr: ^AnsiChar;
Status,
LogLength
// ,ShaderLength
: GLint;
// Log: Array of AnsiChar;
Msg: String;
begin
Source := Asset.loadFile(AShaderPath);
if String.IsNullOrEmpty(Source) then exit;
Result := glCreateShader(AShaderType);
// assert(Result <> 0);
glErrorCheck;
{$IFNDEF MOBILE}
{ Desktop OpenGL doesn't recognize precision specifiers }
if (AShaderType = GL_FRAGMENT_SHADER) then
Source := '#define lowp'#10 + '#define mediump'#10 + '#define highp'#10 + Source;
{$ENDIF}
var ShaderSource : ^AnsiChar := glStringHelper.toPansichar(Source);
glShaderSource(Result, 1, @ShaderSource, nil);
glErrorCheck;
glCompileShader(Result);
glErrorCheck;
Status := Integer(GL_FALSE);
glGetShaderiv(Result, GL_COMPILE_STATUS, @Status);
if (Status <> Integer(GL_TRUE)) then
begin
glGetShaderiv(Result, GL_INFO_LOG_LENGTH, @LogLength);
if (LogLength > 0) then
begin
var Log := new Byte[LogLength];
glGetShaderInfoLog(Result, LogLength, @LogLength, PGLChar(@Log[0]));
Msg := new String(Log, Encoding.UTF8);
raise new Exception('CreateShader Exception '+Msg);
end;
end;
end;
method Shader._GetHandle: GLuint;
begin
Result := FProgram;
end;
method Shader.Use;
begin
glUseProgram(FProgram);
end;
method Shader.GetUniformLocation(const AName: String): Integer;
begin
Result := glGetUniformLocation(FProgram, glStringHelper.toPansichar(AName));
end;
{$ENDREGION}
constructor Shader(const AVertexShaderPath: String; const AFragmentShaderPath: String);
var
Status, LogLength: GLint;
VertexShader, FragmentShader: GLuint;
// Log: array of Byte;
// Msg: String;
begin
FragmentShader := 0;
VertexShader := CreateShader(AVertexShaderPath, GL_VERTEX_SHADER);
try
FragmentShader := CreateShader(AFragmentShaderPath, GL_FRAGMENT_SHADER);
FProgram := glCreateProgram();
glAttachShader(FProgram, VertexShader);
glErrorCheck;
glAttachShader(FProgram, FragmentShader);
glErrorCheck;
glLinkProgram(FProgram);
glGetProgramiv(FProgram, GL_LINK_STATUS, @Status);
if (Status <> Integer(GL_TRUE)) then
begin
glGetProgramiv(FProgram, GL_INFO_LOG_LENGTH, @LogLength);
if (LogLength > 0) then
begin
var Log := new Byte[LogLength];
glGetProgramInfoLog(FProgram, LogLength, @LogLength, PGLChar(@Log[0]));
var Msg := new String(Log, Encoding.UTF8);
raise new Exception('CreateProgram Exception '+Msg);
end;
end;
glErrorCheck;
finally
if (FragmentShader <> 0) then
glDeleteShader(FragmentShader);
if (VertexShader <> 0) then
glDeleteShader(VertexShader);
end;
end;
finalizer Shader;
begin
glUseProgram(0);
if (FProgram <> 0) then
glDeleteProgram(FProgram);
end;
end. |
unit uBaseFormPlugin;
interface
uses SysUtils, Classes, Windows, Controls, Forms, uPluginBase, uParamObject, uFrmParent;
const
Err_FrmExists = '窗体%s已存在,不能重复注册!';
Err_FrmNotSupport = '%s窗体不存在,请先注册!';
Err_FrmNoNotSupport = '%s模块号不存在,请先注册!';
Type
TFormClass = class of TfrmParent;
PFormItem = ^TFormItem;
TFormItem = record
FormNo: Integer; //模块号
FormName: string; //模块名
FormClass: TFormClass; //模块类
end;
TBaseFormPlugin = Class(TPlugin)
private
protected
public
Constructor Create(Intf: IInterface);override;
Destructor Destroy;override;
procedure Init; override;
procedure final; override;
end;
TFormManage = Class(TObject)
private
FFormList: array of PFormItem;
FBasicType: Integer;
function GetItemByName(AFormName: string): PFormItem;
function GetItemByNo(AFormNo: Integer): PFormItem;
protected
function CreateForm(AFormClass: TFormClass; AParam: TParamObject; AOwner: TComponent): IInterface;
public
Constructor Create;
Destructor Destroy; override;
procedure RegForm(AFormClass: TFormClass; AFormNo: Integer);
function GetFormAsFromName(AFromName: string; AParam: TParamObject; AOwner: TComponent): IInterface;//获取业务接口的实例
function GetFormAsFromNo(AFromNo: Integer; AParam: TParamObject; AOwner: TComponent): IInterface;//获取业务接口的实例
end;
var
gFormManage: TFormManage;
implementation
uses uSysSvc, uPubFun, uOtherIntf, uFactoryFormIntf, uDefCom, uMainFormIntf;
{ TBaseFormPlugin }
constructor TBaseFormPlugin.Create(Intf: IInterface);
begin
inherited;
end;
destructor TBaseFormPlugin.Destroy;
begin
inherited;
end;
procedure TBaseFormPlugin.final;
begin
inherited;
end;
procedure TBaseFormPlugin.Init;
begin
inherited;
end;
{ TFormManage }
procedure TFormManage.RegForm(AFormClass: TFormClass; AFormNo: Integer);
var
aItemCount: Integer;
aItem: PFormItem;
begin
New(aItem);
try
aItem.FormNo := AFormNo;
aItem.FormName := AFormClass.ClassName;
aItem.FormClass := AFormClass;
aItemCount := Length(FFormList) + 1;
SetLength(FFormList, aItemCount);
FFormList[aItemCount - 1] := aItem;
except
Dispose(aItem);
end;
end;
constructor TFormManage.Create;
begin
SetLength(FFormList, 0);
end;
destructor TFormManage.Destroy;
var
i: Integer;
begin
for i := 0 to Length(FFormList) - 1 do
begin
Dispose(FFormList[i]);
end;
SetLength(FFormList, 0);
inherited;
end;
function TFormManage.GetFormAsFromName(AFromName: string; AParam: TParamObject; AOwner: TComponent): IInterface;
var
aFormClass: PFormItem;
begin
aFormClass := GetItemByName(AFromName);
if not Assigned(aFormClass) then
begin
raise (SysService as IExManagement).CreateSysEx(StringFormat(Err_FrmNotSupport, [AFromName]));
end;
Result := CreateForm(aFormClass.FormClass, AParam, AOwner);
end;
function TFormManage.GetItemByName(AFormName: string): PFormItem;
var
i: Integer;
begin
Result := nil;
for i := 0 to Length(FFormList) - 1 do
begin
if AnsiCompareStr(LowerCase(AFormName),
LowerCase(FFormList[i].FormClass.ClassName)) = 0 then
begin
Result := FFormList[i];
Exit;
end;
end;
end;
function TFormManage.GetFormAsFromNo(AFromNo: Integer; AParam: TParamObject;
AOwner: TComponent): IInterface;
var
aFormClass: PFormItem;
begin
aFormClass := GetItemByNo(AFromNo);
if not Assigned(aFormClass) then
begin
raise (SysService as IExManagement).CreateSysEx(StringFormat(Err_FrmNoNotSupport, [IntToStr(AFromNo)]));
end;
Result := CreateForm(aFormClass.FormClass, AParam, AOwner);
end;
function TFormManage.GetItemByNo(AFormNo: Integer): PFormItem;
var
i: Integer;
begin
Result := nil;
for i := 0 to Length(FFormList) - 1 do
begin
if AFormNo = FFormList[i].FormNo then
begin
Result := FFormList[i];
Exit;
end;
end;
end;
function TFormManage.CreateForm(AFormClass: TFormClass; AParam: TParamObject; AOwner: TComponent): IInterface;
var
afrmParent: TfrmParent;
aInstance: IInterface;
begin
afrmParent := TfrmParent(AFormClass.NewInstance);
// afrmParent.CreateFrmParamList(AOwner, AParam);
// if AOwner is TWinControl then
// begin
// afrmParent.Parent := TWinControl(AOwner);
// afrmParent.BorderStyle := bsNone;
// afrmParent.Align := alClient;
// end;
if afrmParent.FrmShowStyle = fssShow then
begin
afrmParent.CreateFrmParamList((SysService as IMainForm).GetMDIShowClient, AParam);
// afrmParent.Parent := (SysService as IMainForm).GetMDIShowClient; //这样设置时焦点会跳转到嵌入窗体的第一个控件
afrmParent.ParentWindow := (SysService as IMainForm).GetMDIShowClient.Handle;
afrmParent.WindowState := wsMaximized;
end
else
begin
afrmParent.CreateFrmParamList(AOwner, AParam);
end;
afrmParent.GetInterface(IFormIntf, aInstance);
Result := aInstance;
end;
initialization
gFormManage := TFormManage.Create;
finalization
gFormManage.Free;
end.
|
//////////////////////////////////////////////////////////////////////////
// This file is a part of NotLimited.Framework.Wpf NuGet package.
// You are strongly discouraged from fiddling with it.
// If you do, all hell will break loose and living will envy the dead.
//////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media.Animation;
namespace NotLimited.Framework.Wpf.Animations
{
public class AnimationBag
{
private readonly Dictionary<string, AnimationItem> _storyboards = new Dictionary<string, AnimationItem>();
public void AddAnimation(string name, DependencyObject control, string propertyName, Timeline animation, Action beginAction = null, Action endAction = null)
{
var board = new Storyboard();
var item = new AnimationItem(board)
{
BeginAction = beginAction,
EndAction = endAction,
Control = control,
PropertyPath = new PropertyPath(propertyName)
};
Storyboard.SetTarget(animation, control);
Storyboard.SetTargetProperty(animation, item.PropertyPath);
board.Children.Add(animation);
_storyboards[name] = item;
}
public void StartAnimation(string name)
{
if (!_storyboards.ContainsKey(name))
return;
_storyboards[name].Start();
}
public void StopAnimation(string name)
{
if (!_storyboards.ContainsKey(name))
return;
_storyboards[name].Stop();
}
public static DoubleAnimation CreateDoubleAnimation(double? to, long durationMs, double? from = null, bool repeat = false)
{
var ret = new DoubleAnimation { To = to, From = from, Duration = new Duration(TimeSpan.FromMilliseconds(durationMs)) };
if (repeat)
ret.RepeatBehavior = RepeatBehavior.Forever;
return ret;
}
}
} |
unit feli_value_types;
{$mode objfpc}
interface
type
FeliValueTypes = class(TObject)
public
const
str = 'string';
int = 'integer';
end;
implementation
end. |
unit uSample;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
ComCtrls, Spin, ExtCtrls, MaskEdit, TicketCarListaProduto, types, Windows, Cappta_Gp_Api_Com_1_0_TLB,
xmlread, dom, ActiveX, Variants, StrUtils, Math;
type
{ TFormulario }
TFormulario = class(TForm)
ButtonSolicitarInformacaoPinpad: TButton;
ButtonExecutarCancelamento: TButton;
ButtonExecutarCrediario: TButton;
ButtonExecutarCredito: TButton;
ButtonExecutarDebito: TButton;
ButtonExecutarPagamentoTicketCar: TButton;
ButtonExecutarReimpressao: TButton;
ComboBoxTipoInformacaoPinpad: TComboBox;
ComboBoxTipoParcelamentoPagamentoCredito: TComboBox;
ddd: TEdit;
dddLabel: TLabel;
EditNumeroDocumentoFiscalTicketCar: TEdit;
lblConfiguracaoInterface: TLabel;
numero: TEdit;
numeroLabel: TLabel;
operadoraCombobox: TComboBox;
PanelExibirInterface: TPanel;
productCombobox: TComboBox;
produtosLabel: TLabel;
RadioButtonInterfaceInvisivel: TRadioButton;
RadioButtonInterfaceVisivel: TRadioButton;
recarga: TButton;
TextEditNumeroControleCancelamento: TEdit;
TextEditNumeroControleReimpressaoCupom: TEdit;
EditSenhaAdministrativaCancelamento: TEdit;
EditNumeroSerialTicketCar: TEdit;
FloatSpinEditCupomFiscalCancelamento: TFloatSpinEdit;
FloatSpinEditCupomFiscalPagamentoCrediario: TFloatSpinEdit;
FloatSpinEditCupomFiscalPagamentoCredito: TFloatSpinEdit;
FloatSpinEditCupomFiscalPagamentoDebito: TFloatSpinEdit;
FloatSpinEditCupomFiscalReimpressaoCupom: TFloatSpinEdit;
FloatSpinEditQuantidadeDePagamentosMultiTef: TFloatSpinEdit;
FloatSpinEditQuantidadeParcelasPagamentoCredito: TFloatSpinEdit;
FloatSpinEditQuantidadeParcelasPagamentoCrediario: TFloatSpinEdit;
FloatSpinEditValorPagamentoCrediario: TFloatSpinEdit;
FloatSpinEditValorPagamentoCredito: TFloatSpinEdit;
FloatSpinEditValorPagamentoDebito: TFloatSpinEdit;
FloatSpinEditValorPagamentoTicketCar: TFloatSpinEdit;
GroupBoxDadosCancelamento: TGroupBox;
GroupBoxDadosPagamentoCredito: TGroupBox;
GroupBoxDadosPagamentoCrediario: TGroupBox;
GroupBoxDadosPagamentoDebito: TGroupBox;
GroupBoxDadosPagamentoTicketCar: TGroupBox;
GroupBoxDadosReimpressaoCupom: TGroupBox;
GroupBoxResultado: TGroupBox;
LabelTipoEntradaPinpad: TLabel;
LabelCupomFiscalCancelamento: TLabel;
LabelCupomFiscalPagamentoCrediario: TLabel;
LabelCupomFiscalPagamentoCredito: TLabel;
LabelCupomFiscalPagamentoDebito: TLabel;
LabelCupomFiscalReimpressaoCupom: TLabel;
LabelNumeroControleCancelamento: TLabel;
LabelNumeroControleReimpressaoCupom: TLabel;
LabelNumeroDocumentoFiscalPagamentoTicketCar: TLabel;
LabelNumeroSerialPagamentoTicketCar: TLabel;
LabelPagamentoCreditoComParcelas: TLabel;
LabelQualViaASerImprimida: TLabel;
LabelQuantidadeDePagamentosMultiTef: TLabel;
LabelQuantidadeParcelasPagamentoCrediario: TLabel;
LabelQuantidadeParcelasPagamentoCredito: TLabel;
LabelReimprimirUltimoCupom: TLabel;
LabelSenhaAdministrativaCancelamento: TLabel;
LabelTipoParcelamentoPagamentoCredito: TLabel;
LabelUsarMultiTef: TLabel;
LabelValorPagamentoCrediario: TLabel;
LabelValorPagamentoCredito: TLabel;
LabelValorPagamentoDebito: TLabel;
LabelValorPagamentoTicketCar: TLabel;
PageControlPrincipal: TPageControl;
PanelViaASerImprimida: TPanel;
RadioButtonNaoReimprimirUltimoCupom: TRadioButton;
RadioButtonNaoUsarMultiTef: TRadioButton;
RadioButtonPagamentoCreditoSemParcelas: TRadioButton;
RadioButtonPagamentoCreditoComParcelas: TRadioButton;
RadioButtonReimprimirUltimoCupom: TRadioButton;
RadioButtonReimprimirTodasVias: TRadioButton;
RadioButtonUsarMultiTef: TRadioButton;
RadioButtonReimprimirViaLoja: TRadioButton;
RadioButtonReimprimirViaCliente: TRadioButton;
TabSheet1: TTabSheet;
TabSheetCancelamento: TTabSheet;
TabSheetPagamentoCrediario: TTabSheet;
TabSheetPagamentoCredito: TTabSheet;
TabSheetPagamentoDebito: TTabSheet;
TabSheetReimpressaoCupom: TTabSheet;
TabSheetTicketCar: TTabSheet;
TMemoResultado: TMemo;
valorLabel: TLabel;
valorRecarga: TEdit;
procedure ButtonExecutarPagamentoTicketCarClick(Sender: TObject);
procedure dddChange(Sender: TObject);
procedure numeroChange(Sender: TObject);
procedure operadoraComboboxChange(Sender: TObject);
procedure productComboboxChange(Sender: TObject);
procedure produtosLabelClick(Sender: TObject);
procedure OnButtonPegarDadosPinpadClick(Sender: TObject);
procedure OnButtonExecutarCancelamentoClick(Sender: TObject);
procedure OnButtonExecutarCrediarioClick(Sender: TObject);
procedure OnButtonExecutarCreditoClick(Sender: TObject);
procedure OnButtonExecutarDebitoClick(Sender: TObject);
procedure OnButtonExecutarReimpressaoClick(Sender: TObject);
procedure OnFloatSpinEditQuantidadeDePagamentosMultiTefChange(Sender: TObject
);
procedure OnRadioButtonNaoReimprimirUltimoCupomClick(Sender: TObject);
procedure OnRadioButtonNaoUsarMultiTefClick(Sender: TObject);
procedure OnRadioButtonPagamentoCreditoComParcelasClick(Sender: TObject);
procedure OnRadioButtonPagamentoCreditoSemParcelasClick(Sender: TObject);
procedure OnRadioButtonReimprimirTodasViasClick(Sender: TObject);
procedure OnRadioButtonReimprimirUltimoCupomClick(Sender: TObject);
procedure OnRadioButtonReimprimirViaClienteClick(Sender: TObject);
procedure OnRadioButtonReimprimirViaLojaClick(Sender: TObject);
procedure OnRadioButtonUsarMultiTefClick(Sender: TObject);
procedure AtualizarResultado(mensagem: string);
procedure AutenticarPdv(cliente: IClienteCappta);
procedure CarregarOperadoras(cliente: IClienteCappta);
procedure CriarMensagemErro(mensagem: PChar);
procedure DesabilitarBotoes();
procedure DesabilitarControlesMultiTef();
procedure ExibirDadosOperacaoAprovada(resposta: IRespostaOperacaoAprovada);
procedure ExibirDadosOperacaoRecusada(resposta: IRespostaOperacaoRecusada);
procedure ExibirMensagem(mensagem: IMensagem);
procedure FinalizarPagamento();
procedure FormCreate(Sender: TObject);
procedure IniciarMultiCartoes();
procedure HabilitarBotoes();
procedure HabilitarControlesMultiTef();
procedure IterarOperacaoTef();
procedure RadioButtonInterfaceInvisivelChange(Sender: TObject);
procedure RadioButtonInterfaceVisivelChange(Sender: TObject);
procedure recargaClick(Sender: TObject);
procedure RequisitarParametros(requisicaoParametros: IRequisicaoParametro);
procedure ResolverTransacaoPendente(respostaTransacaoPendente: IRespostaTransacaoPendente);
procedure ConfigurarModoIntegracao(exibirInterface: boolean);
function BuscarNodeXML(XMLAutenticacao: TXMLDocument; nomeNode: string) : TDOMNode;
function ConcatenarCupons(mensagemAprovada: string; cupom: string) : string;
function DeveIniciarMultiCartoes() : boolean;
function FormatarNumeroControle(numeroControle: double) : string;
function GerarMensagemTransacaoAprovada : string;
function OperacaoNaoFinalizada(iteracaoTef: IIteracaoTef): boolean;
private
chaveAutenticacao: string;
cliente: IClienteCappta;
cnpj: string;
pdv: Int32;
processandoPagamento: boolean;
quantidadeCartoes: Int32;
sessaoMultiTefEmAndamento: boolean;
tipoVia: Integer;
produtos: PSafeArray;
public
{ public declarations }
end;
var
Formulario: TFormulario;
const
INTERVALO_MILISEGUNDOS: Integer = 500;
implementation
{$R *.lfm}
{ TFormulario }
{%Region Método AutenticarPdv}
procedure TFormulario.FormCreate(Sender: TObject);
begin
cliente := CoClienteCappta.Create;
tipoVia := 1;
AutenticarPdv(cliente);
ConfigurarModoIntegracao(true);
CarregarOperadoras(cliente);
end;
procedure TFormulario.CarregarOperadoras(cliente: IClienteCappta);
var
detalhesOperadoras: IDetalhesOperadoras;
operadoras: PSafeArray;
operadora: WideString;
LBound, UBound, Contador: LongInt;
begin
productCombobox.Enabled:= false;
valorRecarga.Enabled := false;
numero.Enabled := false;
ddd.Enabled := false;
recarga.Enabled := false;
detalhesOperadoras := cliente.ObterOperadoras;
operadoras := detalhesOperadoras.Operadoras;
SafeArrayGetLBound(operadoras, 1, LBound);
SafeArrayGetUBound(operadoras, 1, UBound);
for Contador := LBound to UBound do
begin
SafeArrayGetElement(operadoras, @Contador, operadora);
operadoraCombobox.Items.Add(operadora);
end;
end;
procedure TFormulario.AutenticarPdv(cliente: IClienteCappta);
var
XMLAutenticacao: TXMLDocument;
ChaveAutenticacaoNode: TDOMNode;
CnpjNode: TDOMNode;
PdvNode: TDOMNode;
erro: string;
resultadoAutenticacao: integer;
valorNumericoCnpj: Int64;
begin
try
ReadXMLFile(XMLAutenticacao, 'autenticacao.xml');
ChaveAutenticacaoNode := BuscarNodeXML(XMLAutenticacao, 'chaveAutenticacao');
chaveAutenticacao := ChaveAutenticacaoNode.FirstChild.NodeValue;
CnpjNode := BuscarNodeXML(XMLAutenticacao, 'cnpj');
cnpj := CnpjNode.FirstChild.NodeValue;
if Length(cnpj) <> 14 then
raise Exception.Create('O valor passado na tag <cnpj> não tem 14 digitos (use um CNPJ sem pontuação).');
if TryStrToInt64(cnpj, valorNumericoCnpj) = false then
raise Exception.Create('O valor passado na tag <cnpj> não é númerico.');
PdvNode := BuscarNodeXML(XMLAutenticacao, 'pdv');
pdv := StrtoIntDef(PdvNode.FirstChild.NodeValue, -1);
if pdv = -1 then
raise Exception.Create('O valor passado na tag <pdv> não é numérico.');
resultadoAutenticacao:= cliente.AutenticarPdv(cnpj, pdv, chaveAutenticacao);
Case resultadoAutenticacao of
0 : exit;
1 : ShowMessage('Não autorizado. Por favor, realize a autenticação para utilizar o CapptaGpPlus.');
2 : ShowMessage('O CapptaGpPlus esta sendo inicializado, tente novamente em alguns instantes.');
3 : ShowMessage('O formato da requisição recebida pelo CapptaGpPlus é inválido.');
4 : ShowMessage('Operação cancelada pelo operador.');
7 : ShowMessage('Ocorreu um erro interno no CapptaGpPlus.');
8 : ShowMessage('Ocorreu um erro na comunicação entre a CappAPI e o CapptaGpPlus.');
end;
Application.Terminate;
except on ex : Exception do
begin
erro := Format('%s%s%s%s%s',
['Não foi possível carregar o arquivo "autenticacao.xml".',
sLineBreak,
sLineBreak,
'Erro: ',
ex.Message]);
ShowMessage(erro);
Application.Terminate;
end;
end;
end;
function TFormulario.BuscarNodeXML(XMLAutenticacao: TXMLDocument; nomeNode: string) : TDOMNode;
var node : TDOMNode;
begin
node := XMLAutenticacao.DocumentElement.FindNode(nomeNode);
if node = nil then
raise Exception.Create(Format('Não existe a tag <%s>.', [nomeNode]));
if node.FirstChild = nil then
raise Exception.Create(Format('A tag <%s> está sem valor definido.', [nomeNode]));
Result := node;
end;
{%EndRegion}
{%Region Métodos de Pagamento}
procedure TFormulario.ButtonExecutarPagamentoTicketCarClick(Sender: TObject);
var
detalhesPessoaFisica: IDetalhesPagamentoTicketCarPessoaFisica;
valor: double;
begin
valor := FloatSpinEditValorPagamentoTicketCar.Value;
detalhesPessoaFisica := CoDetalhesPagamentoTicketCarPessoaFisica.Create;
detalhesPessoaFisica.Set_NumeroReciboFiscal(EditNumeroDocumentoFiscalTicketCar.Text);
detalhesPessoaFisica.Set_NumeroSerialECF(EditNumeroSerialTicketCar.Text);
cliente.PagamentoTicketCarPessoaFisica(valor, detalhesPessoaFisica);
processandoPagamento := true;
IterarOperacaoTef();
end;
procedure TFormulario.dddChange(Sender: TObject);
begin
recarga.Enabled:= true;
end;
procedure TFormulario.operadoraComboboxChange(Sender: TObject);
var
detalhesProdutos: IDetalhesProdutosOperadoras;
produto: IProdutoRecarga;
LBound, UBound, Contador: LongInt;
begin
productCombobox.Enabled:= true;
detalhesProdutos := cliente.ObterProdutosOperadoras(operadoraCombobox.text);
productCombobox.Text := '';
produtos := detalhesProdutos.Produtos;
SafeArrayGetLBound(produtos, 1, LBound);
SafeArrayGetUBound(produtos, 1, UBound);
productCombobox.Items.Clear;
for Contador := LBound to UBound do
begin
SafeArrayGetElement(produtos, @Contador, produto);
productCombobox.Items.Add(produto.Name);
end;
end;
procedure TFormulario.productComboboxChange(Sender: TObject);
var
produto: IProdutoRecarga;
LBound, UBound, Contador: LongInt;
begin
SafeArrayGetLBound(produtos, 1, LBound);
SafeArrayGetUBound(produtos, 1, UBound);
numero.Enabled:= true;
for Contador := LBound to UBound do
begin
SafeArrayGetElement(produtos, @Contador, produto);
IF produto.Name = productCombobox.Text
then valorRecarga.Text:= FloatToStrF(produto.Price, ffFixed,4,0);
end;
end;
procedure TFormulario.produtosLabelClick(Sender: TObject);
begin
end;
procedure TFormulario.numeroChange(Sender: TObject);
begin
ddd.Enabled:= true;
end;
procedure TFormulario.OnButtonExecutarDebitoClick(Sender: TObject);
var
valor: double;
exibirInterface: boolean;
configs: Configuracoes;
begin
valor := FloatSpinEditValorPagamentoDebito.Value;
if DeveIniciarMultiCartoes() then
begin
IniciarMultiCartoes();
end;
cliente.PagamentoDebito(valor);
processandoPagamento := true;
IterarOperacaoTef();
end;
procedure TFormulario.OnButtonExecutarCreditoClick(Sender: TObject);
var
detalhes: DetalhesCredito;
quantidadeParcelas: integer;
tipoParcelamento: integer;
transacaoParcelada: boolean;
valor: double;
begin
quantidadeParcelas := Trunc(FloatSpinEditQuantidadeParcelasPagamentoCredito.Value);
tipoParcelamento := ComboBoxTipoParcelamentoPagamentoCredito.ItemIndex + 1;
transacaoParcelada := RadioButtonPagamentoCreditoComParcelas.Checked;
valor := FloatSpinEditValorPagamentoCredito.Value;
detalhes := CoDetalhesCredito.Create;
detalhes.Set_QuantidadeParcelas(quantidadeParcelas);
detalhes.Set_TransacaoParcelada(transacaoParcelada);
detalhes.Set_TipoParcelamento(tipoParcelamento);
if (DeveIniciarMultiCartoes()) then
begin
IniciarMultiCartoes();
end;
cliente.PagamentoCredito(valor, detalhes);
processandoPagamento := true;
IterarOperacaoTef();
end;
procedure TFormulario.OnButtonExecutarCrediarioClick(Sender: TObject);
var
detalhes: DetalhesCrediario;
quantidadeParcelas: integer;
valor: double;
begin
quantidadeParcelas := Trunc(FloatSpinEditQuantidadeParcelasPagamentoCrediario.Value);
valor := FloatSpinEditValorPagamentoCrediario.Value;
detalhes := CoDetalhesCrediario.Create;
detalhes.Set_QuantidadeParcelas(quantidadeParcelas);
if (DeveIniciarMultiCartoes()) then
begin
IniciarMultiCartoes();
end;
cliente.PagamentoCrediario(valor, detalhes);
processandoPagamento := true;
IterarOperacaoTef();
end;
function TFormulario.DeveIniciarMultiCartoes() : boolean;
begin
Result:= (sessaoMultiTefEmAndamento = false) and RadioButtonUsarMultiTef.Checked;
end;
procedure TFormulario.IniciarMultiCartoes();
begin
quantidadeCartoes:= Trunc(FloatSpinEditQuantidadeDePagamentosMultiTef.Value);
sessaoMultiTefEmAndamento:= true;
cliente.IniciarMultiCartoes(quantidadeCartoes);
end;
{%EndRegion}
{%Region Métodos Administrativos}
procedure TFormulario.ConfigurarModoIntegracao(exibirInterface: boolean);
var
configs: Configuracoes;
begin
configs := CoConfiguracoes.Create;
configs.Set_ExibirInterface(exibirInterface);
cliente.Configurar(configs);
end;
procedure TFormulario.OnButtonExecutarReimpressaoClick(Sender: TObject);
var
reimprimirUltimoCupom: boolean;
numeroControle: string;
begin
if sessaoMultiTefEmAndamento = true then
begin
CriarMensagemErro('Não é possível reimprimir um cupom com uma sessão multitef em andamento.'); exit;
end;
reimprimirUltimoCupom := RadioButtonReimprimirUltimoCupom.Checked;
if (reimprimirUltimoCupom) then
begin
cliente.ReimprimirUltimoCupom(tipoVia)
end
else
begin
numeroControle := FormatarNumeroControle(StrToInt64(TextEditNumeroControleReimpressaoCupom.Text));
cliente.ReimprimirCupom(numeroControle, tipoVia);
end;
processandoPagamento := false;
IterarOperacaoTef();
end;
procedure TFormulario.OnButtonExecutarCancelamentoClick(Sender: TObject);
var
numeroControle: string;
senhaAdministrativa: string;
begin
if sessaoMultiTefEmAndamento = true then
begin
CriarMensagemErro('Não é possível cancelar um pagamento com uma sessão multitef em andamento.'); exit;
end;
numeroControle := FormatarNumeroControle(StrToInt64(TextEditNumeroControleCancelamento.Text));
senhaAdministrativa:= EditSenhaAdministrativaCancelamento.Text;
if Length(senhaAdministrativa) = 0 then
begin
CriarMensagemErro('A senha administrativa não pode ser vazia.');
exit;
end;
cliente.CancelarPagamento(senhaAdministrativa, numeroControle);
processandoPagamento := false;
IterarOperacaoTef();
end;
procedure TFormulario.OnButtonPegarDadosPinpadClick(Sender: TObject);
var
tipoInformacaoPinpad: integer;
requisicaoPinpad: RequisicaoInformacaoPinpad;
resultado: string;
begin
tipoInformacaoPinpad := ComboBoxTipoInformacaoPinpad.ItemIndex + 1;
requisicaoPinpad := CoRequisicaoInformacaoPinpad.Create();
requisicaoPinpad.Set_TipoInformacaoPinpad(tipoInformacaoPinpad);
resultado := cliente.SolicitarInformacoesPinpad(requisicaoPinpad);
AtualizarResultado(resultado);
end;
procedure TFormulario.CriarMensagemErro(mensagem: PChar);
begin
Application.MessageBox(mensagem, 'Erro', MB_OK);
end;
function TFormulario.FormatarNumeroControle(numeroControle: double) : string;
var numeroControleTexto: string;
begin
numeroControleTexto := FloatToStr(numeroControle);
numeroControleTexto := ReplaceStr(PadLeft(numeroControleTexto, 11), ' ', '0');
Result:= numeroControleTexto;
end;
{%EndRegion}
{%Region Método IterarOperacaoTef}
procedure TFormulario.IterarOperacaoTef();
var
iteracaoTef: IIteracaoTef;
begin
if RadioButtonUsarMultiTef.Enabled then DesabilitarControlesMultiTef();
DesabilitarBotoes();
Repeat
iteracaoTef := cliente.IterarOperacaoTef();
if iteracaoTef is IMensagem then
begin
ExibirMensagem(iteracaoTef as IMensagem);
Sleep(INTERVALO_MILISEGUNDOS);
end;
if iteracaoTef is IRequisicaoParametro then RequisitarParametros(iteracaoTef as IRequisicaoParametro);
if iteracaoTef is IRespostaTransacaoPendente then ResolverTransacaoPendente(iteracaoTef as IRespostaTransacaoPendente);
if iteracaoTef is IRespostaOperacaoRecusada then ExibirDadosOperacaoRecusada(iteracaoTef as IRespostaOperacaoRecusada);
if iteracaoTef is IRespostaOperacaoAprovada then
begin
ExibirDadosOperacaoAprovada(iteracaoTef as IRespostaOperacaoAprovada);
FinalizarPagamento();
end;
Until OperacaoNaoFinalizada(iteracaoTef) = false;
if (sessaoMultiTefEmAndamento = false) or (iteracaoTef is IRespostaOperacaoRecusada) then HabilitarControlesMultiTef();
HabilitarBotoes();
end;
procedure TFormulario.DesabilitarControlesMultiTef();
begin
RadioButtonUsarMultiTef.Enabled:= false;
RadioButtonNaoUsarMultiTef.Enabled:= false;
FloatSpinEditQuantidadeDePagamentosMultiTef.Enabled:= false;
end;
procedure TFormulario.DesabilitarBotoes();
begin
ButtonExecutarCancelamento.Enabled:= false;
ButtonExecutarCrediario.Enabled:= false;
ButtonExecutarCredito.Enabled:= false;
ButtonExecutarDebito.Enabled:= false;
ButtonExecutarReimpressao.Enabled:= false;
end;
procedure TFormulario.ExibirMensagem(mensagem: IMensagem);
begin
AtualizarResultado(mensagem.Descricao);
end;
procedure TFormulario.RequisitarParametros(requisicaoParametros: IRequisicaoParametro);
var
parametro: string;
mensagemConvertida: string;
acao: Int32;
begin
mensagemConvertida := AnsiToUtf8(requisicaoParametros.Get_Mensagem);
parametro := InputBox('Sample API COM', mensagemConvertida, '');
if Length(parametro) = 0 then
begin
acao := 2;
parametro := ' ';
end
else begin acao := 1; end;
cliente.EnviarParametro(parametro, acao);
end;
procedure TFormulario.ResolverTransacaoPendente(respostaTransacaoPendente: IRespostaTransacaoPendente);
var
parametro: string;
mensagemConvertida: string;
acao: Int32;
lBound, uBound, contador: LongInt;
transacaoPendente: ITransacaoPendente;
begin
mensagemConvertida := AnsiToUtf8(respostaTransacaoPendente.Get_Mensagem);
SafeArrayGetLBound(respostaTransacaoPendente.Get_ListaTransacoesPendentes, 1, lBound);
SafeArrayGetUBound(respostaTransacaoPendente.Get_ListaTransacoesPendentes, 1, uBound);
for contador := lBound to uBound do
begin
SafeArrayGetElement(respostaTransacaoPendente.Get_ListaTransacoesPendentes, @Contador, transacaoPendente);
mensagemConvertida := Concat(mensagemConvertida, sLineBreak, 'Número de Controle: ', transacaoPendente.Get_numeroControle);
mensagemConvertida := Concat(mensagemConvertida, sLineBreak, 'Bandeira: ', transacaoPendente.Get_NomeBandeiraCartao);
mensagemConvertida := Concat(mensagemConvertida, sLineBreak, 'Adquirente: ', transacaoPendente.Get_NomeAdquirente);
mensagemConvertida := Concat(mensagemConvertida, sLineBreak, 'Valor: ', FloatToStr(transacaoPendente.Get_valor));
mensagemConvertida := Concat(mensagemConvertida, sLineBreak, 'Data: ', DateTimeToStr(transacaoPendente.Get_DataHoraAutorizacao));
end;
parametro := InputBox('Sample API COM', mensagemConvertida, '');
if Length(parametro) = 0 then
begin
acao := 2;
parametro := ' ';
end
else begin acao := 1; end;
cliente.EnviarParametro(parametro, acao);
end;
procedure TFormulario.ExibirDadosOperacaoRecusada(resposta: IRespostaOperacaoRecusada);
var textoCodigoAnsi: string;
begin
if sessaoMultiTefEmAndamento then
begin
sessaoMultiTefEmAndamento := false;
processandoPagamento := false;
quantidadeCartoes := 0;
RadioButtonNaoUsarMultiTef.Checked := true;
end;
textoCodigoAnsi := Utf8ToAnsi('Código');
AtualizarResultado(Format('%s: %d%s%s', [textoCodigoAnsi, resposta.Get_CodigoMotivo, sLineBreak, resposta.Get_Motivo]))
end;
procedure TFormulario.ExibirDadosOperacaoAprovada(resposta: IRespostaOperacaoAprovada);
var mensagemAprovada: string = '';
begin
if (resposta.Get_CupomCliente <> null) then mensagemAprovada := Format('%s%s',[ConcatenarCupons(mensagemAprovada, resposta.Get_CupomCliente), sLineBreak]);
if (resposta.Get_CupomLojista <> null) then mensagemAprovada := ConcatenarCupons(mensagemAprovada, resposta.Get_CupomLojista);
if (resposta.Get_CupomReduzido <> null) then mensagemAprovada := ConcatenarCupons(mensagemAprovada, resposta.Get_CupomReduzido);
AtualizarResultado(ReplaceStr(mensagemAprovada, '"', ''));
end;
function TFormulario.ConcatenarCupons(mensagemAprovada: string; cupom: string) : string;
begin
Result:= Format('%s%s%s', [mensagemAprovada, ReplaceStr(cupom, '"', ''), sLineBreak]);
end;
procedure TFormulario.AtualizarResultado(mensagem: string);
begin
TMemoResultado.Text:= AnsiToUtf8(mensagem);
TMemoResultado.Repaint;
end;
procedure TFormulario.FinalizarPagamento();
var botaoSelecionado: Integer = 0;
var mensagem: string;
begin
if processandoPagamento = false then exit;
if sessaoMultiTefEmAndamento then
begin
quantidadeCartoes:= quantidadeCartoes - 1;
if quantidadeCartoes > 0 then exit;
end;
mensagem := GerarMensagemTransacaoAprovada;
processandoPagamento := false;
sessaoMultiTefEmAndamento := false;
botaoSelecionado := MessageDlg(mensagem, mtConfirmation, mbOKCancel, 0);
if botaoSelecionado = mrOK then cliente.ConfirmarPagamentos()
else cliente.DesfazerPagamentos();
end;
function TFormulario.GerarMensagemTransacaoAprovada : string;
var
trecho1: string = 'ão';
trecho2: string = '';
mensagem: string = 'Transaç%s Aprovada%s!!! %s Clique em "OK" para confirmar a%s transaç%s e "Cancelar" para desfazê-la%s.';
begin
if sessaoMultiTefEmAndamento = true then
begin
trecho1 := 'ões';
trecho2 := 's'
end;
Result := Format(mensagem, [trecho1, trecho2, sLineBreak, trecho2, trecho1, trecho2]);
end;
function TFormulario.OperacaoNaoFinalizada(iteracaoTef: IIteracaoTef): boolean;
var tipoIteracao: integer;
begin
tipoIteracao := iteracaoTef.Get_TipoIteracao;
Result:= (tipoIteracao <> 1) and (tipoIteracao <> 2);
end;
procedure TFormulario.HabilitarControlesMultiTef();
begin
RadioButtonUsarMultiTef.Enabled:= true;
RadioButtonNaoUsarMultiTef.Enabled:= true;
FloatSpinEditQuantidadeDePagamentosMultiTef.Enabled:= true;
end;
procedure TFormulario.HabilitarBotoes();
begin
ButtonExecutarCancelamento.Enabled:= true;
ButtonExecutarCrediario.Enabled:= true;
ButtonExecutarCredito.Enabled:= true;
ButtonExecutarDebito.Enabled:= true;
ButtonExecutarReimpressao.Enabled:= true;
end;
{%EndRegion}
{%Region Eventos}
procedure TFormulario.RadioButtonInterfaceInvisivelChange(Sender: TObject);
begin
if(RadioButtonInterfaceVisivel.Checked = false) then
begin
exit;
end;
ConfigurarModoIntegracao(true);
end;
procedure TFormulario.RadioButtonInterfaceVisivelChange(Sender: TObject);
begin
if(RadioButtonInterfaceInvisivel.Checked = false) then
begin
exit;
end;
ConfigurarModoIntegracao(false);
end;
procedure TFormulario.recargaClick(Sender: TObject);
var
detalhesRecarga: IDetalhesRecarga;
produto: IProdutoRecarga;
response: IRespostaRecarga;
iteracao: IIteracaoTef;
LBound, UBound, Contador: LongInt;
begin
detalhesRecarga := CoDetalhesRecarga.Create;
detalhesRecarga.Celular:= StrToInt64(numero.Text);
detalhesRecarga.Ddd:= strtoint(ddd.Text);
detalhesRecarga.ValorRecarga:= strtofloat(valorRecarga.Text);
SafeArrayGetLBound(produtos, 1, LBound);
SafeArrayGetUBound(produtos, 1, UBound);
for Contador := LBound to UBound do
begin
SafeArrayGetElement(produtos, @Contador, produto);
IF produto.Name = productCombobox.Text
then detalhesRecarga.Produto := produto;
end;
try
iteracao:= cliente.RecargaCelular(detalhesRecarga);
if iteracao is IRespostaRecarga then
begin
response := (iteracao as IRespostaRecarga);
AtualizarResultado(response.CupomCliente + response.CupomLojista);
end;
finally
end;
end;
procedure TFormulario.OnRadioButtonUsarMultiTefClick(Sender: TObject);
begin
if RadioButtonUsarMultiTef.Checked = false then exit;
LabelQuantidadeDePagamentosMultiTef.Show();
FloatSpinEditQuantidadeDePagamentosMultiTef.Show();
end;
procedure TFormulario.OnRadioButtonNaoUsarMultiTefClick(Sender: TObject);
begin
if RadioButtonNaoUsarMultiTef.Checked = false then exit;
sessaoMultiTefEmAndamento:= false;
LabelQuantidadeDePagamentosMultiTef.Hide();
FloatSpinEditQuantidadeDePagamentosMultiTef.Hide();
cliente.DesfazerPagamentos();
end;
procedure TFormulario.OnFloatSpinEditQuantidadeDePagamentosMultiTefChange(
Sender: TObject);
begin
quantidadeCartoes:= Trunc(FloatSpinEditQuantidadeDePagamentosMultiTef.Value);
end;
procedure TFormulario.OnRadioButtonPagamentoCreditoComParcelasClick(Sender: TObject);
begin
LabelTipoParcelamentoPagamentoCredito.Show();
ComboBoxTipoParcelamentoPagamentoCredito.Show();
LabelQuantidadeParcelasPagamentoCredito.Show();
FloatSpinEditQuantidadeParcelasPagamentoCredito.Show();
end;
procedure TFormulario.OnRadioButtonPagamentoCreditoSemParcelasClick(Sender: TObject);
begin
LabelTipoParcelamentoPagamentoCredito.Hide();
ComboBoxTipoParcelamentoPagamentoCredito.Hide();
LabelQuantidadeParcelasPagamentoCredito.Hide();
FloatSpinEditQuantidadeParcelasPagamentoCredito.Hide();
end;
procedure TFormulario.OnRadioButtonReimprimirUltimoCupomClick(Sender: TObject);
begin
LabelNumeroControleReimpressaoCupom.Hide();
TextEditNumeroControleReimpressaoCupom.Hide();
end;
procedure TFormulario.OnRadioButtonNaoReimprimirUltimoCupomClick(Sender: TObject);
begin
LabelNumeroControleReimpressaoCupom.Show();
TextEditNumeroControleReimpressaoCupom.Show();
end;
procedure TFormulario.OnRadioButtonReimprimirTodasViasClick(Sender: TObject);
begin
tipoVia := 1;
end;
procedure TFormulario.OnRadioButtonReimprimirViaLojaClick(Sender: TObject);
begin
tipoVia := 3;
end;
procedure TFormulario.OnRadioButtonReimprimirViaClienteClick(Sender: TObject);
begin
tipoVia := 2;
end;
{%EndRegion}
end.
|
{******************************************************************}
{ SVG path classes }
{ }
{ home page : http://www.mwcs.de }
{ email : martin.walter@mwcs.de }
{ }
{ date : 05-04-2008 }
{ }
{ Use of this file is permitted for commercial and non-commercial }
{ use, as long as the author is credited. }
{ This file (c) 2005, 2008 Martin Walter }
{ }
{ Thanks to: }
{ Kiriakos Vlahos (fixed SVGPath...) }
{ }
{ This Software is distributed on an "AS IS" basis, WITHOUT }
{ WARRANTY OF ANY KIND, either express or implied. }
{ }
{ *****************************************************************}
unit SVGPath;
interface
uses
Winapi.Windows,
Winapi.GDIPOBJ,
System.Types,
System.Classes,
System.Generics.Collections,
SVGTypes,
SVG;
type
TSVGPathElement = class(TSVGObject)
private
FStartX: TFloat;
FStartY: TFloat;
FStopX: TFloat;
FStopY: TFloat;
protected
procedure AssignTo(Dest: TPersistent); override;
public
function GetBounds: TRectF; virtual; abstract;
procedure AddToPath(Path: TGPGraphicsPath); virtual; abstract;
procedure Read(Command: Char; ValueList: TList<TFloat>; var Position: Integer;
Previous: TSVGPathElement); virtual;
procedure PaintToGraphics(Graphics: TGPGraphics); override;
procedure PaintToPath(Path: TGPGraphicsPath); override;
property StartX: TFloat read FStartX write FStartX;
property StartY: TFloat read FStartY write FStartY;
property StopX: TFloat read FStopX write FStopX;
property StopY: TFloat read FStopY write FStopY;
end;
TSVGPathMove = class(TSVGPathElement)
public
function GetBounds: TRectF; override;
procedure AddToPath(Path: TGPGraphicsPath); override;
procedure Read(Command: Char; ValueList: TList<TFloat>; var Position: Integer;
Previous: TSVGPathElement); override;
end;
TSVGPathLine = class(TSVGPathElement)
public
function GetBounds: TRectF; override;
procedure AddToPath(Path: TGPGraphicsPath); override;
procedure Read(Command: Char; ValueList: TList<TFloat>; var Position: Integer;
Previous: TSVGPathElement); override;
end;
TSVGPathCurve = class(TSVGPathElement)
private
FControl1X: TFloat;
FControl1Y: TFloat;
FControl2X: TFloat;
FControl2Y: TFloat;
protected
procedure AssignTo(Dest: TPersistent); override;
public
function GetBounds: TRectF; override;
procedure AddToPath(Path: TGPGraphicsPath); override;
procedure Read(Command: Char; ValueList: TList<TFloat>; var Position: Integer;
Previous: TSVGPathElement); override;
property Control1X: TFloat read FControl1X write FControl1X;
property Control1Y: TFloat read FControl1Y write FControl1Y;
property Control2X: TFloat read FControl2X write FControl2X;
property Control2Y: TFloat read FControl2Y write FControl2Y;
end;
TSVGPathEllipticArc = class(TSVGPathElement)
private
FRX: TFloat;
FRY: TFloat;
FXRot: TFloat;
FLarge: Integer;
FSweep: Integer;
protected
procedure AssignTo(Dest: TPersistent); override;
public
function GetBounds: TRectF; override;
procedure AddToPath(Path: TGPGraphicsPath); override;
procedure Read(Command: Char; ValueList: TList<TFloat>; var Position: Integer;
Previous: TSVGPathElement); override;
property RX: TFloat read FRX write FRX;
property RY: TFloat read FRY write FRY;
property XRot: TFloat read FXRot write FXRot;
property Large: Integer read FLarge write FLarge;
property Sweep: Integer read FSweep write FSweep;
end;
TSVGPathClose = class(TSVGPathElement)
private
function FindLastMoveTo: TSVGPathMove;
public
function GetBounds: TRectF; override;
procedure AddToPath(Path: TGPGraphicsPath); override;
procedure Read(Command: Char; ValueList: TList<TFloat>; var Position: Integer;
Previous: TSVGPathElement); override;
end;
implementation
uses
System.SysUtils, System.Math,
Winapi.GDIPAPI,
SVGCommon, SVGParse;
{$IF CompilerVersion > 23.0}
{$LEGACYIFEND ON}
{$IFEND}
{$IF CompilerVersion <= 28}
function FMod(const ANumerator, ADenominator: Single): Single;
begin
Result := ANumerator - Trunc(ANumerator / ADenominator) * ADenominator;
end;
{$IFEND}
// TSVGPathElement
procedure TSVGPathElement.AssignTo(Dest: TPersistent);
begin
inherited;
if Dest is TSVGPathElement then
begin
TSVGPathElement(Dest).FStartX := FStartX;
TSVGPathElement(Dest).FStartY := FStartY;
TSVGPathElement(Dest).FStopX := FStopX;
TSVGPathElement(Dest).FStopY := FStopY;
end;
end;
procedure TSVGPathElement.Read(Command: Char; ValueList: TList<TFloat>;
var Position: Integer; Previous: TSVGPathElement);
begin
if Assigned(Previous) then
begin
FStartX := Previous.FStopX;
FStartY := Previous.FStopY;
end;
end;
procedure TSVGPathElement.PaintToGraphics(Graphics: TGPGraphics);
begin
end;
procedure TSVGPathElement.PaintToPath(Path: TGPGraphicsPath);
begin
end;
// TSVGPathMove
function TSVGPathMove.GetBounds: TRectF;
begin
Result.Left := 0;
Result.Top := 0;
Result.Width := 0;
Result.Height := 0;
end;
procedure TSVGPathMove.AddToPath(Path: TGPGraphicsPath);
begin
Path.CloseFigure;
Path.StartFigure;
end;
procedure TSVGPathMove.Read(Command: Char; ValueList: TList<TFloat>;
var Position: Integer; Previous: TSVGPathElement);
begin
inherited;
FStopX := ValueList[Position];
FStopY := ValueList[Position + 1];
if Command = 'm' then
begin
FStopX := FStartX + FStopX;
FStopY := FStartY + FStopY;
end;
Inc(Position, 2);
end;
// TSVGPathLine
function TSVGPathLine.GetBounds: TRectF;
begin
Result.Left := Min(FStartX, FStopX);
Result.Top := Min(FStartY, FStopY);
Result.Width := Abs(FStartX - FStopX);
Result.Height := Abs(FStartY - FStopY);
end;
procedure TSVGPathLine.AddToPath(Path: TGPGraphicsPath);
begin
Path.AddLine(FStartX, FStartY, FStopX, FStopY);
end;
procedure TSVGPathLine.Read(Command: Char; ValueList: TList<TFloat>;
var Position: Integer; Previous: TSVGPathElement);
begin
inherited;
if (Command = 'L') or (Command = 'l') then
begin
FStopX := ValueList[Position];
FStopY := ValueList[Position + 1];
if Command = 'l' then
begin
FStopX := FStartX + FStopX;
FStopY := FStartY + FStopY;
end;
Inc(Position, 2);
end
else if (Command = 'H') or (Command = 'h') then
begin
FStopX := ValueList[Position];
if Command = 'h' then
FStopX := FStartX + FStopX;
FStopY := FStartY;
Inc(Position);
end
else if (Command = 'V') or (Command = 'v') then
begin
FStopY := ValueList[Position];
if Command = 'v' then
FStopY := FStartY + FStopY;
FStopX := FStartX;
Inc(Position);
end;
end;
// TSVGPathCurve
procedure TSVGPathCurve.AssignTo(Dest: TPersistent);
begin
inherited;
if Dest is TSVGPathCurve then
begin
TSVGPathCurve(Dest).FControl1X := FControl1X;
TSVGPathCurve(Dest).FControl1Y := FControl1Y;
TSVGPathCurve(Dest).FControl2X := FControl2X;
TSVGPathCurve(Dest).FControl2Y := FControl2Y;
end;
end;
function TSVGPathCurve.GetBounds: TRectF;
var
Right, Bottom: TFloat;
begin
Result.Left := Min(FStartX, Min(FStopX, Min(FControl1X, FControl2X)));
Result.Top := Min(FStartY, Min(FStopY, Min(FControl1Y, FControl2Y)));
Right := Max(FStartX, Max(FStopX, Max(FControl1X, FControl2X)));
Bottom := Max(FStartY, Max(FStopY, Max(FControl1Y, FControl2Y)));
Result.Width := Right - Result.Left;
Result.Height := Bottom - Result.Top;
end;
procedure TSVGPathCurve.AddToPath(Path: TGPGraphicsPath);
begin
Path.AddBezier(FStartX, FStartY, FControl1X, FControl1Y,
FControl2X, FControl2Y, FStopX, FStopY);
end;
procedure TSVGPathCurve.Read(Command: Char; ValueList: TList<TFloat>;
var Position: Integer; Previous: TSVGPathElement);
begin
inherited;
if (Command = 'C') or (Command = 'c') then
begin
FControl1X := ValueList[Position];
FControl1Y := ValueList[Position + 1];
FControl2X := ValueList[Position + 2];
FControl2Y := ValueList[Position + 3];
FStopX := ValueList[Position + 4];
FStopY := ValueList[Position + 5];
Inc(Position, 6);
if Command = 'c' then
begin
FControl1X := FStartX + FControl1X;
FControl1Y := FStartY + FControl1Y;
FControl2X := FStartX + FControl2X;
FControl2Y := FStartY + FControl2Y;
FStopX := FStartX + FStopX;
FStopY := FStartY + FStopY;
end;
end
else if (Command = 'S') or (Command = 's') then
begin
FControl2X := ValueList[Position];
FControl2Y := ValueList[Position + 1];
FStopX := ValueList[Position + 2];
FStopY := ValueList[Position + 3];
Inc(Position, 4);
if Previous is TSVGPathCurve then
begin
FControl1X := FStartX + (FStartX - TSVGPathCurve(Previous).FControl2X);
FControl1Y := FStartY + (FStartY - TSVGPathCurve(Previous).FControl2Y);
end;
if Command = 's' then
begin
FControl2X := FStartX + FControl2X;
FControl2Y := FStartY + FControl2Y;
FStopX := FStartX + FStopX;
FStopY := FStartY + FStopY;
end;
end
else if (Command = 'Q') or (Command = 'q') then
begin
FControl1X := ValueList[Position];
FControl1Y := ValueList[Position + 1];
FStopX := ValueList[Position + 2];
FStopY := ValueList[Position + 3];
FControl2X := FControl1X;
FControl2Y := FControl1Y;
Inc(Position, 4);
if Command = 'q' then
begin
FControl1X := FStartX + FControl1X;
FControl1Y := FStartY + FControl1Y;
FControl2X := FStartX + FControl2X;
FControl2Y := FStartY + FControl2Y;
FStopX := FStartX + FStopX;
FStopY := FStartY + FStopY;
end;
{
https://forums.asp.net/t/1787224.aspx?How+to+draw+quadratic+bezier+curve+in+GDI+
"quadratic bezier of the form [P1, C, P2] (where C is the control point)
you can form an equivalent cubic bezier with [P1, (C*2/3 + P1 * 1/3), (C*2/3 + P2 * 1/3), P2]. "
}
FControl1X := 2 * FControl1X / 3 + FStartX / 3;
FControl1Y := 2 * FControl1Y / 3 + FStartY / 3;
FControl2X := 2 * FControl2X / 3 + FStopX / 3;
FControl2Y := 2 * FControl2Y / 3 + FStopY / 3;
end
else if (Command = 'T') or (Command = 't') then
begin
FControl1X := FStartX;
FControl1Y := FStartY;
FStopX := ValueList[Position];
FStopY := ValueList[Position + 1];
Inc(Position, 2);
if Previous is TSVGPathCurve then
begin
FControl1X := FStartX + (FStartX - TSVGPathCurve(Previous).FControl2X);
FControl1Y := FStartY + (FStartY - TSVGPathCurve(Previous).FControl2Y);
end;
FControl2X := FStartX + (FStartX - TSVGPathCurve(Previous).FControl1X);
FControl2Y := FStartY + (FStartY - TSVGPathCurve(Previous).FControl1Y);
if Command = 't' then
begin
FStopX := FStartX + FStopX;
FStopY := FStartY + FStopY;
end;
end;
end;
// TSVGPathEllipticArc
procedure TSVGPathEllipticArc.AssignTo(Dest: TPersistent);
begin
inherited;
if Dest is TSVGPathEllipticArc then
begin
TSVGPathEllipticArc(Dest).FRX := FRX;
TSVGPathEllipticArc(Dest).FRY := FRY;
TSVGPathEllipticArc(Dest).FXRot := FXRot;
TSVGPathEllipticArc(Dest).FLarge := FLarge;
TSVGPathEllipticArc(Dest).FSweep := FSweep;
end;
end;
function TSVGPathEllipticArc.GetBounds: TRectF;
begin
Result.Left := Min(FStartX, FStopX);
Result.Top := Min(FStartY, FStopY);
Result.Width := Abs(FStartX - FStopX);
Result.Height := Abs(FStartY - FStopY);
end;
procedure TSVGPathEllipticArc.AddToPath(Path: TGPGraphicsPath);
var
R: TGPRectF;
X1, Y1: TFloat;
DX2, DY2: TFloat;
Angle: TFloat;
SinAngle: TFloat;
CosAngle: TFloat;
LRX: TFloat;
LRY: TFloat;
PRX: TFloat;
PRY: TFloat;
PX1: TFloat;
PY1: TFloat;
RadiiCheck: TFloat;
sign: TFloat;
Sq: TFloat;
Coef: TFloat;
CX1: TFloat;
CY1: TFloat;
sx2: TFloat;
sy2: TFloat;
cx: TFloat;
cy: TFloat;
ux: TFloat;
uy: TFloat;
vx: TFloat;
vy: TFloat;
p: TFloat;
n: TFloat;
AngleStart: TFloat;
AngleExtent: TFloat;
ArcPath: TGPGraphicsPath;
Matrix: TGPMatrix;
Center: TGPPointF;
begin
if (FStartX = FStopX) and (FStartY = FStopY) then
Exit;
if (FRX = 0) or (FRY = 0) then
begin
Path.AddLine(FStartX, FStartY, FStopX, FStopY);
Exit;
end;
//
// Elliptical arc implementation based on the SVG specification notes
//
// Compute the half distance between the current and the final point
DX2 := (FStartX - FStopX) / 2.0;
DY2 := (FStartY - FStopY) / 2.0;
// Convert angle from degrees to radians
Angle := DegToRad(FMod(FXRot, c360));
cosAngle := cos(Angle);
sinAngle := sin(Angle);
//
// Step 1 : Compute (x1, y1)
//
x1 := (cosAngle * DX2 + sinAngle * DY2);
y1 := (-sinAngle * DX2 + cosAngle * DY2);
// Ensure radii are large enough
LRX := abs(Frx);
LRY := abs(Fry);
Prx := LRX * LRX;
Pry := LRY * LRY;
Px1 := x1 * x1;
Py1 := y1 * y1;
// check that radii are large enough
RadiiCheck := Px1/Prx + Py1/Pry;
if (RadiiCheck > 1) then
begin
LRX := sqrt(RadiiCheck) * LRX;
LRY := sqrt(RadiiCheck) * LRY;
Prx := LRX * LRX;
Pry := LRY * LRY;
end;
//
// Step 2 : Compute (cx1, cy1)
//
sign := IfThen(FLarge = FSweep, -1, 1);
Sq := ((Prx * Pry)-(Prx * Py1)-(Pry * Px1)) / ((Prx * Py1)+(Pry * Px1));
Sq := IfThen(Sq < 0, 0.0, Sq);
Coef := (sign * sqrt(Sq));
CX1 := Coef * ((LRX * y1) / LRY);
CY1 := Coef * -((LRY * x1) / LRX);
//
// Step 3 : Compute (cx, cy) from (cx1, cy1)
//
sx2 := (FStartX + FStopX) / 2.0;
sy2 := (FStartY + FStopY) / 2.0;
cx := sx2 + (cosAngle * CX1 - sinAngle * CY1);
cy := sy2 + (sinAngle * CX1 + cosAngle * CY1);
//
// Step 4 : Compute the angleStart (angle1) and the angleExtent (dangle)
//
ux := (x1 - CX1);
uy := (y1 - CY1);
vx := (-x1 - CX1);
vy := (-y1 - CY1);
// Compute the angle start
n := (ux * ux) + (uy * uy);
n := sqrt(n);
// n := sqrt((ux * ux) + (uy * uy));
p := ux; // (1 * ux) + (0 * uy)
sign := IfThen(uy < 0, -1, 1);
AngleStart := RadToDeg(sign * arccos(p / n));
// Compute the angle extent
n := sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy));
p := ux * vx + uy * vy;
sign := IfThen(ux * vy - uy * vx < 0, -1, 1);
AngleExtent := RadToDeg(sign * arccos(p / n));
if ((Fsweep = 0) and (AngleExtent > 0)) then
begin
AngleExtent := AngleExtent - c360;
end else if ((FSweep = 1) and (AngleExtent < 0)) then
begin
AngleExtent := AngleExtent + c360;
end;
AngleStart := FMod(AngleStart, c360);
AngleExtent := FMod(AngleExtent, c360);
R.x := cx - LRX;
R.y := cy - LRY;
R.width := LRX * 2.0;
R.height := LRY * 2.0;
ArcPath := TGPGraphicsPath.Create;
try
ArcPath.AddArc(R, AngleStart, AngleExtent);
Matrix := TGPMatrix.Create;
try
Center.X := cx;
Center.Y := cy;
Matrix.RotateAt(FXRot, Center);
ArcPath.Transform(Matrix);
finally
Matrix.Free;
end;
Path.AddPath(ArcPath, True);
finally
ArcPath.Free;
end;
end;
procedure TSVGPathEllipticArc.Read(Command: Char; ValueList: TList<TFloat>;
var Position: Integer; Previous: TSVGPathElement);
begin
inherited;
if (Command = 'A') or (Command = 'a') then
begin
FRX := ValueList[Position];
FRY := ValueList[Position + 1];
FXRot := ValueList[Position + 2];
FLarge := Trunc(ValueList[Position + 3]);
FSweep := Trunc(ValueList[Position + 4]);
FStopX := ValueList[Position + 5];
FStopY := ValueList[Position + 6];
Inc(Position, 7);
FRX := Abs(FRX);
FRY := Abs(FRY);
if FLarge <> 0 then
FLarge := 1;
if FSweep <> 0 then
FSweep := 1;
if Command = 'a' then
begin
FStopX := FStartX + FStopX;
FStopY := FStartY + FStopY;
end;
end;
end;
// TSVGPathClose
function TSVGPathClose.FindLastMoveTo: TSVGPathMove;
var
Index: Integer;
Previous: TSVGObject;
begin
for Index := Parent.Count - 2 downto 0 do
begin
Previous := Parent.Items[Index];
if Previous is TSVGPathMove then
begin
Result := TSVGPathMove(Previous);
Exit;
end;
end;
Result := nil;
end;
function TSVGPathClose.GetBounds: TRectF;
begin
Result.Left := 0;
Result.Top := 0;
Result.Width := 0;
Result.Height := 0;
end;
procedure TSVGPathClose.Read(Command: Char; ValueList: TList<TFloat>;
var Position: Integer; Previous: TSVGPathElement);
var
LastMoveTo: TSVGPathMove;
begin
FStartX := Previous.FStopX;
FStartY := Previous.FStopY;
LastMoveTo := FindLastMoveTo;
if Assigned(LastMoveTo) then
begin
FStopX := LastMoveTo.FStopX;
FStopY := LastMoveTo.FStopY;
end else begin
FStopX := FStartX;
FStopY := FStartY;
end;
end;
procedure TSVGPathClose.AddToPath(Path: TGPGraphicsPath);
begin
Path.CloseFigure;
end;
end.
|
{$B-,I-,Q-,R-,S-}
{$M 16384,0,655360}
{Problema 12: Estanque de Nenúfares Bronce [Ho/Kolstad, 2007]
GJ ha instalado un estanque hermoso para el disfrute estético y ejercicio
de sus vacas. El estanque rectangular ha sido particionado en celdas
cuadradas de M filas y N columnas (1 <= M <= 30; 1 <= N <= 30). Algunas
de las celdas tienen nenúfares asombrosamente robustos, otras tienen
rocas; las restantes tienen simplemente, agua azul, fresca, hermosa.
Bessie está practicando sus movimientos de ballet saltando de un nenúfar a
otro y está actualmente ubicada en uno de los nenúfares. Ella quiere ir a
otro nenúfar en el estanque saltando de un nenúfar a otro.
Sorprendentemente, solo para los iniciados, los saltos de Bessie entre
nenúfares siempre se parecen a los movimientos de un caballo de ajedrez:
movers M1 (1 <= M1 <= 30) 'cuadrados' en una dirección y luego M2 ((1 <=
M2 <= 30; M1 !=M2) mas en una dirección ortogonal ( o tal vez M2 en una
dirección y luego M1 en una dirección ortogonal). Bessie algunas veces
podría tener hasta 8 posibilidades para su salto.
Dada la distribución del estanque y el formato de los saltos de Bessie,
determine el menor número de saltos que Bessie debe hacer para moverse de
su ubicación inicial a su ubicación final, un hecho que siempre es
posible para los conjuntos de entrada a usar.
NOMBRE DEL PROBLEMA: bronlily
FORMATO DE ENTRADA:
* Línea 1: Cuatro enteros separados por espacio: M, N, M1 y M2.
* Líneas 2..M+1: La línea i+1 describe la fila i del estanque usando N
enteros separados por espacio con estos valores: 0 indica agua
vacía; 1 indica un nenúfar; 2 indica una roca; 3 indica el nenúfar
desde el cual Bessie comienza; 4 indica el nenúfar que es el
destino de Bessie.
ENTRADA EJEMPLO (archivo bronlily.in):
4 5 1 2
1 0 1 0 1
3 0 2 0 4
0 1 2 0 0
0 0 0 1 0
DETALLES DE LA ENTRADA:
Bessie comienza en la izquierda de la fila 2; su destino está en la
derecha de la fila 2. Varios nenúfares y rocas ocupan el estaque.
FORMATO DE SALIDA:
* Línea 1: Un solo entero que es el minimo numero de saltos entre
nenúfares que Bessie debe hacer para ir de su lugar inicial a
su destino.
SALIDA EJEMPLO (archivo bronlily.out):
2
DETALLES DE LA SALIDA:
De manera inteligente Bessie salta en el nenúfar en la fila 1, columna 3
en su camino al lado derecho.
}
var
fe,fs : text;
n,m,m1,m2,s1,s2,f1,f2 : integer;
mtx : array[0..36,0..36] of integer;
a : array[boolean,1..1000,1..2] of integer;
procedure open;
var
t0,t1 : integer;
begin
assign(fe,'bronlily.in'); reset(fe);
assign(fs,'bronlily.out'); rewrite(fs);
read(fe,m,n,m1,m2);
for t0:=1 to m do
begin
for t1:=1 to n do
begin
read(fe,mtx[t0,t1]);
if mtx[t0,t1] = 0 then mtx[t0,t1]:=maxint;
if mtx[t0,t1] = 1 then mtx[t0,t1]:=0;
if mtx[t0,t1] = 2 then mtx[t0,t1]:=maxint;
if mtx[t0,t1] = 3 then
begin
s1:=t0; s2:=t1; mtx[t0,t1]:=0;
end;
if mtx[t0,t1] = 4 then
begin
f1:=t0; f2:=t1; mtx[t0,t1]:=0;
end;
end;
end;
close(fe);
end;
procedure swap(p : integer);
var
t : integer;
begin
m1:=abs(m1); m2:=abs(m2);
case p of
1..2:begin
t:=m1; m1:=m2; m2:=t;
end;
3..4:begin
t:=m1; m1:=m2; m2:=t;
m1:=-m1;
end;
5..6:begin
t:=m1; m1:=m2; m2:=t;
m1:=-m1; m2:=-m2;
end;
7..8:begin
t:=m1; m1:=m2; m2:=t;
m2:=-m2;
end;
end;
end;
procedure work;
var
i,j,cp,ch,x,y : integer;
s : boolean;
z : array[1..2] of integer;
begin
cp := 1; ch := 0; s:=true; a[s,1,1]:=s1; a[s,1,2]:=s2;
while cp>0 do
begin
for i:=1 to cp do
begin
x:=a[s,i,1]; y:=a[s,i,2];
for j:=1 to 8 do
begin
z[1]:=x+m1; z[2]:=y+m2;
if (z[1] > 0) and (z[1] <= m) and (z[2] > 0) and (z[2] <= n)
and (mtx[z[1],z[2]] = 0){ and (mtx[z[1],z[2]] <> 2)} then
begin
inc(ch);
a[not s,ch,1]:=z[1]; a[not s,ch,2]:=z[2];
mtx[z[1],z[2]] := mtx[x,y] + 1;
end;
swap(j);
end;
end;
cp:=ch; ch:=0; s:= not s;
end;
write(fs,mtx[f1,f2]);
close(fs);
end;
begin
open;
work;
end. |
unit uImportSource;
interface
uses
Generics.Defaults,
Generics.Collections,
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Buttons,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Vcl.Themes,
Vcl.Imaging.PngImage,
Dmitry.Utils.Files,
Dmitry.Controls.Base,
Dmitry.Controls.LoadingSign,
Dmitry.PathProviders,
UnitDBFileDialogs,
uConstants,
uRuntime,
uMemory,
uBitmapUtils,
uGraphicUtils,
uResources,
uFormInterfaces,
uThreadForm,
uThreadTask,
uPortableClasses,
uPortableDeviceManager,
uVCLHelpers;
type
TImportType = (itRemovableDevice, itUSB, itHDD, itCD, itDirectory);
TButtonInfo = class
Name: string;
Path: string;
ImportType: TImportType;
SortOrder: Integer;
end;
type
TFormImportSource = class(TThreadForm, ISelectSourceForm)
LsLoading: TLoadingSign;
LbLoadingMessage: TLabel;
TmrDeviceChanges: TTimer;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure TmrDeviceChangesTimer(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
FLoadingCount: Integer;
FButtons: TList<TSpeedButton>;
procedure StartLoadingSourceList;
procedure AddLocation(Name: string; ImportType: TImportType; Path: string; Image: TBitmap);
procedure LoadLanguage;
procedure FillDeviceCallBack(Packet: TList<IPDevice>; var Cancel: Boolean; Context: Pointer);
procedure LoadingThreadFinished;
procedure ReorderForm;
procedure SelectSourceClick(Sender: TObject);
procedure WMDeviceChange(var Msg: TMessage); message WM_DEVICECHANGE;
procedure PortableEventsCallBack(EventType: TPortableEventType; DeviceID: string; ItemKey: string; ItemPath: string);
protected
procedure InterfaceDestroyed; override;
function GetFormID: string; override;
public
{ Public declarations }
procedure Execute;
end;
implementation
{$R *.dfm}
{$MINENUMSIZE 4}
const
IOCTL_STORAGE_QUERY_PROPERTY = $002D1400;
type
STORAGE_QUERY_TYPE = (PropertyStandardQuery = 0, PropertyExistsQuery, PropertyMaskQuery, PropertyQueryMaxDefined);
TStorageQueryType = STORAGE_QUERY_TYPE;
STORAGE_PROPERTY_ID = (StorageDeviceProperty = 0, StorageAdapterProperty);
TStoragePropertyID = STORAGE_PROPERTY_ID;
STORAGE_PROPERTY_QUERY = packed record
PropertyId: STORAGE_PROPERTY_ID;
QueryType: STORAGE_QUERY_TYPE;
AdditionalParameters: array [0..9] of AnsiChar;
end;
TStoragePropertyQuery = STORAGE_PROPERTY_QUERY;
STORAGE_BUS_TYPE = (BusTypeUnknown = 0, BusTypeScsi, BusTypeAtapi, BusTypeAta, BusType1394, BusTypeSsa, BusTypeFibre,
BusTypeUsb, BusTypeRAID, BusTypeiScsi, BusTypeSas, BusTypeSata, BusTypeMaxReserved = $7F);
TStorageBusType = STORAGE_BUS_TYPE;
STORAGE_DEVICE_DESCRIPTOR = packed record
Version: DWORD;
Size: DWORD;
DeviceType: Byte;
DeviceTypeModifier: Byte;
RemovableMedia: Boolean;
CommandQueueing: Boolean;
VendorIdOffset: DWORD;
ProductIdOffset: DWORD;
ProductRevisionOffset: DWORD;
SerialNumberOffset: DWORD;
BusType: STORAGE_BUS_TYPE;
RawPropertiesLength: DWORD;
RawDeviceProperties: array [0..0] of AnsiChar;
end;
TStorageDeviceDescriptor = STORAGE_DEVICE_DESCRIPTOR;
function GetBusType(Drive: AnsiChar): TStorageBusType;
var
H: THandle;
Query: TStoragePropertyQuery;
dwBytesReturned: DWORD;
Buffer: array [0..1023] of Byte;
sdd: TStorageDeviceDescriptor absolute Buffer;
OldMode: UINT;
begin
Result := BusTypeUnknown;
OldMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
H := CreateFile(PChar(Format('\\.\%s:', [AnsiLowerCase(string(Drive))])), 0, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, 0, 0);
if H <> INVALID_HANDLE_VALUE then
begin
try
dwBytesReturned := 0;
FillChar(Query, SizeOf(Query), 0);
FillChar(Buffer, SizeOf(Buffer), 0);
sdd.Size := SizeOf(Buffer);
Query.PropertyId := StorageDeviceProperty;
Query.QueryType := PropertyStandardQuery;
if DeviceIoControl(H, IOCTL_STORAGE_QUERY_PROPERTY, @Query, SizeOf(Query), @Buffer, SizeOf(Buffer), dwBytesReturned, nil) then
Result := sdd.BusType;
finally
CloseHandle(H);
end;
end;
finally
SetErrorMode(OldMode);
end;
end;
function CheckDriveItems(Path: string): Boolean;
var
OldMode: Cardinal;
Found: Integer;
SearchRec: TSearchRec;
Directories: TQueue<string>;
Dir: string;
begin
Result := False;
OldMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
Directories := TQueue<string>.Create;
try
Directories.Enqueue(Path);
while Directories.Count > 0 do
begin
Dir := Directories.Dequeue;
Dir := IncludeTrailingBackslash(Dir);
Found := FindFirst(Dir + '*.*', faDirectory, SearchRec);
try
while Found = 0 do
begin
if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then
begin
if (faDirectory and SearchRec.Attr = 0) then
Exit(True);
if faDirectory and SearchRec.Attr <> 0 then
Directories.Enqueue(Dir + SearchRec.Name);
Found := System.SysUtils.FindNext(SearchRec);
end;
end;
finally
FindClose(SearchRec);
end;
end;
finally
F(Directories);
end;
finally
SetErrorMode(OldMode);
end;
end;
function CheckDeviceItems(Device: IPDevice): Boolean;
var
Directories: TQueue<TPathItem>;
PI, Dir: TPathItem;
Childs: TPathItemCollection;
Res: Boolean;
begin
Res := False;
Directories := TQueue<TPathItem>.Create;
try
PI := PathProviderManager.CreatePathItem(cDevicesPath + '\' + Device.Name);
Directories.Enqueue(PI);
while Directories.Count > 0 do
begin
if Res then
Break;
Dir := Directories.Dequeue;
try
Childs := TPathItemCollection.Create;
try
Dir.Provider.FillChildList(nil, Dir, Childs, PATH_LOAD_NO_IMAGE or PATH_LOAD_FAST, 0, 10,
procedure(Sender: TObject; Item: TPathItem; CurrentItems: TPathItemCollection; var Break: Boolean)
var
I: Integer;
begin
for I := 0 to CurrentItems.Count - 1 do
begin
if not CurrentItems[I].IsDirectory then
begin
Res := True;
Break := True;
end else
Directories.Enqueue(CurrentItems[I].Copy);
end;
CurrentItems.FreeItems;
end
);
finally
Childs.FreeItems;
F(Childs);
end;
finally
F(Dir);
end;
end;
while Directories.Count > 0 do
Directories.Dequeue.Free;
finally
F(Directories);
end;
Result := Res;
end;
{ TFormImportSource }
procedure TFormImportSource.AddLocation(Name: string; ImportType: TImportType; Path: string; Image: TBitmap);
var
Button: TSpeedButton;
BI: TButtonInfo;
procedure UpdateGlyph(Button: TSpeedButton);
var
Png: TPngImage;
B, B24: TBitmap;
Image: string;
Font: TFont;
begin
case ImportType of
itCD:
Image := 'IMPORT_CD';
itRemovableDevice:
Image := 'IMPORT_CAMERA';
itUSB:
Image := 'IMPORT_USB';
itHDD:
Image := 'IMPORT_HDD';
else
Image := 'IMPORT_DIRECTORY';
end;
Png := TResourceUtils.LoadGraphicFromRES<TPngImage>(Image);
try
B := TBitmap.Create;
try
AssignGraphic(B, Png);
Font := TFont.Create;
try
Font.Assign(Self.Font);
Font.Color := Theme.WindowTextColor;
Font.Style := [fsBold];
Font.Size := 12;
B.Height := B.Height + 4 - Font.Height;
FillTransparentColor(B, Theme.WindowTextColor, 0, B.Height - 4 + Font.Height, B.Width, 4 - Font.Height, 0);
DrawText32Bit(B, Name, Font, Rect(0, B.Height - 4 + Font.Height, B.Width, B.Height), DT_CENTER or DT_END_ELLIPSIS);
if not TStyleManager.IsCustomStyleActive then
begin
B24 := TBitmap.Create;
try
LoadBMPImage32bit(B, B24, Theme.WindowColor);
Button.Glyph := B24;
finally
F(B24);
end;
end else
Button.Glyph := B;
finally
F(Font);
end;
finally
F(B);
end;
finally
F(Png);
end;
end;
begin
if Visible then
BeginScreenUpdate(Handle);
try
Button := TSpeedButton.Create(Self);
Button.Parent := Self;
Button.Width := 132;
Button.Height := 132 + 20;
Button.Top := 4;
Button.OnClick := SelectSourceClick;
BI := TButtonInfo.Create;
BI.Name := Name;
BI.Path := Path;
BI.ImportType := ImportType;
BI.SortOrder := 1000 * Integer(ImportType);
if (Path.Length > 1) and (Path[2] = ':') then
BI.SortOrder := BI.SortOrder + Byte(AnsiChar(Path[2]));
Button.Tag := NativeInt(BI);
if Image = nil then
UpdateGlyph(Button)
else
Button.Glyph := Image;
FButtons.Add(Button);
ClientHeight := Button.Height + 5 * 2;
ReorderForm;
finally
if Visible then
EndScreenUpdate(Handle, True);
end;
end;
procedure TFormImportSource.Execute;
begin
StartLoadingSourceList;
ShowModal;
end;
procedure TFormImportSource.FillDeviceCallBack(Packet: TList<IPDevice>;
var Cancel: Boolean; Context: Pointer);
var
I: Integer;
Thread: TThreadTask;
begin
Thread := TThreadTask(Context);
for I := 0 to Packet.Count - 1 do
if CheckDeviceItems(Packet[I]) then
Cancel := not Thread.SynchronizeTask(
procedure
begin
TFormImportSource(Thread.ThreadForm).AddLocation(Packet[I].Name, itRemovableDevice, cDevicesPath + '\' + Packet[I].Name, nil);
end
);
end;
procedure TFormImportSource.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caHide;
end;
procedure TFormImportSource.FormCreate(Sender: TObject);
begin
FLoadingCount := 0;
FButtons := TList<TSpeedButton>.Create;
LoadLanguage;
GetDeviceEventManager.RegisterNotification([peDeviceConnected, peDeviceDisconnected], PortableEventsCallBack);
end;
procedure TFormImportSource.FormDestroy(Sender: TObject);
var
I: Integer;
begin
GetDeviceEventManager.UnRegisterNotification(PortableEventsCallBack);
for I := 0 to FButtons.Count - 1 do
TObject(FButtons[I].Tag).Free;
F(FButtons);
end;
procedure TFormImportSource.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then
Close;
end;
function TFormImportSource.GetFormID: string;
begin
Result := 'ImportSource';
end;
procedure TFormImportSource.InterfaceDestroyed;
begin
inherited;
Release;
end;
procedure TFormImportSource.LoadingThreadFinished;
begin
Dec(FLoadingCount);
if FLoadingCount = 0 then
ReorderForm;
end;
procedure TFormImportSource.LoadLanguage;
begin
BeginTranslate;
try
Caption := L('Import photos and video');
LbLoadingMessage.Caption := L('Please wait until program searches for sources with images');
finally
EndTranslate;
end;
end;
procedure TFormImportSource.PortableEventsCallBack(
EventType: TPortableEventType; DeviceID, ItemKey, ItemPath: string);
begin
case EventType of
peDeviceConnected,
peDeviceDisconnected:
TmrDeviceChanges.Restart;
end;
end;
procedure TFormImportSource.ReorderForm;
var
I,
CW,
LoadingWidth: Integer;
begin
FButtons.Sort(TComparer<TSpeedButton>.Construct(
function (const L, R: TSpeedButton): Integer
begin
Result := TButtonInfo(L.Tag).SortOrder - TButtonInfo(R.Tag).SortOrder;
end
));
for I := 0 to FButtons.Count - 1 do
FButtons[I].Left := 5 + FButtons.IndexOf(FButtons[I]) * (130 + 5);
CW := 5 + FButtons.Count * (130 + 5);
LockWindowUpdate(Handle);
try
if FLoadingCount > 0 then
begin
LoadingWidth := 100;
Inc(CW, LoadingWidth);
LbLoadingMessage.Left := CW - LoadingWidth + LoadingWidth div 2 - LbLoadingMessage.Width div 2;
LsLoading.Left := CW - LoadingWidth + LoadingWidth div 2 - LsLoading.Width div 2;
end else
begin
LbLoadingMessage.Hide;
LsLoading.Hide;
end;
ClientWidth := CW;
Left := Monitor.Left + Monitor.Width div 2 - Width div 2;
finally
LockWindowUpdate(0);
end;
end;
procedure TFormImportSource.SelectSourceClick(Sender: TObject);
var
BI: TButtonInfo;
Path: string;
begin
BI := TButtonInfo(TControl(Sender).Tag);
if BI.ImportType = itDirectory then
begin
Path := UnitDBFileDialogs.DBSelectDir(Application.Handle, Caption);
if Path = '' then
Exit;
ImportForm.FromFolder(Path);
Close;
Exit;
end;
ImportForm.FromFolder(BI.Path);
Close;
end;
procedure TFormImportSource.StartLoadingSourceList;
begin
LbLoadingMessage.Show;
LsLoading.Show;
//load CDs
Inc(FLoadingCount);
TThreadTask.Create(Self, Pointer(nil),
procedure(Thread: TThreadTask; Data: Pointer)
var
I: Integer;
OldMode: Cardinal;
VolumeName: string;
begin
OldMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
for I := Ord('A') to Ord('Z') do
if (GetDriveType(PChar(Chr(I) + ':\')) = DRIVE_CDROM) and CheckDriveItems(Chr(I) + ':\') then
begin
VolumeName := GetDriveVolumeLabel(AnsiChar(I));
if not Thread.SynchronizeTask(
procedure
begin
TFormImportSource(Thread.ThreadForm).AddLocation(VolumeName, itCD, Chr(I) + ':\', nil);
end
) then Break;
end;
finally
SetErrorMode(OldMode);
Thread.SynchronizeTask(
procedure
begin
TFormImportSource(Thread.ThreadForm).LoadingThreadFinished;
end
);
end;
end
);
//load HDDs by USB
Inc(FLoadingCount);
TThreadTask.Create(Self, Pointer(nil),
procedure(Thread: TThreadTask; Data: Pointer)
var
I: Integer;
OldMode: Cardinal;
VolumeName: string;
begin
OldMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
for I := Ord('A') to Ord('Z') do
if (GetDriveType(PChar(Chr(I) + ':\')) = DRIVE_FIXED) and (GetBusType(AnsiChar(I)) = BusTypeUsb) and CheckDriveItems(Chr(I) + ':\') then
begin
VolumeName := GetDriveVolumeLabel(AnsiChar(I));
if not Thread.SynchronizeTask(
procedure
begin
TFormImportSource(Thread.ThreadForm).AddLocation(VolumeName, itHDD, Chr(I) + ':\', nil);
end
) then Break;
end;
finally
SetErrorMode(OldMode);
Thread.SynchronizeTask(
procedure
begin
TFormImportSource(Thread.ThreadForm).LoadingThreadFinished;
end
);
end;
end
);
//load Flash cards
Inc(FLoadingCount);
TThreadTask.Create(Self, Pointer(nil),
procedure(Thread: TThreadTask; Data: Pointer)
var
I: Integer;
OldMode: Cardinal;
VolumeName: string;
begin
OldMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
for I := Ord('A') to Ord('Z') do
if (GetDriveType(PChar(Chr(I) + ':\')) = DRIVE_REMOVABLE) and CheckDriveItems(Chr(I) + ':\') then
begin
VolumeName := GetDriveVolumeLabel(AnsiChar(I));
if not Thread.SynchronizeTask(
procedure
begin
TFormImportSource(Thread.ThreadForm).AddLocation(VolumeName, itUSB, Chr(I) + ':\', nil);
end
) then Break;
end;
finally
SetErrorMode(OldMode);
Thread.SynchronizeTask(
procedure
begin
TFormImportSource(Thread.ThreadForm).LoadingThreadFinished;
end
);
end;
end
);
//load Devices
Inc(FLoadingCount);
TThreadTask.Create(Self, Pointer(nil),
procedure(Thread: TThreadTask; Data: Pointer)
var
Manager: IPManager;
begin
Manager := CreateDeviceManagerInstance;
try
Manager.FillDevicesWithCallBack(FillDeviceCallBack, Thread);
finally
Manager := nil;
Thread.SynchronizeTask(
procedure
begin
TFormImportSource(Thread.ThreadForm).LoadingThreadFinished;
end
);
end;
end
);
AddLocation(L('Select a folder'), itDirectory, '', nil);
end;
procedure TFormImportSource.TmrDeviceChangesTimer(Sender: TObject);
var
I: Integer;
begin
TmrDeviceChanges.Enabled := False;
BeginScreenUpdate(Handle);
try
//Refresh buttons
for I := 0 to FButtons.Count - 1 do
TObject(FButtons[I].Tag).Free;
for I := 0 to FButtons.Count - 1 do
FButtons[I].Free;
FButtons.Clear;
StartLoadingSourceList;
finally
EndScreenUpdate(Handle, False);
end;
end;
procedure TFormImportSource.WMDeviceChange(var Msg: TMessage);
begin
TmrDeviceChanges.Restart;
end;
initialization
FormInterfaces.RegisterFormInterface(ISelectSourceForm, TFormImportSource);
end.
|
(******************************************************************************
* Copyright (C) 2023 Tomáš Horák
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************************)
unit uCryptic;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, trl_icryptic, DCPtwofish, DCPsha256;
type
ECryptic = class(Exception);
{ TCryptic }
TCryptic = class(TInterfacedObject, ICryptic)
private
fKey: string;
protected
function Decode(const AData: String): String;
function Encode(const AData: String): String;
procedure Decode(AInStream, AOutStream: TStream);
procedure Encode(AInStream, AOutStream: TStream);
function GetKey: string;
procedure SetKey(AValue: string);
property Key: string read GetKey write SetKey;
end;
implementation
{ TCryptic }
function TCryptic.Decode(const AData: String): String;
var
mCipher: TDCP_twofish;
begin
if AData = '' then
begin
Result := '';
Exit;
end;
mCipher:= TDCP_twofish.Create(nil);
try
mCipher.InitStr(fKey, TDCP_sha256);
Result := mCipher.DecryptString(AData);
finally
mCipher.Free;
end;
end;
function TCryptic.Encode(const AData: String): String;
var
mCipher: TDCP_twofish;
begin
mCipher := TDCP_twofish.Create(nil);
try
mCipher.InitStr(fKey, TDCP_sha256);
Result := mCipher.EncryptString(AData);
finally
mCipher.Free;
end;
end;
procedure TCryptic.Decode(AInStream, AOutStream: TStream);
var
mCipher: TDCP_twofish;
begin
mCipher:= TDCP_twofish.Create(nil);
try
mCipher.InitStr(fKey, TDCP_sha256);
AInStream.Position := 0;
AOutStream.Size := 0;
mCipher.DecryptStream(AInStream, AOutStream, AInStream.Size);
finally
mCipher.Free;
end;
end;
procedure TCryptic.Encode(AInStream, AOutStream: TStream);
var
mCipher: TDCP_twofish;
begin
mCipher := TDCP_twofish.Create(nil);
try
mCipher.InitStr(fKey, TDCP_sha256);
AInStream.Position := 0;
AOutStream.Size := 0;
mCipher.EncryptStream(AInStream, AOutStream, AInStream.Size);
finally
mCipher.Free;
end;
end;
function TCryptic.GetKey: string;
begin
Result := fKey;
end;
procedure TCryptic.SetKey(AValue: string);
begin
if fKey <> AValue then begin
fKey := AValue;
end;
end;
end.
|
unit Magento.AttributeSets;
interface
uses
Magento.Interfaces, System.Classes,REST.Response.Adapter, System.JSON, Data.DB,
SysUtils;
type
TMagentoAttributeSets = class (TInterfacedObject, iMagentoAttributeSets)
private
FAttributeSetID : Integer;
FAttibuteSetName : String;
FSortOrder : Integer;
FEntityTypeID : Integer;
public
constructor Create;
destructor Destroy; override;
class function New : iMagentoAttributeSets;
function ListAttibuteSets(Value : TDataSet) : iMagentoAttributeSets;
function ListAttributeSetsID(Value : TDataSet; ID : String) : iMagentoAttributeSets;
function AttributeSetID(Value : Integer) : iMagentoAttributeSets;
function AttibuteSetName(Value : String) : iMagentoAttributeSets;
function SortOrder(Value : Integer) : iMagentoAttributeSets;
function EntityTypeID(Value : Integer) : iMagentoAttributeSets;
function &End : String;
end;
implementation
{ TMagentoAttributeSets }
uses Magento.Factory;
function TMagentoAttributeSets.&End: String;
var
lObj,lJSON : TJSONObject;
begin
lObj := TJSONObject.Create;
lJSON := TJSONObject.Create;
lObj.AddPair('skeletonId',TJSONNumber.Create(4));
lJSON.AddPair('attribute_set_id',TJSONNull.Create);
lJSON.AddPair('attribute_set_name', FAttibuteSetName);
lJSON.AddPair('sort_order',TJSONNumber.Create(FSortOrder));
lJSON.AddPair('entity_type_id',TJSONNumber.Create(FEntityTypeID));
lJSON.AddPair('extension_attributes', TJSONNull.Create);
lObj.AddPair('attributeSet',lJSON);
lObj.AddPair('entityTypeCode','catalog_product');
Result := lObj.ToString;
end;
function TMagentoAttributeSets.AttibuteSetName(
Value: String): iMagentoAttributeSets;
begin
Result := Self;
FAttibuteSetName := Value;
end;
function TMagentoAttributeSets.AttributeSetID(
Value: Integer): iMagentoAttributeSets;
begin
Result := Self;
FAttributeSetID := Value;
end;
constructor TMagentoAttributeSets.Create;
begin
end;
destructor TMagentoAttributeSets.Destroy;
begin
inherited;
end;
function TMagentoAttributeSets.EntityTypeID(
Value: Integer): iMagentoAttributeSets;
begin
Result := Self;
FEntityTypeID := Value;
end;
function TMagentoAttributeSets.ListAttibuteSets(Value : TDataSet) : iMagentoAttributeSets;
var
lJSONObj : TJSONObject;
lJSONArray : TJSONArray;
lConv : TCustomJSONDataSetAdapter;
lJSON : String;
begin
Result := Self;
lJSON := TMagentoFactory.New.MagentoHTTP.GetAtributo;
lJSONObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(lJSON), 0) as TJSONObject;
lConv := TCustomJSONDataSetAdapter.Create(nil);
lJSONArray := lJSONObj.Get('items').JsonValue as TJSONArray;
try
lConv.DataSet := Value;
lConv.UpdateDataSet(lJSONArray);
finally
lConv.Free;
end;
end;
function TMagentoAttributeSets.ListAttributeSetsID(Value: TDataSet;
ID: String): iMagentoAttributeSets;
var
lJSONObj, lArray, JSONArray : TJSONArray;
lObj, lSubObj, JSONObj : TJSONObject;
lConv : TCustomJSONDataSetAdapter;
lJSON,Select_Value : String;
I, J: Integer;
begin
Result := Self;
lJSON := TMagentoFactory.New.MagentoHTTP.GetAtributoID(ID);
lJSONObj := TJSONObject.ParseJSONValue(lJSON) as TJSONArray;
JSONArray := TJSONArray.Create;
for I := 0 to lJSONObj.Size-1 do
begin
lObj := TJSONObject.Create;
Select_Value := '';
lSubObj := (lJSONObj.Get(I) as TJSONObject);
lObj.AddPair('default_frontend_label',lSubObj.Get(7).JsonValue.Value);
lObj.AddPair('attribute_id',lSubObj.Get(0).JsonValue.Value);
lObj.AddPair('attribute_code',lSubObj.Get(1).JsonValue.Value);
lArray := lSubObj.Get(5).JsonValue as TJSONArray;
for J := 0 to lArray.Size-1 do
begin
JSONObj := (lArray.Get(J) as TJSONObject);
if Select_Value='' then
Select_Value := JSONObj.Get(1).JsonValue.Value+' ('+JSONObj.Get(0).JsonValue.Value+')'
else
Select_Value := Select_Value+','+JSONObj.Get(1).JsonValue.Value+' ('+JSONObj.Get(0).JsonValue.Value+')';
end;
lObj.AddPair('Attribute_Value',Select_Value);
JSONArray.Add(lObj);
end;
lConv := TCustomJSONDataSetAdapter.Create(nil);
try
lConv.DataSet := Value;
lConv.UpdateDataSet(JSONArray);
finally
lConv.Free;
end;
end;
class function TMagentoAttributeSets.New: iMagentoAttributeSets;
begin
Result := self.Create;
end;
function TMagentoAttributeSets.SortOrder(Value: Integer): iMagentoAttributeSets;
begin
Result := Self;
FSortOrder := Value;
end;
end.
|
unit uI2XImageProcJobThread;
interface
uses
SysUtils,
Classes,
uI2XDLL,
uDWImage,
GR32,
uI2XThreadBase,
uStrUtil,
uHashTable,
uI2XConstants,
uImage2XML,
uI2XTemplate,
uI2XOCR,
uI2XPluginManager
;
type
TI2XImageProcJobThread = class(TI2XThreadedImageJob)
private
FInstructionList : TStringList2;
FReturnValue : integer;
FTriggerOCRAfter : boolean;
protected
procedure Execute; override;
public
property InstructionList : TStringList2 read FInstructionList write FInstructionList;
property TriggerOCRAfter : boolean read FTriggerOCRAfter write FTriggerOCRAfter;
constructor Create(); overload;
constructor Create( bmp32: TBitmap32 ); overload;
destructor Destroy; override;
function ExecuteImageProc() : boolean;
end;
implementation
{ TI2XImageProcJobThread }
constructor TI2XImageProcJobThread.Create;
begin
inherited Create();
FInstructionList := TStringList2.Create;
FTriggerOCRAfter := false;
end;
constructor TI2XImageProcJobThread.Create(bmp32: TBitmap32);
begin
inherited Create( bmp32 );
FInstructionList := TStringList2.Create;
FTriggerOCRAfter := false;
end;
destructor TI2XImageProcJobThread.Destroy;
begin
FreeAndNil( FInstructionList );
inherited;
end;
procedure TI2XImageProcJobThread.Execute;
Begin
ExecuteImageProc();
End;
function TI2XImageProcJobThread.ExecuteImageProc() : boolean;
var
DLLImageProc : TDLLImageProc;
iInst : smallint;
sDLLShortName : string;
ImageDLLs : THashTable;
Plugins : TI2XPluginManager;
Begin
try
Result := false;
//Load Image Plugins
try
if ( self.FCreatePluginMananger ) then begin
Plugins := TI2XPluginManager.Create( DLLSearchPath );
if ( Plugins.SearchAndLoadImagePlugins = 0 ) then
raise Exception.Create('Image Processing DLLS were not found in search path ' + DLLSearchPath );
end else
Plugins := self.PluginManager;
if ( self.FInstructionList.Count > 0 ) then begin
if EnableJobEvents then OnJobStart( self.FInstructionList.Count );
for iInst := 0 to self.FInstructionList.Count - 1 do begin
OnStatusChange( 'Processing instruction ' + IntToStr( iInst + 1 ) + ' of ' + IntToStr(self.FInstructionList.Count));
sDLLShortName := Split( FInstructionList[iInst], IMGPROC_PLUGIN_SEP, 0 );
DLLImageProc := Plugins.ImageDLLByShortName( sDLLShortName );
if ( DLLImageProc = nil ) then
raise Exception.Create('ImageProc DLL with shortname "' + sDLLShortName + '" could not be found.' );
FReturnValue := DLLImageProc.ProcessImage( self.ImageMemoryMapID, FInstructionList[iInst] );
if ( FReturnValue <> ERROR_OK ) then
raise Exception.Create( 'IMG-' + sDLLShortName + ':' + DLLImageProc.LastErrorMessage );
end;
end;
OnStatusChange( 'Image processing completed');
except
on E : Exception do begin
self.OnJobError( ERROR_IMAGE_THREAD_FAILED, E.ClassName + ': ' + E.Message );
end;
end;
if EnableJobEvents then OnJobEnd( iInst, self.ImageMemoryMapID );
Result := true;
finally
if ( FCreatePluginMananger ) then FreeAndNil( Plugins );
end;
End;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.